From 4a3ca7f207552e2a7b4a88fd51f4055d2243f27b Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:20:48 +0800 Subject: [PATCH 1/9] feat: manage agent configuration and portable packages --- .agent/agents.json | 17 - .agent/agents.yaml | 13 + .github/ci/linux-tests.Dockerfile | 13 + .github/swift-package.json | 27 +- .github/workflows/ci.yml | 2 +- .github/workflows/source-policy.yml | 2 +- .gitignore | 2 +- CHANGELOG.md | 28 + Documentation/Architecture/Instructions.md | 129 +- Documentation/Architecture/NativeDocuments.md | 98 + Documentation/Architecture/Package.md | 331 +- Documentation/Architecture/README.md | 22 +- Documentation/Architecture/State.md | 1010 +- Documentation/Architecture/Updates.md | 493 +- Documentation/Architecture/Watch.md | 61 +- Documentation/Archive/AgentsManifest.md | 647 + Documentation/Archive/README.md | 3 +- Documentation/Decisions/AgentComponents.md | 92 + .../Decisions/ConfigurationApplication.md | 53 + Documentation/Decisions/ExecutableApproval.md | 55 + Documentation/Decisions/README.md | 7 + Documentation/Decisions/SwiftManifest.md | 91 + Documentation/Decisions/YAMLManifest.md | 24 + Documentation/Proposals/AgentInstructions.md | 147 +- Documentation/README.md | 3 +- Documentation/Reference/APMImport.md | 22 + Documentation/Reference/AgentClients.md | 70 + Documentation/Reference/AuthorPackaging.md | 138 + Documentation/Reference/ContentAudit.md | 65 + Documentation/Reference/MCPRegistry.md | 118 + Documentation/Reference/Manifest.md | 268 + Documentation/Reference/ManifestSchema.md | 668 + Documentation/Reference/Marketplace.md | 178 + Documentation/Reference/OrganizationPolicy.md | 152 + Documentation/Reference/Presentation.md | 2 +- Documentation/Reference/README.md | 7 + Documentation/Reference/SourceAccess.md | 101 + Documentation/Reference/UserSourceAccess.md | 103 + Package.resolved | 91 +- Package.swift | 114 +- README.md | 150 +- Scripts/generate-manifest-schema.py | 217 + Scripts/test-linux.py | 39 + Scripts/test_manifest_schema.py | 86 + .../AcquisitionCache/AcquisitionCache.swift | 155 + .../AcquisitionCache/AcquisitionStorage.swift | 702 + .../DeployedAcquisition.swift | 36 + .../AcquisitionCache/GitAcquisition.swift | 331 + .../AgentsCore/AgentClientApplications.swift | 37 + .../AgentsCore/AgentClientObservation.swift | 181 + Sources/AgentsCore/AgentRegistry.swift | 135 +- .../AgentsCore/ArchiveDeploymentAccess.swift | 63 + Sources/AgentsCore/BundleSourceLocation.swift | 21 + Sources/AgentsCore/BundleStoredSource.swift | 73 + .../ClientBackups/BackupArchive.swift | 183 + .../ClientBackups/BackupClaudeImports.swift | 160 + .../BackupGeminiCheckpoints.swift | 176 + .../ClientBackups/BackupJSONStream.swift | 233 + .../ClientBackups/BackupNativeData.swift | 495 + .../BackupRestoreTransaction.swift | 345 + .../ClientBackups/BackupScope.swift | 652 + .../ClientBackups/BackupStorage.swift | 360 + .../AgentsCore/ClientBackups/BackupZstd.swift | 34 + .../ClientBackups/ClientBackups.swift | 921 + Sources/AgentsCore/ComponentConditions.swift | 43 + Sources/AgentsCore/ComponentDeclaration.swift | 350 + Sources/AgentsCore/ContentAuditFiles.swift | 221 + Sources/AgentsCore/CoreError.swift | 10 + Sources/AgentsCore/Declaration.swift | 468 +- Sources/AgentsCore/DeclarationAccess.swift | 30 + Sources/AgentsCore/DeclarationIR.swift | 83 + Sources/AgentsCore/DirectoryHandle.swift | 842 +- Sources/AgentsCore/FileAccess.swift | 382 + Sources/AgentsCore/FileHash.swift | 110 +- Sources/AgentsCore/FileLock.swift | 174 +- Sources/AgentsCore/FileSystem.swift | 101 + Sources/AgentsCore/FileTransaction.swift | 905 +- Sources/AgentsCore/GitError.swift | 6 +- Sources/AgentsCore/HostedMarketplace.swift | 151 + Sources/AgentsCore/InstructionLocations.swift | 75 +- Sources/AgentsCore/LedgerAdmission.swift | 252 + .../AgentsCore/LedgerDisplayEvidence.swift | 84 + .../AgentsCore/LedgerNativeAuthority.swift | 171 + Sources/AgentsCore/LedgerProjection.swift | 125 + Sources/AgentsCore/LedgerResourceLinks.swift | 103 + Sources/AgentsCore/LedgerResources.swift | 292 + Sources/AgentsCore/LedgerSourcePolicy.swift | 137 + Sources/AgentsCore/LedgerStateStore.swift | 121 + Sources/AgentsCore/LedgerValidation.swift | 556 + Sources/AgentsCore/LifecycleDeclaration.swift | 273 + Sources/AgentsCore/LifecycleFileAccess.swift | 140 + Sources/AgentsCore/MCPRegistryEvidence.swift | 260 + Sources/AgentsCore/MCPTransportPayload.swift | 59 + Sources/AgentsCore/ManagedSourceGit.swift | 122 + Sources/AgentsCore/MarketplaceGraph.swift | 487 + Sources/AgentsCore/MarketplacePackage.swift | 288 + .../AgentsCore/NativeTargetCoordination.swift | 1493 + Sources/AgentsCore/OrganizationPolicy.swift | 207 + .../OrganizationPolicyEvaluation.swift | 521 + Sources/AgentsCore/OwnedDuplexProcess.swift | 255 + Sources/AgentsCore/PackageSourceHTTP.swift | 133 + Sources/AgentsCore/PathSafety.swift | 41 + .../AgentsCore/PortableSourceEvidence.swift | 112 + .../AgentsCore/PrivateMaterialization.swift | 445 + Sources/AgentsCore/PrivateNativeArrays.swift | 215 + .../AgentsCore/PrivateSourceRecovery.swift | 245 + Sources/AgentsCore/PrivateTree.swift | 220 + Sources/AgentsCore/ProcessLimits.swift | 10 + Sources/AgentsCore/ProcessRunner.swift | 130 +- Sources/AgentsCore/ReadDependency.swift | 15 + Sources/AgentsCore/ResolvedLedger.swift | 647 + Sources/AgentsCore/ResolvedLedgerCodec.swift | 245 + Sources/AgentsCore/ResolvedState.swift | 29 +- Sources/AgentsCore/RetentionReferences.swift | 71 + Sources/AgentsCore/SourceAccessAddress.swift | 168 + .../SourceAccessConfiguration.swift | 147 + Sources/AgentsCore/SourceAccessProfile.swift | 278 + .../SourceAccessSettingsEditor.swift | 72 + .../AgentsCore/SourceAccessSettingsFile.swift | 172 + .../AgentsCore/SourceArchiveEvidence.swift | 99 + Sources/AgentsCore/SourceArgument.swift | 34 +- Sources/AgentsCore/SourceCache.swift | 784 +- Sources/AgentsCore/SourceCatalog.swift | 66 + .../SourceCredentialOperations.swift | 208 + Sources/AgentsCore/SourceParser.swift | 37 +- Sources/AgentsCore/SourcePolicy.swift | 277 + Sources/AgentsCore/SourceProvenance.swift | 74 + Sources/AgentsCore/SourceReference.swift | 21 +- Sources/AgentsCore/SourceRequirement.swift | 81 +- .../AgentsCore/SourceResolutionSession.swift | 621 +- .../AgentsCore/SourceRevisionInspection.swift | 16 +- Sources/AgentsCore/SourceSnapshot.swift | 85 + Sources/AgentsCore/StateInspection.swift | 98 +- Sources/AgentsCore/StateJSON.swift | 10 +- Sources/AgentsCore/StateStore.swift | 220 +- .../AgentsCore/TransactionCheckpoint.swift | 92 + Sources/AgentsCore/TransactionDisposal.swift | 188 + Sources/AgentsCore/TransactionEvidence.swift | 499 + Sources/AgentsCore/TransactionJournal.swift | 281 + Sources/AgentsCore/TransactionOutcome.swift | 24 +- Sources/AgentsCore/TransactionPaths.swift | 353 +- .../AgentsCore/TransactionPermissions.swift | 92 + .../AgentsCore/TransactionPublication.swift | 344 + Sources/AgentsCore/TransactionRecovery.swift | 381 + Sources/AgentsCore/TransactionSession.swift | 354 + Sources/AgentsCore/UpdatePreconditions.swift | 283 +- Sources/AgentsCore/VCSArchiveRequest.swift | 208 + Sources/AgentsCore/VerifiedVCSArchive.swift | 248 + Sources/AgentsCore/WatchModels.swift | 16 + Sources/AgentsCore/WatchOperations.swift | 532 +- .../InstructionCompatibility.swift | 84 + .../InstructionDoctor.swift | 125 +- .../InstructionExport.swift | 74 +- .../InstructionFrontMatter.swift | 41 +- .../InstructionInitialization.swift | 50 + .../InstructionLifecycleModels.swift | 84 +- .../InstructionModels.swift | 9 +- .../InstructionOperations.swift | 474 +- .../InstructionPromptReadback.swift | 18 + .../InstructionSnapshotReader.swift | 74 + .../InstructionSourceDiagnostics.swift | 9 +- .../InstructionSources.swift | 128 +- .../InstructionTargets.swift | 73 +- .../InstructionUpdatePlan.swift | 72 - Sources/AgentsInstructions/Instructions.swift | 14 +- .../AgentsManifest/DeclarationDocument.swift | 85 + .../AgentsManifest/DeclarationEditPlan.swift | 88 + Sources/AgentsManifest/DocumentEditor.swift | 346 + Sources/AgentsManifest/DocumentModels.swift | 63 + Sources/AgentsManifest/IRTree.swift | 269 + Sources/AgentsManifest/JSONPointer.swift | 17 + .../AgentsManifest/ManifestDiagnostic.swift | 74 + Sources/AgentsManifest/ManifestDump.swift | 120 + .../ManifestExpansionBudget.swift | 78 + Sources/AgentsManifest/ManifestFrontEnd.swift | 18 + .../AgentsManifest/ManifestJSONValue.swift | 90 + Sources/AgentsManifest/ManifestLimits.swift | 43 + .../AgentsManifest/ManifestProjection.swift | 411 + Sources/AgentsManifest/ManifestSchema.swift | 278 + Sources/AgentsManifest/ManifestState.swift | 74 + .../OrganizationPolicyDocument.swift | 260 + .../Resources/agents.schema.json | 1848 + .../AgentsManifest/SourcePolicyDocument.swift | 167 + .../AgentsManifest/SourceReferenceEdits.swift | 53 + Sources/AgentsManifest/SourceText.swift | 68 + Sources/AgentsManifest/ValueBudget.swift | 108 + Sources/AgentsManifest/YAMLConstruction.swift | 408 + .../AgentsManifest/YAMLDomainValidation.swift | 334 + Sources/AgentsManifest/YAMLParser.swift | 388 + Sources/AgentsManifest/YAMLPatches.swift | 540 + Sources/AgentsManifest/YAMLProjection.swift | 371 + Sources/AgentsManifest/YAMLReader.swift | 30 + Sources/AgentsManifest/YAMLScalar.swift | 67 + Sources/AgentsManifest/YAMLValidation.swift | 219 + Sources/AgentsManifest/YAMLWriter.swift | 147 + Sources/AgentsSkills/Discovery.swift | 94 +- Sources/AgentsSkills/PolicyHTTPRead.swift | 87 + .../AgentsSkills/SkillInitialization.swift | 76 + Sources/AgentsSkills/SkillLifecycle.swift | 368 +- Sources/AgentsSkills/SkillModels.swift | 57 + Sources/AgentsSkills/SkillOperations.swift | 571 +- .../AgentsSkills/SkillSnapshotReader.swift | 103 + Sources/AgentsSkills/SkillUpdatePlan.swift | 78 - Sources/AgentsSkills/WatchSupport.swift | 9 + Sources/AgentsSkills/WellKnownProvider.swift | 102 +- .../AgentsUpdates/AgentClientInspection.swift | 208 + .../Bundles/AuthorLockedMembers.swift | 93 + Sources/AgentsUpdates/Bundles/AuthorMCP.swift | 215 + .../Bundles/AuthorPackageAdmission.swift | 264 + .../Bundles/AuthorPackageCapture.swift | 204 + .../Bundles/AuthorPackageOperations.swift | 285 + .../AgentsUpdates/Bundles/BundleArchive.swift | 339 + .../AgentsUpdates/Bundles/BundleExport.swift | 347 + .../AgentsUpdates/Bundles/BundleImport.swift | 190 + .../Bundles/BundleInstallation.swift | 400 + .../Bundles/BundlePackageProvenance.swift | 97 + .../Bundles/NativePluginOperations.swift | 328 + .../AgentsUpdates/ComponentDiscovery.swift | 261 + .../AgentsUpdates/ComponentInventory.swift | 267 + .../ComponentInventoryEncoding.swift | 173 + .../AgentsUpdates/ContentAuditDiscovery.swift | 304 + .../ContentAuditOperations.swift | 546 + .../AgentsUpdates/ContentAuditReport.swift | 190 + .../AgentsUpdates/ContentAuditSourceMap.swift | 101 + Sources/AgentsUpdates/ContentAuditStrip.swift | 88 + .../AgentsUpdates/ContentAuditUnicode.swift | 163 + .../ExistingGlobalConfiguration.swift | 336 + .../ExistingGlobalConfigurationJSON.swift | 159 + .../ImportedConfigurationLedger.swift | 460 + .../InitializationOperations.swift | 96 + .../AgentsUpdates/InstructionOperations.swift | 336 + .../InstructionOutputPreview.swift | 69 + .../Lifecycle/LifecycleDiscovery.swift | 309 + .../Lifecycle/LifecycleExecution.swift | 341 + .../Lifecycle/LifecycleInvocation.swift | 455 + .../Lifecycle/LifecycleModels.swift | 148 + .../Lifecycle/LifecycleTrust.swift | 331 + .../MCPConnectionOperations.swift | 444 + .../MCPConnectionRedaction.swift | 35 + .../MCPConnectionResources.swift | 204 + .../MCPConnectionSelection.swift | 118 + Sources/AgentsUpdates/MCPRegistry.swift | 351 + .../AgentsUpdates/MCPRegistrySelection.swift | 641 + .../Marketplace/HostedMarketplaceExport.swift | 111 + .../Marketplace/HostedMarketplaceHTTP.swift | 347 + .../Marketplace/HostedMarketplaceIndex.swift | 125 + .../Marketplace/MarketplaceCatalog.swift | 531 + .../Marketplace/MarketplaceDirectory.swift | 155 + .../Marketplace/MarketplaceGraphChange.swift | 405 + .../Marketplace/MarketplaceLegacyRoot.swift | 52 + .../MarketplaceLockOperations.swift | 171 + .../Marketplace/MarketplaceLockPlan.swift | 143 + .../Marketplace/MarketplaceResolution.swift | 485 + .../Marketplace/MarketplaceSolver.swift | 517 + .../Marketplace/MarketplaceUpdate.swift | 392 + .../AgentsUpdates/MarketplaceBundles.swift | 146 + .../OrganizationInstallEvaluation.swift | 510 + .../OrganizationPolicyLoader.swift | 645 + .../OrganizationPolicyOperations.swift | 162 + .../OrganizationWorkspaceInspection.swift | 215 + Sources/AgentsUpdates/PreparedUpdate.swift | 12 +- .../ProducerPatchDestination.swift | 220 + Sources/AgentsUpdates/ProducerPatchDiff.swift | 99 + .../AgentsUpdates/ProducerPatchLineage.swift | 234 + .../ProducerPatchOperations.swift | 276 + Sources/AgentsUpdates/ProducerPatchPlan.swift | 254 + .../AgentsUpdates/ProducerPatchRoutes.swift | 224 + .../AgentsUpdates/RegistryAcquisition.swift | 250 + Sources/AgentsUpdates/ScopeInspection.swift | 367 + Sources/AgentsUpdates/SkillOperations.swift | 187 + .../SourceCatalogInspection.swift | 568 + .../SourceImportOperations.swift | 509 + .../AgentsUpdates/SourcePolicyEditing.swift | 44 + .../SourcePolicyOperations.swift | 61 + Sources/AgentsUpdates/UpdateCompletion.swift | 98 + Sources/AgentsUpdates/UpdateInputs.swift | 51 + Sources/AgentsUpdates/UpdateModels.swift | 144 +- Sources/AgentsUpdates/UpdateOperations.swift | 248 +- Sources/AgentsUpdates/UpdatePlan.swift | 1299 +- .../AgentsUpdates/UpdateReadLocations.swift | 136 + Sources/AgentsUpdates/UpdateReporting.swift | 226 + Sources/AgentsUpdates/UpdateRequest.swift | 71 + Sources/AgentsUpdates/WatchCompletion.swift | 28 + Sources/CPlatform/CPlatform.c | 513 + Sources/CPlatform/DuplexProcess.c | 339 + Sources/CPlatform/include/CPlatform.h | 73 + Sources/CPlatform/include/DuplexProcess.h | 18 + Sources/CSQLite/CSQLite.c | 5 + Sources/CSQLite/include/CSQLite.h | 5 + .../Adapters/AntigravityAdapter.swift | 78 + .../Components/Adapters/ClaudeAdapter.swift | 25 + .../Adapters/ClaudeComponents.swift | 76 + .../Components/Adapters/CodexAdapter.swift | 67 + .../Components/Adapters/CodexComponents.swift | 45 + .../Components/Adapters/CursorAdapter.swift | 22 + .../Adapters/CursorComponents.swift | 54 + .../Components/Adapters/GeminiAdapter.swift | 27 + .../Adapters/GeminiComponents.swift | 116 + .../Components/Adapters/OpenCodeAdapter.swift | 36 + .../Adapters/OpenCodeComponents.swift | 86 + Sources/Components/AntigravityRuleV1.swift | 172 + Sources/Components/ArtifactAggregation.swift | 2539 + Sources/Components/CapabilityRegistry.swift | 290 + .../ClientCapabilityInspection.swift | 77 + Sources/Components/ComponentFields.swift | 114 + Sources/Components/ComponentLinker.swift | 468 + .../Components/DeploymentConstruction.swift | 477 + Sources/Components/Expansion.swift | 890 + Sources/Components/FrozenNativeIdentity.swift | 177 + .../Components/Import/APMInputImport.swift | 73 + .../Import/APMPackageContentImport.swift | 90 + .../Components/Import/ImportFrontmatter.swift | 59 + Sources/Components/Import/ImportInput.swift | 285 + .../Import/ImportSkillContent.swift | 141 + .../Import/NativeCatalogImport.swift | 167 + .../Import/NativeContainerImport.swift | 505 + .../Import/NativeExecutableMembers.swift | 266 + .../Components/Import/NativeImportInput.swift | 454 + .../Import/NativeImportSemantics.swift | 29 + .../Import/NativeMemberImport.swift | 194 + .../Import/NativeSourceImport.swift | 527 + .../Import/RulesyncConfigImport.swift | 731 + .../Import/RulesyncSourceImport.swift | 260 + Sources/Components/Import/SourceImport.swift | 85 + .../Import/SourceImportProposal.swift | 319 + .../Import/VercelSourceImport.swift | 243 + .../Components/Import/YAMLSourceImport.swift | 740 + Sources/Components/LedgerFreeze.swift | 235 + Sources/Components/LedgerImpact.swift | 314 + Sources/Components/LedgerPayload.swift | 187 + Sources/Components/LedgerReplay.swift | 615 + Sources/Components/LinkBudget.swift | 39 + Sources/Components/LinkedComponents.swift | 401 + Sources/Components/MCPBoundedTransport.swift | 193 + Sources/Components/MCPConnectionRunner.swift | 196 + Sources/Components/MCPConnectionTypes.swift | 99 + Sources/Components/MCPHTTPConnection.swift | 406 + Sources/Components/MCPLayoutV1.swift | 186 + Sources/Components/MCPLowering.swift | 419 + Sources/Components/MCPMessageSink.swift | 235 + Sources/Components/MCPStagedValues.swift | 89 + .../NativeAuthorityComposition.swift | 160 + .../NativeComponentContribution.swift | 203 + .../NativeComponentDecodingV1.swift | 455 + .../Components/NativeComponentFieldsV1.swift | 318 + .../Components/NativeComponentLayoutsV1.swift | 107 + .../Components/NativeComponentLowering.swift | 451 + .../Components/NativeDocumentedHooksV1.swift | 208 + .../NativeGeneratedPluginContribution.swift | 282 + .../NativeGeneratedPluginLayoutV1.swift | 320 + Sources/Components/NativeHookLayoutV1.swift | 103 + Sources/Components/NativeIgnoreLayoutV1.swift | 17 + Sources/Components/NativeLSPLayoutV1.swift | 108 + Sources/Components/NativePluginFieldsV1.swift | 756 + Sources/Components/NativePluginLayoutV1.swift | 106 + Sources/Components/NativeProgramV1.swift | 281 + Sources/Components/NativePromptAudit.swift | 163 + Sources/Components/PluginExpansion.swift | 262 + Sources/Components/SourceCatalog.swift | 443 + .../Components/SourceCatalogSelection.swift | 199 + Sources/NativeDocuments/JSONParser.swift | 190 + Sources/NativeDocuments/Model.swift | 298 + Sources/NativeDocuments/NativeDocument.swift | 870 + .../NativePromptReadback.swift | 25 + Sources/NativeDocuments/PatchBuilder.swift | 612 + Sources/NativeDocuments/Semantics.swift | 221 + Sources/NativeDocuments/TOMLIndex.swift | 287 + Sources/TOMLSemantics/DateTime.swift | 424 + Sources/TOMLSemantics/LICENSE | 9 + Sources/TOMLSemantics/PATCHES.md | 47 + Sources/TOMLSemantics/Parsing/Constants.swift | 109 + .../TOMLSemantics/Parsing/Parser+Finish.swift | 24 + Sources/TOMLSemantics/Parsing/Parser.swift | 2696 + .../TOMLSemantics/Parsing/TOMLDocument.swift | 187 + Sources/TOMLSemantics/Parsing/Token.swift | 27 + Sources/TOMLSemantics/SemanticBudget.swift | 93 + Sources/TOMLSemantics/SemanticDocument.swift | 181 + Sources/TOMLSemantics/TOMLError.swift | 147 + Sources/TOMLSemantics/TOMLKey.swift | 33 + Sources/TOMLSemantics/provenance.json | 48 + Sources/TOMLSemantics/upstream.patch | 6993 +++ Sources/TreeSitterTOML/LICENSE | 21 + Sources/TreeSitterTOML/include/toml.h | 16 + Sources/TreeSitterTOML/parser.c | 4739 ++ Sources/TreeSitterTOML/provenance.json | 26 + Sources/TreeSitterTOML/scanner.c | 82 + Sources/TreeSitterTOML/tree_sitter/parser.h | 266 + Sources/TreeSitterYAML/LICENSE | 20 + Sources/TreeSitterYAML/include/yaml.h | 16 + Sources/TreeSitterYAML/parser.c | 41384 ++++++++++++++++ Sources/TreeSitterYAML/provenance.json | 38 + Sources/TreeSitterYAML/scanner.c | 1415 + Sources/TreeSitterYAML/schema.core.c | 204 + Sources/TreeSitterYAML/tree_sitter/alloc.h | 54 + Sources/TreeSitterYAML/tree_sitter/array.h | 291 + Sources/TreeSitterYAML/tree_sitter/parser.h | 286 + .../AcquisitionCacheTests.swift | 218 + .../AgentClientObservationTests.swift | 72 + .../CachePublicationTests.swift | 134 +- .../CheckpointUniquenessTests.swift | 133 + Tests/AgentsCoreTests/ClientBackupTests.swift | 847 + .../CoordinationAdmissionTests.swift | 444 + Tests/AgentsCoreTests/CoreTestSupport.swift | 18 +- .../DeclarationStateTests.swift | 241 + .../DirectoryHandleTests.swift | 122 + Tests/AgentsCoreTests/FileAccessTests.swift | 246 + Tests/AgentsCoreTests/FileHashTests.swift | 28 + .../FileLockProcessTests.swift | 69 +- .../FileSystemAccessTests.swift | 328 + Tests/AgentsCoreTests/GitErrorTests.swift | 39 +- .../IndependentLedgerAdmissionTests.swift | 217 + .../InstructionTransactionTests.swift | 40 +- .../LedgerAuthorityTests.swift | 301 + Tests/AgentsCoreTests/LedgerCodecTests.swift | 130 + .../LedgerGraphReviewTests.swift | 115 + .../LedgerProjectionTests.swift | 42 + .../LedgerRetentionTests.swift | 60 + .../LedgerWireSpellingTests.swift | 169 + .../AgentsCoreTests/MetadataTestSupport.swift | 139 + .../NativeArrayReceiptTests.swift | 437 + .../PreparationEvidenceTests.swift | 186 + .../PrivateMaterializationTests.swift | 525 + Tests/AgentsCoreTests/PrivateTreeTests.swift | 562 + .../AgentsCoreTests/ProcessLimitsTests.swift | 84 + .../ProcessTerminationTests.swift | 67 + .../AgentsCoreTests/ProcessTestSupport.swift | 26 +- Tests/AgentsCoreTests/PublicationTests.swift | 882 + .../AgentsCoreTests/ReadDependencyTests.swift | 21 + .../RegisteredNativeTargetTests.swift | 1055 + .../RequirementSemanticsTests.swift | 259 + Tests/AgentsCoreTests/SharedTargetTests.swift | 1079 + .../SourceAccessSettingsEditorTests.swift | 195 + .../AgentsCoreTests/SourceArgumentTests.swift | 2 +- Tests/AgentsCoreTests/SourceCacheTests.swift | 41 +- .../SourceRegressionTests.swift | 98 +- .../AgentsCoreTests/StateEncodingTests.swift | 18 +- .../StateInspectionTests.swift | 32 +- Tests/AgentsCoreTests/StateModelTests.swift | 136 +- .../StatePublicationTests.swift | 322 + .../StateTransactionTests.swift | 696 +- .../TransactionCostTests.swift | 181 + .../TransactionMetadataTests.swift | 135 +- .../WatchDurabilityTests.swift | 48 +- Tests/AgentsCoreTests/WatchGitLockTests.swift | 46 +- .../WatchInspectionTests.swift | 33 +- .../WatchMirrorConcurrencyTests.swift | 65 +- .../WatchPreparationTests.swift | 109 + .../AgentsCoreTests/WatchReferenceTests.swift | 16 +- Tests/AgentsCoreTests/WatchSourceTests.swift | 139 + Tests/AgentsCoreTests/WatchStateTests.swift | 78 +- .../DeclarationDocumentTests.swift | 113 + .../DoctorLifecycleTests.swift | 7 +- .../FileReadAccessTests.swift | 96 + .../LedgerCompatibilityTests.swift | 49 + .../LifecycleFixture.swift | 1 + .../LifecycleSafetyTests.swift | 93 +- .../LifecycleTests.swift | 35 +- .../MappingReadLocationsTests.swift | 288 + .../OwnershipAndPlacementTests.swift | 50 +- .../SourceDiagnosticTests.swift | 11 +- .../SourceShorthandTests.swift | 4 +- .../TargetLifecycleTests.swift | 53 +- .../DeclarationProgressTests.swift | 72 + Tests/AgentsManifestTests/EditPlanTests.swift | 404 + .../ExpansionBudgetTests.swift | 111 + Tests/AgentsManifestTests/FrontEndTests.swift | 138 + .../FullDeclarationDependencyTests.swift | 54 + .../FullDeclarationDraftTests.swift | 123 + .../FullDeclarationTests.swift | 554 + .../IndependentYAMLAcceptanceTests.swift | 425 + .../ManifestExpectations.swift | 17 + .../MappingFieldInsertionTests.swift | 98 + .../NativeCoordinateTests.swift | 71 + .../AgentsManifestTests/ProjectionTests.swift | 63 + Tests/AgentsManifestTests/ResourceTests.swift | 52 + .../SourceReplacementTests.swift | 143 + Tests/AgentsManifestTests/Watchdog.swift | 142 + .../AgentsManifestTests/YAMLReaderTests.swift | 49 + .../ArchiveSafetyTests.swift | 55 +- .../ArchiveTestSupport.swift | 46 + .../AutomaticSelectionTests.swift | 27 +- Tests/AgentsSkillsTests/CoreTestSupport.swift | 18 + .../DefaultResolutionTests.swift | 9 +- .../DiscoveryBehaviorTests.swift | 33 +- .../FileReadAccessTests.swift | 76 + .../IndexedArtifactLifecycleTests.swift | 303 + .../InstallationSafetyTests.swift | 1 + .../InstalledInventoryTests.swift | 40 +- .../LifecycleRegressionTests.swift | 42 +- .../LockedArtifactLifecycleTests.swift | 229 - .../ManifestLifecycleTests.swift | 278 + Tests/AgentsSkillsTests/NetworkingTests.swift | 47 + .../PublicLifecycleTests.swift | 79 +- .../ReadOnlyInspectionTests.swift | 101 +- .../RetainedLifecycleTests.swift | 18 +- .../SkillLifecycleTests.swift | 72 +- .../AgentsSkillsTests/SourceAliasTests.swift | 38 +- .../SourceShorthandTests.swift | 12 +- .../TransactionDoctorTests.swift | 104 + .../UnmanagedTargetTests.swift | 1 + .../UpdateReportingTests.swift | 83 +- .../WatchSubscriptionTests.swift | 59 +- .../WellKnownArtifactTests.swift | 38 +- .../AgentClientInspectionTests.swift | 243 + .../AntigravityAdapterTests.swift | 178 + .../AntigravityInstructionTests.swift | 380 + .../AuthorLockedPackageTests.swift | 153 + .../AuthorPackageTests.swift | 403 + .../CombinedUpdateTests.swift | 114 +- .../ComponentInventoryTests.swift | 270 + .../ConsumerLifecycleRegressionTests.swift | 595 + .../ConsumerSourceRegressionTests.swift | 140 + .../ContentAuditTests.swift | 442 + .../DeclarationYAMLUpdateTests.swift | 171 + .../ExistingGlobalConfigurationTests.swift | 688 + .../FiniteSkillInstallationTests.swift | 93 + .../FirstUserDeclarationTests.swift | 114 + .../GitAcquisitionTests.swift | 556 + .../HostedMarketplaceTLSTests.swift | 126 + .../HostedMarketplaceTests.swift | 679 + .../ImplicitReadFootprintTests.swift | 159 + ...ImportNativeExecutableLifecycleTests.swift | 116 + .../ImportNativeLifecycleTests.swift | 125 + .../InitializationIntegrationTests.swift | 158 + .../InstructionBuildTests.swift | 534 + .../IntegratedConsumerRegressionTests.swift | 114 + .../LifecycleCompositionTests.swift | 448 + .../MCPConnectionOperationsTests.swift | 448 + .../MCPManagedSelectionTests.swift | 298 + .../AgentsUpdatesTests/MCPRegistryTests.swift | 903 + .../MarketplaceDirectoryTests.swift | 39 + .../MarketplaceResolutionTests.swift | 939 + .../AgentsUpdatesTests/MarketplaceTests.swift | 483 + .../NativeAuthorityIntegrationTests.swift | 512 + .../NativeCompositionIntegrationTests.swift | 336 + .../NativePluginExportTests.swift | 154 + .../OrganizationPolicyTests.swift | 434 + .../PackageLifecycleTLSTests.swift | 242 + .../PackageLifecycleTests.swift | 740 + .../PortableBundleTests.swift | 487 + .../PrivateNativeCompositionTests.swift | 375 + .../ProducerPatchTests.swift | 503 + .../PublicInspectionTests.swift | 415 + .../ReadFootprintIntegrationTests.swift | 62 + .../RegistryAcquisitionTests.swift | 553 + .../RequirementUpdateTests.swift | 70 + .../SkillPathReadLocationsTests.swift | 25 + .../SourceAccessTests.swift | 852 + .../SourceCatalogInspectionTests.swift | 588 + .../SourceImportSelectionTests.swift | 346 + .../SourcePolicyTests.swift | 313 + .../SourceReplacementUpdateTests.swift | 64 + Tests/AgentsUpdatesTests/UpdateFixture.swift | 6 +- .../UpdateTransactionTests.swift | 163 +- .../WatchConfirmationTests.swift | 300 + .../ArtifactLinkingTests.swift | 365 + .../ComponentsTests/Fixtures/MCPHTTPServer.py | 93 + .../GeneratedPluginTests.swift | 429 + Tests/ComponentsTests/ImpactTests.swift | 240 + Tests/ComponentsTests/ImportNativeTests.swift | 920 + .../ImportPinnedFixtures.swift | 114 + .../ComponentsTests/ImportProfileTests.swift | 725 + Tests/ComponentsTests/ImportSourceTests.swift | 372 + .../ImportSupportingLinksTests.swift | 257 + .../LedgerReplayBudgetTests.swift | 102 + Tests/ComponentsTests/LedgerReplayTests.swift | 337 + Tests/ComponentsTests/LinkBudgetTests.swift | 207 + Tests/ComponentsTests/LinkFixture.swift | 97 + .../LinkingAcceptanceTests.swift | 310 + .../LinkingIntegrationTests.swift | 320 + .../LinkingReviewRegressionTests.swift | 147 + Tests/ComponentsTests/LinkingTests.swift | 227 + .../MCPConnectionAcceptanceTests.swift | 53 + .../ComponentsTests/MCPConnectionTests.swift | 394 + .../NativeComponentFieldsTests.swift | 319 + .../NativeComponentTests.swift | 1508 + .../NativeCoordinateLinkingTests.swift | 71 + Tests/ComponentsTests/NativeMCPTests.swift | 862 + .../OpaquePluginIdentityTests.swift | 111 + .../ComponentsTests/PluginLinkingTests.swift | 401 + .../PromptReferenceTests.swift | 137 + Tests/ComponentsTests/SnapshotTests.swift | 427 + .../ComponentsTests/SourceCatalogTests.swift | 253 + Tests/ComponentsTests/UserScopeTests.swift | 153 + Tests/Documentation/PortableBundles.md | 114 + Tests/MCPTestProcess/main.swift | 227 + Tests/ManifestTestProcess/main.swift | 96 + Tests/ManifestTestSupport/ProbeReport.swift | 54 + .../ArrayAuthorityTests.swift | 267 + .../ConditionalPruningTests.swift | 258 + .../NativeDocumentTests.swift | 801 + .../OccurrenceInsertionTests.swift | 286 + .../NativeDocumentsTests/SemanticTests.swift | 144 + Tests/SourcePolicyFixtures.md | 69 + Tests/StateTestProcess/LedgerProbe.swift | 106 + .../StateTestProcess/OpenFileLimitProbe.swift | 120 + .../PrivateMaterializationProbe.swift | 184 + .../StateTestProcess/SourceArchiveProbe.swift | 33 + Tests/StateTestProcess/main.swift | 325 +- .../DeclarationStateFixture.swift | 67 + Tests/StateTestSupport/ManifestText.swift | 6 + Tests/StateTestSupport/ProcessWait.swift | 105 + 602 files changed, 187824 insertions(+), 4500 deletions(-) delete mode 100644 .agent/agents.json create mode 100644 .agent/agents.yaml create mode 100644 .github/ci/linux-tests.Dockerfile create mode 100644 Documentation/Architecture/NativeDocuments.md create mode 100644 Documentation/Archive/AgentsManifest.md create mode 100644 Documentation/Decisions/AgentComponents.md create mode 100644 Documentation/Decisions/ConfigurationApplication.md create mode 100644 Documentation/Decisions/ExecutableApproval.md create mode 100644 Documentation/Decisions/SwiftManifest.md create mode 100644 Documentation/Decisions/YAMLManifest.md create mode 100644 Documentation/Reference/APMImport.md create mode 100644 Documentation/Reference/AgentClients.md create mode 100644 Documentation/Reference/AuthorPackaging.md create mode 100644 Documentation/Reference/ContentAudit.md create mode 100644 Documentation/Reference/MCPRegistry.md create mode 100644 Documentation/Reference/Manifest.md create mode 100644 Documentation/Reference/ManifestSchema.md create mode 100644 Documentation/Reference/Marketplace.md create mode 100644 Documentation/Reference/OrganizationPolicy.md create mode 100644 Documentation/Reference/SourceAccess.md create mode 100644 Documentation/Reference/UserSourceAccess.md create mode 100644 Scripts/generate-manifest-schema.py create mode 100644 Scripts/test-linux.py create mode 100644 Scripts/test_manifest_schema.py create mode 100644 Sources/AgentsCore/AcquisitionCache/AcquisitionCache.swift create mode 100644 Sources/AgentsCore/AcquisitionCache/AcquisitionStorage.swift create mode 100644 Sources/AgentsCore/AcquisitionCache/DeployedAcquisition.swift create mode 100644 Sources/AgentsCore/AcquisitionCache/GitAcquisition.swift create mode 100644 Sources/AgentsCore/AgentClientApplications.swift create mode 100644 Sources/AgentsCore/AgentClientObservation.swift create mode 100644 Sources/AgentsCore/ArchiveDeploymentAccess.swift create mode 100644 Sources/AgentsCore/BundleSourceLocation.swift create mode 100644 Sources/AgentsCore/BundleStoredSource.swift create mode 100644 Sources/AgentsCore/ClientBackups/BackupArchive.swift create mode 100644 Sources/AgentsCore/ClientBackups/BackupClaudeImports.swift create mode 100644 Sources/AgentsCore/ClientBackups/BackupGeminiCheckpoints.swift create mode 100644 Sources/AgentsCore/ClientBackups/BackupJSONStream.swift create mode 100644 Sources/AgentsCore/ClientBackups/BackupNativeData.swift create mode 100644 Sources/AgentsCore/ClientBackups/BackupRestoreTransaction.swift create mode 100644 Sources/AgentsCore/ClientBackups/BackupScope.swift create mode 100644 Sources/AgentsCore/ClientBackups/BackupStorage.swift create mode 100644 Sources/AgentsCore/ClientBackups/BackupZstd.swift create mode 100644 Sources/AgentsCore/ClientBackups/ClientBackups.swift create mode 100644 Sources/AgentsCore/ComponentConditions.swift create mode 100644 Sources/AgentsCore/ComponentDeclaration.swift create mode 100644 Sources/AgentsCore/ContentAuditFiles.swift create mode 100644 Sources/AgentsCore/DeclarationAccess.swift create mode 100644 Sources/AgentsCore/DeclarationIR.swift create mode 100644 Sources/AgentsCore/FileAccess.swift create mode 100644 Sources/AgentsCore/FileSystem.swift create mode 100644 Sources/AgentsCore/HostedMarketplace.swift create mode 100644 Sources/AgentsCore/LedgerAdmission.swift create mode 100644 Sources/AgentsCore/LedgerDisplayEvidence.swift create mode 100644 Sources/AgentsCore/LedgerNativeAuthority.swift create mode 100644 Sources/AgentsCore/LedgerProjection.swift create mode 100644 Sources/AgentsCore/LedgerResourceLinks.swift create mode 100644 Sources/AgentsCore/LedgerResources.swift create mode 100644 Sources/AgentsCore/LedgerSourcePolicy.swift create mode 100644 Sources/AgentsCore/LedgerStateStore.swift create mode 100644 Sources/AgentsCore/LedgerValidation.swift create mode 100644 Sources/AgentsCore/LifecycleDeclaration.swift create mode 100644 Sources/AgentsCore/LifecycleFileAccess.swift create mode 100644 Sources/AgentsCore/MCPRegistryEvidence.swift create mode 100644 Sources/AgentsCore/MCPTransportPayload.swift create mode 100644 Sources/AgentsCore/ManagedSourceGit.swift create mode 100644 Sources/AgentsCore/MarketplaceGraph.swift create mode 100644 Sources/AgentsCore/MarketplacePackage.swift create mode 100644 Sources/AgentsCore/NativeTargetCoordination.swift create mode 100644 Sources/AgentsCore/OrganizationPolicy.swift create mode 100644 Sources/AgentsCore/OrganizationPolicyEvaluation.swift create mode 100644 Sources/AgentsCore/OwnedDuplexProcess.swift create mode 100644 Sources/AgentsCore/PackageSourceHTTP.swift create mode 100644 Sources/AgentsCore/PortableSourceEvidence.swift create mode 100644 Sources/AgentsCore/PrivateMaterialization.swift create mode 100644 Sources/AgentsCore/PrivateNativeArrays.swift create mode 100644 Sources/AgentsCore/PrivateSourceRecovery.swift create mode 100644 Sources/AgentsCore/PrivateTree.swift create mode 100644 Sources/AgentsCore/ProcessLimits.swift create mode 100644 Sources/AgentsCore/ReadDependency.swift create mode 100644 Sources/AgentsCore/ResolvedLedger.swift create mode 100644 Sources/AgentsCore/ResolvedLedgerCodec.swift create mode 100644 Sources/AgentsCore/RetentionReferences.swift create mode 100644 Sources/AgentsCore/SourceAccessAddress.swift create mode 100644 Sources/AgentsCore/SourceAccessConfiguration.swift create mode 100644 Sources/AgentsCore/SourceAccessProfile.swift create mode 100644 Sources/AgentsCore/SourceAccessSettingsEditor.swift create mode 100644 Sources/AgentsCore/SourceAccessSettingsFile.swift create mode 100644 Sources/AgentsCore/SourceArchiveEvidence.swift create mode 100644 Sources/AgentsCore/SourceCatalog.swift create mode 100644 Sources/AgentsCore/SourceCredentialOperations.swift create mode 100644 Sources/AgentsCore/SourcePolicy.swift create mode 100644 Sources/AgentsCore/SourceProvenance.swift create mode 100644 Sources/AgentsCore/SourceSnapshot.swift create mode 100644 Sources/AgentsCore/TransactionCheckpoint.swift create mode 100644 Sources/AgentsCore/TransactionDisposal.swift create mode 100644 Sources/AgentsCore/TransactionEvidence.swift create mode 100644 Sources/AgentsCore/TransactionJournal.swift create mode 100644 Sources/AgentsCore/TransactionPermissions.swift create mode 100644 Sources/AgentsCore/TransactionPublication.swift create mode 100644 Sources/AgentsCore/TransactionRecovery.swift create mode 100644 Sources/AgentsCore/TransactionSession.swift create mode 100644 Sources/AgentsCore/VCSArchiveRequest.swift create mode 100644 Sources/AgentsCore/VerifiedVCSArchive.swift create mode 100644 Sources/AgentsInstructions/InstructionCompatibility.swift create mode 100644 Sources/AgentsInstructions/InstructionInitialization.swift create mode 100644 Sources/AgentsInstructions/InstructionPromptReadback.swift create mode 100644 Sources/AgentsInstructions/InstructionSnapshotReader.swift delete mode 100644 Sources/AgentsInstructions/InstructionUpdatePlan.swift create mode 100644 Sources/AgentsManifest/DeclarationDocument.swift create mode 100644 Sources/AgentsManifest/DeclarationEditPlan.swift create mode 100644 Sources/AgentsManifest/DocumentEditor.swift create mode 100644 Sources/AgentsManifest/DocumentModels.swift create mode 100644 Sources/AgentsManifest/IRTree.swift create mode 100644 Sources/AgentsManifest/JSONPointer.swift create mode 100644 Sources/AgentsManifest/ManifestDiagnostic.swift create mode 100644 Sources/AgentsManifest/ManifestDump.swift create mode 100644 Sources/AgentsManifest/ManifestExpansionBudget.swift create mode 100644 Sources/AgentsManifest/ManifestFrontEnd.swift create mode 100644 Sources/AgentsManifest/ManifestJSONValue.swift create mode 100644 Sources/AgentsManifest/ManifestLimits.swift create mode 100644 Sources/AgentsManifest/ManifestProjection.swift create mode 100644 Sources/AgentsManifest/ManifestSchema.swift create mode 100644 Sources/AgentsManifest/ManifestState.swift create mode 100644 Sources/AgentsManifest/OrganizationPolicyDocument.swift create mode 100644 Sources/AgentsManifest/Resources/agents.schema.json create mode 100644 Sources/AgentsManifest/SourcePolicyDocument.swift create mode 100644 Sources/AgentsManifest/SourceReferenceEdits.swift create mode 100644 Sources/AgentsManifest/SourceText.swift create mode 100644 Sources/AgentsManifest/ValueBudget.swift create mode 100644 Sources/AgentsManifest/YAMLConstruction.swift create mode 100644 Sources/AgentsManifest/YAMLDomainValidation.swift create mode 100644 Sources/AgentsManifest/YAMLParser.swift create mode 100644 Sources/AgentsManifest/YAMLPatches.swift create mode 100644 Sources/AgentsManifest/YAMLProjection.swift create mode 100644 Sources/AgentsManifest/YAMLReader.swift create mode 100644 Sources/AgentsManifest/YAMLScalar.swift create mode 100644 Sources/AgentsManifest/YAMLValidation.swift create mode 100644 Sources/AgentsManifest/YAMLWriter.swift create mode 100644 Sources/AgentsSkills/PolicyHTTPRead.swift create mode 100644 Sources/AgentsSkills/SkillInitialization.swift create mode 100644 Sources/AgentsSkills/SkillSnapshotReader.swift delete mode 100644 Sources/AgentsSkills/SkillUpdatePlan.swift create mode 100644 Sources/AgentsUpdates/AgentClientInspection.swift create mode 100644 Sources/AgentsUpdates/Bundles/AuthorLockedMembers.swift create mode 100644 Sources/AgentsUpdates/Bundles/AuthorMCP.swift create mode 100644 Sources/AgentsUpdates/Bundles/AuthorPackageAdmission.swift create mode 100644 Sources/AgentsUpdates/Bundles/AuthorPackageCapture.swift create mode 100644 Sources/AgentsUpdates/Bundles/AuthorPackageOperations.swift create mode 100644 Sources/AgentsUpdates/Bundles/BundleArchive.swift create mode 100644 Sources/AgentsUpdates/Bundles/BundleExport.swift create mode 100644 Sources/AgentsUpdates/Bundles/BundleImport.swift create mode 100644 Sources/AgentsUpdates/Bundles/BundleInstallation.swift create mode 100644 Sources/AgentsUpdates/Bundles/BundlePackageProvenance.swift create mode 100644 Sources/AgentsUpdates/Bundles/NativePluginOperations.swift create mode 100644 Sources/AgentsUpdates/ComponentDiscovery.swift create mode 100644 Sources/AgentsUpdates/ComponentInventory.swift create mode 100644 Sources/AgentsUpdates/ComponentInventoryEncoding.swift create mode 100644 Sources/AgentsUpdates/ContentAuditDiscovery.swift create mode 100644 Sources/AgentsUpdates/ContentAuditOperations.swift create mode 100644 Sources/AgentsUpdates/ContentAuditReport.swift create mode 100644 Sources/AgentsUpdates/ContentAuditSourceMap.swift create mode 100644 Sources/AgentsUpdates/ContentAuditStrip.swift create mode 100644 Sources/AgentsUpdates/ContentAuditUnicode.swift create mode 100644 Sources/AgentsUpdates/ExistingGlobalConfiguration.swift create mode 100644 Sources/AgentsUpdates/ExistingGlobalConfigurationJSON.swift create mode 100644 Sources/AgentsUpdates/ImportedConfigurationLedger.swift create mode 100644 Sources/AgentsUpdates/InitializationOperations.swift create mode 100644 Sources/AgentsUpdates/InstructionOperations.swift create mode 100644 Sources/AgentsUpdates/InstructionOutputPreview.swift create mode 100644 Sources/AgentsUpdates/Lifecycle/LifecycleDiscovery.swift create mode 100644 Sources/AgentsUpdates/Lifecycle/LifecycleExecution.swift create mode 100644 Sources/AgentsUpdates/Lifecycle/LifecycleInvocation.swift create mode 100644 Sources/AgentsUpdates/Lifecycle/LifecycleModels.swift create mode 100644 Sources/AgentsUpdates/Lifecycle/LifecycleTrust.swift create mode 100644 Sources/AgentsUpdates/MCPConnectionOperations.swift create mode 100644 Sources/AgentsUpdates/MCPConnectionRedaction.swift create mode 100644 Sources/AgentsUpdates/MCPConnectionResources.swift create mode 100644 Sources/AgentsUpdates/MCPConnectionSelection.swift create mode 100644 Sources/AgentsUpdates/MCPRegistry.swift create mode 100644 Sources/AgentsUpdates/MCPRegistrySelection.swift create mode 100644 Sources/AgentsUpdates/Marketplace/HostedMarketplaceExport.swift create mode 100644 Sources/AgentsUpdates/Marketplace/HostedMarketplaceHTTP.swift create mode 100644 Sources/AgentsUpdates/Marketplace/HostedMarketplaceIndex.swift create mode 100644 Sources/AgentsUpdates/Marketplace/MarketplaceCatalog.swift create mode 100644 Sources/AgentsUpdates/Marketplace/MarketplaceDirectory.swift create mode 100644 Sources/AgentsUpdates/Marketplace/MarketplaceGraphChange.swift create mode 100644 Sources/AgentsUpdates/Marketplace/MarketplaceLegacyRoot.swift create mode 100644 Sources/AgentsUpdates/Marketplace/MarketplaceLockOperations.swift create mode 100644 Sources/AgentsUpdates/Marketplace/MarketplaceLockPlan.swift create mode 100644 Sources/AgentsUpdates/Marketplace/MarketplaceResolution.swift create mode 100644 Sources/AgentsUpdates/Marketplace/MarketplaceSolver.swift create mode 100644 Sources/AgentsUpdates/Marketplace/MarketplaceUpdate.swift create mode 100644 Sources/AgentsUpdates/MarketplaceBundles.swift create mode 100644 Sources/AgentsUpdates/OrganizationInstallEvaluation.swift create mode 100644 Sources/AgentsUpdates/OrganizationPolicyLoader.swift create mode 100644 Sources/AgentsUpdates/OrganizationPolicyOperations.swift create mode 100644 Sources/AgentsUpdates/OrganizationWorkspaceInspection.swift create mode 100644 Sources/AgentsUpdates/ProducerPatchDestination.swift create mode 100644 Sources/AgentsUpdates/ProducerPatchDiff.swift create mode 100644 Sources/AgentsUpdates/ProducerPatchLineage.swift create mode 100644 Sources/AgentsUpdates/ProducerPatchOperations.swift create mode 100644 Sources/AgentsUpdates/ProducerPatchPlan.swift create mode 100644 Sources/AgentsUpdates/ProducerPatchRoutes.swift create mode 100644 Sources/AgentsUpdates/RegistryAcquisition.swift create mode 100644 Sources/AgentsUpdates/ScopeInspection.swift create mode 100644 Sources/AgentsUpdates/SkillOperations.swift create mode 100644 Sources/AgentsUpdates/SourceCatalogInspection.swift create mode 100644 Sources/AgentsUpdates/SourceImportOperations.swift create mode 100644 Sources/AgentsUpdates/SourcePolicyEditing.swift create mode 100644 Sources/AgentsUpdates/SourcePolicyOperations.swift create mode 100644 Sources/AgentsUpdates/UpdateCompletion.swift create mode 100644 Sources/AgentsUpdates/UpdateInputs.swift create mode 100644 Sources/AgentsUpdates/UpdateReadLocations.swift create mode 100644 Sources/AgentsUpdates/UpdateReporting.swift create mode 100644 Sources/AgentsUpdates/UpdateRequest.swift create mode 100644 Sources/AgentsUpdates/WatchCompletion.swift create mode 100644 Sources/CPlatform/CPlatform.c create mode 100644 Sources/CPlatform/DuplexProcess.c create mode 100644 Sources/CPlatform/include/CPlatform.h create mode 100644 Sources/CPlatform/include/DuplexProcess.h create mode 100644 Sources/CSQLite/CSQLite.c create mode 100644 Sources/CSQLite/include/CSQLite.h create mode 100644 Sources/Components/Adapters/AntigravityAdapter.swift create mode 100644 Sources/Components/Adapters/ClaudeAdapter.swift create mode 100644 Sources/Components/Adapters/ClaudeComponents.swift create mode 100644 Sources/Components/Adapters/CodexAdapter.swift create mode 100644 Sources/Components/Adapters/CodexComponents.swift create mode 100644 Sources/Components/Adapters/CursorAdapter.swift create mode 100644 Sources/Components/Adapters/CursorComponents.swift create mode 100644 Sources/Components/Adapters/GeminiAdapter.swift create mode 100644 Sources/Components/Adapters/GeminiComponents.swift create mode 100644 Sources/Components/Adapters/OpenCodeAdapter.swift create mode 100644 Sources/Components/Adapters/OpenCodeComponents.swift create mode 100644 Sources/Components/AntigravityRuleV1.swift create mode 100644 Sources/Components/ArtifactAggregation.swift create mode 100644 Sources/Components/CapabilityRegistry.swift create mode 100644 Sources/Components/ClientCapabilityInspection.swift create mode 100644 Sources/Components/ComponentFields.swift create mode 100644 Sources/Components/ComponentLinker.swift create mode 100644 Sources/Components/DeploymentConstruction.swift create mode 100644 Sources/Components/Expansion.swift create mode 100644 Sources/Components/FrozenNativeIdentity.swift create mode 100644 Sources/Components/Import/APMInputImport.swift create mode 100644 Sources/Components/Import/APMPackageContentImport.swift create mode 100644 Sources/Components/Import/ImportFrontmatter.swift create mode 100644 Sources/Components/Import/ImportInput.swift create mode 100644 Sources/Components/Import/ImportSkillContent.swift create mode 100644 Sources/Components/Import/NativeCatalogImport.swift create mode 100644 Sources/Components/Import/NativeContainerImport.swift create mode 100644 Sources/Components/Import/NativeExecutableMembers.swift create mode 100644 Sources/Components/Import/NativeImportInput.swift create mode 100644 Sources/Components/Import/NativeImportSemantics.swift create mode 100644 Sources/Components/Import/NativeMemberImport.swift create mode 100644 Sources/Components/Import/NativeSourceImport.swift create mode 100644 Sources/Components/Import/RulesyncConfigImport.swift create mode 100644 Sources/Components/Import/RulesyncSourceImport.swift create mode 100644 Sources/Components/Import/SourceImport.swift create mode 100644 Sources/Components/Import/SourceImportProposal.swift create mode 100644 Sources/Components/Import/VercelSourceImport.swift create mode 100644 Sources/Components/Import/YAMLSourceImport.swift create mode 100644 Sources/Components/LedgerFreeze.swift create mode 100644 Sources/Components/LedgerImpact.swift create mode 100644 Sources/Components/LedgerPayload.swift create mode 100644 Sources/Components/LedgerReplay.swift create mode 100644 Sources/Components/LinkBudget.swift create mode 100644 Sources/Components/LinkedComponents.swift create mode 100644 Sources/Components/MCPBoundedTransport.swift create mode 100644 Sources/Components/MCPConnectionRunner.swift create mode 100644 Sources/Components/MCPConnectionTypes.swift create mode 100644 Sources/Components/MCPHTTPConnection.swift create mode 100644 Sources/Components/MCPLayoutV1.swift create mode 100644 Sources/Components/MCPLowering.swift create mode 100644 Sources/Components/MCPMessageSink.swift create mode 100644 Sources/Components/MCPStagedValues.swift create mode 100644 Sources/Components/NativeAuthorityComposition.swift create mode 100644 Sources/Components/NativeComponentContribution.swift create mode 100644 Sources/Components/NativeComponentDecodingV1.swift create mode 100644 Sources/Components/NativeComponentFieldsV1.swift create mode 100644 Sources/Components/NativeComponentLayoutsV1.swift create mode 100644 Sources/Components/NativeComponentLowering.swift create mode 100644 Sources/Components/NativeDocumentedHooksV1.swift create mode 100644 Sources/Components/NativeGeneratedPluginContribution.swift create mode 100644 Sources/Components/NativeGeneratedPluginLayoutV1.swift create mode 100644 Sources/Components/NativeHookLayoutV1.swift create mode 100644 Sources/Components/NativeIgnoreLayoutV1.swift create mode 100644 Sources/Components/NativeLSPLayoutV1.swift create mode 100644 Sources/Components/NativePluginFieldsV1.swift create mode 100644 Sources/Components/NativePluginLayoutV1.swift create mode 100644 Sources/Components/NativeProgramV1.swift create mode 100644 Sources/Components/NativePromptAudit.swift create mode 100644 Sources/Components/PluginExpansion.swift create mode 100644 Sources/Components/SourceCatalog.swift create mode 100644 Sources/Components/SourceCatalogSelection.swift create mode 100644 Sources/NativeDocuments/JSONParser.swift create mode 100644 Sources/NativeDocuments/Model.swift create mode 100644 Sources/NativeDocuments/NativeDocument.swift create mode 100644 Sources/NativeDocuments/NativePromptReadback.swift create mode 100644 Sources/NativeDocuments/PatchBuilder.swift create mode 100644 Sources/NativeDocuments/Semantics.swift create mode 100644 Sources/NativeDocuments/TOMLIndex.swift create mode 100644 Sources/TOMLSemantics/DateTime.swift create mode 100644 Sources/TOMLSemantics/LICENSE create mode 100644 Sources/TOMLSemantics/PATCHES.md create mode 100644 Sources/TOMLSemantics/Parsing/Constants.swift create mode 100644 Sources/TOMLSemantics/Parsing/Parser+Finish.swift create mode 100644 Sources/TOMLSemantics/Parsing/Parser.swift create mode 100644 Sources/TOMLSemantics/Parsing/TOMLDocument.swift create mode 100644 Sources/TOMLSemantics/Parsing/Token.swift create mode 100644 Sources/TOMLSemantics/SemanticBudget.swift create mode 100644 Sources/TOMLSemantics/SemanticDocument.swift create mode 100644 Sources/TOMLSemantics/TOMLError.swift create mode 100644 Sources/TOMLSemantics/TOMLKey.swift create mode 100644 Sources/TOMLSemantics/provenance.json create mode 100644 Sources/TOMLSemantics/upstream.patch create mode 100644 Sources/TreeSitterTOML/LICENSE create mode 100644 Sources/TreeSitterTOML/include/toml.h create mode 100644 Sources/TreeSitterTOML/parser.c create mode 100644 Sources/TreeSitterTOML/provenance.json create mode 100644 Sources/TreeSitterTOML/scanner.c create mode 100644 Sources/TreeSitterTOML/tree_sitter/parser.h create mode 100644 Sources/TreeSitterYAML/LICENSE create mode 100644 Sources/TreeSitterYAML/include/yaml.h create mode 100644 Sources/TreeSitterYAML/parser.c create mode 100644 Sources/TreeSitterYAML/provenance.json create mode 100644 Sources/TreeSitterYAML/scanner.c create mode 100644 Sources/TreeSitterYAML/schema.core.c create mode 100644 Sources/TreeSitterYAML/tree_sitter/alloc.h create mode 100644 Sources/TreeSitterYAML/tree_sitter/array.h create mode 100644 Sources/TreeSitterYAML/tree_sitter/parser.h create mode 100644 Tests/AgentsCoreTests/AcquisitionCacheTests.swift create mode 100644 Tests/AgentsCoreTests/AgentClientObservationTests.swift create mode 100644 Tests/AgentsCoreTests/CheckpointUniquenessTests.swift create mode 100644 Tests/AgentsCoreTests/ClientBackupTests.swift create mode 100644 Tests/AgentsCoreTests/CoordinationAdmissionTests.swift create mode 100644 Tests/AgentsCoreTests/DeclarationStateTests.swift create mode 100644 Tests/AgentsCoreTests/DirectoryHandleTests.swift create mode 100644 Tests/AgentsCoreTests/FileAccessTests.swift create mode 100644 Tests/AgentsCoreTests/FileSystemAccessTests.swift create mode 100644 Tests/AgentsCoreTests/IndependentLedgerAdmissionTests.swift create mode 100644 Tests/AgentsCoreTests/LedgerAuthorityTests.swift create mode 100644 Tests/AgentsCoreTests/LedgerCodecTests.swift create mode 100644 Tests/AgentsCoreTests/LedgerGraphReviewTests.swift create mode 100644 Tests/AgentsCoreTests/LedgerProjectionTests.swift create mode 100644 Tests/AgentsCoreTests/LedgerRetentionTests.swift create mode 100644 Tests/AgentsCoreTests/LedgerWireSpellingTests.swift create mode 100644 Tests/AgentsCoreTests/MetadataTestSupport.swift create mode 100644 Tests/AgentsCoreTests/NativeArrayReceiptTests.swift create mode 100644 Tests/AgentsCoreTests/PreparationEvidenceTests.swift create mode 100644 Tests/AgentsCoreTests/PrivateMaterializationTests.swift create mode 100644 Tests/AgentsCoreTests/PrivateTreeTests.swift create mode 100644 Tests/AgentsCoreTests/ProcessLimitsTests.swift create mode 100644 Tests/AgentsCoreTests/ProcessTerminationTests.swift create mode 100644 Tests/AgentsCoreTests/PublicationTests.swift create mode 100644 Tests/AgentsCoreTests/ReadDependencyTests.swift create mode 100644 Tests/AgentsCoreTests/RegisteredNativeTargetTests.swift create mode 100644 Tests/AgentsCoreTests/RequirementSemanticsTests.swift create mode 100644 Tests/AgentsCoreTests/SharedTargetTests.swift create mode 100644 Tests/AgentsCoreTests/SourceAccessSettingsEditorTests.swift create mode 100644 Tests/AgentsCoreTests/StatePublicationTests.swift create mode 100644 Tests/AgentsCoreTests/TransactionCostTests.swift create mode 100644 Tests/AgentsCoreTests/WatchPreparationTests.swift create mode 100644 Tests/AgentsCoreTests/WatchSourceTests.swift create mode 100644 Tests/AgentsInstructionsTests/DeclarationDocumentTests.swift create mode 100644 Tests/AgentsInstructionsTests/FileReadAccessTests.swift create mode 100644 Tests/AgentsInstructionsTests/LedgerCompatibilityTests.swift create mode 100644 Tests/AgentsInstructionsTests/MappingReadLocationsTests.swift create mode 100644 Tests/AgentsManifestTests/DeclarationProgressTests.swift create mode 100644 Tests/AgentsManifestTests/EditPlanTests.swift create mode 100644 Tests/AgentsManifestTests/ExpansionBudgetTests.swift create mode 100644 Tests/AgentsManifestTests/FrontEndTests.swift create mode 100644 Tests/AgentsManifestTests/FullDeclarationDependencyTests.swift create mode 100644 Tests/AgentsManifestTests/FullDeclarationDraftTests.swift create mode 100644 Tests/AgentsManifestTests/FullDeclarationTests.swift create mode 100644 Tests/AgentsManifestTests/IndependentYAMLAcceptanceTests.swift create mode 100644 Tests/AgentsManifestTests/ManifestExpectations.swift create mode 100644 Tests/AgentsManifestTests/MappingFieldInsertionTests.swift create mode 100644 Tests/AgentsManifestTests/NativeCoordinateTests.swift create mode 100644 Tests/AgentsManifestTests/ProjectionTests.swift create mode 100644 Tests/AgentsManifestTests/ResourceTests.swift create mode 100644 Tests/AgentsManifestTests/SourceReplacementTests.swift create mode 100644 Tests/AgentsManifestTests/Watchdog.swift create mode 100644 Tests/AgentsManifestTests/YAMLReaderTests.swift create mode 100644 Tests/AgentsSkillsTests/ArchiveTestSupport.swift create mode 100644 Tests/AgentsSkillsTests/FileReadAccessTests.swift create mode 100644 Tests/AgentsSkillsTests/IndexedArtifactLifecycleTests.swift delete mode 100644 Tests/AgentsSkillsTests/LockedArtifactLifecycleTests.swift create mode 100644 Tests/AgentsSkillsTests/ManifestLifecycleTests.swift create mode 100644 Tests/AgentsSkillsTests/NetworkingTests.swift create mode 100644 Tests/AgentsSkillsTests/TransactionDoctorTests.swift create mode 100644 Tests/AgentsUpdatesTests/AgentClientInspectionTests.swift create mode 100644 Tests/AgentsUpdatesTests/AntigravityAdapterTests.swift create mode 100644 Tests/AgentsUpdatesTests/AntigravityInstructionTests.swift create mode 100644 Tests/AgentsUpdatesTests/AuthorLockedPackageTests.swift create mode 100644 Tests/AgentsUpdatesTests/AuthorPackageTests.swift create mode 100644 Tests/AgentsUpdatesTests/ComponentInventoryTests.swift create mode 100644 Tests/AgentsUpdatesTests/ConsumerLifecycleRegressionTests.swift create mode 100644 Tests/AgentsUpdatesTests/ConsumerSourceRegressionTests.swift create mode 100644 Tests/AgentsUpdatesTests/ContentAuditTests.swift create mode 100644 Tests/AgentsUpdatesTests/DeclarationYAMLUpdateTests.swift create mode 100644 Tests/AgentsUpdatesTests/ExistingGlobalConfigurationTests.swift create mode 100644 Tests/AgentsUpdatesTests/FiniteSkillInstallationTests.swift create mode 100644 Tests/AgentsUpdatesTests/FirstUserDeclarationTests.swift create mode 100644 Tests/AgentsUpdatesTests/GitAcquisitionTests.swift create mode 100644 Tests/AgentsUpdatesTests/HostedMarketplaceTLSTests.swift create mode 100644 Tests/AgentsUpdatesTests/HostedMarketplaceTests.swift create mode 100644 Tests/AgentsUpdatesTests/ImplicitReadFootprintTests.swift create mode 100644 Tests/AgentsUpdatesTests/ImportNativeExecutableLifecycleTests.swift create mode 100644 Tests/AgentsUpdatesTests/ImportNativeLifecycleTests.swift create mode 100644 Tests/AgentsUpdatesTests/InitializationIntegrationTests.swift create mode 100644 Tests/AgentsUpdatesTests/InstructionBuildTests.swift create mode 100644 Tests/AgentsUpdatesTests/IntegratedConsumerRegressionTests.swift create mode 100644 Tests/AgentsUpdatesTests/LifecycleCompositionTests.swift create mode 100644 Tests/AgentsUpdatesTests/MCPConnectionOperationsTests.swift create mode 100644 Tests/AgentsUpdatesTests/MCPManagedSelectionTests.swift create mode 100644 Tests/AgentsUpdatesTests/MCPRegistryTests.swift create mode 100644 Tests/AgentsUpdatesTests/MarketplaceDirectoryTests.swift create mode 100644 Tests/AgentsUpdatesTests/MarketplaceResolutionTests.swift create mode 100644 Tests/AgentsUpdatesTests/MarketplaceTests.swift create mode 100644 Tests/AgentsUpdatesTests/NativeAuthorityIntegrationTests.swift create mode 100644 Tests/AgentsUpdatesTests/NativeCompositionIntegrationTests.swift create mode 100644 Tests/AgentsUpdatesTests/NativePluginExportTests.swift create mode 100644 Tests/AgentsUpdatesTests/OrganizationPolicyTests.swift create mode 100644 Tests/AgentsUpdatesTests/PackageLifecycleTLSTests.swift create mode 100644 Tests/AgentsUpdatesTests/PackageLifecycleTests.swift create mode 100644 Tests/AgentsUpdatesTests/PortableBundleTests.swift create mode 100644 Tests/AgentsUpdatesTests/PrivateNativeCompositionTests.swift create mode 100644 Tests/AgentsUpdatesTests/ProducerPatchTests.swift create mode 100644 Tests/AgentsUpdatesTests/PublicInspectionTests.swift create mode 100644 Tests/AgentsUpdatesTests/ReadFootprintIntegrationTests.swift create mode 100644 Tests/AgentsUpdatesTests/RegistryAcquisitionTests.swift create mode 100644 Tests/AgentsUpdatesTests/RequirementUpdateTests.swift create mode 100644 Tests/AgentsUpdatesTests/SkillPathReadLocationsTests.swift create mode 100644 Tests/AgentsUpdatesTests/SourceAccessTests.swift create mode 100644 Tests/AgentsUpdatesTests/SourceCatalogInspectionTests.swift create mode 100644 Tests/AgentsUpdatesTests/SourceImportSelectionTests.swift create mode 100644 Tests/AgentsUpdatesTests/SourcePolicyTests.swift create mode 100644 Tests/AgentsUpdatesTests/SourceReplacementUpdateTests.swift create mode 100644 Tests/AgentsUpdatesTests/WatchConfirmationTests.swift create mode 100644 Tests/ComponentsTests/ArtifactLinkingTests.swift create mode 100644 Tests/ComponentsTests/Fixtures/MCPHTTPServer.py create mode 100644 Tests/ComponentsTests/GeneratedPluginTests.swift create mode 100644 Tests/ComponentsTests/ImpactTests.swift create mode 100644 Tests/ComponentsTests/ImportNativeTests.swift create mode 100644 Tests/ComponentsTests/ImportPinnedFixtures.swift create mode 100644 Tests/ComponentsTests/ImportProfileTests.swift create mode 100644 Tests/ComponentsTests/ImportSourceTests.swift create mode 100644 Tests/ComponentsTests/ImportSupportingLinksTests.swift create mode 100644 Tests/ComponentsTests/LedgerReplayBudgetTests.swift create mode 100644 Tests/ComponentsTests/LedgerReplayTests.swift create mode 100644 Tests/ComponentsTests/LinkBudgetTests.swift create mode 100644 Tests/ComponentsTests/LinkFixture.swift create mode 100644 Tests/ComponentsTests/LinkingAcceptanceTests.swift create mode 100644 Tests/ComponentsTests/LinkingIntegrationTests.swift create mode 100644 Tests/ComponentsTests/LinkingReviewRegressionTests.swift create mode 100644 Tests/ComponentsTests/LinkingTests.swift create mode 100644 Tests/ComponentsTests/MCPConnectionAcceptanceTests.swift create mode 100644 Tests/ComponentsTests/MCPConnectionTests.swift create mode 100644 Tests/ComponentsTests/NativeComponentFieldsTests.swift create mode 100644 Tests/ComponentsTests/NativeComponentTests.swift create mode 100644 Tests/ComponentsTests/NativeCoordinateLinkingTests.swift create mode 100644 Tests/ComponentsTests/NativeMCPTests.swift create mode 100644 Tests/ComponentsTests/OpaquePluginIdentityTests.swift create mode 100644 Tests/ComponentsTests/PluginLinkingTests.swift create mode 100644 Tests/ComponentsTests/PromptReferenceTests.swift create mode 100644 Tests/ComponentsTests/SnapshotTests.swift create mode 100644 Tests/ComponentsTests/SourceCatalogTests.swift create mode 100644 Tests/ComponentsTests/UserScopeTests.swift create mode 100644 Tests/Documentation/PortableBundles.md create mode 100644 Tests/MCPTestProcess/main.swift create mode 100644 Tests/ManifestTestProcess/main.swift create mode 100644 Tests/ManifestTestSupport/ProbeReport.swift create mode 100644 Tests/NativeDocumentsTests/ArrayAuthorityTests.swift create mode 100644 Tests/NativeDocumentsTests/ConditionalPruningTests.swift create mode 100644 Tests/NativeDocumentsTests/NativeDocumentTests.swift create mode 100644 Tests/NativeDocumentsTests/OccurrenceInsertionTests.swift create mode 100644 Tests/NativeDocumentsTests/SemanticTests.swift create mode 100644 Tests/SourcePolicyFixtures.md create mode 100644 Tests/StateTestProcess/LedgerProbe.swift create mode 100644 Tests/StateTestProcess/OpenFileLimitProbe.swift create mode 100644 Tests/StateTestProcess/PrivateMaterializationProbe.swift create mode 100644 Tests/StateTestProcess/SourceArchiveProbe.swift create mode 100644 Tests/StateTestSupport/DeclarationStateFixture.swift create mode 100644 Tests/StateTestSupport/ManifestText.swift create mode 100644 Tests/StateTestSupport/ProcessWait.swift diff --git a/.agent/agents.json b/.agent/agents.json deleted file mode 100644 index 5c68742..0000000 --- a/.agent/agents.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "instructions": { - "agents": ["claude-code", "codex"], - "sections": [ - "guide", - "agents-tools:shared/swift-package-route", - "agents-tools:shared/swift-package-tests" - ] - }, - "sources": { - "agents-tools": { - "branch": "master", - "git": "github.com/agents-tools/.github", - "path": ".agent" - } - } -} diff --git a/.agent/agents.yaml b/.agent/agents.yaml new file mode 100644 index 0000000..2799bdd --- /dev/null +++ b/.agent/agents.yaml @@ -0,0 +1,13 @@ +version: 1 +sources: + agents-tools: + url: https://github.com/agents-tools/.github + requirement: {branch: master} + subpath: .agent +components: + - kind: instructions + agents: [claude-code, codex] + sections: + - {name: guide} + - {name: shared/swift-package-route, source: agents-tools} + - {name: shared/swift-package-tests, source: agents-tools} diff --git a/.github/ci/linux-tests.Dockerfile b/.github/ci/linux-tests.Dockerfile new file mode 100644 index 0000000..345980c --- /dev/null +++ b/.github/ci/linux-tests.Dockerfile @@ -0,0 +1,13 @@ +ARG SWIFT_IMAGE +FROM ${SWIFT_IMAGE} + +ARG TEST_UID +ARG TEST_GID +RUN apt-get update \ + && apt-get install -y --no-install-recommends libsqlite3-dev python3 zstd \ + && rm -rf /var/lib/apt/lists/* \ + && (getent group "$TEST_GID" || groupadd --gid "$TEST_GID" test-runner) \ + && (getent passwd "$TEST_UID" || useradd --create-home --uid "$TEST_UID" --gid "$TEST_GID" test-runner) + +USER ${TEST_UID}:${TEST_GID} +WORKDIR /workspace diff --git a/.github/swift-package.json b/.github/swift-package.json index 7f67f67..1dafec3 100644 --- a/.github/swift-package.json +++ b/.github/swift-package.json @@ -1,5 +1,28 @@ { + "commands": [ + { + "name": "manifest-schema-generation", + "run": "python3 Scripts/generate-manifest-schema.py --check" + }, + { + "name": "linux-swift-6.4.1", + "runner": "ubuntu-24.04", + "run": "python3 Scripts/test-linux.py swift:6.4.1-noble@sha256:6304481cf2717966b7ba175162e397ea2f2cc3161909f2b2a5cf40036079a0f7" + } + ], + "test_configurations": [ + "debug", + "release" + ], "compilers": [ - {"name": "macos-26-xcode-26.6", "runner": "macos-26", "xcode": "26.6"} - ] + { + "name": "macos-26-xcode-26.6", + "runner": "macos-26", + "xcode": "26.6" + } + ], + "timeout_minutes": 120, + "environment": { + "SWT_EXPERIMENTAL_MAXIMUM_PARALLELIZATION_WIDTH": "1" + } } diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index dd0d3cf..14087b8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -19,4 +19,4 @@ jobs: permissions: contents: read actions: read - uses: agents-tools/github-workflows/.github/workflows/swift-package.yml@bb0a8c8c39827a364b9d3cbf4069754e7d975586 + uses: agents-tools/github-workflows/.github/workflows/swift-package.yml@f5d8edff9e7230ffe93006a0c50edf1e19bd625d diff --git a/.github/workflows/source-policy.yml b/.github/workflows/source-policy.yml index bb2db02..c328110 100644 --- a/.github/workflows/source-policy.yml +++ b/.github/workflows/source-policy.yml @@ -17,7 +17,7 @@ concurrency: jobs: policy: if: github.event_name != 'push' || !github.event.deleted - uses: agents-tools/github-workflows/.github/workflows/policy.yml@bb0a8c8c39827a364b9d3cbf4069754e7d975586 + uses: agents-tools/github-workflows/.github/workflows/policy.yml@f5d8edff9e7230ffe93006a0c50edf1e19bd625d with: allow-terms: | ChatGPT diff --git a/.gitignore b/.gitignore index f27a062..00c45a6 100644 --- a/.gitignore +++ b/.gitignore @@ -10,5 +10,5 @@ DerivedData/ .netrc /.agent/* !/.agent/instructions/ -!/.agent/agents.json +!/.agent/agents.yaml !/.agent/agents.resolved diff --git a/CHANGELOG.md b/CHANGELOG.md index 977f5cf..0c2d228 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,34 @@ publication follows the [release checklist](Documentation/Reference/Release.md). ## Unreleased +## 0.3.0 + +### Added + +- Select instruction recipients per client, install Antigravity global rules and + generate copyable instructions for ChatGPT App and Gemini App. +- Back up local sessions and configuration for Codex, Claude Code and Gemini CLI, + with a file-level preview before restoring. +- Discover MCP servers through a registry, apply source policies, and export or + import portable configuration bundles. + +- Linux support. +- The `AgentsManifest` library reads and edits YAML declarations, reports field + locations and preserves comments and unrelated text during configuration edits. +- Consumers can inspect and import sources, select exported groups, preview + native component changes and apply the reviewed configuration. An explicit + MCP connection test supports initialization and tool discovery. + +### Changed + +- Projects declare configuration in `.agent/agents.yaml` and users in + `~/.agents/agents.yaml`. Prepare and verify the declaration in each existing + scope before applying it with the updated CLI. See the + [manifest reference](Documentation/Reference/Manifest.md). +- `agents.resolved` uses the version 2 JSON ledger. It records locked resources + and ownership of native configuration. Both CLI consumers must use the same + ledger format. See [state and recovery](Documentation/Architecture/State.md). + ## 0.2.0 - 2026-10-27 ### Added diff --git a/Documentation/Architecture/Instructions.md b/Documentation/Architecture/Instructions.md index 202f106..43e1d77 100644 --- a/Documentation/Architecture/Instructions.md +++ b/Documentation/Architecture/Instructions.md @@ -40,12 +40,13 @@ revision, path and original-byte hash. A container of a local source declared in the same scope cannot hold a target. A project's own files live in `.agent/instructions/` and are referenced by bare -name; `alias:name` references a declared source. Own files are read from the +name; `.section(name:source:)` in `agents.yaml`, or `alias:name` in operation +arguments, references a declared source. Own files are read from the working tree as it is. Their lock records have source `.`, the project-relative -path and the hash, and no revision. Resolution and restore read only the named -file, `.agent/instructions/.md`, and so does adding named files, so other -files in the container affect only listing. Restoring a lock fails with `InstructionError.ownChanged` when an -own file's hash changed; update reads the current file. +path and the hash, and no revision. Resolution reads only the named file, `.agent/instructions/.md`, and so does +adding named files, so other files in the container affect only listing. Locked +restore publishes the frozen output and preserves the current own source file. +Update reads the current file; doctor reports changes since the recorded hash. `add(InstructionAddOptions, beforeApply:)` accepts a source alias or string, or `.` for own files, plus an optional alias, requirement, search path, ordered @@ -69,8 +70,9 @@ remain shared across kinds. | Cursor | No file | `AGENTS.md` | | OpenCode | `$XDG_CONFIG_HOME/opencode/AGENTS.md`, default `~/.config/opencode/AGENTS.md` | `AGENTS.md` | | Gemini CLI | `~/.gemini/GEMINI.md` | `GEMINI.md` | +| Antigravity | `~/.gemini/config/rules/.md` | `.agents/rules/.md` | -Every target is generated in full by `Instructions.render`: the notice line +The combined Markdown targets are generated in full by `Instructions.render`: the notice line `Instructions.notice`, a blank line, and the sections in declared order separated by one blank line, ending with a newline. Rendering rejects two sections whose first headings share level and whitespace-collapsed text, and @@ -81,7 +83,7 @@ In project scope, sections are grouped by `directory`: each group renders into the `AGENTS.md`, or `GEMINI.md`, of that directory, which must already exist. No component of a nested target's directory may be a symbolic link or `.git`, or hold another repository or worktree. -User scope renders all sections into each recipient's file. Project keys are +Combined user targets render all sections selected for that recipient. Project keys are relative to the project root, and a nested key names `AGENTS.md` or `GEMINI.md` in a directory outside any `.git` and the top-level `.agent`; user keys are `~/`-relative to the supplied home, and configured user locations outside home use absolute keys. @@ -90,7 +92,7 @@ runtime environment; lock contents cannot authorize arbitrary writes. Configured user containers may resolve through symlinks. Journal validation opens project descendants without following links. -A file is owned when `Instructions.isOwned` finds it blank or finds the notice +A combined Markdown file is owned when `Instructions.isOwned` finds it blank or finds the notice on its first line; a lock entry alone does not make a file owned. A planned write over an existing file that is not owned marks the change `foreign`; add, update apply, combined apply, remove and install stop with @@ -119,6 +121,45 @@ Ancestor files are reported and never modified. Claude Code reads a nested directory, unless that directory's Claude file imports it; nested Claude files are not modified, and doctor reports one that hides a generated target. +## Antigravity Rules + +Select `antigravity` in the instruction component's recipients. A section's +`condition.agents` can narrow that selection. Each source-qualified section gets +one deterministic Markdown filename under project `.agents/rules/` or user +`~/.gemini/config/rules/`. Project `paths` become `trigger: glob` with a +comma-separated `globs` string. Patterns with commas or outer whitespace cannot +be represented by this list. Unscoped project sections and user sections use +`trigger: always_on`. + +The lock records the source revision, selected resource bytes and hashes, and +the rendered hash. Equivalent selections of the same unit share one rule. +Incompatible selections for the same leaf stop preview. Restore renders the +same bytes from the lock, and handwritten sibling files stay in place. + +`@[label](relative/path)` inlines UTF-8 text from the section's source +snapshot. Nested includes resolve from the including file, and any included +frontmatter is stripped. The same locked inputs supply restore. Unsafe, +unresolved or cyclic includes and unresolved local Markdown links stop +planning. Literal mentions and native path-only `@filename` references stay +in the generated Markdown for Antigravity to interpret. The 24,000 UTF-8 byte limit counts the +complete rendered file including frontmatter. Preview and apply reports expose +the shared 20,000-token budget for active global and always-on rules through +`InstructionUpdateReport.advisories`. [Antigravity Rules](https://antigravity.google/docs/rules) + +Recipient selection controls which files Core generates. Antigravity also +loads workspace `AGENTS.md` and `GEMINI.md`, and user files such as +`~/.gemini/GEMINI.md`. A section selected for both a shared Markdown target and +an Antigravity rule can therefore load through both paths. +[Antigravity customization discovery](https://antigravity.google/docs/customization-discovery) + +In user scope, a temporary Memex rule with the `memex-` prefix and the source unit's filename +can migrate when its standalone marker names the selected source path and +revision and its full bytes equal the pinned rendering. Preview reports both file changes. Any mismatch or unmanaged +collision appears in `InstructionUpdateReport.conflicts` and blocks apply. +Apply revalidates both file generations and uses one transaction for the new +rule, the old rule's removal and the lock. Doctor checks managed rules for +missing content, drift and lost ownership markers. + ## Operations and Mutation Contract | Consumer operation | Behavior | @@ -135,21 +176,39 @@ are not modified, and doctor reports one that hides a generated target. | `doctor(projectRoots:environment:codexConfiguration:)` | Audit explicit project roots without writing | | `export(projectRoots:environment:)` | Map the user scope's and each root's locked targets to their sections without writing | -An `agents` argument sets the complete instruction recipient list. A name to +An `agents` argument to update sets the default local recipients for +sections without an explicit recipient list. +Adding a section adds only its missing local recipients. Existing source-qualified +sections keep their app recipients and conditions, and sibling sections keep +their own recipients. A name to remove that equals a declared reference, such as an own file's bare name or `alias:name`, selects that reference; another bare name must match exactly one source reference. Removal also removes those sections from prompts. Empty prompts are removed. Other source declarations and skill records remain available to their owners. -Export maps a user target to every locked section from the lock alone. A -project section's placement needs its `paths`, read from the working tree or -the cache without fetching; a section whose content is unavailable is listed as -unplaced. +Export maps each scope's locked deployments and prompt sections from ledger +metadata alone. `InstructionMapping.readDependencies` contains `ReadDependency.entry` +values for declaration, resolved and watch-state leaves, the scope root and state +directory, scope lock, recovery markers and attempted external admission paths. +Absent paths and failed admission anchors remain available for missing-lock, +pending-recovery and unavailable statuses. Permitted scope-root aliases retain +both logical and physical paths; forbidden state-directory and lock links do not +introduce their destinations as authority. Entry dependencies observe the named +path and its ancestors, including creation, replacement and access changes; they +do not observe unrelated descendants of directory entries. Mapping does not read +section bodies, append content or deployed target bytes; content inspection +operations supply their own dependencies. Planning validates required content before applying. Reports include old and new section records, target before/after bytes and recipients, drift, foreign targets, a missing-lock status and changed prompt names. +`InstructionUpdateReport.outputs` provides the complete candidate bytes for +each local recipient and target, including unchanged files and the assembled +Claude forwarding file. Recipients that share a file have the same URL and +bytes. ChatGPT App and Gemini App produce ordered Markdown with no file URL. +Their selections and input pins can be saved with the declaration and lock. +Named prompt exports use their own declaration and append file. `InstructionTargetChange.beforeAgents` is nil when the previous lock has no target entry; `afterAgents` is empty when the target is no longer managed. Both recipient arrays are sorted by agent raw value. `agentsChanged` compares those recipients, @@ -163,17 +222,17 @@ The optional throwing `beforeApply` callback runs before replacements so a consumer can show differences or cancel. Target bytes are checked again after the callback; intervening edits stop the commit. Update also revalidates state bytes/presence, target ancestry and all Claude forwarding decision inputs -before and after retention. `InstructionUpdatePlan` supplies package-visible -planning, validation, retention and staging to both standalone updates and -`AgentsUpdates`; the latter commits both kinds together as described in -[Updates](Updates.md). +before and after retention. Lifecycle methods are public extensions in +`AgentsUpdates`, which owns the complete linked ledger and one transaction for +selected deployments, declaration, resources and pruning. Consumers import that +product for lifecycle and ChatGPT export; pure text APIs remain here. +See [Updates](Updates.md) for selection, prepared handles and exact restore. Mutations hold the scope writer lock and use the durable journal for instruction -files, forwarding files, declaration, lock and cache pruning. Exact source -materializations are verified and published through cache transactions before -the target/state transaction. The journal has fixed project instruction paths, +files, forwarding files, declaration, ledger, materializations and cache pruning. The journal has fixed project instruction paths, nested project `AGENTS.md` and `GEMINI.md` paths, configured user instruction -roots and new top-level named Markdown files in `.agent/instructions/`. +roots, the registered Antigravity rule leaves and new top-level named Markdown +files in `.agent/instructions/`. Initialization uses the project's state lock and journal without creating a declaration or resolved file. @@ -199,17 +258,23 @@ generated files, takes over others only with `replace`, and records targets as ## ChatGPT Prompts -`instructions.chatgpt.` has ordered `sections` and an optional scope-relative -`append` file. Update locks prompt sections with file targets. Reports list -prompts whose section content, order, membership or append path changed. A -revision change with identical section hashes alone does not mark a prompt -changed. Append files remain live owner content; their independent edits do not -require a lock update. - -Render verifies locked hashes, renders sections as in targets without the -notice, and appends the custom file's bytes. It fails without locked sections or -if an append path escapes the scope through a symlink. It never writes to -ChatGPT. +An instructions component's `chatgpt` mapping declares named prompts with ordered +`sections` and an optional `append` path. Update locks prompt sections with file +targets. Reports list prompts whose section content, order, membership or append +path changed. A revision change with identical section hashes alone does not mark +a prompt changed. + +For consumer-authored prompts, append remains current owner content. Its authored +path is project-relative in project scope and home-relative in user scope. Update +and installation do not require that export-only file to exist. Export verifies +locked section hashes, renders them without the notice and reads the current append +bytes. Missing, unreadable or escaping append content fails export; recorded bytes +are never a fallback. Append edits do not require a lock update. Export never writes +to ChatGPT. + +The component freeze seam records consumer append coordinates as payload metadata, +separate from deterministic installation inputs. Producer-owned append content is +instead read from the selected source snapshot and retained as an exact resource. ## Diagnostics diff --git a/Documentation/Architecture/NativeDocuments.md b/Documentation/Architecture/NativeDocuments.md new file mode 100644 index 0000000..487b991 --- /dev/null +++ b/Documentation/Architecture/NativeDocuments.md @@ -0,0 +1,98 @@ +# Native Documents + +`NativeDocuments` is a package-only byte inspection and regional editing layer. +It receives `Data`, a fixed JSON/JSONC/TOML format, an operation budget and typed +region intents. Adapters own client dialects and ownership decisions. Filesystem +access, routes, secrets, locks, freshness, transactions and publication stay with +their existing owners. + +## Inspection and evidence + +`NativeDocument` preserves the supplied bytes. Regions consist of exact decoded +keys and array occurrence evidence. Key and string identity uses decoded UTF-8 +sequences. Canonically equivalent Unicode strings remain distinct native values. +Objects retain ordered entries; projecting a region that Core dictionaries cannot +represent returns no Core value. TOML date/time and non-finite numbers likewise +remain native atoms, retaining their lexemes. + +`read` returns an optional package-only observation with a Core value when +representable, native kind, raw numeric lexeme, explicit projection failure, +ephemeral byte ranges, exact structural fingerprint +and array occurrence evidence. Observations and prepared bytes can contain +materialized secrets; they are neither preview records nor serialized ledger +models. Diagnostics use fixed codes and byte ranges, without source excerpts. + +A put requires an absent expectation or matching owned observation. Removal +requires matching owned evidence. Empty object-container removal requires explicit +caller-supplied creation evidence and fails if comments must remain. An existing +unmanaged region is never adopted by matching a desired value. Missing object +ancestors can be created; the preparation reports created container regions. + +Stable array IDs are exact string fields and must be unique. Without an ID, +observations retain a structural fingerprint, ordinal and neighboring evidence. +Duplicate content is rejected when it cannot be uniquely identified; an ordinal +alone does not authorize a match. Individual occurrence edits preserve other +array entries and their order. An absent terminal occurrence with a stable ID can +append an exactly matching object. Owned array-of-table sets diff their entries +and append complete new occurrences; removing the final occurrence retains an +explicit empty array. New child tables bind only where their native scope can be +proved. + +## Parsers and edits + +JSON has one root and preserves raw numeric lexemes. JSONC comments and trailing +commas are independent fixed-dialect capabilities. The scanner validates string +escapes/surrogates and decoded duplicate keys. A leading UTF-8 BOM is preserved. + +TOML uses the fixed grammar in `TreeSitterTOML` with the existing formal runtime +dependency for locations. `TOMLSemantics` contains the licensed parser/validator +subset from pinned TOMLDecoder, with exact key identity, lexical scalar +classification, complete lazy validation, actual EOF checks and cooperative +resource admission. Each target records upstream file hashes and patch details. +The semantic parser remains the validity owner when the older CST grammar +cannot locate legal TOML syntax; such documents can be inspected and return +`syntaxNotLocated` for edits. No error recovery tree is used for editing. + +The TOML index resolves quoted/dotted keys, inline tables and array-of-table +headers in source order. Child table headers bind to the latest array table. +Scalar updates replace only the value span. Object updates diff members; +removal uses individual owned entries and headers across table blocks. Inline +punctuation is located independently of comments. Structural edits with ambiguous +trivia or scope are refused. New members use their containing table block or a +precise new table declaration, preserving subsequent table scope. + +Every preparation checks overlap and ownership, builds the complete expected +native tree, constructs nonoverlapping patches, copies every unselected byte +segment unchanged and reparses the complete candidate. Only a candidate equal to +the expected tree is returned. No-op intent returns the original bytes, including +escape spelling, newline style, comments and key order. Multiple internal drafts +are private; failure returns no partially prepared result. + +JSON integer/decimal declarations can encode the same numeric token. TOML +integer-looking decimal declarations append `e0` to retain native float kind. +Encoding and comparison preserve exact decimal text without a Double round trip. +Core projection removes TOML digit separators and a leading plus while retaining +the original numeric token separately in the observation. +Declarations and ledger identity remain with their owners, independently of +native byte no-ops. + +## Budget and cancellation + +`NativeDocumentBudget` is one serial operation-scoped mutable reference supplied +by the caller. Input admission, semantic construction, node/depth checks, decoded +storage, scans/key comparisons, reads, fingerprints, rendering, patches, drafts +and reparses consume that reference. No stage resets it. Limits are explicit +caller inputs rather than copies of YAML or ledger policy. + +Before entering the C parser, the entire input must fit the caller's maximum +uninterrupted-byte envelope. This covers strings, keys, skipped comments and +whitespace alike. The fixed grammar also reserves a conservative logical node +envelope of four nodes per input byte plus the document root before CST entry; +traversal and progress callbacks consume additional work. The progress callback +checks the same cancellation source and budget between parser work intervals. +All parser/tree handles are synchronously released on every exit. + +These are conservative logical admission units and cooperative cancellation, +not exact heap/RSS quotas or hard real-time deadlines. A caller requiring a +smaller uninterrupted interval must supply a smaller envelope. There is no +background timeout task or filesystem provider in this layer. diff --git a/Documentation/Architecture/Package.md b/Documentation/Architecture/Package.md index b05e09f..1518f7a 100644 --- a/Documentation/Architecture/Package.md +++ b/Documentation/Architecture/Package.md @@ -2,45 +2,87 @@ ## Purpose and Consumers -`core` supplies skill and instruction management and instruction text -transformations. Both `agents` in `agents-tools/cli` and `skill` in -`skill-cli/cli` consume this package. Consumers own command trees, argument -parsing, terminal presentation, and executable distribution. The package uses -Swift 6.3, Swift 6 language mode, and a macOS 15 minimum deployment platform. +`core` supplies symbolic agent declarations, source linking, skill and instruction +management, resolved state and recoverable application. Both `agents-tools/cli` +and `skill-cli/cli` consume its public products. Consumers own command parsing, +terminal/UI presentation and executable distribution. -## Products and Dependencies +## Target Boundaries ```text -AgentsUpdates ──> AgentsCore, AgentsSkills, AgentsInstructions - -AgentsSkills ──> AgentsCore - │ - └───────> Yams - -AgentsInstructions ──> AgentsCore - │ - └───────> Markdown (swift-markdown) ──> cmark-gfm - -StateTestProcess ──> AgentsCore, AgentsSkills, AgentsInstructions, AgentsUpdates -AgentsCoreTests ──> AgentsCore, StateTestProcess -AgentsSkillsTests ──> AgentsSkills, AgentsCore, Yams, StateTestProcess -AgentsInstructionsTests ──> AgentsInstructions -AgentsUpdatesTests ──> AgentsUpdates, StateTestProcess +AgentsManifest → AgentsCore, TreeSitterYAML, TreeSitter, Yams +AgentsSkills → AgentsCore, AgentsManifest, Yams +AgentsInstructions → AgentsCore, AgentsManifest, Markdown +Components → AgentsCore, AgentsManifest, AgentsSkills, AgentsInstructions, NativeDocuments, MCP +AgentsUpdates → AgentsCore, AgentsManifest, AgentsSkills, AgentsInstructions, Components, NativeDocuments +NativeDocuments → AgentsCore, TOMLSemantics, TreeSitterTOML, TreeSitter +TOMLSemantics → Foundation +TreeSitterTOML → (vendored C grammar) +AgentsCore → CPlatform, CSQLite, Crypto, Markdown, TOMLSemantics, Yams ``` -`AgentsCore`, `AgentsSkills`, `AgentsInstructions` and `AgentsUpdates` are library products with -matching targets under `Sources/` and test targets under `Tests/`. Shared -implementation uses `package` access; consumers receive the -workflow APIs and the state and result models they need. `Package.swift` owns -this dependency graph. +`TreeSitterYAML` is an internal C target containing the pinned, unmodified YAML +parser/scanner and headers, with upstream license and per-file provenance. +The runtime is a normal SwiftPM dependency. Consumers never receive parser types. + +## NativeDocuments + +`NativeDocuments` inspects provided JSON, JSONC and TOML bytes and prepares +ownership-checked regional changes. It preserves no-op bytes, unmanaged content, +comments and exact native semantics, and reparses each complete candidate. +`TOMLSemantics` owns bounded standard TOML validation; `TreeSitterTOML` supplies +pinned concrete locations through the existing Tree-sitter runtime dependency. +These targets are package-only, with no library product or filesystem provider. +See [native documents](NativeDocuments.md) for typed regions, observations, +creation evidence, read-only syntax and cumulative operation budgets. + +## AgentsManifest + +The frontend reads `.agent/agents.yaml` or the user scope’s `agents.yaml` and +produces complete syntax-independent IR and typed declarations. Admission checks +UTF-8 and unsupported raw line separators before parsing. Tree-sitter supplies +concrete byte ranges under an enforced parser work policy; bounded CST admission +precedes public Yams ordered-node composition. The source schema owns field +shapes and generates finite runtime constraints and reference help. Core scalar +resolution preserves string values, integer kind and exact decimal payloads. + +`DeclarationDocument` is an immutable validated snapshot with digest-scoped +occurrence handles. `ManifestEdit` carries Core domain values. Its editor changes +owned ranges, preserves unrelated bytes/comments, refreshes source maps and checks +full expected IR. Public changes are domain-valid, including no-op preparations. +`DeclarationEditPlan` privately composes bounded drafts for complete domain changes +and validates final IR, domain and declaring environments before returning bytes. + +`ManifestDump` exposes schema version 2, format `yaml`, manifest version 1, typed +IR records and semantic indexed source locations. Parsing, projection, dump and +edit preparation do not resolve sources, read resources or execute programs. + +`StateStore` extensions supply declaration reads, loading and edit planning; +`DeclarationAccess.manifest` connects watch operations. All state I/O, evidence, +locks and publication remain in Core. See [state](State.md) and the +[manifest reference](../Reference/Manifest.md). + +`ManifestTestProcess` and `ManifestTestSupport` own isolated parser/editing probes +and their resource reports. Package tests cover the complete YAML/domain contract +and the existing state, linking, lifecycle and recovery guarantees. ## AgentsCore +`SourceAccessSettingsEditor` validates and publishes the operator's +[user source access settings](../Reference/UserSourceAccess.md). The settings +document uses Yams and belongs to the runtime home independently of the +manifest and its project scope. + +- `ClientBackups` captures local Codex, Claude Code and Gemini CLI sessions and + configuration in private SQLite packages. The Core restore preview binds + the package, explicitly mapped projects, and the observed destination files + to one publication plan. Native session indexes and supported Codex SQLite + schemas merge into live client storage through a separate restore journal. - `SourceParser` and `ParsedSource` parse local paths, Git URLs and HTTP indexes. `SourceDeclaration` owns normalized source identity and discovery roots. - `SourceArgument` splits a source argument into its location and typed selectors, such as `owner/repo@branch:main@path:skills@skill:pdf`. Labels are - `branch`, `revision`, `ref` (a revision), `exact`, `from` (next major), + `branch`, `tag` (a literal tag), `revision`, `ref` (a revision), `exact`, `from` (next major), `minor` (next minor), `path` and `skill`; each kind appears at most once. Selectors start at the first `@` followed by a label and `:`, so SSH locations keep their `@`, and values are percent-decoded. A selection resolves the @@ -51,32 +93,49 @@ this dependency graph. - `SourceRequirement` expresses branch, revision, exact version, next-major, next-minor and half-open version ranges. Semantic-version comparison governs Git tag selection, including prerelease bounds. -- `Declaration` and `ResolvedState` define intent and resolved version 1 state, - including the complete instruction section, prompt and physical-target models. -- `StateStore` owns scope paths, validation, deterministic encoding and state - persistence. `FileLock` serializes state access; `FileTransaction` durably - journals replacements across installations, state and cache. Mutating state - access recovers interrupted transactions before proceeding, as described in - [State and cache](State.md). +- `DeclarationIR`, `DeclarationRecord` and `DeclarationValue` hold syntax-independent + manifest intent; `SourceSpan`, `SourceProvenance` and `DeclarationSourceMap` + carry document coordinates and origins without syntax or source access. +- `Declaration` holds complete typed symbolic manifest intent: ordered component + and group occurrences, conditions, native values, symbolic group references and + source declaration directories. It has no serialized form. `ResolvedLedger` owns version 2 resolved state. `ResolvedState` is the derived + skill/instruction inventory view, including sections, prompts and physical targets. +- `StateStore` owns scope paths, validation, deterministic lock and watch + encoding and state persistence. It holds declaration bytes, their evidence, + the absent-declaration rule and publication without knowing the declaration + format. `FileLock` serializes state access; `FileTransaction` durably + journals replacements across installations, state and cache. `FileSnapshot`, + `FileObjectIdentity` and `DirectoryWriteLease` own content, physical-object + and temporary directory-write evidence, including directory descendants and + permission bits. Within the transaction protocol only `DirectoryHandle` calls + `CPlatform`; it owns verified deletion, durable synchronization, + inode-checked directory permission updates and typed cross-directory rename + results. Mutating state access recovers interrupted transactions before + proceeding, as described in [State and cache](State.md). - `SourceCache` owns bare Git mirrors, requirement resolution, exact snapshots, - digest-addressed downloads and pruning across skill, instruction and watch pins. - `SourceResolutionSession` shares disposable exact snapshots between domain - planners during one update. `StatePrecondition` and `PathIdentity` validate - the rendered generation before application. `TransactionOutcome` follows - its owning journal through commit and recovery. - `ProcessRunner` executes subprocesses. + digest-addressed downloads and pruning across skill, instruction and watch + pins. `SourceResolutionSession` shares disposable exact snapshots between + domain planners during one update. `StatePrecondition`, `TargetPrecondition` + and `PathIdentity` validate the rendered generation before application. + `TransactionOutcome` follows its owning journal through commit and recovery. + `ProcessRunner` executes synchronous subprocesses. `OwnedDuplexProcess` is a + separate package-only, nonblocking pipe/process-group owner for bidirectional + connection tests. - `WatchOperations` owns source subscriptions, seen baselines, branch tracking and file comparisons. `WatchState` defines version 1 of `agents.watch`. Skill discovery and artifact loading are injected by `AgentsSkills` through - `SkillOperations.watchOperations()`. See [Watch](Watch.md) for the public API. + `SkillOperations.watchOperations()`, and declaration access by + `AgentsManifest`. See [Watch](Watch.md) for the public API. - `AgentRegistry` owns agent skill locations. `RuntimeEnvironment` supplies the project root, home directory and environment. Universal agent skill locations can be shared, so recipients sharing one directory must agree on install mode. - `FileHash` hashes tree entries, hidden files and symlink destinations; `PathSafety` checks paths and creates filesystem skill identities. -Core has no dependency on skill discovery, frontmatter, Yams or Markdown. -`AgentsInstructions` owns instruction text transformations and lifecycle. +Core has no dependency on manifest syntax, skill discovery, frontmatter, Yams or +Markdown. +`AgentsInstructions` owns instruction text transformations, inventory and diagnostics. +`AgentsUpdates` owns its deployment lifecycle. `InstructionLocations` supplies fixed target locations to lifecycle and journal validation. @@ -108,6 +167,17 @@ inspecting arguments, exit codes, or diagnostic text. Non-Git process failures continue to use `CoreError.commandFailed`; process launch errors retain their underlying platform error. +`OwnedDuplexProcess` takes explicit argv, cwd, environment and PATH. Its CPlatform +spawn closes nonstandard child descriptors and creates a separate process group; +it never inherits transaction locks. The owner closes stdin, waits a finite grace, +signals TERM/KILL while the unreaped leader reserves its identity, and confirms +reap with nonblocking waits. It refuses auto-reaping SIGCHLD configurations and +reports ownership loss or unconfirmed cleanup. Darwin inspects only the reserved +group, under a finite byte bound, to distinguish a zombie-only group before +signalling. It does not operate on unrelated processes or promise ownership of +children that detach into another session/group. `ProcessRunner` owns synchronous +Git/one-shot execution; transaction publication owns filesystem state. + ## AgentsSkills `SkillOperations` is the public lifecycle surface: @@ -142,7 +212,7 @@ means the before membership is unrecorded, not that files were absent. equal hashes do not suppress mode-only changes. The optional `beforeApply` callback runs before any replacement, and a thrown -error cancels the operation. The extracted `SkillUpdatePlan` validates state +error cancels the operation. The shared Updates plan validates state and target preconditions around content retention, including execute flags. Prepared, cached and staged skill content must agree in bytes and mode. A CLI auditing several projects calls `doctor` with an explicit environment @@ -249,8 +319,159 @@ The probe is never emitted. Malformed managed markers still produce errors. declaration and lock updates, and deletion decisions using the lock's `created` flag. The `Instructions` and `ClaudeForwarding` text APIs perform no I/O. +## Components + +`Components` is an internal target. Its package-only `ComponentLinker` reads a +complete symbolic declaration and explicitly exported producer groups into an +ordered, exact source graph. Root components precede uses; groups follow the +same depth-first order. Producer defaults and frontmatter restrictions determine +recipients together with nested reference and component conditions. Instructions +retain repeated occurrences; identical named hooks and policies coalesce while +retaining their origins. Logical conflicts are checked before artifact lowering. + +Core owns frozen Git candidate evidence, exact snapshots, source containment and +the scoped temporary-read session. Export constraints share one version variable +per normalized source; discovery roots remain distinct namespaces. Direct skill +and section pins are independent. Exact annotated Git objects are peeled to commits +before conjunction, candidate selection and snapshot identity. Acquiring a known +object does not enumerate mutable refs or refresh the frozen reference mirror. +The session reuses existing exact cached objects only under existing locks; other mirrors, refs, locks and content remain +temporary. The caller consumes borrowed resources within the linking closure; +cleanup runs on success, error and cooperative cancellation. The synchronous Git +runner completes owned in-flight work before cancellation returns. + +An exact view retains the original actual-local source environment independently +of its borrowed content and live-edit eligibility. Local producer aliases resolve +from that source's actual discovery root and home, even with a Git requirement. +Remote-contained local declarations inherit their immutable parent snapshot and +remain subject to lexical and real symlink containment. + +`SkillSnapshotReader` and `InstructionSnapshotReader` consume already selected +views without independently resolving or retaining sources. Actual local edit +skills preserve their live paths. Skill keys, exclusions and overrides use canonical +semantic names while resource paths and display names retain their source spelling. +An all-selection includes members from their effective override views, admits live-only +members only when that view is selected, and omits missing effective-view members; +named selections still require their members. Named own-instruction reads validate only +the selected path and its ancestors, while full enumeration remains strict. +Remote-contained local sources inherit the producer snapshot. Existing skill-index +formats supply skill artifacts, and do not define an export-package format. Indexed +members have independent artifact-digest pins. A scoped link can retain an admitted +ledger alongside its direct pins: protected members borrow their exact resource trees +and content objects, while selected members download only their requested artifacts. +The recorded index transport and artifact digest must both match; a missing closure +fails rather than refreshing that member. Nested artifact files and executable flags +are materialized only inside the source session's disposable workspace. + +The linked result records relative resource evidence, source requirements, +reference and contribution occurrences, provenance and exact dependency pins. +Its protected projection compares other domains' payloads, resource hashes, +recipients and pins; source sharing alone does not imply a changed projection. +Producer-owned children report `notEditableHere` with producer and reference +coordinates. The ledger freeze seam captures complete durable inputs within the source session. +Versioned replay produces verified artifacts and owned-region intentions; its +compatibility renderer table contains only existing formats. Test process formats +are supplied explicitly and are absent from production registration. These +package seams do not publish state. +Updates consumes the full linked graph and paired ledger freeze for deployment. + +Root package resources use the project directory in project scope and the +user-state directory in user scope. Explicit sources retain their declaring +environment. Root user instructions require named sources, while imported +producer groups retain their own sections. Consumer-owned prompt append references +are metadata anchored to the project or, for root user declarations, runtime home. +Linking and freezing do not open these export-only inputs. Public export reads their +current bytes with lexical and real containment checks; missing or unreadable content +fails export without a frozen-byte fallback. Producer-owned append content remains +anchored to the selected immutable source and is a frozen replay resource. Installation +replay reads only its recorded resources and does not open consumer append references. + +`ReadDependency` in AgentsCore distinguishes entry/access interests from recursive +subtree interests. `MCPConnectionSnapshot.readDependencies` and the Codable +`MCPConnectionDescription.readDependencies` expose logical and resolved entry +paths for live resources. Live directories retain live content semantics and +revalidate their identity before binding and start. Captured resources expose no +borrowed or staging paths. Managed selections additionally preserve the existing +ledger/source read footprint as subtree dependencies; an independent subtree +interest remains recursive when it overlaps a live entry. These monitoring fields +do not change CLI reports, which use their existing report types and binding list. + +The package-only `MCPConnectionRunner` performs one explicit connection test on +already-bound ephemeral values. Only Components links the exact official MCP SDK; +SDK models do not enter public APIs. The SDK Client owns automatic initialization +and typed tools/list requests. A bounded receive admission gate validates the +negotiated version before initialized is sent, and discovery runs only when the +server declares tools. There are no business tool, resource, prompt, sampling or +elicitation handlers; SDK logging is no-op. + +The selected transport is stdio, Streamable HTTP, or legacy SSE. Stdio frames +nonblocking owned pipes and discards counted stderr. HTTP uses one ephemeral +Foundation/FoundationNetworking data-delegate session with incremental JSON/SSE +admission, owned session/version headers and bounded SSE resumption without POST +replay. Legacy SSE waits for its same-origin endpoint event before posting. No +cookie/cache/credential store or OAuth flow is used; redirects and legacy +endpoints cannot transfer headers to another origin or downgrade transport. + +A monotonic total deadline includes preparation and all requests; a request +budget cannot extend it. Input, frame, cumulative input/output, stderr, queued +payload, discovery pages/tools/text and redirect/resume bounds are finite and +validated before I/O. Overflow is a structured failure or incomplete discovery, +not a successful dropped message. Cancellation and every terminal path abort I/O, +disconnect Client and join the owned work. Finite process/URLSession cleanup +budgets are additional to the protocol deadline. Unconfirmed cleanup prevents +complete success. Internal outcomes contain bounded private text values for the +caller to redact; they have no automatic serialized representation. + +`MCPTestProcess` and the owned loopback HTTP fixture exercise real wire, process, +origin, deadline and resource-cleanup behavior in ComponentsTests. They do not +use external services or execute configured third-party clients. + +Components' package-only `SourceCatalog` enumerates one explicit source and discovery +root using temporary snapshot acquisition, existing skill/instruction readers, +producer export linking and native import adapters. Inspection-bound IDs identify +representable units; exported groups keep symbolic uses and complete producer-owned +closures. Native registration and component expansion are explicit choices, including +empty containers. Opaque registration requires the exact container name from adapter +metadata; unresolved requirements remain visible and cannot be selected. Member +units carry typed kind selections and byte-exact sibling exclusions. Importer +keys retain the adapter's complete family effects, fixed contributions, requirements +and separate producer selection claims. Captured content and paths remain source- +relative; borrowed extraction URLs never escape. Empty selection yields no addition. +Destination-bound composition, pin protection and publication remain in AgentsUpdates; +the package catalog does not create update requests. + ## AgentsUpdates +`MCPRegistry` reads MCP Registry v0.1 pages and exact server versions. Request +credentials stay in the registry's in-memory HTTP transport. Each returned choice +captures a portable configuration. Selection admits explicit recipients through +the same native transport and binding rules used by lowering, then captures a +finite addition to the inspected destination. Ordinary preparation publishes the +declaration and native configuration through the scope transaction. +See [MCP registry](../Reference/MCPRegistry.md) for the API and supported choices. + +`MarketplaceOperations` publishes immutable release directories and static +indexes, browses local, Git and HTTPS catalogs, and verifies selected bundle +bytes. Hosted resolutions retain verified archives and their request provenance +in the graph lock for offline replay. Bundle +import owns the archive format and staged sources. Updates binds the +importer's producer aliases to the selected coordinate and records the +package pin alongside the frozen graph in the scope transaction. See the +[marketplace reference](../Reference/Marketplace.md). + +`UpdateOperations.inspectSource` exposes inspection-bound source choices, linked +closures, adapter key effects, fixed contributions and typed missing inputs. +`SourceCatalogInspection.select` composes a finite addition through the captured +scope destination. Empty selection returns nil without acquiring a source or +creating a request. Exported groups remain symbolic; plugin member selections +compose into one components declaration per container, and native registration +remains indivisible. Adapter selections rerun the owning converter with its real +keys and retain independent raw-resource admission. Source evidence is revalidated +at selection and preparation, including original documents behind inline imported +intent. Public inspection values contain no borrowed extraction URLs or runtime +environment/private freshness observations. The ordinary request retains exact +protected pins and destination identity through preview, reprepare and apply. + `UpdateOperations.preview` plans all declared skills, instruction targets and prompts under one shared scope lock. `withPreparedUpdate` holds one writer lock through preparation and the synchronous consumer closure. Its @@ -258,12 +479,15 @@ lock through preparation and the synchronous consumer closure. Its retained or reused handles fail before I/O after closure exit. Reports cannot be reconstructed into applicable plans. -Package-visible `SkillUpdatePlan` and `InstructionUpdatePlan` own discovery, -reports, preconditions, retention and staging for their domains. Standalone -updates use those same plans and preserve the other domain. Neither domain -depends on the other or on `AgentsUpdates`. The composition target merges -owned records and commits both kinds, changed state and cache pruning in one -`FileTransaction`; the skill-only consumer need not link Markdown. +`UpdatePlan` owns complete declaration linking, paired freeze, locked replay, +artifact aggregation, the v2 ledger and the one publication transaction. Domain +lifecycle methods are public extensions in Updates, so their consumers add an +`AgentsUpdates` dependency and import. The domain modules keep discovery, +frontmatter, rendering, inventory and diagnostic helpers. Restricted requests +protect the recorded other-domain semantics and independent direct pins. +Preview uses temporary acquisition; prepared callbacks remain inside both source +and replay resource closures. Shared native files are aggregated once per physical +destination, and reports expose selected owned changes only. See [combined updates](Updates.md) for callback restrictions, state-only changes, cancellation, failure dispositions and recovery. @@ -272,8 +496,11 @@ changes, cancellation, failure dispositions and recovery. Core tests cover source identities, declarations, lock validation, deterministic state, transactions, concurrency, requirements, mirrors, snapshots, hashes and -agent paths. Skill tests cover discovery, artifact formats and the full declared -lifecycle, including public consumer calls and failed-operation preservation. +agent paths. Transaction fault tests interrupt every publication and recovery +stage, including concurrent creation of an absent destination and external +replacement of existing targets and recovery paths. Skill tests cover +discovery, artifact formats and the full declared lifecycle, including public +consumer calls and failed-operation preservation. Fixtures create isolated homes and explicit Git initial branches and remove their temporary roots. Instruction tests cover the instructions file format, generation, link checks, Claude forwarding and ChatGPT rendering through public diff --git a/Documentation/Architecture/README.md b/Documentation/Architecture/README.md index b953f61..27a4af1 100644 --- a/Documentation/Architecture/README.md +++ b/Documentation/Architecture/README.md @@ -1,12 +1,21 @@ # Architecture This directory holds the current truth for `core`, a SwiftPM library package. -`AgentsCore` owns shared sources, declaration and lock storage, cache, watch subscriptions, and agent locations; -`AgentsSkills` owns skill discovery and lifecycle operations and depends on -`AgentsCore` and Yams. `AgentsInstructions` owns instruction lifecycle and text -transformations. It depends on `AgentsCore` for sources and state, and on -`swift-markdown` for CommonMark structure. `AgentsUpdates` composes both domains -above those modules. Tests follow those module boundaries. +`AgentsManifest` owns YAML admission, scalar resolution, schema validation, +source maps and lossless edits for the complete typed declaration. It plans +writes through `StateStore`, whose file I/O stays in core. `AgentsCore` owns +syntax-independent declaration IR, spans, provenance, shared sources, +declaration bytes and lock storage, cache, watch subscriptions, and agent +locations, without knowing the declaration format. `AgentsSkills` owns skill +discovery and lifecycle operations and depends on `AgentsCore`, +`AgentsManifest` and Yams. `AgentsInstructions` owns instruction lifecycle and +text transformations. It depends on `AgentsCore` for sources and state, +`AgentsManifest` for the declaration, and `swift-markdown` for CommonMark +structure. `Components` links exact source exports through package readers above those +modules. `AgentsUpdates` composes the existing skill and instruction lifecycle. Tests +follow those module boundaries. `NativeDocuments` supplies package-only native +JSON/JSONC/TOML inspection and ownership-checked byte edits, backed by the +internal TOML semantic validator and pinned CST grammar. ## Belongs Here @@ -25,6 +34,7 @@ above those modules. Tests follow those module boundaries. ## Current Files - `Package.md`: library products, module boundaries, and public workflows +- `NativeDocuments.md`: native byte inspection, ownership evidence and regional edits - `State.md`: declaration, resolved state, source cache and installation invariants - `Instructions.md`: instruction discovery, targets, lifecycle, prompts and diagnostics - `Watch.md`: subscription operations, upstream comparisons and seen-state retention diff --git a/Documentation/Architecture/State.md b/Documentation/Architecture/State.md index 262c834..d9d4295 100644 --- a/Documentation/Architecture/State.md +++ b/Documentation/Architecture/State.md @@ -4,161 +4,671 @@ | Scope | Declaration | Lock | Watch state | Cache | | --- | --- | --- | --- | --- | -| Project | `.agent/agents.json` | `.agent/agents.resolved` | `.agent/agents.watch` | `.agent/cache/` | -| User | `~/.agents/agents.json` | `~/.agents/agents.resolved` | `~/.agents/agents.watch` | `~/.agents/cache/` | +| Project | `.agent/agents.yaml` | `.agent/agents.resolved` | `.agent/agents.watch` | `.agent/cache/` | +| User | `~/.agents/agents.yaml` | `~/.agents/agents.resolved` | `~/.agents/agents.watch` | `~/.agents/cache/` | -User paths are relative to `RuntimeEnvironment.homeDirectory`. State files belong -to their scope. A project may commit its declaration and lock; the cache, the -writer lock and the journal stay local. `agents.watch` stores subscription baselines -independently of installed pins; [Watch](Watch.md) describes the operations. +User paths are relative to `RuntimeEnvironment.homeDirectory`. State files +belong to their scope. A project may commit its declaration and lock; the cache, +the writer lock and the journal stay local. `agents.watch` stores subscription +baselines independently of installed pins; [Watch](Watch.md) describes the +operations. ## Declaration -`agents.json` records user intent. `agents` defaults to `codex` and -`claude-code`. Source aliases name exactly one `git`, `local` or `well-known` -location, an optional requirement, and an optional search `path`. A source added -by location keeps the alias already declaring it, or receives its location's last -path component; while another source holds that name, preceding components are -prefixed (`anthropics-skills`), then a number is appended. `sources` may be -omitted. - -`agents.json` and `agents.resolved` are written with sorted keys in Prettier's -default JSON layout: two-space indentation, `"key": value`, every non-empty -object expanded, empty containers as `{}` and `[]`, and an array without objects -on one line when it fits in 80 columns. A repository whose Prettier -configuration uses another print width may lay out an array between the two -widths differently. An operation that writes state rewrites either file when -its bytes differ from that layout, even when its content is unchanged. Empty -lock sections such as `"skills": {}` remain, because earlier readers require -them. Journals, `agents.watch` and content hashes keep the encoder's fixed -layout. - -```json -{ - "agents": ["codex", "claude-code"], - "sources": { - "team": { "git": "github.com/example/skills", "from": "1.0.0" }, - "drafts": { "local": "~/Developer/skills" } - }, - "skills": { - "team": { "select": "all", "exclude": ["retired"] }, - "drafts": { - "select": ["release-notes"], - "mode": "edit", - "overrides": { "release-notes": { "agents": ["codex"] } } - } - } -} +`agents.yaml` records user intent in the [manifest +language](../Reference/Manifest.md). The document is the declaration's only +truth. `AgentsManifest` parses and validates its bytes and projects them onto +`AgentsCore.Declaration`, the complete typed symbolic intent with no serialized +form. Ordered sources, components, groups, uses, exports, prompt sections and +parameters retain their occurrences. Conditions, native values, runtime bindings +and source declaration directories remain data for later linking. `AgentsCore` holds the declaration's bytes and evidence, the +absent-declaration rule and publication, and knows no syntax; `AgentsManifest` +extends `StateStore` with declaration reading, planning and loading. Parse, edit +and deployment-boundary failures are `ManifestFailure` diagnostics located in the declaration +file. + +```yaml +version: 1 +sources: + drafts: {path: ~/Developer/skills} + team: + url: https://github.com/example/skills + requirement: {from: "1.0.0"} +components: + - kind: skills + source: drafts + select: [release-notes] + mode: edit + overrides: {release-notes: {agents: [codex]}} + - {kind: skills, source: team, exclude: [retired]} ``` -A skill selection is `"all"` or a name array, with optional exclusions, -recipients, mode and per-skill overrides. `all` follows discovery membership on -an unnamed update. Removing a member adds an exclusion. Explicitly named -updates resolve only those members and fail if a requested member is missing. -Skill filesystem identities are unique within a scope across sources. - -Requirements encode as `branch`, `revision`, `exact`, `from`, `upToNextMinor`, -or `from` plus `to`. Ranges include their lower bound and exclude their upper -bound. A prerelease requires a prerelease bound with the same major, minor and -patch. With no requirement, resolution chooses the latest semantic-version tag, -then the source's default branch when no version tag exists. +### Complete declarations + +`loadDeclaration()` projects every declared component family, including MCP, +hooks, subagents, commands, LSP, permissions, ignores and plugins. It preserves +unused groups and inactive structures and never resolves sources, reads resources +or runs component programs. `Declaration.sourceDeclarations` and `components` +are the ordered owners; alias dictionaries and the flat skill/instruction accessors +are derived views. Source aliases retain their declaring project and home +directories so importing code cannot reinterpret their relative paths. + +`AgentsUpdates` links the complete declaration, including group uses, conditions, +producer restrictions and native payloads, before choosing concrete deployments. +Concrete adapters own supported schemas and registered routes. A missing mapping +or route is an explicit preparation error, not a declaration-reader restriction. + +`Declaration.skills` and `instructions` are throwing root-selection views: they +reject multiple matching occurrences. `setSkills`, `setInstructions`, +`updateSkills` and `updateInstructions` serve unambiguous root selections and +preserve unrelated components. Full occurrence edits use `components`, group +payloads and typed section references directly. `Declaration.validate(environment:)` +checks source identities using the aliases' declaring directories and validates +skill and instruction references. + +`defaultAgents` defaults to `codex` and `claude-code`. Explicit recipients, +including an empty array, replace the default; the projection keeps omitted and +empty recipients distinct. A source added by location keeps the alias already +declaring it, or receives its location's last path component; while another +source holds that name, preceding components are prefixed (`anthropics-skills`), +then a number is appended. + +A skill selection is all members, when `select` is omitted or `all`, or an +explicit name array, with optional exclusions, recipients, mode and per-skill +overrides. An all-member selection follows discovery membership on an unnamed +update. Removing a member adds an exclusion and uses recorded membership without +installing newly discovered members. Explicitly named updates resolve only those +members and fail if a requested member is missing. Physical skill targets have one +compatible owner; distinct sources may serve the same name at disjoint targets. + +Requirements are `branch:`, `revision:`, `exact:`, `from:` (up to the next +major version), `upToNextMinor:` or `{from:, to:}`. Ranges include +their lower bound and exclude their upper bound. A prerelease requires a +prerelease bound with the same major, minor and patch. With no requirement, +resolution chooses the latest semantic-version tag, then the source's default +branch when no version tag exists. Source IDs are Git `host[:port]/path` with a lowercase host and without user, scheme or `.git`; `local:` plus an absolute path; or a well-known URL retaining its scheme. Declaring two aliases for one normalized ID is an error. -`instructions` holds recipients, ordered section references (`alias:name`, or a -bare name for the project's own instructions), and -named `chatgpt` prompts with ordered sections and optional relative `append` -paths. `watch` is a unique alias array. Skill operations preserve both fields -and existing watch-state bytes. - -## Lock - -`agents.resolved` version 1 has identity-keyed `sources` and `skills`, and an -`instructions` object containing `sections`, `chatgpt` and `targets`. - -A locked source records its kind, Git URL where applicable, requirement and -search path. A skill records its source ID, its own revision and optional -version, relative directory path, content hash and `installs` mapping agent IDs -to `link`, `copy` or `edit`. Every non-edit item carries an immutable pin. -Updating one skill leaves other item pins unchanged. - -Well-known items record an artifact's `type`, `url` and SHA-256 `digest`. -`files` artifacts additionally record every file's URL, path and digest. Their -aggregate digest covers the sorted, deterministically encoded file records. -Restoration reads these recorded URLs or verified digest cache entries and -never reads an index. Missing pins or mismatched content stop restoration. - -Instruction section records carry name, source, revision or artifact, path and -hash; a project's own files use source `.`, their project-relative path and hash, -and no revision. Prompts hold ordered locked sections and optional append paths. -Physical targets record agents, heading offset 0 or import, the hash of the -generated file or import block, and `created`, which unit targets always record -as false. Skill writes retain these records unchanged. -Instruction lifecycle writes preserve skill records. Target keys are project -relative or user-home relative; configured user files outside home use absolute -keys checked against the runtime's registered instruction locations. - -Maps are key sorted. Unordered selections and agent lists are sorted; section -arrays and each prompt's section order are preserved. Files have a trailing -newline and no timestamps. State and journal JSON must be UTF-8 without a byte -order mark; validation consumes the entire document. Other encodings, invalid -state, duplicate JSON keys at any depth and -fields that would be discarded by decoding cause an error. Tree hashes use -length-prefixed paths and typed entry payloads, including empty -directories and symbolic link destinations. - -Tree hashes intentionally exclude permissions. Skill update snapshots compare -the any-execute-bit Boolean separately for regular files. Preparation, -retention and transaction staging verify that dimension without changing -stored hashes, pins or the version 1 declaration, lock and watch schemas. +The `.instructions` component holds recipients, ordered section references (a +bare string for the project's own instructions, `.section(name:source:)` for a +declared source), and named `chatGPT` prompts with ordered sections and optional +relative `append` paths. `watch` is a unique alias array. Skill operations +preserve both and existing watch-state bytes. + +### Absent declaration + +| Declaration | Lock or watch state | Behavior | +| --- | --- | --- | +| Absent | Absent | An empty declaration. Reads return empty results; the first write that declares something creates `agents.yaml` with no-replace publication. A write whose declaration and resulting lock are both empty creates neither file. | +| Present | Any | Normal. An absent lock is an empty resolved state. Declared marketplace packages require committed pins before restore. | +| Absent | Present | The state cannot be used. Throwing APIs report `CoreError.missingDeclaration` with the declaration path; export returns `.unavailable`, and batch doctor reports a `.stateUnavailable` diagnostic for the affected scope. Nothing is written, and no `.agents.lock` is created. | + +Read paths apply the rule after their pending-recovery check, and writers after +transaction recovery. Before taking the writer lock, a writer in a scope without +`.agents.lock`, journal or pending watch-reference marker validates the lock and +watch state and checks only the declaration's presence. An interrupted first +write of the declaration and lock therefore recovers on the next write instead +of reporting a missing declaration. Watch state counts because its baselines +derive from the declaration; treating a missing declaration as empty would let +the next update remove what was deployed. + +### Declaration writes + +Every declaration write passes through two entries. +`planDeclaration(_:replacing:prepared:)` in `AgentsManifest` compares the next +declaration with the previous one the operation read from the same prepared +baseline. It returns no change when they are semantically equal, and otherwise +bytes that passed the complete front end and the projection check. +`stageDeclaration(_:in:prepared:)` in `AgentsCore` publishes those bytes in the +operation's transaction, expecting the baseline's evidence for the declaration. +Skill, instruction, watch and update writes use only these entries; adding or +changing a source is a difference in the declaration's sources. Combined and +skill updates leave the declaration unchanged; the transaction still checks its +prepared evidence through `FileTransaction.requireUnchanged(since:)` before +publication. + +Planning completes before `beforeApply`, cache retention, a watch's Git fetch +and any staging, so an edit that cannot be addressed exactly fails without side +effects. When the previous declaration differs from the projection of the +baseline bytes, planning reports a stale preparation, +`CoreError.invalidState("declaration changed during preparation: ")`, +rather than overwriting an external change. Under the scope writer lock, a +later writer reads its own baseline and plans again, so concurrent writers lose +no update. + +Semantic equality decides whether anything changes: + +- sources are equal when identity, requirement and normalized subpath are + equal, so URL spelling, relative or absolute local paths and range spelling + never cause a rewrite; +- recipient arrays compare as sets, with omitted and empty distinct; +- omitted and empty exclusions, overrides, prompts, watch lists and skills + components are equal; +- components, source aliases, groups, uses, exports, sections and prompts compare + in order; conditions, symbolic references, runtime bindings and native values + all participate. + +Planning edits direct fields, dictionary members and ordered occurrences. Core's +skill/instruction convenience mutations retain their insertion order. Repeated +ambiguous selections require an occurrence-addressed `ManifestEdit`. The editor +changes owned ranges and retains comments, while unrelated bytes stay exact. + +Complete changes use one direct IR edit script throughout composition. Each array +step fixes the next target position or removes a surplus occurrence; each field is +visited once. Its finite operation bound is twice the combined current/target +value-node counts. Batches contain at most 100 operations and are sized against +actual editing work. Private drafts refresh the CST/source map and compare the +complete expected IR after every operation. Domain references can transition +across internal batches. Final normal domain validation, environment-aware typed +projection and full intended-IR comparison precede returning bytes. Public +prepared changes always validate final domain, including no-ops. No draft enters +state storage or a public change. + +Without declaration bytes, planning prints the complete typed declaration with the +[YAML writer](../Reference/Manifest.md#edits-and-source-maps), retaining its +ordered collections and symbolic group uses. Dictionary-based convenience +initializers and domain mutations choose deterministic order for new entries. +First state-declaration creation sorts only the set-like watch aliases; pure +construction retains input order, and equivalent watch reorders in existing +documents preserve their bytes. +The printed bytes pass the same front end and projection check and are published +with no-replace. A semantically empty declaration creates no file. + +One transaction covers the declaration, lock, affected watch state, installation +targets, cache retention and pruning; a declaration-only change uses the same +journal and evidence. The declaration is published only as planned source bytes, +while the lock and watch state keep their own encoders. Preparation records +presence, physical identity and byte digest for the declaration, lock, watch +state and related targets. A changed comment, or another inode with equal bytes, +therefore invalidates a prepared preview, and a declaration created externally +after preparation is an existence conflict that keeps the external file. + +### Requirement comparison + +Semantic comparison expands range requirements to their bounds; raw case or +encoded-field equality is insufficient. Branch and revision compare their +strings, exact versions compare normalized full versions, and absence keeps its +distinct latest-tag/default-branch policy. Canonical spelling applies to new IR +and newly serialized requirement fields. + +| Site | Rule | +| --- | --- | +| Declaration IR and dump | Canonical requirement kinds and normalized version strings; a factory and a literal range with equal bounds compare equal. | +| Declaration writes and `upsertSource` | Semantic values are compared; an equal edit keeps the original source bytes. New or changed nodes print canonically; untouched spelling is retained. | +| `LedgerSourceUse.requirement` in the ledger | Newly written records use canonical requirements. Existing records keep their bytes and are compared through a semantic view. A requirement-spelling difference alone never changes pins, reports an update or stages a write. | +| Linked component pins and change detection | Source identity, discovery root and semantic requirement values are compared; equal ranges have equal meaning. A semantically unchanged lock keeps its original bytes even when another state file changes; a necessary rewrite emits canonical requirements. | +| Resolution-session reuse and cache descriptors | Requirements are keyed by semantic value. Cache identity and materialization keys use source identity and exact revision or artifact digest; restoration uses the stored pins without re-resolving requirements. | +| `agents.watch` | Stores source identities and seen baselines, with no requirement. Re-evaluating an equivalent declaration preserves the subscription and baseline; watch-created lock descriptors follow the lock rule. | + +State transactions compare semantic state before choosing any serialization and +never rewrite records on read. + +## Resolved ledger + +`agents.resolved` is a version 2 JSON ledger. It records exact sources and source +uses, symbolic components, ordered occurrences and group dependencies, complete +resources, ownership, deployments and versioned lowerings. Marketplace pins record +exact declared catalog/package/version selections, acquired archive digests and +the imported component closure. Local and artifact +resources retain deduplicated non-secret content objects; Git resources retain +exact acquisition coordinates and commits. Trees record empty directories, +symlinks and execute flags. Runtime bindings remain symbolic. + +The codec accepts one ledger version and rejects unknown fields, duplicate keys, +invalid references, unsupported versions and corrupt content objects. Admission +bounds bytes, depth, nodes, entries and decoded content before object decoding. +Equivalent state preserves the original bytes. Newly encoded state is deterministic +JSON with sorted map keys, meaningful array order, a trailing newline and no time +or machine-temporary fields. Journals and watch state keep their own encoders. + +`StateStore.loadResolved()` supplies the existing skill/instruction inventory view +by projecting the ledger. This view is not a second stored graph and is never +saved as a lock. Native components and dependency relationships remain in the +ledger. Listings, diagnostics and watch validate the same committed generation. +An unconfigured empty scope needs no resolved file; a declaration-backed empty +ledger remains valid. + +Updates link the complete declaration and freeze one paired source result before +lowering. Restore uses only locked format/layout/resources and verifies every +rendered artifact. It never selects current producer requirements or refs. +Embedded inputs can reconstruct without their authoring tree; live edit skills +remain explicit live locations. Regional ownership is distinct from whole-file +freshness, and existing unmanaged equal values do not grant ownership. + +`RetentionReferences` derives the complete source/resource closure, including +empty groups, container parents, other component domains, watch pins and live +locations. The last skill's removal cannot prune resources still referenced by +instructions, native components or watch. New materializations and pruning share +the configuration transaction. Source ref cleanup follows the committed closure +only after physical commit or recovery. + +Tree content hashes exclude permissions. Resource entries and staging separately +verify regular-file execute flags. Pinned resource bytes, modes and locked renderer +outputs must agree before publication. + +## State Transaction and Recovery + +The scope's `transaction.json` is the sole persistent transaction owner for +installation targets, declaration, lock, watch state, cache publication and +pruning. Its protocol accepts regular files, directories and symbolic links +independently of the declaration format. The declaration is published as the +source bytes its plan produced; the lock keeps its state encoder and watch state +its fixed encoder. + +### Preparation and preconditions + +Prepare captures presence, physical identity and content digest for declaration, +lock, watch state and affected targets. `TargetPrecondition`, `PathIdentity` and +`StatePrecondition` in `UpdatePreconditions.swift` bind those snapshots and +existing ancestry. Directory target snapshots include descendant identities. +Linked non-edit content is checked separately from its link; live edit content +remains live. Domain plans also validate source content and executable flags. + +The scope writer lock covers recovery, preparation, retention and publication. +Recovery runs first. Apply checks the prepared evidence before retention, after +retention at commit entry, and after staging before publication. The journal's +expected preimages are the evidence the plan captured. Watch subscription, +acknowledgment and removal capture declaration, lock and watch state before +contacting Git; that evidence is also the baseline for the lock that pruning +follows. Transactions without a state plan, such as cache publication, do not +implicitly add declaration, lock or watch preconditions. Domain hooks check +related inputs that the journal does not replace. State parsing consumes the +captured raw bytes, so decoded inputs and journal evidence describe the same +generation. + +Changed bytes, including declaration comments or whitespace and target comments, +invalidate preparation. Another inode with equal bytes also invalidates a +captured target entry or directory descendant. Apply requires a newly prepared +plan and never rebases an old edit onto changed inputs. Readers and writers serialize through `.agents.lock`. Missing scope and target -ancestry is created with descriptor-relative operations; each parent directory -is fsynced before target mutation, including when an interrupted creator left a -visible directory entry. Empty managed containers can remain after a failed -operation. - -A durable `transaction.json` in the scope state directory records target, state -file and pruning replacements before mutation. Paths are relative to named -roots in that scope: `state`, registered agent installation directories, and -registered instruction destinations. Instruction roots permit fixed project -files, configured user files and named Markdown files in the project's own -instructions container. The -journal binds the state directory and each used root to its physical location -and filesystem identity. Configured agent containers are resolved at the -registry boundary; recovery opens journal descendants without following links. -Symlinked journals, symlinked descendants, unregistered destinations and journals -copied or moved from another scope location are rejected before replay. All -parents are validated and their directory descriptors retained throughout -recovery. Backup and staging basenames are derived from the transaction ID, -never accepted as arbitrary journal paths. - -Backups and staged data are fsynced before applying changes. macOS `fcopyfile` -preserves original bytes, permissions, ACLs and extended attributes in backups -and restores. Data replacements inherit the existing regular file's metadata -from its backup before publication; new files default to `0600`. Final modes -are applied explicitly rather than through the umask. -`renameatx_np(RENAME_SWAP)` atomically exchanges existing directories, files and -links with their replacements; installations always retain a directory entry. -Discarding transaction-owned trees grants owner access through pinned directory -descriptors so read-only backups and staging can be removed. This never changes -the metadata of the installed or restored tree, nor of a backup still needed -for rollback; symbolic links are unlinked without following their destinations. - -After a process kill or power loss at any point, the next mutating state access -recovers one consistent generation of targets, declaration, lock, watch state and -cache references. +ancestry is created with descriptor-relative operations. Parent directories are +synced before target mutation, including when an interrupted creator left a +visible entry. Empty ancestor directories can remain after a failed operation. +Successful managed directory creation uses mode 0700; files and locks use 0600. +Final file modes are set explicitly rather than inherited from the process +umask. Copies preserve their source modes, ACLs and extended attributes. + +Directory permissions, inherited/default ACLs and other filesystem policy must +allow owner access to newly created entries. Core checks that access without +repairing the policy. Permission denial reports the affected path and asks the +owner to check directory permissions and default ACLs. Retrying does not bypass +the denial. Existing user content and metadata are preserved. + +### Journal records + +Journal format version 3 is independent of the manifest language, lock and watch +versions. +The root records its version, transaction UUID, scope identity, registered root +identities, transaction phase, operations, private containers, disposal +intent, shared physical footprint, reservation readiness and terminal finalization. A journal without this version, or with another version, is retained +unchanged. Recovery reports that it was written by another version and must be +recovered with the version that wrote it; it does not guess a compatible replay. + +Paths are relative to named roots: scope state, registered agent installation +directories, registered instruction destinations and closed native routes. +Shared metadata destinations are derived by Core and cannot be requested as ordinary targets. The journal binds the state +directory, each root and every destination parent to its physical location and +identity. Registry boundaries resolve configured containers; descendants open +without following links. Symlinked journals or descendants, overlapping targets, +unregistered paths and copied or moved journals are rejected before replay. +Directory descriptors remain pinned. + +Each operation records its path, install/delete action, expected preimage or +absence, parent identity, private container, sealed staged object, progress and +any conflict reason and retained locations. Object evidence contains device, +inode, type, SHA-256 digest, permission bits and executable status. Directory +evidence includes child identities and digests. Ordinary data replacements inherit the +existing regular file's metadata. Known sensitive files use private construction +for replacements, including ordinary byte edits. Undo restores the original object and its +metadata. + +Each used target parent has one private container with a UUID-derived name and +mode 0700 on the same filesystem as its targets. The journal records the name +before `mkdir`, then records the container's physical identity before inserting +anything. Probes, extraction work and staging stay inside it. An identified +container owns all construction before publication: incomplete objects can be +disposed of as a whole without individual ownership evidence. Another writer has +no ownership claim on content inserted into this private transaction storage. An +unidentified container may only be removed with `rmdir` when empty; a nonempty +one is an unresolved conflict. + +Construction is sealed once, and sealing is its only journal write. Snapshot and +content verification consume the same read bytes, and check the expected content +hash and executable flags. `ready` and that snapshot become durable together. +Changes after sealing are conflicts; recovery never refreshes a sealed snapshot +to adopt changed content. + +Container entries are named by operation index and slot. `staged` holds a +creation's private staging. `exchanged` holds an exchange's private staging +until publication, then the displaced preimage, and after undo the published +object exchanged back out. `deleted` holds the object a deletion moved aside, +and `withdrawn` holds a published creation that undo moved aside. Displaced +preimages, the contents of `deleted` and `withdrawn`, and published objects are +user data. Their identity and digest remain mandatory evidence even inside a +private container. A container holding such slot objects receives complete +terminal disposal evidence after their expected distribution has been verified. + +| Progress | Durable evidence and possible distribution | +| --- | --- | +| `queued` | Expected preimage and container name; construction is private and unsealed. | +| `ready` | Verified staged snapshot for an install; no publication intent. | +| `publishing` | Publication and temporary directory-write intent; objects can be prepared or installed. | +| `applied` | Rename parents and original directory modes synced; postimage and preimage verified. | +| `restoring` | Undo and temporary directory-write intent; installed or reverted objects can be present. | +| `restored` | Undo parents and original modes synced; restored target and remaining slot objects verified. | +| `cancelled` | Original modes restored; publication did not consume private staging. | + +One operation-type/progress table defines every expected target and recovery +slot. Publication validation, rollback classification and disposal preparation +use that table. Before durable disposal intent, every expected slot object must +exist and match; absence cannot be treated as completed disposal. + +Journal publication orders the new journal file barrier before rename, then the +parent directory barrier. Ordinary preimage files are synced once with their +parent barrier; tree synchronization syncs file contents and concentrates each +level's directory barrier after its children. On macOS a synchronization barrier +also uses `F_FULLFSYNC` to request a storage flush. + +### Publication and concurrent writers + +Atomic exchange and no-replace rename are checked before modifying any target, +preimage or state file. Before this check the transaction can only create +missing ancestry, its journal and its private containers. Probes run on +container objects on the actual publication device. A successful result is +cached by `st_dev` only for the rest of that commit; every commit probes its +devices again, because a device number can be reused after an unmount. +Unsupported primitives remove the journal and containers; empty missing ancestry +may remain. There is no replacing-rename fallback, including for declaration, +lock and watch creation. + +Only `EINVAL`, `ENOSYS`, `ENOTSUP` and `EOPNOTSUPP` mean unsupported. `EEXIST` +and `ENOTEMPTY` mean an existence conflict. Other failures retain their errno +and system reason. Probes and publication use the same classification. + +| Expected destination | Publication | +| --- | --- | +| Absent | Persist the sealed inode and digest, then move it from the container with Darwin `renameatx_np(RENAME_EXCL)` or Linux `renameat2(RENAME_NOREPLACE)`. A concurrent creator keeps its bytes and inode. | +| Existing | Recheck the preimage, then exchange it with staging using Darwin `RENAME_SWAP` or Linux `RENAME_EXCHANGE`. The displaced object stays inside the container and is compared before confirmation. A mismatched preimage is retained as a conflict. | +| Deletion | Move the entry without replacement into the container's `deleted` slot, then verify its physical identity and digest. Disposal verifies that evidence again. | + +Each operation checks its preimage before and again after its publication intent +becomes durable; a preparation already stale before the intent cancels from +`ready` without leasing or moving any object. Publication intent is durable +before rename. Both container and target parent are synced before `applied` +becomes durable. Replacement always retains a directory entry at the +installation path. The operation's complete target and recovery-object +distribution must match before confirmation and again before the commit marker. +The scope lock excludes cooperating writers; the atomic protocol also preserves +objects changed by editors that ignore it. + +Read-only directory targets retain their final modes. Darwin and Linux require +write access to a directory to move it between parents, because the rename +updates its `..` entry. Before granting owner-write on a recorded inode, +`publishing` or `restoring` intent and the original permission bits are +durable. The transaction syncs the temporary mode, performs the atomic rename, +then restores and syncs the original mode before recording `applied`, `restored` +or `cancelled`. Only the recorded mode or that mode plus owner-write is admitted +while intent is active. Other modes and other inodes remain conflicts; ACL and +ownership denials are reported rather than bypassed. + +### Recovery outcomes + +Every mutating state operation first checks for an abandoned journal under the +scope lock, after taking any journal/request shared physical locks, validates watch state and finishes pending reference cleanup before +proceeding. Recovery never reads the declaration: journal and watch-reference +recovery complete even when `agents.yaml` does not parse, and orphaned mirror +locations come from watch state and the lock, then from the mirror's origin. +Journal recovery selects and syncs a consistent generation before watch +reconciliation can release any ref. Pending watch-reference recovery also +reports `CoreError.transactionRecovered` when no journal remains. Retained refs +remain available while a journal conflict is unresolved. + +Recovery treats any observed `transaction.json` as possibly renamed without its +directory barrier: before granting permissions, renaming objects or deleting any +resource it syncs that file and its parent, including on retry. A lone unstarted +`transaction.new` owns no object and is discarded directly. An applying journal +reverses verified publications in reverse order. A committed journal completes +terminal disposal. Physical identity and digest distinguish a transaction's +publication even after rename but before `applied`. Another inode with identical +bytes remains external. Missing or changed evidence causes an unresolved +conflict; names and equal bytes never establish ownership. Other verified +operations can roll back while conflicted objects remain available. + +Replacement undo exchanges a retained preimage only with the verified published +object and verifies the displaced object. An external replacement before or +during undo leaves both available versions and stops recovery. Deleted entries +return with no-replace rename, preserving an occupied original name. Creation +undo moves only a verified published object into its `withdrawn` slot and checks +it there. A retry recognizing an interrupted reverse rename repeats both parent +barriers before recording restoration. + +Interrupted permission changes are restored by recorded inode, independently of +payload rollback. Changed payload bytes remain available. Restoration repeats the +mode barrier even when the original mode is already visible. A recorded directory +inode missing from every location the operation/progress table allows, or a mode +outside the original/temporary pair, leaves an unresolved conflict with the +original mode and intent retained. + +Before disposal the journal persists terminal `committed` or `rolledBack` state +and the complete recovery-object evidence. A commit disposes immediately after +sealing that evidence; recovery first revalidates every target and container +against it. A separate global disposal intent then becomes durable. Only after +that intent may missing objects or descendants mean interrupted disposal. +Changed identities, digests or unexpected descendants in sealed disposal +evidence remain conflicts. Unpublished private construction is disposed of by +verified container identity. Links are never followed during deletion. Owner +access may be granted to directories being disposed of without changing +installed or restored metadata. Absent entries still receive a parent barrier. + +After every container disposal barrier, the terminal journal durably records +`finalized = true`, retaining its `committed` or `rolledBack` phase. Only then +may it remove its reservations, sync their parents and remove the scope journal. +Recovery and diagnosis dispatch finalized records before constructing data roots +or parents: they validate scope and required coordination metadata only. Recovery +removes only that journal's metadata; diagnosis reports the terminal result and +pending cleanup without writes. A later writer's target, receipt and reservation +are left untouched, even when old data parents no longer exist. + +Conflicts retain `transaction.json`, the available target objects and private +containers holding user data in their slots. Each conflicting entry records the +reason and scope-relative recovery locations. Doctor lists those reasons and +locations and asks for owner action; it does not promise that another write will +resolve them or provide a conflict-resolution command. + +Recovery can itself be interrupted and repeated. Successful recovery reports +`CoreError.transactionRecovered` and callers retry the whole preparation. +Outcomes distinguish unchanged, committed and unresolved recovery and belong to +their journal UUID: recovering a cache publication cannot mark a later combined +update committed. Failure after a commit marker can still be unresolved if +recovery material changed. A committed failure is never described as rollback. + +The public `StateStore.loadResolved()` and `loadWatch()` in `AgentsCore` and +`loadDeclaration()` and `loadManifest()` in `AgentsManifest` are read-only, as +described below; the latter two require `import AgentsManifest`. +`loadDeclaration()` returns the complete typed symbolic declaration; `loadManifest()` +returns the complete `DeclarationDocument`, or `nil` for a +scope without state. Both can also throw the declaration's `ManifestFailure`. + +### Private runtime materialization + +Package callers obtain a `MaterializationTarget` from `StateStore` and prepare it +with `preparePrivateMaterialization`. Core admits only its registered file paths; +source-authoring and arbitrary external paths are refused. Current registrations +cover existing instruction-file destinations and the verified Claude MCP project, +local and user physical routes. `nativeTarget(for:)` accepts a closed +`NativeTargetRoute`; it grants no arbitrary external destination or regional +ownership. Native adapters still own regional editing and capability validation. + +Callers pass the complete `footprint: Set` to the existing +`withLock` or `withReadLock` boundary and retain that context around preparation. +Pending journal footprints are independently included before taking the scope lock. Preparation captures the target's physical identity, UID/GID, mode and ordered +ACL evidence, together with every existing physical ancestor. It does not call a +binding provider or renderer. A permissive existing file requires the caller's +explicit `changingAccess` intent, as does an existing owner-only mode that differs +from the intended 0600 (for example, owner execute). The prepared `accessChange` exposes its before +access and intended owner-only mode for the caller's report. This is part of the +prepared mutation, without a separate approval record. Missing ancestors may be +created by the transaction; their final identities and access are sealed before +staging. Existing ancestry, ACL, ownership or permission drift invalidates the +preparation. The prepared `accessFingerprint()` is a non-secret segment for the +complete displayed candidate fingerprint: it covers registered target, intended +owner, access/ancestry evidence, effective permission-change intent and local +receipt generation, and excludes binding values and materialized content digests. +It does not replace the enclosing candidate fingerprint or apply-handle lifecycle. + +`FileTransaction.replacePrivate` queues a cold renderer and explicitly injected +`RuntimeBindingProvider` using the store's runtime environment. Binding names are +data, never commands supplied by a source. The same scope lock and sole journal +cover ordinary targets, private targets, declaration/lock updates and the local +receipt. Ordinary non-sensitive requests preserve their metadata behavior. A private +replacement uses its own independently sealed access rather than copying the +live target's metadata. Core verifies its private construction directory and an +empty owner-readable/writable file before resolving bindings or writing payload +bytes. It rechecks access before writing and publication. Arbitrary path-based +prepared producers are not a private materialization interface. Provider and +renderer failures have fixed diagnostics; returned values have no encoding and +redacted diagnostic/reflection representations. + +The private `materializations.json` file in the scope directory stores only +registered target coordinates, materialization generation, registered-root +identity, materialized digest and access evidence. It contains no binding values, +source closure or declaration model. It is updated in the same transaction as +the target. A later ordinary byte replacement keeps both preimage and replacement +sensitive, constructs the replacement privately before its first byte and updates +the receipt from the sealed generation without invoking a provider. Region deletion +retains whole-file sensitivity while a file remains; whole-file deletion removes +the record in the same journal. Copy, link and arbitrary prepared producers cannot +replace a known sensitive file. Direct caller writes to the receipt +are refused. Corrupt, permissive or stale receipts stop mutation rather than +silently downgrading a known sensitive object. `materializationReceipt(for:)` +returns only the local generation and access metadata. A caller that knows from +its prior symbolic deployment that an existing target was materialized must set +`requiringReceiptForExistingTarget`; a missing receipt then stops preparation. +`expecting:` also binds a known local receipt generation. These expectations stay +local; host materialization data does not enter the portable declaration or +ledger. A freshly observed absent target has no sensitive preimage and can be +restored or removed while its stale receipt record is reconciled atomically. + +Journal entries require preimage/replacement security classifications and the +necessary sealed access/ancestry evidence. Private container identity and access +are durable before payload construction. Missing security fields or older +journal versions require recovery with the writing version; there is no implicit +ordinary default or migration. Recovery consumes physical evidence only and +never invokes binding providers or renderers. Before restoring a sensitive +preimage, it verifies the destination ancestry, private container and preimage +access again, including after the restoration checkpoint. Unsafe or stale +access retains the journal and available private objects as a conflict. +Ordinary preimages keep their recorded metadata on rollback, including when a +private replacement had an explicit permission-change intent. Disposal validates +sensitive evidence before erasing retained objects. + +Linux assessment applies POSIX ACL masks to named and owning-group entries; +default ACLs are captured and inherited access is checked on the actual created +inode. macOS assessment preserves ACE order/inheritance, ignores inherit-only +ACEs for the current inode, and refuses active content/control grants or relevant +denials whose principal membership cannot be proved without directory-service +lookups. Unprovable layouts fail without repairing host permissions. Traversable +ordinary ancestors are allowed when trusted ownership and effective replacement +protection hold; sticky protection is bound to the child owner. Root and same-UID +adversaries are outside this boundary. Snapshot capture may retry a transient +stat/ACL generation race; retries never refresh prepared or sealed evidence. + +### Shared physical native targets + +Claude project MCP uses project `.mcp.json` and remains scope-local. Claude local +and user MCP use the same `.claude.json`: a nonempty supplied `CLAUDE_CONFIG_DIR` +selects its parent, otherwise the supplied HOME does. Overrides must be absolute +filesystem directories; ambiguous relative roots are refused. This global configuration +root is distinct from the ordinary Claude skills/settings directory. + +The opened parent's device, inode and kind plus the registered basename define +the coordination identity and total lock order. Pathname authorization and +freshness remain separate. HOME, route and path aliases do not split a physical +resource; replacing the file does not change its coordination identity. Private +metadata under that parent lives in `.agents-native//`, containing +a persistent `lock`, authoritative private `receipt` and transient `reservation`. +The receipt records one physical file's generation, digest, root identity and +access evidence. Shared files have no second authoritative scope receipt. +Metadata, lock, receipt and reservation access are verified through opened +nofollow descriptors. A conflicting or unprovable domain stops publication. + +Admission takes the union of requested routes and a bounded read of the pending +scope journal, deduplicates and locks shared resources in physical order, then +locks the scope. It rereads scope and footprint before any preparation callback. +An expanded footprint releases all locks and re-admits before callback delivery. +The thread-confined context spans preparation, apply, synchronous failure recovery +and disposal. Nested scope acquisition or upgrades are refused. Skill, +instruction, combined update and watch mutations use this same boundary even +when only a pending journal requires shared coordination. Unrelated read-only +scope data does not acquire an absent shared footprint. + +The sole scope journal durably records reservation intents before creating any +reservation slot. A journal-UUID-derived private temporary file is written and +synced, then published with no-replace rename and a parent barrier. All +reservations become durable before readiness and any target publication. A +half-written temporary slot is recognized by its exact durable intent and +verified private file metadata; cleanup does not decode partial bytes. Before +readiness, reservation-only recovery has no constructed data objects and disposes +only its intent-owned metadata. Unknown slots and malformed final reservations +are retained. Another scope reports the owner locator and journal UUID; it never +runs cross-project recovery or steals by PID, time or missing owner journal. +Ready non-finalized journals require their reservations to remain present. + +The kernel locks last through finalization and metadata cleanup. A finalized +owner may encounter a newer reservation and leaves it untouched. Read-only paths +use existing locks and create no coordination directories, lock files, receipts +or reservations. They diagnose pending recovery without replay. External native +clients do not participate in these locks: preimage, digest, identity and access +changes cause freshness conflicts rather than overwriting client siblings. + +E supplies the complete new/old deployment footprint and redacted composition; +F supplies exact owned-region edits and route semantics. These Core registrations +do not claim native parser, adapter or real-client acceptance. + +### Read-only access + +Configuration preview additionally keeps all source acquisition temporary and never +creates persistent cache or shared coordination locks, retains content or invokes +a runtime binding provider. Exact cached objects are reused only through existing +read locks; missing objects and extraction are cleaned on every exit. + +Non-applying skill and instruction operations, listings, previews, watch status +and watch diff take an existing shared lock, report pending recovery and never +replay it or create state files. With no lock, inspection rechecks for a new +lock or recovery marker before returning either its result or its error. A +writer causes that attempt to be discarded and retried under the shared lock. +Writers create the scope lock before mutation and never remove it. The scope +lock exists before the declaration is parsed, so a first writer that meets an +invalid `agents.yaml` reports its `ManifestFailure` after creating +`.agents.lock`; invalid lock or watch state stops the writer before the lock +exists. + +The `load*` accessors follow the same rules and never create `.agents.lock`. +Pending journals and watch-reference markers stop inspection with +`CoreError.recoveryPending`, whose description is the recovery diagnostic text +itself; a mutating operation on the scope performs the recovery. The +absent-declaration rule applies after this check. Doctor distinguishes pending +automatic recovery from an unresolved conflict requiring owner action, and skips +checks needing a consistent generation. Skill doctor uses `pending-recovery` or +`unresolved-transaction`; instruction doctor uses `pendingRecovery` or +`unresolvedTransaction`. Explicit multi-root instruction audits never write. +Corrupt or foreign-version journals remain available rather than being replayed. + +### Watch references and mirror locks + Mirror Git invocations pass `-c core.fsync=objects,reference,pack-metadata` and `-c core.fsyncMethod=fsync`; durability settings never rewrite configuration. -Mirror configuration must be a regular file, checked before invoking Git. -Before a Git acknowledgment publishes watch state, existing object bytes and -object directory entries are flushed as well. The retained ref, its parent, -Git config and HEAD, and mirror/cache directory entries are synced before the -scope journal can commit the baseline. This orders durable Git content before -the durable watch reference; power loss cannot publish a baseline ahead of its -retained content. +Mirror configuration must be a regular file, checked before invoking Git. Before +a Git acknowledgment publishes watch state, existing object bytes and object +directory entries are flushed as well. The retained ref, its parent, Git config +and HEAD, and mirror/cache directory entries are synced before the scope journal +can commit the baseline. This orders durable Git content before the durable +watch reference; power loss cannot publish a baseline ahead of its retained +content. Before preparing a watch ref or changing watch/lock pins, the scope writes and syncs `watch-refs.pending`. Under the scope lock, reconciliation runs only after @@ -167,35 +677,40 @@ consistent generation. It removes only `refs/agents-watch/` refs no longer named by watch state, skills, instruction sections or prompt sections. Loose-ref parents and packed refs are synced before the pending marker is removed and its parent synced. The marker survives interrupted preparation or -cleanup, so the next mutating access repeats reconciliation against the recovered -state; refs needed for rollback remain until that state is durable. +cleanup, so the next mutating access repeats reconciliation against the +recovered state; refs needed for rollback remain until that state is durable. Mirrors are exclusively owned by agents. Each mirror has a per-source lock at `cache/locks/.lock`, created before cloning or first access. All mirror reads and writes take this lock, including instruction listings and cached revision inspection. Doctor uses only existing mirror locks; when one is -absent, cached revision inspection falls back to remote refs without creating it. -Scope mutations take the scope lock first, then the mirror lock; mirror access never acquires the scope lock in reverse order. -An instruction listing can therefore populate a mirror before `.agents.lock` -exists while still excluding concurrent recovery and watch mutations. +absent, cached revision inspection falls back to remote refs without creating +it. Scope mutations take the scope lock first, then the mirror lock; mirror +access never acquires the scope lock in reverse order. An instruction listing +can therefore populate a mirror before `.agents.lock` exists while still +excluding concurrent recovery and watch mutations. + +Pending Git ref cleanup can leave mirror Git lock files that prevent safe fetch. +Recovery takes the mirror lock and validates and syncs their cleanup before Git +can proceed. Git children explicitly inherit a duplicate of the mirror lock descriptor allocated at 3 or above with `F_DUPFD_CLOEXEC`. Spawn file actions inherit that duplicate without changing the parent's close-on-exec flags. Output pipe sources also use descriptors above the standard streams before redirection; closed stdin is connected to `/dev/null` in the child. Unrelated descriptors remain closed, -and the parent closes the temporary duplicates immediately after spawning. -The parent closes its lock descriptor without explicitly unlocking the shared -open file description. If the Swift -parent is killed, a surviving Git child keeps the mirror locked until it exits. -Git automatic maintenance is disabled. Recovery must acquire this same mirror -lock before classifying Git `*.lock` files (including `packed-refs.lock`) and -the root `packed-refs.new` staging file as abandoned. Within each mirror it -validates all candidates as regular files through directory descriptors, -without following symlinks, before deleting any candidate. It syncs lock-file -deletions before retrying Git; the pending marker also covers interruption of -this cleanup. Live mirror users and surviving Git children block recovery, so -their Git locks and refs cannot be removed or recreated beneath them. +and the parent closes the temporary duplicates immediately after spawning. The +parent closes its lock descriptor without explicitly unlocking the shared open +file description. If the Swift parent is killed, a surviving Git child keeps the +mirror locked until it exits. Git automatic maintenance is disabled. Recovery +must acquire this same mirror lock before classifying Git `*.lock` files +(including `packed-refs.lock`) and the root `packed-refs.new` staging file as +abandoned. Within each mirror it validates all candidates as regular files +through directory descriptors, without following symlinks, before deleting any +candidate. It syncs lock-file deletions before retrying Git; the pending marker +also covers interruption of this cleanup. Live mirror users and surviving Git +children block recovery, so their Git locks and refs cannot be removed or +recreated beneath them. Git runs with terminal and Git Credential Manager prompting disabled while preserving the rest of the inherited environment. Failures identify the action @@ -203,51 +718,17 @@ and source location rather than its mirror, staging or extraction paths; see [process execution and errors](Package.md#process-execution-and-errors) for the consumer error contract. -Each mutating state operation first checks for an abandoned journal under the -scope lock, then validates watch state and finishes pending ref cleanup before -proceeding. An applying journal rolls back every replacement, including watch -baselines; a committed journal -finishes cleanup. Recovery is repeatable if interrupted. Before deleting any -recovery material, both the terminal journal file and its parent directory are -fsynced, even when that phase was already visible on entry. State and backup -files and their parent directories are synced before publishing the terminal -phase. Replayed deletions sync their own parent directories even when the entry -is already absent; a visible unlink alone does not establish durability on that -target's volume. On macOS these barriers also use `F_FULLFSYNC` to request a -storage flush. - -Recovery throws `CoreError.transactionRecovered` after completing, reporting -the scope and asking the caller to retry against the recovered generation. -This includes recovery of pending watch refs even when no journal remains. -Non-applying skill and instruction operations and watch status and diff take an -existing shared lock without creating scope state files or replaying recovery. -When the scope lock is absent, inspection reads without a lock, then checks again -for a lock or pending recovery before returning either a result or an error. -If a writer appeared, inspection discards that attempt and retries under the -shared lock. Writers create the scope lock before mutation and never remove it. -Listings, previews, watch status and watch diff fail with `CoreError.invalidState` -when a transaction journal or watch-ref cleanup marker is pending. Inspection -leaves recovery material, state and retained refs untouched; pending Git ref -cleanup can also leave mirror locks that prevent fetching safely. -Each doctor instead reports one pending-recovery diagnostic per affected scope -and skips checks that require that scope's consistent state. The diagnostic -explains that the next command changing the scope will recover it. Explicit -multi-root instruction audits never write. Corrupt journals stop mutations -without guessing a recovery plan. -Tests interrupt writers between rename and parent fsync, interrupt rollback and terminal cleanup, and verify -that a competing reader waits for the recovering process's lock. - ## Materialization and Installation Git materializations, downloaded artifact bytes and expanded artifact trees use private journal-owned staging. Exact Git commits are extracted there; expanded artifacts are checked against their locked tree hash. Copied trees are hashed through pinned directory descriptors and verified before publication. Files, -metadata and directory entries are synced before atomic publication of the -final cache name. Git extraction scratch also belongs to the journal, so -recovery cleans an incomplete copy or extraction without retaining a partial -final directory just because the lock references its pin. Cache publication -completes before the installation transaction references that content. +metadata and directory entries are synced before atomic publication of the final +cache name. Git extraction 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. Each scope's cache contains: @@ -260,76 +741,89 @@ cache/ locks/ ``` -A source key combines a readable prefix and the SHA-256 of its normalized ID. -A source has one bare mirror; requirement resolution reads its refs and tags. +A source key combines a readable prefix and the SHA-256 of its normalized ID. A +source has one bare mirror; requirement resolution reads its refs and tags. Exact trees are extracted with Git archive and contain no repository metadata. Read-only revision inspection uses local Git reads or remote ref advertisements -with the same requirement selection policy, without fetching or populating caches. -Consumers of the same source and revision share a materialized directory. +with the same requirement selection policy, without fetching or populating +caches. Consumers of the same source and revision share a materialized +directory. `link` points an agent's skill entry at verified cached content. `copy` installs that content as a directory and rejects links escaping the installed subtree. Links to content within the same project or user state root are relative, so -moving that root preserves them; external live edit links are absolute. -`edit` points directly at a live local skill -without pin or hash and requires a source without a requirement. Local -non-Git directories support edit mode. Git-backed link and copy operations read -committed trees, including when the source has uncommitted changes. - -An update preview or source listing can fetch into a mirror. -Inspection snapshots are disposable and do not move an installed tree or write -state or targets. Skill and instruction `add` discover choices through the read -path when no names or `all` are supplied, and for `listOnly`. Their discovery -uses disposable mirrors and locks, leaving the scope unchanged. Exact cached -commits can be extracted under an existing mirror lock without fetching. Pending -recovery stops selection discovery before source access. An automatic single-item -addition carries the normalized source ID and exact discovered name into the -writer path separately from user-entered names. Rediscovery must match that -identity or fail with an error asking the caller to retry; its content and pin -can refresh. Explicit names and `all` enter the writer path directly. -Applying prepares all selected content, computes differences, -stages replacements, and commits target changes and state under the scope lock. -Combined updates share a source-resolution session and baseline across skills -and instructions. The coordinator merges their owned records and rejects -incompatible source records and overlapping targets before exposing an apply -handle. It holds the writer lock while the consumer renders, revalidates -state-file bytes/presence and target/source identities, then retains pinned -content before the combined journal starts. Live edit content remains live; -its source identity and usable metadata are checked instead of a content pin. - -After retention, preconditions are checked again. One transaction queues -physical skill targets, instruction/forwarding targets, changed declaration -and lock files, and pruning against the merged lock and existing watch state. -Paths are sorted within target groups. No-change combined apply returns -receipts without rewriting state. Cancellation before apply publishes no -targets, state or retained trees; fetched mirror objects and the scope -container/lock may remain. - -Commit outcome tracking is bound to the combined journal's UUID. Recovering -a separate cache publication cannot claim that the combined generation -committed. An uncertain commit-marker write is classified by validated -recovery. `UpdateApplyError` distinguishes confirmed unchanged and committed -generations from unresolved recovery, including failures during enclosing -watch-reference cleanup. A committed error must not be described as rollback. -After process death the next writer recovers and raises -`CoreError.transactionRecovered`; consumers retry the whole preparation. -Previews reject pending recovery without replay. See [Updates](Updates.md) -for the public handle and error contracts. +moving that root preserves them; external live edit links are absolute. `edit` +points directly at a live local skill without pin or hash and requires a source +without a requirement. Link and copy freeze non-Git local directories into embedded +resources that support cold restore; an explicit Git requirement needs a Git source. +Git-backed link and copy operations read committed trees, including when the source +has uncommitted changes. + +Source listing and configuration previews use temporary acquisition and never +mutate persistent mirrors, refs, cache contents or locks. Inspection snapshots are +disposable and do not move an installed tree or write state or targets. Skill and instruction `add` discover choices through the read path when +no names or `all` are supplied, and for `listOnly`. Their discovery uses +disposable mirrors and locks, leaving the scope unchanged. Exact cached commits +can be extracted under an existing mirror lock without fetching. Pending +recovery stops selection discovery before source access. An automatic +single-item addition carries the normalized source ID and exact discovered name +into the writer path separately from user-entered names. Rediscovery must match +that identity or fail with an error asking the caller to retry; its content and +pin can refresh. Explicit names and `all` enter the writer path directly. +Applying captures the complete declaration, ledger and watch baseline under the +admitted locks. One source session links the graph with independent retained pins; +freeze keeps its ledger and source mapping paired through real lowering. Physical +aggregation rejects incompatible contributions and prepares shared native documents +once. The synchronous prepared handle retains these borrowed resources and writer +locks while the consumer renders its report and applies it. Live edit content stays +live; its identity and usable metadata are checked instead of a content pin. + +Apply validates state, targets and source evidence, retains the complete ledger/watch +reference closure, and validates again. One transaction stages resource trees and +capsules, selected physical targets, declaration, ledger, receipts and cache pruning. +No-change apply returns receipts without rewriting state. Exiting before apply +publishes no targets, state or retained trees; writer lock containers may remain. +Temporary source and replay resources are released at closure exit. + +Commit outcome tracking is bound to the combined journal's UUID. Recovering a +separate cache publication cannot claim that the combined generation committed. +An uncertain commit-marker write is classified by validated recovery. +`UpdateApplyError` distinguishes confirmed unchanged and committed generations +from unresolved recovery, including failures during enclosing watch-reference +cleanup. A committed error must not be described as rollback. After process +death the next writer recovers and raises `CoreError.transactionRecovered`; +consumers retry the whole preparation. Previews reject pending recovery without +replay. See [Updates](Updates.md) for the public handle and error contracts. Pruning participates in that transaction. Pins referenced by skills, instruction -sections or prompt sections remain cached, as do artifact contents referenced -by watch state and trees containing live edit sources. Pruning opens directory -ancestry without following symlinks and uses -directory-relative enumeration, rename and deletion. It rejects symlinked cache -containers and never recursively follows a link during cleanup. -Mirrors remain available for source history and future resolution. Watch-owned -Git refs retain only revisions still referenced by watch state or installed -pins; obsolete histories can be collected by Git after those refs are released. +sections or prompt sections remain cached, as do artifact contents referenced by +watch state and trees containing live edit sources. Pruning opens directory +ancestry without following symlinks and uses directory-relative enumeration, +rename and deletion. It rejects symlinked cache containers and never recursively +follows a link during 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. Both doctors inspect cached objects, local Git refs or remote ref advertisements without fetching or populating caches. Local Git status disables optional locks to avoid index refresh writes. Skill doctor reports pending recovery as a -`DoctorCheck` with ID `pending-recovery` and warning status. It also reports -missing installs, changed content and broken links, newer matching Git resolutions, and uncommitted changes in selected local source -paths. `install` restores all recorded recipients and modes without changing -lock bytes. The consuming CLI controls presentation and user interaction. +`DoctorCheck` with ID `pending-recovery` and warning status. An unresolved +transaction uses `unresolved-transaction` and lists retained recovery locations. +It also reports missing installs, changed content and broken links, newer +matching Git resolutions and uncommitted changes in selected local source paths. +`install` restores all recorded recipients and modes without changing lock +bytes. The consuming CLI controls presentation and user interaction. + +## Ledger composition interfaces + +`LedgerFreeze.freezeWithSources` returns the ledger and its ephemeral source map +from one linked result. Native lowering consumes that paired result inside the +source session. `LedgerReplay.withPreparedLowerings` seals artifact identities and +keeps all acquired resources alive through its callback. `withLockedResources` +replays a locked candidate with the same resource lifetime. Borrowed URLs never +escape into public reports or outlive a prepared handle's synchronous closure. +The production renderer table is explicit and format-versioned. Tests supply +separate renderers without registering production fallback behavior. + +`StateStore.loadLedger()` returns the complete public ledger model without resolving sources or recovering transactions. `loadResolved()` returns the derived skill/instruction summary for domain consumers; it is never a persisted state format. diff --git a/Documentation/Architecture/Updates.md b/Documentation/Architecture/Updates.md index ed53e76..817f314 100644 --- a/Documentation/Architecture/Updates.md +++ b/Documentation/Architecture/Updates.md @@ -1,125 +1,182 @@ -# Combined Updates - -`AgentsUpdates` composes the skill and instruction planners for one project or -user scope. It updates all declared skills, instruction recipients and named -ChatGPT prompts. Named skill selection and instruction recipient overrides -belong to the standalone APIs. Consumers own rendering and completion output. - -## Reports and Preparation - -`UpdateOperations.preview(scope:environment:)` returns `CombinedUpdateReport` -under one existing shared scope lock. It never returns an applicable handle, -retains source trees, writes state or replays recovery. Mirror fetching and -disposable snapshots are allowed. If a first writer appears during an -unprotected inspection, the result or error is discarded and inspection -retries under the shared lock. - -`UpdateOperations.withPreparedUpdate(scope:environment:_:)` acquires the -writer lock, recovers pending work before reading the baseline, and prepares -both kinds before calling the consumer. Shared pinned sources use one exact -snapshot per normalized identity and effective declaration, so source movement -between domain planners cannot produce different pins for the same source. -Independent sources are not promised a simultaneous upstream snapshot. - -The combined lock takes skills from the skill plan and instruction records -from the instruction plan. It merges compatible source updates and retained -baseline records, preserves declaration and watch data, and then validates the -complete prospective state. Domain preparation defers whole-state validation -until this merge so shared source changes are checked against both domains' -prospective records. Standalone operations validate their complete resulting -state before returning a preview or invoking a consumer callback. Applying -preparation checks ownership and physical path collisions before the closure. -Preview can report prospective membership that an applying preparation rejects -as unmanaged. - -The report contains `scope`, `skills`, `instructions`, `lockMissing` and -`hasChanges`. The last includes normalized lock changes, physical differences -and required missing-lock reconstruction. An empty unconfigured scope is -unchanged. Section ordering and identical-content prompt repins can require -application even without changed target bytes or changed prompt names. - -Skill results expose old/new versions from the resolved records, full revisions -and hashes. Versions remain nil for absent sides, edit installations, -well-known artifacts and Git resolutions without a selected version tag. -`SkillFileEntry.file(Data, executable: Bool)` uses the same any-execute-bit rule -as watch. Directories and links keep their own entry types; a symlink's mode is -not its destination's mode. Persistent content hashes do not include mode. - -Each result's `membership` has one `SkillMembershipChange` per agent in the -union of previous and prospective installations, sorted by agent raw value. -`SkillMembership` is `.absent` or `.installed(mode:)`. These are managed -membership states, independent of physical presence. Rows use physical paths -with resolved parents and unfollowed final entries. Agents sharing a path -retain separate rows while physical changes remain deduplicated. Unchanged -results include membership too; `installed` retains its post-apply meaning. - -A missing `agents.resolved` makes the before membership unrecorded and -`lockMissing` true. A correct existing live link can therefore have added -membership and no physical diff. It still fails applying preparation's -unmanaged-content guard. A locked but missing target remains installed on the -before side. If both record and selection are lost, no removal is invented. -Loss of resolved state is distinct from replacing the never-removed writer -lock file. - -## Handle Lifetime and Application - -The closure receives a `PreparedUpdate` with a report and `apply()`. The handle -has no public initializer, serialization or `Sendable` conformance. Its -internal plan is separate from the report. Any apply attempt consumes it; -inactive, repeated or wrong-thread use fails before I/O. Closure exit -invalidates retained handles and releases their disposable planning resources. - -The writer lock remains held through preparation, rendering and apply. The -closure must stay synchronous on its preparing thread and must not re-enter -scope operations, await work, or dispatch the handle. In particular, reading -a separate output inventory can deadlock. Render the supplied report and -apply or return. An interactive pause holds off other scope users; a UI that -needs a long pause should preview first and prepare/display a fresh plan when -ready to apply. - -Returning or throwing before apply cancels without publishing targets, state -or retained content. A caller error after successful apply does not undo it. -Applying revalidates declaration/resolved/watch bytes and presence, target -entries, execute flags, links, path ancestry, instruction bytes and forwarding -decision inputs. Live source identities and usable skill metadata are checked; -their contents remain live. Pinned content is retained and verified, then -preconditions are rechecked before one transaction stages both kinds, changed -state and pruning. Copy staging and pinned-link destinations are verified -against prepared bytes and execute flags before publication. - -`UpdateApplyResult` contains the rendered `report` and `installedSkills` -receipts. A no-change apply returns receipts without rewriting state. -Standalone skill and instruction updates use the same domain planners and -staging functions, with their existing callback signatures and domain isolation. +# Configuration Lifecycle + +`AgentsUpdates` owns configuration update, declaration edit, removal and locked +restore for one project or user scope. It composes the complete YAML declaration, +linked source graph, resolved ledger, domain rendering and native regional edits. +Consumers own command parsing, presentation and completion output. + +## Requests and Reports + +`UpdateRequest.operation` selects source update, locked restore, typed YAML edits, +a complete declaration replacement, or removal. `kinds` restricts the component +domains and `names` restricts members. A restricted operation protects the other +recorded components' pins, payloads, resources and effective recipients. A change +that requires a wider operation reports `requiresCombinedUpdate` before publishing. +Producer-owned children cannot be edited as consumer declarations; their diagnostic +identifies the producer and group reference. Root occurrence edits use +`ManifestEdit` and digest-scoped document handles. Skill removal uses recorded +membership while preserving authored all-member selections and their exclusions; +new upstream members are admitted by update, not by removal. + +`UpdateOperations.preview(_:scope:environment:)` returns a serializable +`CombinedUpdateReport`. It uses existing shared locks and never creates persistent +scope, cache or native coordination locks, changes refs, retains content, recovers a +journal, invokes a binding provider or runs source programs. Existing exact cached +objects may be read under their existing locks. Missing objects, downloads, +extraction and their locks remain temporary and are cleaned on success, failure +and cancellation. A first writer invalidates an unlocked inspection attempt. + +Reports include skill membership and typed file differences, instruction targets +and prompts, selected native changes, marketplace pin changes, missing-lock status, +`hasChanges` and a +`displayedFingerprint`. Native reports contain the owned symbolic values; complete +shared documents, unrelated siblings, runtime secret values and private freshness +evidence remain internal. `ComponentUpdateChange.symbolicBefore` and `symbolicAfter` +are readable selected configuration, rendered through the native document owner. +Generated-plugin text includes the final target, selected native files and member +content, and frozen resource paths and executable flags. Binding values remain +symbolic references; private deployed bytes and unrelated members are never read +for display. `nil` means the selected value is unavailable; unavailable recorded +skill content is labelled in the projection. Consumers display these strings directly. Equal unmanaged +values do not establish ownership. +`hasChanges` includes declaration and ledger changes even when target bytes agree. + +The versioned display fingerprint covers the operation and selection, complete +candidate declaration and ledger, exact pins, resources, locked renderer/layout, +ownership, actual destinations and stable access semantics. It excludes temporary +paths and inodes, random IDs, timestamps, runtime secret values and complete native +preimage digests. Repeated preparation of the same candidate and environment has +the same fingerprint. This is a presentation comparison, not an authorization token. + +## Preparation and Application + +`withPreparedUpdate(_:scope:environment:_:)` acquires the request and pending-journal +footprint before the scope writer lock. Source linking can discover a larger +footprint; preparation releases the locks and readmits the union before delivering +the consumer closure. Finite skill installation targets for current and previous +slots join this admission union and retain their legacy directory/link intention. +This never repeats a delivered callback or binding provider. +It captures declaration, ledger and watch together, links and freezes one paired +source result, lowers it and aggregates contributions by physical destination. +Shared native files receive one aggregated regional edit with all logical owners. + +The closure receives `PreparedUpdate.report` and `apply(ifUnchangedFrom:)`. Any +apply attempt consumes the handle. It has no public initializer, serialization or +`Sendable` conformance. It is valid only on its preparing thread inside the +synchronous closure; exit invalidates retained handles and releases all borrowed +source/replay resources. Do not re-enter scope operations, await, or dispatch the +handle. Render the supplied report directly. + +A UI may preview without holding a writer lock, then prepare on a worker thread +and pass the displayed fingerprint to `apply(ifUnchangedFrom:)`. A changed +fingerprint requires a refreshed report. Matching fingerprints still execute all +private freshness, ownership, permission, binding and publication checks. + +Application validates the captured state, targets, linked inputs and forwarding +decisions. Live skill contents stay live while their source identity and valid +metadata remain required. It retains the complete ledger/watch closure, stages +resources, selected deployments, declaration, ledger, receipts and pruning, and +commits through one `FileTransaction`. Required literal bindings are resolved only +inside Core's private staged render. Ordinary application never starts an MCP +server, hook, plugin or model call. + +Returning or throwing before apply cancels publication. A caller error after a +successful apply does not undo the commit. A no-change apply returns receipts +without rewriting state. + +## Producer Patches + +`UpdateOperations.previewProducerPatches(scope:environment:)` returns a +`ProducerPatchPreview` with exact UTF-8 patch files and typed skip reasons. +Each file includes its safe filename, immutable producer coordinates, base, +repository-relative paths and contributing component selectors. The encoded +report contains the same preview content available to Swift callers. Freshness +evidence stays private to the in-memory preview. + +The operation reads the deployed lock, evaluates effective source and +organization policy, and replays qualifying locked resources offline. It follows +recorded copy routes for skills, opaque native plugin trees and the resource +placements of generated native plugins. Direct Git base bytes must match an +exact regular blob in the pinned commit. A package subdirectory is part of the +patch path. For a hosted marketplace release, the selected member, frozen +producer seal and verified archive must agree on the regular entry and its +bytes. These paths are relative to the release payload tree. Forwarded or +ambiguous producer claims need an independent source-path mapping. + +The comparison strips a native copy's UTF-8 BOM and converts CRLF to LF. +The source must already have those normalized bytes. Authored comments, +including text resembling a generated header, remain content. Generated +instructions, Antigravity rule frontmatter and headers, and merged configuration +are transformed outputs and are skipped. Routes that deploy a link, local +producers, unavailable path or identity attribution, nonregular files, binary +files, deletions and mode changes have separate skip reasons. A missing or +unverifiable required locked input fails the preview. The standard ledger +limits also bound the native reads, compared paths and combined patch bytes. + +Modified copies are compared by origin, base and source path before package +grouping. Identical edits share one diff, with every contributing selector +listed. Divergent edits are reported at each modified copy, while unchanged +copies have no effect. The lexicographically first eligible root owns a shared +diff. Patch files use repository-relative paths and a digest suffix to keep +filenames stable across previews. + +`UpdateOperations.exportProducerPatches(_:to:)` writes the reviewed bytes +under a scope read lock. The caller can present a destination picker between +preview and export, then pass its URL directly. On macOS, export keeps any +security-scoped access for the duration of the synchronous call. A default +destination is `patches` under the project directory. Policy, deployed state, +native copy generations and locked resource proofs are checked again before +publication. A pending-only marketplace change is compatible with a preview +whose deployed inputs still match. + +The export reports one output directory and its written, reused and failed +files. It reuses regular files with identical bytes and preserves occupied +filenames on collision. An empty preview creates no directory. Installed +paths, scope state, policy files and producer trees are excluded as destinations. +Retrying the same preview after a collision reuses files already written if the +inputs still match. Apply the patch from the producer repository root at the +recorded commit, or from the extracted exact release tree. +See [APM's producer patch reference](https://microsoft.github.io/apm/reference/cli/export-patch/). + +## Exact Restore and Domain APIs + +`UpdateOperations.restore(scope:environment:)` restores the complete locked +deployment in one transaction. Restore admits package declarations against their +committed pins and contribution closure before acquiring resources. It runs the locked +format/layout; it does not link mutable producer declarations, choose current +refs or select a newer adapter. Missing resources, unknown renderers, output +mismatches and incompatible platforms fail before publication. Embedded resources +support cold reconstruction without the authoring tree. Live skills retain their +explicit authoring location. Native restore preserves unmanaged regions. + +`SkillOperations` and `InstructionOperations` retain their type identities. +Their add, update, remove and restore methods are public extensions in +`AgentsUpdates`; consumers calling them must depend on and import `AgentsUpdates` +as well as the domain product. Discovery, frontmatter and text rendering stay in +the domain modules. Skill-only restore and update apply only the skill domain. +`InstructionOperations.renderChatGPT` verifies locked sections and reads the current +consumer-owned append file at export. Update and install do not require that file; +producer-owned append resources remain frozen at their selected source. +Watch remains a separate subscription API. Add inspection returns source-relative `Skill.path` and `Skill.skillFile` coordinates, never paths into a released snapshot. ## Failure and Recovery -Handle misuse throws `CoreError.invalidState` before I/O. Failures during plan -validation or application throw `UpdateApplyError`, preserving -`underlyingError` and an `UpdateApplyDisposition`: +Handle misuse fails before I/O. Apply failures are `UpdateApplyError` with the +underlying error and a disposition: | Disposition | Established result | | --- | --- | -| `unchanged` | No combined target/state publication, or validated rollback | -| `committed` | The new combined generation is confirmed; a later failure still makes the operation fail | -| `recoveryRequired` | Recovery could not establish a consistent completed generation | - -Errors before preparation finishes and caller errors retain their original -types. A commit error does not itself imply rollback: publication of the -committed marker can precede a cleanup error. Outcome tracking follows the -owning journal through validated recovery, including enclosing scope cleanup, -and does not infer disposition from journal-file presence. Cache-only -publication journals cannot claim the combined update committed. - -The next applying operation recovers an abandoned transaction and raises -`CoreError.transactionRecovered`. Consumers retry the entire preparation and -render its fresh report. Read-only preview rejects pending recovery. The -existing journal, descriptor-relative path checks, metadata preservation and -fsync barriers supply the durability guarantees described in [State](State.md). -The lock remains advisory: preconditions detect changes made while rendering -but do not provide compare-and-swap against editors racing the final check. - -## Consumer Example +| `unchanged` | No publication, or validated rollback | +| `committed` | The generation committed; a later failure still makes the operation fail | +| `recoveryRequired` | Recovery could not establish a consistent generation | + +Preparation errors retain their original type. Domain convenience APIs also unwrap unchanged apply failures; committed and recovery-required failures retain their disposition. Commit-marker publication can +precede a cleanup error, so callers must inspect the disposition before retrying. +The next writer recovers an abandoned journal and raises +`CoreError.transactionRecovered`; retry the whole preparation. Read-only access +reports pending recovery. Recovery uses sealed physical evidence and never invokes +linkers, renderers or binding providers. See [State](State.md) for durability and +concurrent-writer guarantees. ```swift import AgentsUpdates @@ -131,7 +188,203 @@ let receipt = try UpdateOperations.withPreparedUpdate { update in renderCompletion(receipt) ``` -`render` and `renderCompletion` are consumer-owned functions. Consumers should -render the combined report once before applying, use `hasChanges` for the -no-change decision, and report completion only after the closure returns. -Serialized reports are presentation values, not offline approval tokens. +`render` and `renderCompletion` belong to the consumer. Completion is reported only +after the closure returns. + +## Public Inspection and Interactive Consumers + +`UpdateOperations.inspect` captures the Manifest document (including typed values, +source maps and NodeIDs), complete declaration, v2 source/component/occurrence/group +and resource descriptions, deployments, watch state and recovery diagnostics under +one admitted read footprint. Public record IDs join these immutable descriptions; +logical selections remain independent of revisions and temporary directories. +The report excludes retained content objects and complete native file bytes. +Deployment drift compares owned content or validates the physical private receipt. +An unverified observation is explicit. `readLocations` contains actual state, +source, retained resource and deployment URLs, including missing leaves. + +A pending journal returns recovery diagnostics without reading inconsistent +configuration. Inspection does not recover, resolve sources, call a provider or +create persistent files. It is suitable for App refresh and filesystem invalidation. + +`ScopeInspection.inventory(format:createdAt:)` returns distributable JSON from +the captured lock evidence. Select `.cycloneDX` for CycloneDX 1.6 or `.spdx` for +SPDX 2.3. Pass a Foundation `Date` for reproducible bytes. Without a date, +`cycloneDXInventory()` and `.cycloneDX` omit the timestamp, while SPDX uses the +current UTC time. Both formats require a scope free of pending recovery and +marketplace intent errors. + +The inventory records locked versions and revisions, captured resource +checksums, and marketplace release archive digests. The resource evidence labels +file and tree SHA-256 separately. CycloneDX nests source components and uses +`agents:contains` references for additional memberships. SPDX uses `CONTAINS` +relationships and `NOASSERTION` for unknown package licenses. GitHub and Bitbucket +package URLs use their registered types. Other Git hosts use the registered `git` +type with the host and repository path. A subpath is included where the lock +identifies one package root. Origins exclude authentication and local filesystem +locations. + +Pass a component's `selection` in `UpdateRequest.selections` to update or remove +that logical component. An occurrence selects that contribution when it is the +sole contribution; a coalesced component requires complete-component selection or +a typed declaration-reference edit. The captured document/ledger generation is +revalidated before linking. Bare names that match multiple logical components +report ambiguity. Unselected components keep their recorded projection and pins. + +`UpdateOperations.discover` resolves an explicit complete declaration, including +exported groups, in B's temporary source session without native lowering. It +returns symbolic descriptions, all exact source revisions, stable identities and +actual local read locations. `ComponentDiscovery.updateRequest()` carries the +captured declaration identity and discovered graph fingerprint into preparation; +a changed source fails before callback delivery. File enumeration and native input +conversion remain with their domain/import owners. + +Finite source and import additions use the package `UpdateOperations.captureAddition` +seam. It accepts explicit declaration additions and a captured `ScopeInspection`, +returning no candidate for an empty or source-only selection. Composition preserves +existing source aliases, groups, uses, defaults and direct occurrences. Alias/group +conflicts and pending authored changes require resolution rather than a broader +update. All existing pins and protected projections remain fixed while the selected +addition links; its fingerprint is captured after composition. The request retains +Core path identity, scope/root mappings, declaration absence or digest and baseline +state evidence. Another destination, changed evidence or a modified candidate +requires a refreshed inspection. Ordinary preparation repeats these checks before +offering its synchronous handle. Existing authored whole-graph discovery remains +an explicit complete-graph workflow. + +`SourceImportOperations.inspect` consumes an explicit existing importer profile, +root, document, selection and supplied resource locations. Its immutable report +preserves producer coordinates, pins/integrity, ordered sources, selections, +bindings, unconverted diagnostics, resource preservation obligations and foreign +deployment claims. `updateRequest(in:)` merges admitted canonical intent into the +captured scope declaration. Preparation rereads the same inputs, compares the +proposal, captures their private freshness evidence and validates it again around +publication. Unresolved conversion/binding diagnostics stop submission; foreign +claims do not establish ownership. Import requests use destination-bound finite +addition protection; admitted canonical bindings cannot clear independent raw +preservation/rewrite requirements. Input content that would overwrite its own +local authoring source requires independent preservation before submission. + +Pass D's `RuntimeBindingProvider` as `bindingProvider:` to public +`withPreparedUpdate`, `perform` or full `restore`. Preparation and preview never +call it. The provider resolves bounded data only during private staging. Native +reports separate intended recipients from the verified physical object's reader +union and retain sensitivity from an existing shared receipt, including when the +selected change has no bindings. + +`UpdateOperations.perform` returns `UpdateCompletion` after the whole synchronous +operation and outer cleanup have returned. It preserves the result/error and +`unchanged`, `rolledBack`, `committed` or `recoveryRequired` disposition, reports +recovery before callback delivery, and includes pending recovery/cleanup evidence. +A durable commit remains committed when cleanup is pending. Render the disposition +before deciding whether to retry. The terminal value is Sendable when its consumer +result is Sendable; the prepared handle is always invalidated before it returns. + +```swift +let displayed = try UpdateOperations.preview(request, environment: environment) +let completion = UpdateOperations.perform(request, environment: environment, + bindingProvider: bindings +) { prepared in + try prepared.apply(ifUnchangedFrom: displayed.displayedFingerprint) +} +``` + +The closure runs on one thread and must not await. A UI may await the completed +operation's result, refresh a changed candidate and reprepare for confirmation. +Agents CLI restores the full scope once with `UpdateOperations.restore`; domain +consumers continue using their restricted lifecycle methods. + +`CombinedUpdateReport.readLocations`, discovery and scope inspection expose durable +state, source, own-instruction, resource and deployment inputs, including absent +leaves introduced by an unsaved declaration. `inspectOwnInstructions` and +`inspectChatGPTExport` pair their results with their owner-computed read locations. +Export reads the consumer appendix at export time; an absent appendix is allowed +while installing, but must exist when explicitly exported. + +Initialization uses a pure `describeInstructionsInitialization` or +`describeProjectSkillInitialization` and then `UpdateOperations.initialize`. +The immutable description contains the exact file/template and captured existing +project identity. `describeSkillInitialization(directory:)` is explicit standalone +authoring and can select a new direct child of an existing parent. Apply holds +that observed root through the lower domain's sole transaction. Registered roots +removed or replaced after description are never recreated. Existing URL-returning +initializers use the same lower writer; consumers needing terminal evidence use +the description/completion API. A committed operation with pending cleanup stays +committed; durable rollback stays rolled back even with pending cleanup. Earlier +recovery failure has unchanged current disposition and pending recovery evidence. +No executing resource or borrowed descriptor outlives the synchronous return. + +`WatchOperations.previewAdd` and `previewRemove` produce immutable confirmation +requests with a stable fingerprint, selected source/content and read locations. +Add resolves Git in disposable storage or uses the existing verified index reader; +preview never retains content, changes scope files or recovers. `apply(preview)` +revalidates scope state and exact content in the existing subscription writer. +`UpdateOperations.performWatch(preview)` returns that writer's outer +`UpdateCompletion` without nesting a transaction. Subscriptions do +not deploy native targets or skills. + +Watch consumers can pass a displayed `WatchStatus` to `WatchOperations.seen`. +The existing writer revalidates both normalized source identity and the exact Git +commit or artifact digest map before retention and watch-state publication. A +redirected alias or changed content requires refresh. Status and diff never deploy +configuration. + +Concrete native contributions are decoded from their sealed F artifacts inside +replay's resource lifetime. Composition resolves D's closed routes and descriptor +physical identities before grouping logical owners. A shared document receives +one regional preparation, including protected MCP and native component siblings. +Reader and sensitivity evidence covers the physical object; selection controls +which runtime bindings may be requested. Ordinary changes preserve an unselected +private region using its verified receipt, without replaying its provider. + +Public prompt export renders locked sections in their recorded order and retains +producer append resources. A recorded consumer `localAppend` is read from its +current contained file only during export. Update, install and locked recovery do +not read that mutable consumer file. + +`SourceImportInspection.producerRevision` is optional. Documentation-backed native +profiles retain an unavailable upstream revision as `nil`; their +`specificationStatus` remains available. Import requests rebase producer-local +source coordinates into the captured declaration while retaining the proposal's +input freshness evidence and conversion/binding diagnostics. + +A consumer presenting authored YAML occurrences can use the captured document's +`node(at:)`, verify `editability(of:)`, and submit a typed `ManifestEdit` through +`UpdateRequest.operation.edit`, with `expectedDeclarationDigest`. This addresses +the selected authored node; it does not infer a producer child's ownership from a +recorded occurrence index. The node and expected digest reject stale reuse. + + +## Package-manager Lifecycle + +`LifecycleOperations.list`, `validate`, `simulate` and the declaration and +enablement previews are read-only. Discovery uses the admitted administrator +directory and the user and consuming-project `StateStore` declarations. +Administrator source errors withhold all starts. User and project source errors +withhold their own actions. Shell output and HTTP response bodies are omitted +from reports. Reviewed enablement definitions retain authored values for the +local confirmation UI. + +`UpdateOperations.previewLifecycle` requires a caller-supplied operation intent. +`InstructionOperations.previewCompilation` uses the instruction update +request. Marketplace resolution, lock-only and frozen deployment and bundle +import expose lifecycle previews for their existing operation routes. +`UpdateOperations.perform(_:)` consumes the review's in-memory confirmation, +runs eligible pre actions, reprepares and attempts the reviewed package write, +then runs eligible post actions after successful completion. Submission again +returns the in-progress or recorded result. A fresh review supports an +intentional repeat. Recovery does not replay effects. + +Project enablement binds the complete canonical subtree digest to the physical +root and canonical path. Receipts live in `~/.agents/lifecycle/receipts.json` +with owner-private access. Receipt replacement serializes updates across roots. +Each grant or revoke advances the selected root's revision. The project handoff +lock orders revocation against a command spawn or webhook resume. Each action +start checks current source provenance, authority, applicable policy and +receipt. Set `APM_NO_SCRIPTS=1` to suppress starts for one invocation. + +Pre action failures are advisory. Stale input, rollback, cancellation and +pending recovery prevent post starts. Production webhooks may settle during +package application. Reports distinguish OS handoff, confirmed HTTP success, +HTTP rejection and unknown delivery. Explicit execute-test waits for each +response and uses the same eligibility gate. diff --git a/Documentation/Architecture/Watch.md b/Documentation/Architecture/Watch.md index 8514dd4..8f5c8f1 100644 --- a/Documentation/Architecture/Watch.md +++ b/Documentation/Architecture/Watch.md @@ -1,8 +1,9 @@ # Watch Subscriptions `AgentsCore.WatchOperations` manages subscriptions independently of installation -intent and pins. `agents.json` lists subscribed source aliases in `watch`; -`agents.watch` records a seen baseline per normalized source ID. Subscribing +intent and pins. `agents.yaml` lists subscribed source aliases in the `watch:` +argument of `Agents(...)`; `agents.watch` records a seen baseline per normalized +source ID. Subscribing installs nothing, and removing a subscription preserves source declarations, skill selections, locked records and installed content. @@ -11,21 +12,27 @@ skill selections, locked records and installed content. Both CLI consumers can construct `SkillOperations.watchOperations()` from `AgentsSkills`. It supplies the existing skill discovery rules and well-known loader to `AgentsCore`. Callers implementing another content provider can use -`WatchOperations.init(discoverSkills:fetchArtifacts:)` directly. This keeps -frontmatter, skill discovery and artifact format parsing in their owning module; -core has no dependency on `AgentsSkills`, Yams or instruction rendering. +`WatchOperations.init(discoverSkills:fetchArtifacts:)` after `import +AgentsManifest`; that module provides the initializer because it also supplies +the declaration access that core receives by injection. This keeps frontmatter, +skill discovery, artifact format parsing and manifest syntax in their owning +modules; core has no dependency on `AgentsManifest`, `AgentsSkills`, Yams or +instruction rendering. Every operation accepts `scope` and `RuntimeEnvironment`: | Operation | Behavior | | --- | --- | -| `add(_:alias:requirement:path:scope:environment:)` | Resolve an alias or source location, declare it if needed, subscribe and record current content as seen. Returns `WatchSeen`. | +| `add(_:alias:requirement:path:scope:environment:)` | Resolve an alias or source location, declare it if needed, subscribe and record current content as seen. Returns `WatchChange`. | | `status(scope:environment:)` | Return sorted `WatchStatus` values for all subscribed sources. | | `diff(_:name:kind:scope:environment:)` | Inspect one subscribed source, optionally filtering item name and kind. Returns file bytes and entry metadata for presentation by the caller. | -| `seen(_:revision:scope:environment:)` | Acknowledge the current head or resolve a supplied Git revision to a full commit ID. Well-known sources accept no revision argument. | -| `remove(_:scope:environment:)` | Remove the alias from `watch` and delete its baseline without changing installations. | +| `seen(_:revision:scope:environment:)` | Acknowledge the current head or resolve a supplied Git revision to a full commit ID. Well-known sources accept no revision argument. Returns `WatchChange`. | +| `remove(_:scope:environment:)` | Remove the alias from `watch` and delete its baseline without changing installations. Returns `WatchChange` without a baseline. | -Existing subscriptions can be addressed by alias, normalized source ID or source +`WatchChange` has `alias`, the normalized `sourceID` and `seen`, the +acknowledged `WatchSeen` baseline or `nil` after removal, so callers need no +separate declaration read. Existing +subscriptions can be addressed by alias, normalized source ID or source location. Repeating `add` records current content as seen. Missing subscriptions, invalid revisions and missing baseline content produce errors. A local directory must be a Git repository to be subscribed. @@ -103,31 +110,33 @@ is reported even when expanded file contents are identical. Expanded baseline contents remain in the digest-addressed cache while referenced by watch state; skill lifecycle pruning respects those references. -`StateStore.loadWatch()` reads and validates the baseline. `save` accepts an -optional `watch` value; omitting it preserves existing watch bytes. JSON is +`StateStore.loadWatch()` reads and validates the baseline without recovery or +writes. Writes that do not replace watch state preserve its bytes. JSON is sorted, timestamp-free, UTF-8 without a BOM and newline-terminated. Duplicate keys, malformed input, unknown non-null fields, unsupported versions and invalid revisions or digests are errors. Subscriptions cannot repeat an alias. Add, seen and remove hold the scope writer lock and recover interrupted -transactions and pending ref cleanup before proceeding. Add and seen prepare -cached content before publishing its baseline. Declaration and watch replacements -and cache pruning commit through the existing scope transaction journal; recovery -follows the same retry contract as other mutating state operations. Every scope +transactions and pending ref cleanup before proceeding. They capture declaration, +lock and watch evidence before contacting Git. Add and remove plan the +`agents.yaml` change at that point, so a declaration the editor cannot change +fails before any fetch; seen leaves the declaration unchanged. Add and seen +prepare cached content before publishing its baseline. Declaration and watch +replacements and cache pruning commit through the existing scope transaction +journal, expecting the captured evidence; recovery follows the same retry +contract as other mutating state operations. Every scope mutation checks watch state after transaction recovery, and corrupt watch state blocks mutations before fetching, cache publication, installation or state replacement. Status and diff take an existing shared scope lock without creating state files or replaying recovery. When a first writer creates the scope lock during an -unlocked read, inspection discards that attempt, including any error, and retries -under the shared lock. A pending transaction journal or watch-ref cleanup marker -fails inspection with -`CoreError.invalidState` ("transaction recovery is required before inspection"). -Inspection leaves pending cleanup and retained refs untouched for the next -mutating operation to recover. -Status and diff may fetch into mirrors under each mirror's lock and download -current index artifacts for inspection. They use disposable snapshots and memory, -leave retained artifact content unchanged, and do not write declaration, lock, -watch state, installations or source working trees. Scheduling and diff rendering -belong to consumers. +unlocked read, inspection discards that attempt, including any error, and +retries under the shared lock. A pending transaction journal or watch-ref +cleanup marker fails inspection with `CoreError.recoveryPending`. Inspection +leaves pending cleanup and retained refs untouched for the next mutating +operation to recover. Status and diff may fetch into mirrors under each mirror's +lock and download current index artifacts for inspection. They use disposable +snapshots and memory, leave retained artifact content unchanged, and do not +write declaration, lock, watch state, installations or source working trees. +Scheduling and diff rendering belong to consumers. diff --git a/Documentation/Archive/AgentsManifest.md b/Documentation/Archive/AgentsManifest.md new file mode 100644 index 0000000..d8c3ea8 --- /dev/null +++ b/Documentation/Archive/AgentsManifest.md @@ -0,0 +1,647 @@ +# Agents Manifest Contract + +## Status + +The frontend/authoring portions are superseded by the accepted +[YAML manifest decision](../Decisions/YAMLManifest.md) and +[current manifest reference](../Reference/Manifest.md). This proposal retains +historical design context for the broader component-management requirement; +source, targeting, state, security and lifecycle ownership remain with their +current architecture documents. + +## Authors / Owners + +- Author: showxu. +- Implementation owner: core; CLI, macOS GUI and skill CLI are consumers. +- Accepting authority: repository owner showxu. + +## Summary + +`Agents.swift` is source for a non-executing configuration compiler: bounded +grammar recognition, SwiftSyntax parsing and static type checking produce an +agent-independent intermediate +representation (IR); source linking and capability-driven adapters produce native +configuration files. The **deployment ledger**, `agents.resolved`, records exact +source pins, physical artifacts, owned keys/sections and their hashes. CLI and +GUI apply concrete configuration changes through one shared transaction. + +The core repository's complete declaration is: + +```swift +// agents-tools-version: 1.0 +import AgentsDescription + +let agents = Agents( + sources: [ + .source( + name: "agents-tools", + url: "https://github.com/agents-tools/.github", + branch: "master", + subpath: ".agent" + ), + ], + components: [ + .instructions( + sections: [ + "guide", + .section(name: "shared/swift-package-route", source: "agents-tools"), + .section(name: "shared/swift-package-tests", source: "agents-tools"), + ], + agents: [.claudeCode, .codex] + ), + ] +) +``` + +A **producer** publishes content or a named group; a **consumer** selects it for +installation. A **recipient** is the agent that will read a component's native +configuration. This consumer narrows an exported group's recipients to Codex, +while its own indexing rule inherits Cursor as its default recipient: + +```swift +// agents-tools-version: 1.0 +import AgentsDescription + +let agents = Agents( + defaultAgents: [.cursor], + sources: [.source(name: "team", path: "./team")], + components: [ + .ignore( + name: "build-products", patterns: [".build/"], purpose: .indexing, + condition: .when(scopes: [.project]) + ), + ], + uses: [ + .group(name: "review", source: "team", condition: .when(agents: [.codex])), + ] +) +``` + +CLI, GUI and skill CLI send domain edits to one document layer. It maps edits to +source patches, reparses and validates the entire candidate, and passes it to +core's prepare/apply transaction. The manifest owns intent; the ledger owns +resolved deployment facts. Comments and untouched source bytes remain intact. + +## Implementation Status + +| Part | Status and owner | +| --- | --- | +| Construction vocabulary, files and versions, grammar, typing, resource limits, document editing, evaluated dump, diagnostics and conformance | Implemented; specified in the [manifest language reference](../Reference/Manifest.md). | +| `Agents.swift` as scope declaration, deployable subset, declaration writes, absent-declaration rule and requirement comparison | Implemented; specified in [State](../Architecture/State.md#declaration). | +| [Component deployment](#component-deployment), [Targeting](#targeting), [Groups and source linking](#groups-and-source-linking), the `Components` target in [Target Architecture](#target-architecture), [Configuration application](#configuration-application) and [Lock version 2](#lock-version-2-and-ownership-conversion) | Pending; specified below. | + +## Motivation + +A typed Swift vocabulary provides reusable composition and editor completion +while static interpretation keeps reads independent of arbitrary code execution. +One component construction shape lets groups combine every family. Explicit +conditions and source provenance make deployment and conflicts explainable. + +The accepted [Swift manifest](../Decisions/SwiftManifest.md), +[component](../Decisions/AgentComponents.md) and +[configuration application](../Decisions/ConfigurationApplication.md) decisions +constrain this contract. + +## Proposed Change + +Adopt the vocabulary, static grammar, source editing and JSON contract of the +[manifest language reference](../Reference/Manifest.md), and complete deployment +of the whole vocabulary: targeting, group and source linking, native adapters +and shared configuration application. The types-only `AgentsDescription` and +document/compiler-front-end `AgentsManifest` library products exist; linking and +native adapters belong in an internal `Components` target. Shared IR, source +storage, capabilities and transactions stay in `AgentsCore`, and orchestration in +`AgentsUpdates`. + +## Detailed Design + +### Language + +The [manifest language reference](../Reference/Manifest.md) specifies: + +- [construction vocabulary](../Reference/Manifest.md#construction-vocabulary) + and [domain rules](../Reference/Manifest.md#domain-rules); +- [source files and versions](../Reference/Manifest.md#source-files-and-versions), + [static grammar](../Reference/Manifest.md#static-grammar), + [type inference](../Reference/Manifest.md#type-inference-and-literal-conversions) + and the [admission grammar](../Reference/Manifest.md#normative-admission-grammar); +- [resource limits](../Reference/Manifest.md#resource-limits) and + [group references](../Reference/Manifest.md#group-references); +- [document editing](../Reference/Manifest.md#document-editing), + the [evaluated JSON dump](../Reference/Manifest.md#evaluated-json-dump) and + [diagnostics](../Reference/Manifest.md#diagnostics). + +[State](../Architecture/State.md#deployable-subset) specifies the subset that +the state layer deploys; every other active structure is reported as +`manifest.unsupported`. The sections below specify the remaining deployment. + +### Component deployment + +Deployment gives every vocabulary family its native meaning. The front end +already checks the +[domain rules](../Reference/Manifest.md#domain-rules); the rules below apply when +resolved components are lowered to native configuration. + +| Family | Payload semantics | +| --- | --- | +| Skills | Selection, exclusions, installation mode and member overrides preserve membership tracking and item pins. Duplicate names and conflicting members are diagnosed. | +| Instructions | Contributions append sections in traversal order. Prompt names are unique; each prompt has its own ordered sections. | +| MCP server | Stdio, Streamable HTTP and SSE are distinct transports. Transport conversion must be exact. Registration is a configuration change; an optional connection test is a separate explicit action. | +| Hook | Portable events mean before/after a tool invocation and session start/end. Adapters preserve event and command-result behavior. `.native("event")` uses its single recipient's event grammar. Matchers use its verified grammar. Omitted timeouts retain the native default. Hooks preserve declaration order. | +| Subagent | Description and prompt are portable text. Model/tool names are identifiers validated by the recipient adapter. Omitted tools inherit its default; `[]` requires no tools. | +| Command | A named user-invoked prompt. Parameter tokens appear as literal `${input:name}`; missing required inputs are errors. Substitution is text, not shell evaluation. | +| LSP server | A stdio executable invocation, an extension-keyed `languages` dictionary and initialization options. One extension has one language by construction. Plugin-only recipients get an adapter-generated native plugin recorded in the ledger. | +| Permissions | Ordered last-match rules, with no match inheriting native policy. Read/write patterns are scope-relative globs (`*`, `**`, `?`). Execute/tool patterns use the adapter's verified request representation. Translation must preserve the full policy, including unmanaged rules; otherwise deployment fails. | +| Ignore | Ordered gitignore-style patterns with `!` negation, rooted at scope. Context and indexing are separate purposes, neither an access-denial guarantee. | +| Plugin/extension | Components mode decomposes a pinned container and selects all kinds when `select` is omitted; `[]` selects none. Typed references exclude individual children. Native mode keeps the container unchanged. Native configuration may configure only its registration, not rewrite container content. | + +Shell interpretation requires an explicitly declared shell command. Symbolic +environment and secret bindings are resolved by core's machine binding provider +at apply, or emitted as native references where supported. Previews redact +secrets; locks retain binding identity, not values. Secret rotation does not +change command identity. Exported resources, own sections and prompt `append` +paths remain attached to their producer snapshot; exported own sections may be +consumed in either supported scope. + +A native schema ID, for example `claude-code/subagent@1`, identifies its agent, +component kind and adapter schema version. Agent identity is not repeated in the +value. Registry validation checks fields, client-version compatibility and the +component's recipients. A schema contributes only to its own agent and cannot +replace portable fields, conditions, resource identities, target paths, owned-key +boundaries. Collisions and unknown schemas/fields/types are errors for active +deployment. A native permission policy can use empty portable +rules when no exact portable translation exists. Native configuration remains +subject to ordinary preview, ownership and freshness checks. + +Capability validation checks every active agent/component/scope/feature against +the registry; unsupported requests are reported rather than dropped. Inactive +branches still undergo syntax, type and domain checks. Applying a valid candidate +commits its selected configuration changes. Imports and group selections use the +same preview and application boundary. Client runtime trust and tool-call +permissions remain with the client. + +### Targeting + +`defaultAgents` supplies recipients when a component omits `agents`. The language +1.0 fallback is `{claude-code, codex}`. Explicit `agents`, including an empty +array, is the complete recipient set and replaces the default everywhere. +An exported component retains its producer's explicit set; it does not become +an intersection with consumer defaults. When the component omits `agents`, its +declaring document supplies the default, which is captured when exporting it, +including its language-version fallback. A producer omitting `defaultAgents` +publishes to Claude Code and Codex in language 1.0. Consumer defaults never +retarget imported content. The state layer applies this fallback to the +unconditional root components it deploys. + +A skill member's explicit override recipients replace its selection's recipients; +otherwise those selection recipients are its default. This is the same fallback +rule. A component discovered without a declaring manifest gets its default from +the enclosing selection. Producer front matter expresses conditions, never a +consumer-editable default. Imported metadata retains those conditions. + +For each component or selected member: + +```text +requested = explicitAgents ?? defaultAgents +active = requested ∩ agents admitted by every applicable condition +``` + +For candidate agent `a`, operation scope `s` and explicit platform context `p`, +`when(agents:scopes:platforms:)` is: + +```text +(agents == nil OR a belongs to agents) +AND (scopes == nil OR s belongs to scopes) +AND (platforms == nil OR p belongs to platforms) +``` + +Members within a dimension are OR; dimensions and nested conditions are AND. +A specified empty dimension is false; `.when()` is true. Duplicate members are +domain errors. Applicable conditions include front matter, the component, +its section, every enclosing `ComponentGroup` and every `GroupReference` in its +expansion chain. Group references expose only `condition` for narrowing. +Consumers can add conditions but cannot remove producer conditions or replace +published recipients. Scope selects one operation's destination, not a request +to write multiple scopes. Platform is data supplied to resolution, not a Swift +compile-time conditional. + +ChatGPT rendering has no agent recipient. For that destination, project each +condition onto scope/platform dimensions and preserve all those restrictions; +agent dimensions apply to native agent rendering only. Watch has no conditions +and is independent of this algebra. + +Registry checks follow targeting. Every unsupported active request is a +capability error with origin and reason; the tool does not silently filter it. +Physical visibility is checked independently: if a shared destination exposes +content to additional agents, prepare reports the extra readers. An explicit +producer-authorized sharing change or a registry-supported private location is +required. Consumers cannot override published restrictions to resolve such a +conflict. Targeting is deployment intent, not filesystem isolation. + +### Groups and source linking + +A `ComponentGroup` is an inert ordered fragment until selected by a +`GroupReference`; a string literal denotes an unconditional local reference, +equivalent to `.group(name: "review")` for `"review"`. A conditional local +reference uses `.group(name:condition:)`. The root emits its components, then `uses` in order. Each group +emits its components, then recursively its `uses`, depth first. This defines +section, hook and policy contribution order. A source's root components, root +subscriptions and unrelated exports are not imported through a group reference. +The producer's defaults are captured as described under targeting. + +`exports: ["review"]` publishes that local group. A consumer writes +`.group(name: "review", source: "team")`. To publish an existing group under a +new name, declare a wrapper `.group(name: "quality", uses: +["review"])` and export `"quality"`. References do not import Swift +symbols. There are no wildcard exports, implicit exports or executable package +initializers. The front end checks +[local group references](../Reference/Manifest.md#group-references), including +in unused declarations. + +A source manifest is `/.agent/Agents.swift`; when the discovery +root itself is `.agent`, it is `/Agents.swift`. Exactly one lookup +is performed. Conventional repositories need no manifest to provide skills or +instructions; an export request from such a source reports a missing export. +An index export must identify an immutable package artifact containing a manifest. +An index publishing only individual skills cannot satisfy a group reference. + +Aliases bind in the document that declares them. Within an exported component, +`source: "rules"` refers to the producer's alias; `.` refers to its package. +Relative local sources in a downloaded package must remain within that snapshot; +absolute, home-relative and escaping producer-local sources are invalid for +remote consumption. Root local sources retain core's existing path rules. +Qualified identity includes normalized source identity, snapshot, discovery root, +group name, component kind and component name. Different discovery roots retain +different namespaces even when they share a repository revision. + +Resolve one snapshot per normalized source identity for the export graph, +satisfying all requirements on that source. SemVer constraints intersect; choose +the greatest permitted version. Explicit branch/revision constraints must name +the same commit; mixed version and revision constraints require a matching +permitted tag at that commit. Core owns version ordering and tag tie-breaking. +Resolve dependencies to a complete consistent graph, with deterministic descending +version candidates and normalized-source-ID ordering for equally eligible next +choices; backtrack on incompatible transitive requirements within the link budget. +An unsatisfiable graph reports both dependency paths. Existing direct skill and +section pins remain item-specific and are not upgraded by group resolution. + +The ledger records every reference with source identity, discovery root, effective +requirement, exact revision/artifact digest, manifest digest, group name and full +child closure. Non-Git local export packages receive content-addressed snapshots; +explicit edit-mode skill children remain live. `install` restores the recorded +closure without consulting a mutable index or branch. `update` re-resolves the +affected closure and previews changes. Pins are never copied into the manifest. + +Cross-source cycle detection follows the active reference stack before +memoization and reports `manifest.group.cycle` with source spans. A diamond is +not a cycle. Repeated references retain occurrence provenance. Conflicting active +payloads for the same named identity and overlapping recipients are +`manifest.group.conflict` errors. Equal named +hooks/policies coalesce at their first position to avoid duplicate execution; +ordered instruction sections retain intentional repetition. Disjoint targeting +may reuse a name. + +Skill selections expand to member identities; instruction contributions form +ordered section streams; adapters may aggregate disjoint structured entries. +These explicit aggregations retain every owner. Other collisions on physical +names, paths or keys fail, even across different aliases. Permission aggregation +must preserve the entire ordered policy including unmanaged rules. There is no +last-writer-wins merge or implicit deployment rename. Resolve conflicts through +producer naming, selection/exclusions or conditions. + +Linking is bounded by 256 distinct source snapshots, 16,777,216 aggregate +manifest input bytes, 64 active group references, 10,000 component contributions +and 1,000,000 total resolution/evaluation steps, including backtracking. Linked +expanded values also obey the +[expanded-value limits](../Reference/Manifest.md#resource-limits). Source +download and extraction limits remain in core's loader before the linker +receives bytes. + +An exported declaration is read-only in a consumer: an edit changes its +`GroupReference.condition` or the producer's own document, never cached source. +After a document edit, prepare re-links affected sources and revalidates +capabilities and targets. + +### Examples + +#### showxu/skills + +The skills repository declares: + +```swift +// agents-tools-version: 1.0 +import AgentsDescription + +let agents = Agents( + components: [ + .instructions( + sections: ["guide", "code-review-rules"], + agents: [.claudeCode, .codex] + ), + ] +) +``` + +#### Producer + +A package at `team` publishes this `team/.agent/Agents.swift`. Its own instruction +sections live under `team/.agent/instructions/`; skills follow source discovery +conventions. The project condition prevents deployment of this group in user scope. + +```swift +// agents-tools-version: 1.0 +import AgentsDescription + +let agents = Agents( + exports: ["review"], + groups: [ + .group( + name: "review", + components: [ + .instructions(sections: ["review-principles"], agents: [.claudeCode, .codex]), + .skills(source: ".", select: ["review"], mode: .copy, agents: [.claudeCode, .codex]), + ], + condition: .when(scopes: [.project]) + ), + ] +) +``` + +#### Consumer with every component family + +This consumer combines local and exported groups. The exported reference selects +Codex from the producer's two recipients; its local subagent runs only on macOS. +The plugin container activates only in user scope. Files, commands, native schema +IDs and source exports are validated during resolution, not accessed by parsing. + +```swift +// agents-tools-version: 1.0 +import AgentsDescription + +let base: [SectionReference] = ["guide"] +let sections = base + [.section(name: "engineering", source: "rules")] +let reviewer: Component = .subagent( + name: "reviewer", + description: "Review correctness and tests.", + prompt: "Check invariants and explain concrete failures.", + agents: [.claudeCode], + condition: .when(platforms: [.macOS]), + native: ["claude-code/subagent@1": ["memory": "project"]] +) + +let agents = Agents( + sources: [ + .source(name: "team", path: "./team"), + .source(name: "drafts", path: "./draft-skills"), + .source(name: "rules", url: "https://example.org/team/rules.git", from: "1.2.0"), + .source(name: "catalog", index: "https://example.org/skills/index.json"), + .source(name: "vendor", url: "https://example.org/vendor/tools.git", exact: "2.1.0"), + ], + components: [ + .skills( + source: "rules", exclude: ["experimental"], mode: .copy, + overrides: [.skill(name: "testing", mode: .link, agents: [.codex])] + ), + .skills( + source: "drafts", select: ["draft"], mode: .edit, + condition: .when(agents: [.claudeCode], scopes: [.project]) + ), + .instructions( + sections: sections, + chatGPT: [.prompt(name: "weekly", sections: base, append: "notes/weekly.md")] + ), + .mcpServer( + name: "workspace", + transport: .stdio( + "workspace-tools", arguments: ["serve"], + environment: ["TOKEN": .secret("workspace-token"), "LOG_LEVEL": "info"] + ), + agents: [.claudeCode] + ), + .mcpServer( + name: "reference", + transport: .streamableHTTP( + url: "https://example.org/mcp", headers: ["Authorization": .environment("MCP_AUTH")] + ), + agents: [.openCode] + ), + .hook( + name: "format", event: .afterTool, + run: .executable( + "swift", arguments: ["format", "--in-place", "Sources"], + workingDirectory: .path("tools", source: "rules") + ), + timeoutSeconds: 30, agents: [.claudeCode], condition: .when(scopes: [.project]) + ), + .command( + name: "review/change", description: "Review a selected change.", + prompt: "Review ${input:change} and cite evidence.", + parameters: [.parameter(name: "change", description: "The change to review.")], + agents: [.claudeCode] + ), + .lspServer( + name: "swift", run: .executable("sourcekit-lsp"), + languages: [".swift": "swift"], + initializationOptions: ["backgroundIndexing": true], + agents: [.claudeCode], condition: .when(platforms: [.macOS]) + ), + .permissions( + name: "private-files", + rules: [.deny(.read, "secrets/**")], + agents: [.claudeCode], condition: .when(scopes: [.project]) + ), + .ignore( + name: "build-products", patterns: [".build/", "DerivedData/"], purpose: .indexing, + agents: [.cursor], condition: .when(scopes: [.project]) + ), + .plugin( + name: "vendor-tools", path: "plugins/tools", source: "vendor", mode: .native, + agents: [.claudeCode], condition: .when(scopes: [.user]) + ), + .plugin( + name: "shared-tools", path: "plugins/shared", source: "vendor", + exclude: [.hook(name: "format")], condition: .when(scopes: [.project]) + ), + ], + groups: [ + .group( + name: "review-tools", components: [reviewer], + uses: [.group(name: "review", source: "team", condition: .when(agents: [.codex]))] + ), + ], + uses: ["review-tools"], + watch: ["rules", "catalog"] +) +``` + +## Target Architecture + +```text +UTF-8 -> strict lexer + bounded grammar recognizer -> SwiftParser -> iterative tree guard + -> vocabulary type checking/static evaluation + -> declaration IR + source map -> source/group linking + discovery + -> resolved component IR -> capability validation/native adapter lowering + -> artifact and ledger plan -> state transaction + +CLI/GUI/skill CLI -> domain edits -> source patches -> front end again + -> expected-IR comparison -> prepare -> transaction +``` + +[Package Architecture](../Architecture/Package.md) owns the current targets. +Deployment adds or extends: + +| Target | Ownership and dependencies | +| --- | --- | +| `AgentsCore` | Adds capability protocols/descriptors, resolved component IR and content identity. No syntax or adapter-implementation dependency. | +| `Components` | Internal group linker, input-container adapters and native output adapters. Depends on `AgentsCore`, `AgentsManifest`, `AgentsSkills`, `AgentsInstructions`. Uses core source-resolution sessions and registers capability implementations during composition. Agent adapters are types/files, not one target per agent. | +| `AgentsUpdates` | Public prepare/apply orchestration across document edits, domains, components and one state transaction. Depends on the targets above; front ends consume its workflows. | + +Core does not depend on `Components`; descriptions and document editing do not +own a second state store. Public import names retain family identity; the +internal `Components` name reflects its responsibility. + +Declaration IR preserves defaults versus explicit values, ordered sections, +conditions and symbolic groups without choosing a host or reading sources. +Resolved IR carries tagged component payloads, logical identity, effective +recipients, content identity and provenance. Neither contains native output +paths. Backend plans add registered physical targets, owned keys/sections, +observed hashes, replacement bytes and adapter verification versions. + +Every field's source map records use/definition spans and inherited defaults. +Provenance includes normalized source identity, exact revision/artifact digest, +relative path, input format/adapter version, group and reference chain. Cache +paths are not identity. Coalesced artifacts retain all owners and origins. + +Future language versions can add bounded pure functions within the front end's +syntax, typing, evaluation and provenance rules. Their results lower to the same +values and IR. Adapters and the state engine remain independent of expression +syntax; editability remains a document-layer capability. + +## State Transaction and Recovery + +[State Transaction and Recovery](../Architecture/State.md#state-transaction-and-recovery) +owns the current publication, precondition and recovery guarantees. + +### Manifest integration + +[Declaration writes](../Architecture/State.md#declaration-writes) own the +publication of validated source bytes, the shared transaction with the ledger, +watch state, native outputs and cache, and the preparation evidence for the +manifest. + +### Configuration application + +The GUI presents concrete configuration changes and targets. Confirming applies +that candidate through core. An explicit modifying CLI command expresses the +same application intent. Before publication, core checks the candidate and +relevant target state against the preparation evidence; changed evidence +requires preparation and preview to be refreshed. + +Configuration reads and application do not start declared component programs. +An optional MCP connection test is explicitly invoked against a selected +configuration snapshot. It initializes the protocol and discovers tools, with +bounded time/output, cancellation and cleanup of its own connections and +processes. A local stdio test starts the displayed command. The test does not +invoke business tools or determine whether configuration can be applied. +Client runtime trust, authentication and tool-call authorization remain with +the client. [Configuration Application](../Decisions/ConfigurationApplication.md) +owns this boundary. + +## Compatibility / Migration Impact + +The product reads and writes only `Agents.swift`. It does not read, recognize +or convert the earlier JSON declaration; existing repository and user scopes are +converted once outside the product at release. A scope with a lock or watch state +and no `Agents.swift` reports the missing declaration +([absent declaration](../Architecture/State.md#absent-declaration)). + +### Requirement persistence and comparison + +[Requirement comparison](../Architecture/State.md#requirement-comparison) +specifies semantic requirement comparison across declarations, edits, the +ledger, update planning, resolution sessions and watch state. Lock version 2 +extends it to group resolutions below. + +### Lock version 2 and ownership conversion + +Version 2 retains exact item-specific source identities, revisions, versions, +artifact coordinates, hashes, section order and installation modes. Content +records refer to unified `deployments` IDs instead of duplicating ownership. +`groupResolutions` records the source/group closure; `components` records resolved +MCP servers, hooks, subagents, commands, LSP servers, permission/ignore policies +and plugins. Empty new collections are present; future unknown versions are refused. + +A deployment records registered-root-relative target, artifact kind, owners, +recipients, owned keys/sections, expected content hash, source pins and adapter +format. Whole-file versus managed-section ownership is explicit. For structured +files, hash the owned values and retain formatting-sensitive patch preconditions; +unmanaged keys are not claimed. + +Lock conversion derives ownership only from existing install/target records. +Shared skill destinations coalesce only when mode, content and ownership agree. +Instruction records preserve these separate removal rules exactly: + +| Existing instruction record | Version-2 ownership and removal | +| --- | --- | +| Generated unit target (`import == nil`) | Whole generated rendering, governed by `blockHash`. When obsolete, delete the file if its current bytes hash to `blockHash`; preserve drifted bytes. Its existing `created: false` does not prevent deletion. | +| Forwarding/import target (`import != nil`) | Managed import block with its marker/hash and the existing `created` flag. Remove the managed block; delete the whole file only when `created` is true and no custom content remains. Otherwise preserve the remaining file. | + +Heading offsets, import markers, block hashes and creation provenance retain +their meanings. Missing targets remain missing; drifted targets retain expected +hashes, not hashes of adopted bytes. Lock conversion does not scan and claim +unmanaged native files. No generated unit is reclassified as a non-deletable +custom file, and no forwarding file gains whole-file ownership from a +unit-target rule. + +Lock conversion is deterministic for the same old lock and explicit registered +layout. An already-version-2 ledger remains byte-identical when unchanged. +Restoration must address the same original pins and physical targets after +conversion, and removing the last instruction must produce the same deletion or +preservation result as before conversion. + +Lock conversion canonicalizes requirements while preserving exact source and +item pins and ownership; an existing version-2 ledger is not upgraded merely to +canonicalize requirements. Requirements in `groupResolutions` follow the +[ledger rule](../Architecture/State.md#requirement-comparison): newly written +records are canonical, existing records keep their bytes, and comparison is +semantic. + +## Validation Contract + +[Conformance and +Validation](../Reference/Manifest.md#conformance-and-validation) owns the +language, editing and dump validation. The pending parts add tests for condition +narrowing, default capture on export, qualified namespaces, cross-source cycles +and diamonds, conflicting requirements, shared-target exposure and lock +restoration/removal equivalence after lock conversion. Native capability claims +require current client probes. + +## Alternatives Considered + +- **Parsing in the description module.** A types-only dependency keeps authoring + and compiler-backed editor support independent of parsing, I/O and state. +- **Syntax in `AgentsCore`.** Shared IR and persistence remain independent of the + source language; the document front end owns syntax and edits. +- **A public payload wrapper for each component.** Direct typed factories keep one + construction level while private storage preserves family-specific structure. +- **Different targeting rules for exports.** One explicit-or-default rule plus + intersected conditions preserves the meaning of a component across packages. +- **Whole-file regeneration.** Exact patches and explicit read-only constructs + preserve comments, formatting and reviewable local edits. +- **Resolution during dump.** A declaration dump remains deterministic and offline; + group linking is a separate source operation. + +## Related Documentation + +- [Agents Manifest Language](../Reference/Manifest.md) +- [Swift Manifest](../Decisions/SwiftManifest.md) +- [Agent Components and Adapters](../Decisions/AgentComponents.md) +- [Configuration Application](../Decisions/ConfigurationApplication.md) +- [Package Architecture](../Architecture/Package.md) +- [State and Source Cache](../Architecture/State.md) +- [Updates](../Architecture/Updates.md) +- [Product Scope](https://github.com/agents-tools/cli/blob/master/Documentation/Decisions/ProductScope.md) +- [Front Ends](https://github.com/agents-tools/cli/blob/master/Documentation/Decisions/FrontEnds.md) +- [CLI reference](https://github.com/agents-tools/cli/blob/master/Documentation/Reference/CLI.md) +- [Swift API Design Guidelines](https://www.swift.org/documentation/api-design-guidelines/) +- [Swift Lexical Structure](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/lexicalstructure/) diff --git a/Documentation/Archive/README.md b/Documentation/Archive/README.md index dca5aa5..06aa6bd 100644 --- a/Documentation/Archive/README.md +++ b/Documentation/Archive/README.md @@ -3,7 +3,8 @@ This directory holds retired or superseded material that remains useful for historical reference. -There is no archived material yet. +- [Agents Manifest Contract](AgentsManifest.md) — original frontend and + component-management design proposal. ## Placement diff --git a/Documentation/Decisions/AgentComponents.md b/Documentation/Decisions/AgentComponents.md new file mode 100644 index 0000000..33ecfa9 --- /dev/null +++ b/Documentation/Decisions/AgentComponents.md @@ -0,0 +1,92 @@ +# Agent Components and Adapters + +## Status + +Accepted + +## Context + +Core manages skills and instructions, with each agent's locations encoded in +the agent registry. The next stage manages every agent configuration +component: MCP servers, hooks, subagents, commands and prompts, LSP servers, +permissions, ignore rules and plugins. Each supported agent stores these in +its own places and formats, often several components in one settings file. + +Other tools distribute the same components in their own containers: Claude +Code, Codex and Cursor plugins and marketplaces, Gemini CLI extensions, APM +packages, rulesync sources and npx skills locks. Some agents also share +physical locations; Codex, Cursor, Gemini CLI and OpenCode read the same +`.agents/skills` directory. + +## Decision + +- **One component model.** Core models components independently of any agent. + The manifest declares components; adapters deploy them. +- **Capability registry.** Core records, for each agent, component and scope, + whether the agent supports it, its native location and format, and the keys + agents owns in a shared file. CLI validation and GUI controls derive from + the registry. Each supported combination is verified against the agent's + current stable client. +- **Key-level ownership.** In shared configuration files agents changes and + removes only the keys it wrote and preserves every other key. +- **Deployment ledger.** The lock records each physical target with its owner + and content hash, and cleanup removes only what the lock proves agents owns. +- **Agent targeting.** Every component can be limited to agents and platforms. + A producer declares targeting in front matter or a package manifest; a + consumer narrows it in the manifest with `agents` or `condition` and never + widens it. A component reaches the declared agents that the registry says + support it. When a shared location exposes a component to agents beyond its + targeting, agents reports the conflict and the user chooses to share or to + deploy to the agent's own location. +- **Absorb, decompose, recompose.** Input adapters read Claude marketplaces and + plugins, Codex and Cursor plugins, Gemini CLI extensions, APM packages, + rulesync sources, npx skills locks and hand-written native files. They split + each container into components and record its provenance. A marketplace is a + source that can be browsed and searched; installing from it is declared in + the manifest and pinned in the lock. +- **Import.** The same adapters back `agents import`, which previews the + manifest changes and target ownership it would take, and writes only with + `--apply`. Import is one-way and never automatic. Adopting an existing + native file goes through import, as the whole file or as a marked section. +- **Native deployment.** Components deploy to each agent's native locations. + Where an agent accepts a component only through its plugin system, as Claude + Code does for LSP servers, agents generates a native plugin that carries it. + A vendor plugin can also be installed unchanged for its own agent. A + component an agent cannot represent is reported, not dropped or + approximated. +- **Distribution.** A source is a Git repository, local directory or index. + A repository publishes reusable groups through the `exports` field in its + [YAML manifest](../Reference/Manifest.md). + +## Consequences + +- The agent registry grows into the capability registry and gains per-agent + adapters for every component; adding an agent or component means adding + registry entries, adapters and client probes. +- The lock grows from pins and hashes into a deployment ledger, a lock format + change with its own lock conversion. +- Input adapters are versioned against the upstream formats they read and need + fixtures from those formats. +- Shared settings files require structured, format-preserving edits for JSON, + TOML and Markdown targets. +- Targeting is deployment intent, not isolation; shared locations remain + visible to every agent that reads them. + +## Alternatives Considered + +- **Per-agent code paths without a registry.** Every new component would add + special cases across CLI and GUI. +- **Copying plugins between agents unchanged.** Plugin formats and runtimes + differ; components move between agents, containers do not. +- **Reading and writing other tools' manifests as agents' own.** Two managers + would own the same outputs. +- **A hosted marketplace.** Git repositories already identify, version and + distribute sources. + +## Related Documentation + +- Accepted by the repository owner (showxu) on 2026-10-28. +- Current agent locations and state: [Package](../Architecture/Package.md), + [State](../Architecture/State.md) +- Manifest that declares components: [YAML Manifest](YAMLManifest.md) +- Configuration application and connection tests: [Configuration Application](ConfigurationApplication.md) diff --git a/Documentation/Decisions/ConfigurationApplication.md b/Documentation/Decisions/ConfigurationApplication.md new file mode 100644 index 0000000..1b97c10 --- /dev/null +++ b/Documentation/Decisions/ConfigurationApplication.md @@ -0,0 +1,53 @@ +# Configuration Application + +## Status + +Accepted by the repository owner (showxu) on 2026-11-06. +Supersedes [Executable Component Approval](ExecutableApproval.md). + +## Context + +`agents` manages declarations, installed resources and native configuration. +The agent that consumes a configuration owns its runtime: starting servers, +authenticating, trusting a workspace and deciding whether to call a tool. +Configuration changes and runtime operations have different owners. + +## Decision + +- **One application action.** The GUI shows the concrete configuration changes + and targets, then applies them when the user confirms. An explicit modifying + CLI command expresses the same intent. External automation invokes those + commands within its supplied scope. The GUI checks, notifies and applies on + request. +- **Preview freshness.** Core validates that the candidate and relevant target + state still match the presented changes. If they changed, the front end + refreshes the preview before applying. +- **Configuration lifecycle.** Installation and updates write configuration, + resources and registration files. Parsing, inspection and configuration + application do not start the declared component programs. The manifest is + statically evaluated. +- **Optional MCP connection test.** A separate explicit action tests the chosen + configuration through protocol initialization and tool discovery. A stdio + test starts its displayed command; a remote test connects through the + declared transport. The test has bounded time and output, supports + cancellation and cleans up the connections and processes it owns. It does + not invoke business tools. Testing is independent of configuration apply. +- **Client-owned runtime decisions.** Server trust, tool-call authorization and + authentication remain with the consuming client. An adapter does not modify + those records merely to make a configured component appear active. Explicit + permission configuration remains a managed component with its own declared + intent. + +## Consequences + +The declaration records intent and the ledger records committed configuration +and ownership. CLI and GUI use the same prepare/apply transaction. Connection +tests return observations about the selected configuration in the current +environment; their result does not establish that a native client has loaded +or enabled the component. + +## Related Documentation + +- [Agent Components and Adapters](AgentComponents.md) +- [YAML Manifest](YAMLManifest.md) +- [Manifest reference](../Reference/Manifest.md) diff --git a/Documentation/Decisions/ExecutableApproval.md b/Documentation/Decisions/ExecutableApproval.md new file mode 100644 index 0000000..34a57d1 --- /dev/null +++ b/Documentation/Decisions/ExecutableApproval.md @@ -0,0 +1,55 @@ +# Executable Component Approval + +## Status + +Superseded on 2026-11-06 by +[Configuration Application](ConfigurationApplication.md). The original decision +and its acceptance record below are retained as history. + +## Context + +Hooks, MCP servers, LSP servers and plugins run commands on the machine where +they are deployed. A project's manifest is committed and changed by every +contributor, and sources change upstream, so a component can appear in a +scope's declaration without the person who runs `agents update` having +written or reviewed it. + +## Decision + +- Approval is per machine and bound to content identity: the component's + declaration, the command it runs and the content it ships. +- A component that runs code is not deployed to a machine until it is approved + there. Adding it through the CLI or GUI on that machine approves it. + Components that arrive through a project manifest, an imported container or + a source are pending until approved. +- A change to an approved component's content identity makes it pending again. +- Approvals are stored in the machine's user state, never in a committed lock. +- Update previews list pending components and what they would run. Applying + deploys approved components and leaves pending ones undeployed and reported. +- Non-interactive runs approve only components named with their content + identity. +- Reading, previewing and inspecting never run manifest code; the manifest is + parsed, not executed. + +## Consequences + +- The deployment ledger distinguishes approved, pending and refused + components. +- CLI and GUI share one approval flow; the GUI can show an on-device + explanation of a pending command before the user decides. +- Teams that want shared trust approve on each machine or name approved + content identities in automation. + +## Alternatives Considered + +- **Trust everything declared in the manifest.** A contributor's change to a + committed manifest would run on everyone's machine without review. +- **Trust per source.** One approval would cover every later change from that + source. +- **No approval.** Comparable tools already gate executable content. + +## Related Documentation + +- Accepted by the repository owner (showxu) on 2026-10-28. +- Components and deployment ledger: [Agent Components and Adapters](AgentComponents.md) +- Parse-only manifest: [Swift Manifest](SwiftManifest.md) diff --git a/Documentation/Decisions/README.md b/Documentation/Decisions/README.md index 7c1a0d8..ce05841 100644 --- a/Documentation/Decisions/README.md +++ b/Documentation/Decisions/README.md @@ -10,6 +10,13 @@ This directory holds durable decision records for `skill-cli`. - `SPMInspiredRegistry.md`: SPM-inspired first-party skill registry schema - `SwiftStyleFlagSurface.md`: Swift-style canonical flag spelling for install/list/remove/update +- `YAMLManifest.md`: YAML authoring, bounded parsing and lossless source edits +- `SwiftManifest.md`: superseded frontend decision, retained as history +- `AgentComponents.md`: component model, capability registry, input adapters + and native deployment +- `ConfigurationApplication.md`: shared configuration preview/application and + explicitly invoked MCP connection tests +- `ExecutableApproval.md`: superseded decision, retained as history ## Placement diff --git a/Documentation/Decisions/SwiftManifest.md b/Documentation/Decisions/SwiftManifest.md new file mode 100644 index 0000000..bcc5909 --- /dev/null +++ b/Documentation/Decisions/SwiftManifest.md @@ -0,0 +1,91 @@ +# Swift Manifest + +## Status + +Superseded by [YAML Manifest](YAMLManifest.md). + +## Context + +A scope's declaration is standard JSON that the state store rewrites in full on +every save. People cannot annotate it, and every write normalizes it. + +The declaration is about to describe every agent configuration component, not +only skills and instructions, and two front ends will edit it: the `agents` +CLI and a macOS GUI. People still read it in review and edit it by hand, so it +needs comments, and every tool write must keep them. + +Swift has no maintained library that edits YAML without losing comments; a +YAML route needs a custom editor built on libyaml internals, plus rules for +YAML's implicit typing and indentation. A SwiftPM-style manifest that is +compiled and run executes repository code whenever a project is opened or +previewed, needs a toolchain and compile step on every read, and becomes +uneditable for tools once it contains logic. + +## Decision + +- The declaration is a Swift file, `Agents.swift`: `.agent/Agents.swift` for a + project and `~/.agents/Agents.swift` for the user scope. +- Its vocabulary is a types-only module, `AgentsDescription`, modeled on + `PackageDescription`. Sources, skills, instructions, MCP servers, hooks, + subagents, commands and LSP servers are types, as are agents, scopes, + platforms and conditions. A valid manifest type-checks against + `AgentsDescription`. +- Core never compiles or runs a manifest. It parses the file with SwiftSyntax + and evaluates a static subset: literals; initializers, static members and + enum cases of `AgentsDescription` types; arrays and array concatenation; + top-level `let` constants and references to them; `.when(agents:scopes:platforms:)` + conditions; named groups, and references to groups that sources export. + Functions, closures, loops, `var`, `if`, `#if`, `switch`, string + interpolation and other imports are rejected with a line and column, and + nothing is written. +- A leading version comment, in the manner of `swift-tools-version`, declares + the language version. A tool refuses a manifest newer than it understands. +- Every write is a source edit. A write with no semantic change returns the + original bytes; a change replaces only its target ranges, keeps comments by + defined ownership rules, and is parsed and validated again before it is + committed. A valid construct that an edit cannot address exactly, such as a + constant assembled by concatenation, stays readable but is not edited by + tools. +- `agents.resolved` remains the tool-owned JSON lock. Resolved pins live in the + lock, not in the manifest. +- `agents manifest dump --json` prints the evaluated declaration for tools in + other languages. +- The product reads and writes only `Agents.swift`. Existing repository and user + scopes are converted once outside the product at release; the product does not + read the earlier JSON declaration. A scope with a lock or watch state but no + `Agents.swift` is an error. + +## Consequences + +- Core depends on swift-syntax, which lengthens clean builds. +- The static subset is a versioned contract. `AgentsDescription` and the static + evaluator must not drift; examples are compiled against the types and + compared with the evaluated model in tests. +- The state store gains a document layer that owns the original bytes, syntax + tree, model and source locations, and that CLI and GUI edits share. Writes + join the existing transaction and recovery model. +- Parsing untrusted manifests needs explicit limits on file size, nesting and + evaluation work, and fuzzing before release. +- Editors offer completion only where `AgentsDescription` is available to them. +- Every repository that commits a JSON declaration, and every user scope, is + converted once at release, outside the product. + +## Alternatives Considered + +- **Keep JSON.** No comments; explanations would need a structured field. +- **YAML.** Readable and familiar, but comment-preserving edits need a custom + editor on non-public libyaml APIs, and implicit typing and indentation + errors reach users. +- **JSONC or TOML.** Not chosen. +- **A compiled manifest, as in SwiftPM.** Full Swift, but opening or + previewing a repository would run its code, every read would compile, and + the GUI could not edit computed values. + +## Related Documentation + +- Accepted by the repository owner (showxu) on 2026-10-28. +- Current declaration, lock and state layout: [State](../Architecture/State.md) +- Language specification: [Agents Manifest Language](../Reference/Manifest.md) +- Component model the manifest describes: [Agent Components and Adapters](AgentComponents.md) +- Configuration application: [Configuration Application](ConfigurationApplication.md) +- Product scope and front ends: [agents-tools/cli decisions](https://github.com/agents-tools/cli/tree/master/Documentation/Decisions) diff --git a/Documentation/Decisions/YAMLManifest.md b/Documentation/Decisions/YAMLManifest.md new file mode 100644 index 0000000..00f1757 --- /dev/null +++ b/Documentation/Decisions/YAMLManifest.md @@ -0,0 +1,24 @@ +# YAML Manifest + +## Status + +Accepted. + +## Decision + +The canonical authoring document is `agents.yaml`, using YAML version 1 field +shapes owned by AgentsManifest. Core domain and lifecycle semantics remain +independent of syntax. The lock remains JSON. No component program runs while +reading, inspecting or editing a declaration. + +A pinned Tree-sitter runtime and unmodified YAML grammar provide concrete ranges; +public Yams ordered-node composition decodes scalars after bounded admission. +Finite schema-generated constraints validate shapes. Explicit NativeValue-only +float tags retain decimal kind and exact text. Raw Unicode line separators that +parsers interpret differently are rejected before parsing; escaped values remain +exact strings. + +Edits preserve unrelated bytes and owned comments. Complete intent, source +references and ordering are checked before returning candidate bytes. The +existing transaction, source identity, security and client-owned trust boundaries +continue unchanged. See the [current reference](../Reference/Manifest.md). diff --git a/Documentation/Proposals/AgentInstructions.md b/Documentation/Proposals/AgentInstructions.md index 3588242..3c146c7 100644 --- a/Documentation/Proposals/AgentInstructions.md +++ b/Documentation/Proposals/AgentInstructions.md @@ -2,7 +2,9 @@ ## Status -Draft +Historical design draft. Frontend examples are superseded by the accepted +[YAML manifest decision](../Decisions/YAMLManifest.md); current lifecycle and +state contracts live in `../Architecture/`. ## Problem @@ -160,8 +162,8 @@ Two declared sources that normalize to the same ID are an error. | Scope | Declaration | Lock | Watch state | Targets | | --- | --- | --- | --- | --- | -| Project | `.agent/agents.json` | `.agent/agents.resolved` | `.agent/agents.watch` | Project skills; `AGENTS.md` and `GEMINI.md` at the project root and in directories named by `paths`; Claude forwarding; ChatGPT prompts | -| User | `~/.agents/agents.json` | `~/.agents/agents.resolved` | `~/.agents/agents.watch` | User skills; each agent's user instructions file; ChatGPT prompts | +| Project | `.agent/Agents.swift` | `.agent/agents.resolved` | `.agent/agents.watch` | Project skills; `AGENTS.md` and `GEMINI.md` at the project root and in directories named by `paths`; Claude forwarding; ChatGPT prompts | +| User | `~/.agents/Agents.swift` | `~/.agents/agents.resolved` | `~/.agents/agents.watch` | User skills; each agent's user instructions file; ChatGPT prompts | A project commits its declaration and lock, with its instructions files and generated targets, as it would a package manifest and its lock: every checkout, @@ -173,64 +175,83 @@ always lives under `~/.agents`. ### Declaration -Commands edit the declaration; editing it by hand is possible. - -```json -{ - "agents": ["codex", "claude-code"], - "sources": { - "rules": { "local": "~/Developer/rules", "branch": "main" }, - "swift-skills": { "git": "github.com/swift-library/skills", "from": "1.0.0" }, - "my-skills": { "local": "~/Developer/my-skills", "path": "skills" }, - "anthropic": { "git": "github.com/anthropics/skills" } - }, - "skills": { - "swift-skills": { "select": "all", "exclude": ["legacy-docx"] }, - "my-skills": { - "select": ["pdf-forms", "release-notes"], - "mode": "edit", - "overrides": { "release-notes": { "agents": ["codex"] } } - } - }, - "instructions": { - "agents": ["codex", "claude-code", "cursor", "opencode"], - "sections": ["guide", "rules:canonical-artifacts", "code-review-rules"], - "chatgpt": { - "training": { - "sections": ["rules:canonical-artifacts", "rules:training-logging"], - "append": ".agent/chatgpt-training.md" - }, - "weekly-export": { "sections": ["rules:weekly-nutrition-export"] } - } - }, - "watch": ["anthropic"] -} +Commands edit the declaration in place and keep its comments; editing it by hand +is possible. + +```swift +// agents-tools-version: 1.0 +import AgentsDescription + +let agents = Agents( + sources: [ + .source(name: "anthropic", url: "https://github.com/anthropics/skills"), + .source(name: "my-skills", path: "~/Developer/my-skills", subpath: "skills"), + .source(name: "rules", path: "~/Developer/rules", branch: "main"), + .source( + name: "swift-skills", url: "https://github.com/swift-library/skills", + from: "1.0.0" + ), + ], + components: [ + .skills( + source: "my-skills", select: ["pdf-forms", "release-notes"], mode: .edit, + overrides: [.skill(name: "release-notes", agents: [.codex])] + ), + .skills(source: "swift-skills", exclude: ["legacy-docx"]), + .instructions( + sections: [ + "guide", + .section(name: "canonical-artifacts", source: "rules"), + "code-review-rules", + ], + chatGPT: [ + .prompt( + name: "training", + sections: [ + .section(name: "canonical-artifacts", source: "rules"), + .section(name: "training-logging", source: "rules"), + ], + append: ".agent/chatgpt-training.md" + ), + .prompt( + name: "weekly-export", + sections: [.section(name: "weekly-nutrition-export", source: "rules")] + ), + ], + agents: [.codex, .claudeCode, .cursor, .openCode] + ), + ], + watch: ["anthropic"] +) ``` -- A source names its kind by key (`git`, `local`, `well-known`), plus an - optional requirement and search `path`. Requirements are `branch`, - `revision`, `exact` (one version), `from` (up to the next major version), - `upToNextMinor`, or `from` with `to` (a half-open range). Without one, the - latest version tag is used, or the default branch when there are no version - tags. -- `agents` is the default agent list. Without it the default is `codex` and - `claude-code`. -- `select` is `"all"` or a list of names. `"all"` follows the source's current - membership on `update`; `exclude` names skills it skips. Removing one skill - of an `"all"` selection adds it to `exclude`. -- `agents` and `mode` on a selection apply to its skills; `overrides` sets - them for single skills. `mode` is `link` (default), `copy` or `edit`. - `edit` links the live directory of a local source, takes no requirement and - is never pinned. -- `instructions` holds one ordered section list per scope, written to the - instruction file of every listed agent. Every change to the list or its pins - is applied to all listed targets together; `--agent` on instruction - commands sets the list of recipients. -- A section reference is `alias:name` for a declared source, or a bare name for - the project's own instructions. -- `chatgpt` names prompts for ChatGPT project instructions and scheduled - tasks. Each prompt has its own ordered section list and an optional - custom-content file, relative to the scope root, that `render` appends. +- A source is `.source(name:url:)` for Git, `.source(name:path:)` for a local + directory or `.source(name:index:)` for a well-known index, with an optional + requirement and `subpath`. Requirements are `branch:`, `revision:`, `exact:` + (one version), `from:` (up to the next major version), + `.upToNextMinor(from:)`, or a half-open range such as `"1.0.0"..<"1.4.0"`. + Without one, the latest version tag is used, or the default branch when there + are no version tags. +- `defaultAgents` is the default agent list. Without it the default is `codex` + and `claude-code`. +- A `.skills` component without `select` selects all members; `select:` lists + names. An all-member selection follows the source's current membership on + `update`; `exclude` names skills it skips. Removing one skill of an + all-member selection adds it to `exclude`. +- `agents` and `mode` on a selection apply to its skills; + `overrides: [.skill(name:mode:agents:)]` sets them for single skills. `mode` + is `.link` (default), `.copy` or `.edit`. `.edit` links the live directory of + a local source, takes no requirement and is never pinned. +- The `.instructions` component holds one ordered section list per scope, + written to the instruction file of every listed agent. Every change to the list + or its pins is applied to all listed targets together; `--agent` on + instruction commands sets the list of recipients. +- A section reference is a bare string for the project's own instructions, or + `.section(name:source:)` for a declared source. +- `chatGPT: [.prompt(name:sections:append:)]` names prompts for ChatGPT project + instructions and scheduled tasks. Each prompt has its own ordered section list + and an optional custom-content file, relative to the scope root, that `render` + appends. - `watch` lists the aliases of subscribed sources. A source can be subscribed without selecting anything from it. @@ -355,9 +376,9 @@ Commands edit the declaration; editing it by hand is possible. each pin. A pin that cannot be fetched, content whose digest does not match, or an own instructions file whose hash changed since the lock is an error, never a substitution. -- Output is sorted, except section order, and has no timestamps. The declaration - and lock use Prettier's default JSON layout. Writes take a file lock and - replace the file atomically. +- Output is sorted, except section order, and has no timestamps. The lock uses + Prettier's default JSON layout; the declaration keeps its own source layout. + Writes take a file lock and replace the file atomically. ### Watch State @@ -425,7 +446,7 @@ For skills, omitting `--agent` makes `remove` act on all recipients and `list` s | Command | Behavior | | --- | --- | | `add` | Update the declaration, resolve, write, update the lock. Any stop leaves the declaration, lock and files unchanged | -| `update` | Re-resolve the declaration and show what would change against the files on disk. `--apply` writes the resolved content and the new lock together, showing the difference before it replaces drifted content. Without names it reconciles `"all"` selections with the source's membership; with names it touches only those skills, and a named skill missing upstream is an error. `--apply` lists the ChatGPT prompts whose content changed, since ChatGPT has to be updated by pasting the new render | +| `update` | Re-resolve the declaration and show what would change against the files on disk. `--apply` writes the resolved content and the new lock together, showing the difference before it replaces drifted content. Without names it reconciles all-member selections with the source's membership; with names it touches only those skills, and a named skill missing upstream is an error. `--apply` lists the ChatGPT prompts whose content changed, since ChatGPT has to be updated by pasting the new render | | `install` | Restore skills and instruction targets exactly as the lock records them, without resolving. It takes no `--agent` or `--mode` | | `list` | Installed skills, or managed sections and targets; with a source, what it provides | | `remove` | Remove from the declaration, files and lock | diff --git a/Documentation/README.md b/Documentation/README.md index b0dcf37..ce3b110 100644 --- a/Documentation/README.md +++ b/Documentation/README.md @@ -11,7 +11,8 @@ This directory indexes repository-native documentation for `core`. - `Migrations/`: transition and cutover records - `Archive/`: retired or superseded material kept for record - `Reference/`: supporting reference material and examples, including - [presentation reproduction](Reference/Presentation.md) + [presentation reproduction](Reference/Presentation.md) and + [user source access settings](Reference/UserSourceAccess.md) The [README logos](../.github/assets/logo/) are generated from the `core` entry in [the organization DESIGN][design]. The committed diff --git a/Documentation/Reference/APMImport.md b/Documentation/Reference/APMImport.md new file mode 100644 index 0000000..de6a2de --- /dev/null +++ b/Documentation/Reference/APMImport.md @@ -0,0 +1,22 @@ +# Importing APM files + +Select one document for each import. Use the APM manifest profile to preview +a package declaration or the APM lock profile to inspect exact revisions. Each proposal +identifies accepted source declarations, selectable components, unresolved +inputs and diagnostics at their original locations. Review the proposal in +the destination scope before applying it. + +| Input | Behavior | +| --- | --- | +| Package name, version and target information | The importer checks the manifest shape and translates recognized targets. Conflicting target declarations produce diagnostics. | +| APM dependencies | Supported Git references and local package paths become candidate sources. Local package contents are inspected within the selected input directory. | +| APM lock file | Its own proposal records exact commits, source coordinates and transitive entries from the lock. | +| Incomplete, ambiguous or unsupported input | The diagnostic identifies the affected location. Review unresolved entries before selecting components. | + +The import profile reads APM dependency mappings under `dependencies.apm`. +Entries under `dependencies.mcp` require separate configuration via MCP +Registry selection or the Agents manifest. The installed configuration uses the +Agents YAML declaration and JSON lock. + +See the upstream [APM manifest schema](https://microsoft.github.io/apm/reference/manifest-schema/) +and [package installation guide](https://microsoft.github.io/apm/consumer/install-packages/). diff --git a/Documentation/Reference/AgentClients.md b/Documentation/Reference/AgentClients.md new file mode 100644 index 0000000..82c4b0c --- /dev/null +++ b/Documentation/Reference/AgentClients.md @@ -0,0 +1,70 @@ +# Passive agent client inspection + +`AgentsUpdates` exposes a synchronous, read-only client observation API. Supply +one captured `RuntimeEnvironment`; the default scope is `.user`. + +```swift +import AgentsCore +import AgentsUpdates + +let environment = RuntimeEnvironment() +let report = try AgentClientOperations.inspect(environment: environment) +for client in report.clients { + for command in client.commands { + print(client.agent.displayName, command.name, command.status.rawValue) + print(command.version.rawVersion ?? "Unknown") + } +} +``` + +`AgentClientInspection` and its immutable `Sendable` records describe the +observation interval, captured project/home context, PATH coverage, command and +application observations, logical configuration locations and frozen schema +evidence. Request `.project` with the selected project's explicit environment +to inspect its locations. + +Command lookup searches only absolute entries in the supplied PATH, in order, +and stops at the first regular executable for each command. Empty and relative +entries appear in `excludedEntries`. `lookupIssues` preserves failed access +before a selection; a later selection then does not guarantee shell resolution. +Missing commands mean no executable was found within this coverage. Shell +aliases, functions and installations outside PATH are outside this observation. +Cursor's `editorLauncher` and `agentCLI` records are separate. + +On macOS, application lookup uses registered bundle identifiers with an existing +discovery recipe and validates the bundle's metadata identity. Other platforms +report application lookup as unavailable. Currently the evidenced application +recipe is Cursor; other agents return an unavailable application observation. +Only Cursor's recognized editor launcher layout is associated with that bundle. +Other executable layouts return `unrecognizedLayout`; arbitrary neighboring +package metadata and directory labels do not supply versions. + +Versions retain raw labels. Bundle version and build are separate fields, with +metadata URL/key provenance. Missing, unreadable, malformed, oversized or +non-regular metadata has a typed `unknownReason`. Metadata reads follow ordinary +installation symlinks, validate the opened descriptor and enforce a 1 MiB limit +throughout reading. Inspection never executes candidate files. + +Configuration locations come from their existing skill, instruction and native +route owners. Presence checks inspect type only, without reading configuration +contents. Semantic records remain distinct when paths coincide, including +Claude local/user MCP regions. OpenCode JSON and JSONC alternatives are both +reported. Skill scan paths and installation destinations have different +purposes. Gemini/OpenCode skill and native overrides follow their respective +owners, so their paths can differ. Invalid native overrides affect their own +location observations; absent roots still yield logical paths. + +Schema evidence preserves the registry's surface, component kind, scope and +standalone/plugin-member placement. `recorded` means the profile has frozen +schema evidence; `unsupportedUnderEvidence` reflects an explicit unsupported +contract, and `unverified` means the contract is not established. Revisions and +source references are evidence provenance. In particular, `installed:2.1.309` +is a historical evidence revision, not a currently detected client version. +Preview remains responsible for configuration admission. + +Consumers should run inspection on their existing operation executor and retain +the latest result in their client settings state. Re-detection is explicit. +Returned paths are provenance, rather than workspace-monitor read footprints. +Unknown versions, missing clients and detection failures do not change editing +availability. The report is an interval of observations, rather than an atomic +filesystem snapshot. This operation neither recovers nor writes managed state. diff --git a/Documentation/Reference/AuthorPackaging.md b/Documentation/Reference/AuthorPackaging.md new file mode 100644 index 0000000..a5bc32e --- /dev/null +++ b/Documentation/Reference/AuthorPackaging.md @@ -0,0 +1,138 @@ +# Author project packaging + +Use `AuthorPackageOperations` in `AgentsUpdates` to build an Agents bundle +from an author project, even when no client has installed its components. A +project's author specification is separate from its installation declaration. + +## Inputs and review + +`scaffold(_:at:environment:)` creates a new directory below an existing +parent. It writes `author-package.json`, an empty `.agent/agents.yaml`, and +one complete starter skill. It does not choose a license, initialize Git, or +install anything. It refuses an existing directory unless its tree exactly +matches the scaffold. + +In `author-package.json`, `package` is a `BundlePackage`; the other fields +are explicit selections: + +| Field | Selects | +| --- | --- | +| `instructions` | Named instruction sections under `.agent/instructions/`, without the `.md` suffix. A referenced local attachment must be a regular file within that instruction container. | +| `skills` | Project-relative author-owned directories containing `SKILL.md`. Each entire directory is included. | +| `mcpServers` | Unambiguous, unconditional first-party MCP names in the root `.agent/agents.yaml` components list. | +| `lockedMembers` | Unique `{ "kind": "...", "name": "..." }` members of the project's verified `agents.resolved`. Kinds are `instructions`, `skills`, and `mcpServer`. | + +Use first-party paths only for content you own. Use locked members for vendored +content rather than choosing installed client files as author inputs. Embedded +objects and exact offline Git resources are verified against the lock. +Live edit resources, missing locks or objects, ambiguous members, and digest +mismatches fail. Packaging does not solve a different release, access a +dependency catalog, or read client deployments. `package.dependencies` can +separately declare portable marketplace requirements for later resolution by an +Agents consumer; that does not implicitly vendor any members. + +`preview(environment:)` reads the specification. `preview(_:environment:)` +accepts the same specification as a Swift value. Both return an +`AuthorPackageArtifact` with the exact canonical archive, SHA-256 digest, +component and source evidence, included paths, and separate content, policy, +and credential-omission findings. The preview leaves source state and output +destinations untouched. Paths, link spellings, executable flags, objects, and +metadata enter the archive identity. Local checkout and catalog paths do not. + +Only selected inputs and their included support are scanned. Credential +filenames such as `.env`, `.env.*`, `*.pem`, `*.key`, `id_rsa` and +`id_ed25519` are refused, not silently skipped. Tree links must be relative +and resolve within the included tree. Marked-up local references in instruction +sections and skill manifests must resolve within the packaged resource root. +Hard-linked author files are refused. Other hidden characters are reported with +locations; audit findings do not change the underlying bytes. These checks do +not certify arbitrary file contents as free of secrets. + +MCP environment and secret references stay symbolic. Both author capture and +`BundleOperations.export` preserve a literal environment value or header only +when it matches a public fixed value, default, or choice from the selected +registry server version and transport. Selection records the invocation and +public input fingerprints so these values can be packaged offline. Callers +can supply a typed `MCPRegistryServer` in `registrySchemas:` to validate the +values against that exact schema. An unverified literal requires a new +registry selection, a matching schema, or a symbolic reference. + +New author captures report omitted credential-like native fields and command +arguments. Credential-bearing endpoints and unbound absolute resource +coordinates are refused. A first-party MCP can declare a relative executable +and working directory within its selected source. Capturing a declaration +never starts a process. + +## Save and publish + +- `write(_:to:environment:)` saves a captured archive file. +- `publish(_:to:environment:)` publishes the captured archive to an existing + local Agents marketplace, using its authored description as the summary. +- `readArchive(at:expectedDigest:environment:registrySchemas:)` reads a + selected archive file once and admits those exact bytes for review and later + output. The archive carries the fingerprints for selected public inputs. +- `rebuild(expectedDigest:environment:)` and + `rebuild(_:expectedDigest:environment:)` require the reviewed digest when + reconstructing from source in another process. + +In an interactive flow, show the preview and retain the capture until the user +chooses to write or publish. Do not rebuild from source under that decision. +Supply the same trusted environment to every operation. The author publisher +and `MarketplaceOperations.publishBundle` read fresh source and organization +policies for the archive and destination before creating release files. Both +revalidate file-backed policy before the final rename. When schema validation is requested, the capture retains those schemas +for its later write or publication. + +Named marketplace releases retain their package name, version and archive +digest. Hosted releases also retain the exact HTTPS index and recorded +download routes, so the recipient can apply policy to the original package +and paths. Checkout and installation paths are omitted. Author captures use +portable local catalog evidence, and installed exports can retain an observed +local catalog directory for recipient policy. + +Output stages beside the destination. The operating system must support atomic +no-replace rename on that volume. The same archive or complete tree is +idempotent; conflicting paths are never overwritten. Immutability here describes +the publication guarantee, not OS write protection against another program. +An interrupted process can leave a private `.stage-…` sibling, not a partially +published artifact. Existing bundle APIs and archives without author metadata +remain supported; clients reading archives with the new optional author or +dependency-provenance fields need a reader that understands those fields. + +## Native plugin export + +`NativePluginOperations.preview(_:for:marketplace:environment:)` takes a +checked author package capture and returns a `NativePluginArtifact`. +`write(_:to:expectedDigest:environment:)` writes only that complete tree; +use the native digest if rebuilding the native tree for a later write. +The native preview lists all files, links, modes, and findings, and +`contents(at:)` provides a file's exact bytes for inspection. + +Native outputs require a lowercase kebab-case package name, a canonical +SemVer version, a description and an author. All support complete skills in +`skills/` and compatible MCP declarations in `.mcp.json`: + +| Client | Plugin manifest | Optional one-plugin marketplace | +| --- | --- | --- | +| Claude Code | `.claude-plugin/plugin.json` | `.claude-plugin/marketplace.json` | +| Codex compatibility layout | `.codex-plugin/plugin.json` | `.agents/plugins/marketplace.json` | + +The optional marketplace wraps the plugin at `plugins//`, supplies its +listing metadata and points to that directory with a local relative reference. +For Codex, the caller supplies a listing category. Export cannot install or +register this marketplace. + +Claude Code supports symbolic environment and sensitive `userConfig` +references, SSE, and bundled executables resolved via +`${CLAUDE_PLUGIN_ROOT}`. Codex supports streamable HTTP and stdio with a +named executable, HTTP header environment references, and same-name stdio +environment forwarding. The +current projections refuse authored MCP working directories, target-specific +native overrides, Agents catalog requirements, and instruction sections, +rather than emitting files the client will not load. Prepare a separate +explicit selection for the native target if needed. The client owns installation +and removal; Agents still owns its independent bundle deployment and lock. + +Layout sources: [APM pack behavior](https://microsoft.github.io/apm/reference/cli/pack/), +[Claude Code plugin reference](https://code.claude.com/docs/en/plugins/manifest-reference), +and [Codex plugin packaging](https://developers.openai.com/plugins/build/plugins). diff --git a/Documentation/Reference/ContentAudit.md b/Documentation/Reference/ContentAudit.md new file mode 100644 index 0000000..9154eb4 --- /dev/null +++ b/Documentation/Reference/ContentAudit.md @@ -0,0 +1,65 @@ +# Content audit + +Use `ContentAuditOperations` from `AgentsUpdates` to inspect local prompts. +A scope scan discovers recognized files even before `agents.resolved` exists. +Pass `agents:` to limit discovery to selected readers. An explicit file scan +accepts a recognized native document or a Markdown or plain text prompt +(`.md`, `.mdc`, `.txt`, `.prompt`) inside the selected project or home. + +```swift +import AgentsCore +import AgentsUpdates +import Foundation + +let project = URL(fileURLWithPath: "/path/to/project", isDirectory: true) +let environment = RuntimeEnvironment(projectDirectory: project) +let audit = ContentAuditOperations.scan(environment: environment) +let status = audit.ciExitCode +let sarif = try audit.export(.sarif) + +let prompt = project.appendingPathComponent("AGENTS.md") +let fileAudit = ContentAuditOperations.scan(file: prompt, environment: environment) +func stripReviewedPrompt( + _ file: URL, environment: RuntimeEnvironment, + approve: (ContentAuditStripPreview) throws -> Bool +) throws { + let preview = try ContentAuditOperations.previewStrip(file: file, environment: environment) + if try approve(preview) { try ContentAuditOperations.applyStrip(preview) } +} +``` + +| Agent | Prompt surfaces | +| --- | --- | +| Codex | `AGENTS.md` and overrides, `SKILL.md` entries, `developer_instructions` in agent TOML | +| Claude Code | Context files, Markdown rules, commands and agents, `SKILL.md` entries, `prompt` on nested prompt and agent hooks | +| Cursor | Context files, Markdown commands and agents, MDC rules, `SKILL.md` entries, `prompt` on flat prompt hooks | +| Gemini CLI | Context files, Markdown agents, `SKILL.md` entries, `prompt` in command TOML | +| OpenCode | Context files, Markdown commands and agents, `SKILL.md` entries, command `template` and agent `system` fields in native JSON or JSONC | +| Antigravity | Project rules and skill entry points, and user rules and skills in the native config directory | + +Project discovery also covers local `.agent/instructions`. Use `scope: .user` with +the intended home in `RuntimeEnvironment` for user profiles. Discovery stays +inside that scope, skips nested repositories and protected paths, and admits +linked skills through a matching in-scope ledger entry. Structured documents +contribute only recognized decoded prompt fields. A recognized document without +prompt fields appears as skipped. Source coordinates use one-based UTF-16 +columns. Native findings carry a field pointer, decoded coordinates, and +physical coordinates when the literal spelling can be mapped. + +The gate fails for critical Unicode, incomplete coverage and detected +recorded-content drift. Warnings and informational findings pass the gate. +`scanExitCode` distinguishes warning-only reports from clean or informational +reports. Scope scans compare present, admitted prompts to recorded file hashes +where available. Shared settings attribute managed fields using ledger region +evidence. Combine this report with existing lifecycle inspection for +deployment presence, source policy and full deployment drift. Explicit file +scans use ledger ownership and omit the recorded hash comparison. The report +exports JSON, SARIF 2.1.0 and Markdown with scope-relative locations. [APM audit reference](https://microsoft.github.io/apm/reference/cli/audit/) · [Baseline content-integrity check](https://microsoft.github.io/apm/reference/baseline-checks/#content-integrity) + +Strip is a separate one-file operation for explicitly selected regular text +prompts. The preview identifies deletions by exact UTF-8 byte ranges and +preserves the BOM, line endings and informational characters. Apply revalidates +the file identity and reviewed bytes before publishing the replacement. Native +settings and linked files require manual edits. Rerun the audit after applying +a strip. A managed file edited in place may then need changes to its source +and a refreshed deployment. diff --git a/Documentation/Reference/MCPRegistry.md b/Documentation/Reference/MCPRegistry.md new file mode 100644 index 0000000..c494944 --- /dev/null +++ b/Documentation/Reference/MCPRegistry.md @@ -0,0 +1,118 @@ +# Install an MCP server from a registry + +The `AgentsUpdates` registry API reads the public MCP Registry or a configured +v0.1 subregistry. A consumer can browse pages, inspect a specific version, choose +one of its remote or package configurations, and preview a managed server in a +project or user scope. + +## Find a version + +```swift +import AgentsCore +import AgentsUpdates +import Foundation + +let registry = MCPRegistry.official +let page = try await registry.search("weather", limit: 20) +if let cursor = page.nextCursor { + let next = try await registry.search("weather", limit: 20, cursor: cursor) + // Display next.servers. +} +``` + +Omit the search text to list servers. The default version filter is `"latest"`. +Pass an exact version or pass `nil` to browse all versions. Reuse the cursor with +the same registry and query. To retrieve a known version directly, call +`server(named:version:credentials:scope:environment:)` with the full registry name. An omitted +version resolves the registry's latest alias and returns its exact version. + +For a private registry, initialize `MCPRegistry(endpoint:)` with the base URL +before `/v0.1`, including any deployment path prefix. Pass authorization or an +API key as `credentials` headers on each request. Requests with credentials +require HTTPS, with HTTP available on the loopback IP addresses. The client +rejects redirects and uses no stored cookies, credentials, or cache. The +credential headers are used only for the registry request. Pass the consuming +`scope` and `environment` to discovery so the project, user and configured +organization policies can check the registry origin before the request. + +## Select a choice and preview its targets + +Each version returns its remote and package choices. Display the endpoint or +package coordinates, transport, binding requirements and any +`unavailableReason`. Supply `.environment(name)` for symbolic inputs and +`.choice(value)` for inputs restricted to listed values. A non-secret default +is used when the input has no listed choices and the caller leaves it unset. +HTTP header references supply the entire header value. The variable for bearer authorization +contains the `Bearer ` prefix as well as the token. Clients obtain these values +at run time. + +```swift +func previewRegistryChoice( + _ choice: MCPRegistryChoice, + named name: String, + agents: [AgentID], + bindings: [String: MCPRegistryBinding], + packageCommand: String? = nil, + scope: InstallScope, + environment: RuntimeEnvironment +) throws -> (UpdateRequest, CombinedUpdateReport) { + let destination = try UpdateOperations.inspect(scope: scope, environment: environment) + let discovery = try choice.select( + named: name, agents: agents, in: destination, bindings: bindings, + packageCommand: packageCommand) + let request = discovery.updateRequest() + let report = try UpdateOperations.preview(request, scope: scope, environment: environment) + return (request, report) +} +``` + +Use `compatibleAgents(in:bindings:packageCommand:)` to populate the recipient +picker for the configured choice. It uses the native adapters' transport and +symbolic reference rules. The preview then checks the actual destination, +including existing configuration and ownership. + +After confirmation, use `UpdateOperations.withPreparedUpdate` with the same +scope and environment and call +`apply(ifUnchangedFrom: report.displayedFingerprint)`. The transaction writes +the MCP declaration, lock, and selected client configuration. It uses the +captured endpoint or package coordinate even if the registry changes in the +meantime. The declaration and lock preserve the registry base URL, full +server name, exact server version, and selected endpoint or artifact origin. +For stdio, they also record the exact package or image coordinate. +`ComponentInspection.mcpRegistry` and portable bundles expose this evidence. +The invocation digest binds the record to the selected launcher, arguments, +transport and binding configuration. Reselect the exact registry version to +change those values. Older declarations and locks can still be read and +restored when their launcher and package coordinate agree. Reselect legacy +records when organization policy requires verified registry selection or a +package export needs to verify which literal bindings came from that selection. + +Install, update and restore check the registry and selected origin under the +applicable policies. When egress is proxy-only, restore and the source and +organization CI audits require each locked registry to match the configured +HTTPS authority, port and base path. Searching, selecting, previewing and +applying do not start a server or run a package launcher. + +## Supported choices + +- Remote Streamable HTTP and legacy SSE use fixed HTTP(S) endpoints. A template + can use fixed, non-secret registry variables. A runtime-bound header requires + HTTPS or a loopback IP endpoint. +- Stdio packages support npm via `npx`, PyPI via `uvx`, and OCI via `docker`. + npm and PyPI require an exact package version. When `requiresPackageCommand` + is true, supply the Python distribution's console command as `packageCommand`. + OCI accepts a fixed tag or a SHA-256 image digest. Fixed package arguments and + process environment bindings are supported. Client-side runtime availability + and package access are the caller's responsibility. +- Choices requiring unresolved endpoint variables, dynamic command-line values, + custom launcher arguments, external package-file checksum verification, or + another package type carry an availability reason. Secret inputs are available + as symbolic header or environment bindings on clients that preserve those + references. + +The HTTP and metadata contracts are the [MCP Registry v0.1 OpenAPI +specification](https://github.com/modelcontextprotocol/registry/blob/main/docs/reference/api/openapi.yaml) +and the [2025-12-11 server schema](https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json). +The consumer workflow follows the public [APM MCP discovery +reference](https://microsoft.github.io/apm/reference/cli/mcp/) and [MCP installation +guide](https://microsoft.github.io/apm/consumer/install-mcp-servers/). diff --git a/Documentation/Reference/Manifest.md b/Documentation/Reference/Manifest.md new file mode 100644 index 0000000..b731954 --- /dev/null +++ b/Documentation/Reference/Manifest.md @@ -0,0 +1,268 @@ +# YAML Manifest + +A project declares intent in `.agent/agents.yaml`; user intent lives in +`~/.agents/agents.yaml`. Producers publish the same canonical filename under +`.agent/`, or `agents.yaml` when the producer root is itself `.agent`. +`agents.resolved` remains tool-owned JSON. + +```yaml +version: 1 +sources: + team: {url: https://github.com/example/config, requirement: {from: "1.0.0"}} +components: + - {kind: skills, source: team, select: [review], agents: [codex]} + - kind: instructions + sections: [{name: common}] + chatgpt: + review: {sections: [{name: common}], append: prompts/review.md} +groups: + checks: + components: [{kind: ignore, name: private, patterns: [private/**]}] +uses: [{group: checks}] +exports: [checks] +``` + +The source [JSON schema](../../Sources/AgentsManifest/Resources/agents.schema.json) +is the field-shape owner. [Generated field help](ManifestSchema.md) lists supported +shapes, field descriptions, examples and schema-owned collection bounds. The finite compiler +rejects unsupported validation keywords, values and combinations; its generated +rules enforce the accepted constraints. Parser and decoded-value safety budgets +apply independently of these field constraints. +Unknown fixed fields, decoded duplicate keys and invalid scalar +kinds are errors. Domain validation also checks unused groups and inactive +components. References remain symbolic until linking; declaration reads never +resolve sources, access resources or execute component programs. + +Git requirements also apply to local Git repositories declared with `path`; +their local source identity and declaring environment remain unchanged. +Aliases can share a repository by selecting distinct `subpath` discovery roots. +The source alias on each section selects its discovery root. + +## Values and Ordering + +Sources, groups, components, uses, exports, prompt sections and named ChatGPT +prompts retain order and occurrences. Ordinary dictionaries and NativeValue +objects have unordered domain semantics while their untouched document spelling +is preserved. Omitted recipients/condition dimensions inherit or impose no +restriction; explicit empty lists select nothing. Omitted `select` means all; +`select: []` selects none. Watch omission and an empty list are equivalent, and +watch order is set-like. Ordinary optional fields do not accept null. + +Scalar resolution follows YAML 1.2 Core. `yes`, `on` and dates are strings; +quoted and block scalars are strings. Integer fields require representable plain +integers. Native values also admit finite decimals, arrays, objects and null. +Every decimal is written as `!!float ""`; integer-shaped +payloads, negative zero, exponent spelling and trailing zeroes retain identity. +This tag is permitted only on NativeValue scalars. `<<` is an ordinary data key. + +Core diagnostics are authoritative for YAML admission, scalar kinds, numeric +identity and domain relationships. General JSON Schema treats `1.0` as a +mathematical integer and cannot preserve decimal lexical identity. + +UTF-8, a leading BOM, LF/CRLF, block and flow collections and all ordinary scalar +styles are supported. Raw NEL, line separator and paragraph separator characters +are rejected before either parser; use double-quoted escapes `\u0085`, +`\u2028` and `\u2029` to retain those exact characters. Anchors, aliases, +directives, complex keys, multiple documents and other tags are rejected. + +## Package-manager Lifecycle + +The optional `lifecycle` mapping defines ordered action arrays for +`pre-install`, `post-install`, `pre-update`, `post-update`, +`pre-uninstall`, `post-uninstall`, and `pre-compile`. Repeated entries +are separate actions. The user manifest and consuming project manifest can +each declare actions. Administrators can supply version 1 JSON files in +`/etc/agents/lifecycle.d` with a `scripts` mapping of the same shape. +Administrator files run in filename order, followed by the user and project +declarations. + +```yaml +version: 1 +lifecycle: + pre-install: + - type: command + run: 'printf "%s\n" "Preparing package installation"' + timeout: 10 + post-install: + - type: http + url: https://example.invalid/lifecycle + headers: + X-Build: "${BUILD_ID}" + timeout: 5 +``` + +A command action selects one of `bash`, `command` or `run`. It may supply +an `env` mapping of string overrides. A webhook supplies an HTTPS `url` +and may supply `headers` and `allowedEnvVars`. Header values can reference +`$NAME` and `${NAME}` from the invocation's environment. Credential-like +names require an exact match in that action's `allowedEnvVars` sequence. +The optional `timeout` is a whole number of seconds from 1 through 300. +The default is 30 seconds. + +Commands run in the confirmed operation's project root or, for user scope, +in the user home. The shell gets an event JSON object on stdin and runs with +the user's access. It may invoke mutable checkout files outside the reviewed +digest. Webhooks receive the same event JSON by HTTPS POST. Review project +actions locally before enabling that project. See the [confirmed operation +contract](../Architecture/Updates.md#package-manager-lifecycle). + +## Marketplace Packages + +A package root names a catalog, package and SemVer requirement. The root +alias is local to the declaring scope. Relative catalog paths are anchored +at the project directory or the user home for user-scoped roots. + +```yaml +version: 1 +packages: + team-start: + catalog: {kind: directory, location: "./team-catalog"} + package: starter + requirement: {from: "1.2.0", to: "2.0.0"} + selections: + - package: shared-tools + member: {kind: skills, name: review} + targets: [codex, claude-code] +``` + +`exact` matches the complete version, including build metadata. `from` alone +sets an exclusive upper bound at the next major version, including when the +lower major is zero. `upToNextMinor` sets an exclusive bound at the next minor +version. `from` with `to` gives an inclusive lower and exclusive upper bound. +A range admits a prerelease only when one of its bounds is a prerelease with +the same major, minor and patch. A root can also specify `version` for an exact installation. + +A member selection identifies a logical member by kind and name. It defaults +to the root's catalog. Use an explicit portable Git `catalog` to select a +member from another reachable catalog. An empty or omitted selection list +records package requirements with no enabled members for that root. The +union of all requesting roots' recipients controls deployment. New members +need a selection in the declaration to receive targets. + +The portable bundle's `BundlePackage.dependencies` list is authoritative at +publication and acquisition. Each dependency defaults to the publishing +catalog and can specify an explicit remote Git catalog. Catalog identity +includes Git subpath. A resolution uses one discovery ref per catalog. + +Use `MarketplaceOperations.resolve` to discover available versions and +members, then `previewResolution` and `withPreparedResolution` to publish +the reviewed changes. `reconcile` resolves hand-edited roots and can +reconstruct a missing lock. A targeted `upgrade` prefers newer eligible +versions in that root's reachable graph. `remove` uses the committed graph +and drops only the removed root's contribution. Frozen `UpdateOperations.restore` +uses the recorded graph and embedded producer material. + +## Instruction recipients + +Set `recipients` on an ordered instruction section to select exactly where it +is rendered. Omit it to inherit the component's `agents` or the declaration's +`defaultAgents`. An empty list selects no outputs. The six local agent IDs +can share a list with `chatgpt-app` and `gemini-app`, which produce Markdown +for copying. Scope and platform conditions constrain every recipient. Agent +conditions constrain the local agents. + +```yaml +components: + - kind: instructions + sections: + - {source: team/rules, name: code-review, recipients: [codex, chatgpt-app]} + - {source: team/rules, name: writing, recipients: [chatgpt-app, gemini-app]} +``` + +## Antigravity + +Include `antigravity` in the component's recipients or declaration defaults. +Use section conditions when recipients need different instructions. Here `team` +is an existing source alias. + +```yaml +components: + - kind: instructions + agents: [codex, antigravity] + sections: + - {source: team, name: code-review, condition: {agents: [codex]}} + - {source: team, name: general-review, condition: {agents: [antigravity]}} +``` + +| Component | Project | User | +| --- | --- | --- | +| Instructions | `.agents/rules/.md` | `~/.gemini/config/rules/.md` | +| Skills | `.agents/skills//SKILL.md` | `~/.gemini/config/skills//SKILL.md` | +| MCP | `.agents/mcp_config.json` | `~/.gemini/config/mcp_config.json` | +| Hooks | `.agents/hooks.json` | `~/.gemini/config/hooks.json` | + +Project skill selections can share one physical skill with other recipients. +Removal keeps the directory while a recipient still owns it. Distinct contents +at a shared skill destination conflict. In `agy`, skills in the CLI-specific +user directories can take precedence over the common user directory. + +MCP names own individual `mcpServers` +entries. Antigravity supports stdio and Streamable HTTP, with remote endpoints +written as `serverUrl`. The adapter accepts `disabled`, `enabledTools` and +`disabledTools`, plus `authProviderType: google_credentials` for remote servers. +Binding materialization uses the normal private Core update path. Registry +choices requiring symbolic environment references are unavailable because the +target profile has no documented interpolation syntax. An explicit workspace +selection permits Core to create `.agents/`. +[Customization discovery](https://antigravity.google/docs/customization-discovery) · +[Skills](https://antigravity.google/docs/skills) · [MCP](https://antigravity.google/docs/mcp) + +Use `event: {kind: native, value: PreToolUse}` for a hook whose program understands +Antigravity's JSON input and output. The supported native names are `SessionStart`, +`PreToolUse`, `PostToolUse`, `PreInvocation`, `PostInvocation` and `Stop`. Only +tool events accept a matcher. Matchers use Antigravity tool names and the +supported subset of literal names, alternatives, anchors and trailing `.*`. +`timeoutSeconds` is emitted in seconds. The component name owns one top-level +hook entry. Identical declarations can share that entry. Conflicting declarations +or a handwritten entry with the same name require resolution before applying. +[Hooks](https://antigravity.google/docs/hooks) · +[APM target matrix](https://microsoft.github.io/apm/reference/targets-matrix/#antigravity) · +[Rule rendering and limits](../Architecture/Instructions.md#antigravity-rules) + +## Edits and Source Maps + +`DeclarationDocument` exposes complete IR and semantic JSON Pointer locations: +`sources.team` maps to `/sources/0`, its key to `/sources/0/name`, and nested +group components to `/groups/0/components/...`. Handles belong to one digest. +`ManifestEdit` accepts Core domain values and prepares bytes without writing. +Agents App uses these document and edit APIs for configuration editing. Save +operations preserve YAML text and scalar identity through the prepared edits. + +Editing a named source uses `replaceSource(sourceNode, with: replacement)`, where +`sourceNode` is captured from `/sources/` in the current document snapshot. +The replacement retains collection position and rewrites typed references to the +old alias, including declaration `watch`, root and unused-group references, +executable sources and independent working-directory sources. Native data and +other strings remain unchanged. Same-alias replacement updates the definition; +new sources use `upsertSource`. Handles and the expected document digest must come +from the same snapshot. Invalid final source kinds, modes or aliases are rejected; +persisted Watch source-identity keys are outside document editing. + +No-op changes return exact bytes. Changed fields and collection entries preserve +unrelated bytes. Adjacent leading comments and same-line trailing comments belong +to their item; moves carry them. Deletion retains comments unless explicitly +owned by a replaced value. Blank-separated headers belong to their container. +Special layouts that cannot be changed precisely fail before publication. + +Complete declaration planning composes private parser/schema-checked drafts, +refreshes occurrence ranges and verifies full expected IR at every step. Final +domain and environment validation precede returning any candidate bytes. +Public documents and public prepared changes never expose unchecked drafts. + +## Bounds and Dump + +Input is bounded at 2,097,152 bytes; CSTs at 100,000 nodes/depth 128; decoded +values at 100,000 nodes/depth 64, 10,000 entries per container and 16,777,216 +string bytes. Parser-stage progress callbacks enforce an additional measured +work bound before CST traversal. Scalar scanning remains input-byte bounded; +these are work limits, not a claim of a fixed allocation bound. + +Source maps admit 100,000 locations, 1,000,000 origins and 16,777,216 encoded +bytes. Dump output is bounded at 33,554,432 bytes. Public edit batches admit 100 +requests, with 200,000 comparison pairs and 1,000,000 editing steps. Private +composition retains finite total work and bounded internal batches. + +`ManifestDump` uses schema version 2, `format: "yaml"`, manifest version 1, +source digest, complete typed IR and indexed locations. Decimal records retain +`{kind: "decimal", value: ""}`; arbitrary native object keys cannot +collide with this dump-only envelope. diff --git a/Documentation/Reference/ManifestSchema.md b/Documentation/Reference/ManifestSchema.md new file mode 100644 index 0000000..7478ec6 --- /dev/null +++ b/Documentation/Reference/ManifestSchema.md @@ -0,0 +1,668 @@ +# Manifest Field Shapes + +Generated from `Sources/AgentsManifest/Resources/agents.schema.json`. + +## Declaration + +Version 1 declaration of symbolic sources, components and groups. Parsing validates supplied YAML without resolving sources, reading referenced resources or running programs. Unknown fixed fields and null optional fields are errors; omitted collections are empty unless a field says otherwise. Core diagnostics also enforce YAML scalar kinds, numeric identity and domain relationships that general JSON Schema cannot express. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `version` | yes | `1` | Required manifest version, written as the plain integer 1. Core rejects decimal spelling such as 1.0 even when a JSON Schema validator treats it as an integer. | +| `defaultAgents` | | sequence of agent (at most 10000 items) | Default recipients for components that omit agents. Omission defaults to codex and claude-code; an empty list selects no recipients. Component overrides and conditions further determine effective targets.
Examples: ["codex", "claude-code"], [] | +| `sources` | | name → source (at most 10000 properties) | Source aliases local to this declaration, retained in declaration order. References use these keys; aliases must be nonempty, must not be . or contain a colon, and must identify distinct normalized sources. Omission or an empty mapping declares none. | +| `packages` | | name → marketplacePackage (at most 10000 properties) | Marketplace roots keyed by consumer alias. Each root specifies a catalog, package and version requirement. Member selections record the recipients requested by that root. | +| `components` | | sequence of component (at most 10000 items) | Direct component declarations, retained in order and checked even when their conditions select no targets. Omission or an empty sequence declares none. | +| `groups` | | name → group (at most 10000 properties) | Named reusable groups, retained in declaration order. Defining a group does not activate it; uses selects it and exports makes it available to importers. Unused groups are still validated. | +| `uses` | | sequence of use (at most 10000 items) | Group references expanded in declaration order. Omission or an empty sequence activates no groups. Local reference cycles are errors, including in inactive groups. | +| `exports` | | sequence of string (at most 10000 items) | Names of local groups available to importing declarations, retained in order. Every name must name a declared group and occur once. Omission or an empty sequence exports none. | +| `lifecycle` | | lifecycle | Ordered package-manager lifecycle actions. Project execution requires explicit local trust. | +| `watch` | | sequence of string (at most 10000 items) | Source aliases subscribed independently of installations. Names must be unique and refer to declared source aliases. Omission and an empty sequence are equivalent; watch order has set-like semantics. | + +## lifecycle + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `pre-install` | | sequence of lifecycleAction (at most 128 items) | | +| `post-install` | | sequence of lifecycleAction (at most 128 items) | | +| `pre-update` | | sequence of lifecycleAction (at most 128 items) | | +| `post-update` | | sequence of lifecycleAction (at most 128 items) | | +| `pre-uninstall` | | sequence of lifecycleAction (at most 128 items) | | +| `post-uninstall` | | sequence of lifecycleAction (at most 128 items) | | +| `pre-compile` | | sequence of lifecycleAction (at most 128 items) | | + +## lifecycleAction + + + +### Alternative 1 + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `type` | yes | `command` | | +| `bash` | yes | string | | +| `env` | | name → string (at most 128 properties) | | +| `timeout` | | integer ≥ 1 | | + +### Alternative 2 + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `type` | yes | `command` | | +| `command` | yes | string | | +| `env` | | name → string (at most 128 properties) | | +| `timeout` | | integer ≥ 1 | | + +### Alternative 3 + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `type` | yes | `command` | | +| `run` | yes | string | | +| `env` | | name → string (at most 128 properties) | | +| `timeout` | | integer ≥ 1 | | + +### Alternative 4 + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `type` | yes | `http` | | +| `url` | yes | string | | +| `headers` | | name → string (at most 128 properties) | | +| `allowedEnvVars` | | sequence of string (at most 128 items) | | +| `timeout` | | integer ≥ 1 | | + +## marketplacePackage + + + +### Alternative 1 + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `package` | yes | string | | +| `version` | yes | string | | +| `catalog` | yes | marketplaceCatalog | | + +### Alternative 2 + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `package` | yes | string | | +| `requirement` | yes | marketplaceRequirement | | +| `catalog` | yes | marketplaceCatalog | | +| `selections` | | sequence of marketplaceSelection (at most 1024 items) | | + +## marketplaceRequirement + + + +### Alternative 1 + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `exact` | yes | string | | + +### Alternative 2 + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `from` | yes | string | | + +### Alternative 3 + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `upToNextMinor` | yes | string | | + +### Alternative 4 + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `from` | yes | string | | +| `to` | yes | string | | + +## marketplaceSelection + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `package` | yes | string | | +| `catalog` | | marketplaceCatalog | | +| `member` | yes | mapping | | +| `targets` | yes | sequence of agent (at most 6 items) | | + +## marketplaceCatalog + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `kind` | yes | `directory` / `git` / `hosted` | A local catalog directory, Git catalog or hosted HTTPS index. | +| `location` | yes | string | A project-relative or absolute path for a directory, a Git repository locator, or a hosted HTTPS index URL. | +| `ref` | | string | Git commit, branch or tag for release discovery. Omission uses the default branch. | +| `subpath` | | string | Relative directory inside the Git catalog tree. | + +## agent + +Recipient identifier. Support for deploying an individual component is checked by its consuming operation; accepting the identifier does not imply every component is supported by that client. + +`codex` / `claude-code` / `cursor` / `gemini-cli` / `opencode` / `antigravity` + +## condition + +Intersecting restrictions on recipients, scope and platform. Omitted dimensions impose no restriction; an explicit empty dimension matches nothing. Nested group, use, component and section conditions combine by intersection, without removing inactive intent from the declaration. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `agents` | | sequence of agent (at most 10000 items) | Only these recipients remain eligible. Omission leaves recipients unrestricted; an empty list matches none. Duplicate recipients are errors. | +| `scopes` | | sequence of `project` / `user` (at most 10000 items) | Only these installation scopes match. Omission allows either scope; an empty list matches neither. Duplicate scopes are errors. | +| `platforms` | | sequence of `macos` / `linux` (at most 10000 items) | Only these operating systems match. Omission allows either platform; an empty list matches neither. Duplicate platforms are errors. | + +## resource + +A resource path with an optional source alias. It remains symbolic during declaration reads; linking resolves and confines it to the selected source root. + +Examples: {"path": "prompts/review.md", "source": "team"} + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `path` | yes | string | Required relative resource path within the selected source. Absolute paths, home expansion and parent traversal are not allowed. | +| `source` | | string | Alias declared in this document. Omission or . uses the current declaring source; imported declarations retain their own source context. | + +## section + +One instruction section reference. Section sequences retain their declared order and occurrences; the referenced content is read only by the consuming operation. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `name` | yes | string | Instruction name relative to its instruction container, without .md. Nested names use / separators. | +| `source` | | string | Source alias for this section. Omission or . selects the declaring source's own instructions; root user instructions require a named source when linking. | +| `condition` | | condition | Additional restrictions for this section, intersected with enclosing conditions. Omission imposes no additional restriction. | +| `recipients` | | sequence of `codex` / `claude-code` / `cursor` / `gemini-cli` / `opencode` / `antigravity` / `chatgpt-app` / `gemini-app` (at most 8 items) | Exhaustive section recipients. Omission inherits the component's local recipients. An empty list selects none. ChatGPT App and Gemini App produce copyable text. Available on the component's sections. Named prompt sections inherit their prompt destination. | + +## binding + +A literal string or a symbolic local environment/secret binding. Declaration reads preserve the binding without looking up values. Only the consuming operation resolves bindings; they are not source-provided literals. + +Examples: "literal text", {"env": "SERVICE_TOKEN"}, {"secret": "service-token"} + +### Alternative 1 + +Literal text, used exactly as supplied. Strings resembling binding syntax are not interpolated. + +string + +### Alternative 2 + +Symbolic local environment binding; no value is captured in the declaration. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `env` | yes | string | Name of an environment variable resolved locally by the consuming operation. | + +### Alternative 3 + +Symbolic local secret binding; no value is captured in the declaration. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `secret` | yes | string | Name of a secret resolved locally by the consuming operation's binding provider. | + +## prompt + +Inline prompt text or a reference to a prompt file. Declaration reads do not read the file. Command input tokens use ${input:name}; $${input:name} escapes a literal token. + +### Alternative 1 + +Inline prompt body, including any literal newlines. + +string + +### Alternative 2 + +Prompt body read from a resource by the consuming operation. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `file` | yes | resource | Resource containing the prompt body, resolved in its declaring source context. | + +## run + +A declared invocation, preserved as data until a consuming operation explicitly uses it. It does not contain a shell command line. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `executable` | yes | string | Required program name or relative executable path. A bare name is resolved by the consuming operation; paths containing / are source resources. Reading the declaration never starts the program. | +| `arguments` | | sequence of string (at most 10000 items) | Arguments in invocation order, passed as individual strings. Omission or an empty sequence supplies no arguments. | +| `environment` | | name → binding (at most 10000 properties) | Environment variable names mapped to literals or local bindings. Omission or an empty mapping supplies no declared entries; reading the declaration does not resolve bindings. | +| `workingDirectory` | | resource | Working directory resource, resolved by the consuming operation. Omission leaves the directory unspecified in the declaration. | +| `executableSource` | | string | Source alias for a resource executable path. Omission uses the declaring source; a bare PATH command cannot specify a source. | + +## transport + +MCP connection declaration: a local stdio invocation, Streamable HTTP or SSE. Parsing neither starts a server nor opens a connection. + +### Alternative 1 + +Local MCP server invocation over standard input/output. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `kind` | yes | `stdio` | Selects the local stdio transport. | +| `executable` | yes | string | Required program name or relative executable path. A bare name is resolved by the consuming operation; paths containing / are source resources. Reading the declaration never starts the program. | +| `arguments` | | sequence of string (at most 10000 items) | Arguments in invocation order, passed as individual strings. Omission or an empty sequence supplies no arguments. | +| `environment` | | name → binding (at most 10000 properties) | Environment variable names mapped to literals or local bindings. Omission or an empty mapping supplies no declared entries; reading the declaration does not resolve bindings. | +| `workingDirectory` | | resource | Working directory resource, resolved by the consuming operation. Omission leaves the directory unspecified in the declaration. | +| `executableSource` | | string | Source alias for a resource executable path. Omission uses the declaring source; a bare PATH command cannot specify a source. | + +### Alternative 2 + +Remote MCP endpoint with optional literal or locally bound headers. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `kind` | yes | `streamableHTTP` / `sse` | Selects Streamable HTTP or SSE transport. | +| `url` | yes | string | Required HTTP or HTTPS endpoint with a host and no embedded credentials or fragment. | +| `headers` | | name → binding (at most 10000 properties) | HTTP header names mapped to literals or local bindings. Omission or an empty mapping supplies no declared headers. Values remain unresolved during declaration reads. | + +## event + +Portable hook event or a client-native event name. A native event requires exactly one explicit component recipient. + +### Alternative 1 + +Portable event mapped by the target client adapter. + +`beforeTool` / `afterTool` / `sessionStart` / `sessionEnd` + +### Alternative 2 + +Client-specific hook event; support is checked by the consuming adapter. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `native` | yes | string | Event name in the selected client's vocabulary; the component must explicitly target exactly one agent. | + +## operation + +Portable permission operation or a named client tool operation. Interpretation belongs to the target client adapter. + +### Alternative 1 + +Portable file-read, file-write or program-execution operation. + +`read` / `write` / `execute` + +### Alternative 2 + +Named tool operation interpreted by the target client. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `tool` | yes | string | Tool identifier to which the rule applies. | + +## rule + +One permission rule. Rules retain declaration order; the target client determines enforcement semantics. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `effect` | yes | `allow` / `ask` / `deny` | Allow, ask for confirmation, or deny the matching operation in the target client. | +| `operation` | yes | operation | Portable operation or named client tool to match. | +| `pattern` | yes | string | Match pattern interpreted for the operation by the target adapter. Read and write patterns must be safe relative resource paths. | + +## parameter + +A named command input. Parameter names must be unique within the command; inline prompt tokens must refer to declared parameters. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `name` | yes | string | Input token name used in ${input:name}. It must be nonempty and contain no }, colon or NUL. | +| `description` | yes | string | User-facing explanation of the input requested by the command. | +| `defaultValue` | | string | Optional literal default input text. Omission leaves the default unspecified; an empty string is an explicit empty default. | + +## promptDeclaration + +A named ChatGPT prompt composed from ordered instruction sections and an optional append file. Names are the keys in chatgpt; omission of sections means an empty sequence. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `sections` | | sequence of section (at most 10000 items) | Instruction sections in rendering order, including repeated references. Omission or an empty sequence supplies none. | +| `append` | | string | Relative file appended to the prompt by the consuming operation. In project scope it uses the declaring source; in user scope it is relative to the user home directory. Omission appends no file. | +| `condition` | | condition | Additional scope/platform restrictions for this named prompt. Omission imposes no additional restriction. | + +## override + +Per-skill recipient and installation-mode overrides. The mapping key is the skill name and must belong to an explicit selection when one is supplied. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `agents` | | sequence of agent (at most 10000 items) | Recipients for this skill instead of component/default recipients. Omission inherits; an empty list selects no recipients. Enclosing conditions still restrict the result. | +| `mode` | | `link` / `copy` / `edit` | Installation mode for this skill instead of the component mode. Omission inherits. edit requires a live local source without a requirement. | + +## requirement + +One Git selection policy, also applicable to local Git repositories. Version requirements select semantic-version tags; a resolved lock records the exact revision. Reading the declaration never performs resolution. + +Examples: {"from": "1.2.0"}, {"from": "1.2.0", "to": "2.0.0"}, {"branch": "main"} + +### Alternative 1 + +Track the named Git branch. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `branch` | yes | string | Track the named Git branch. | + +### Alternative 2 + +Select the specified Git revision. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `revision` | yes | string | Select the specified Git revision. | + +### Alternative 3 + +Select exactly this semantic version tag. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `exact` | yes | string | Select exactly this semantic version tag. | + +### Alternative 4 + +Inclusive semantic-version lower bound, below the next major version. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `from` | yes | string | Inclusive semantic-version lower bound, below the next major version. | + +### Alternative 5 + +Inclusive semantic-version lower bound, below the next minor version. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `upToNextMinor` | yes | string | Inclusive semantic-version lower bound, below the next minor version. | + +### Alternative 6 + +Semantic-version interval with an inclusive lower bound and exclusive upper bound. The lower bound must be less than the upper bound. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `from` | yes | string | Inclusive semantic-version lower bound. | +| `to` | yes | string | Exclusive semantic-version upper bound, greater than from. | + +## source + +Exactly one Git URL, local path or well-known skill index per alias. subpath narrows the discovery root. No source is accessed while reading the declaration. + +### Alternative 1 + +Git repository selected by a transport URL and optional requirement. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `url` | yes | string | Git transport URL. Complete URLs avoid canonicalization warnings; normalized repository identities must be distinct across aliases. | +| `subpath` | | string | Safe relative discovery path inside the source. Omission uses the source root; it cannot escape that root. | +| `requirement` | | requirement | Git selection policy. Omission leaves the source without an explicit requirement; resolution and exact locking belong to the consuming operation. | + +### Alternative 2 + +Local source interpreted using the directories of its declaring environment. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `path` | yes | string | Local path, relative to the declaring project directory unless absolute or home-relative. A requirement selects committed content from a local Git repository; edit mode requires no requirement. | +| `subpath` | | string | Safe relative discovery path inside the source. Omission uses the source root; it cannot escape that root. | +| `requirement` | | requirement | Git selection policy. Omission leaves the source without an explicit requirement; resolution and exact locking belong to the consuming operation. | + +### Alternative 3 + +Well-known skill index accessed only during source-consuming operations. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `index` | yes | string | HTTP or HTTPS well-known skill index URL, without embedded credentials or fragment. Git requirements do not apply to this source kind. | +| `subpath` | | string | Safe relative discovery path inside the source. Omission uses the source root; it cannot escape that root. | + +## componentReference + +A typed member reference used to exclude one component from a plugin expansion. The singular skill and instruction kinds identify individual members. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `kind` | yes | `skill` / `instruction` / `mcpServer` / `hook` / `subagent` / `command` / `lspServer` / `permissions` / `ignore` / `plugin` | Kind of the individual plugin member to exclude. | +| `name` | yes | string | Relative member name within the plugin, paired with kind to identify the exclusion. Duplicate kind/name exclusions are errors. | + +## component_skills + +Select skills from a source and declare their recipients and installation modes. + +Examples: {"kind": "skills", "source": "team", "select": ["review"], "agents": ["codex"]} + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `kind` | yes | `skills` | Selects the skills component shape. | +| `agents` | | sequence of agent (at most 10000 items) | Explicit component recipients. Omission inherits the declaring document's defaultAgents; an empty list selects none. Conditions further restrict effective recipients. | +| `condition` | | condition | Additional restrictions intersected with enclosing group/use conditions. Omission imposes no additional restriction; inactive components remain validated and preserved. | +| `native` | | name → name → NativeValue (at most 10000 properties) (at most 10000 properties) | Client-schema identifiers mapped to native field mappings. Omission or an empty mapping supplies no native fields. Values are data, never environment/secret bindings: strings, representable integers, finite decimals, booleans, null, arrays and objects. Core preserves integer/decimal kind and exact decimal text; !!float "1.00" explicitly retains decimal identity, which general JSON Schema cannot validate. Objects have unordered domain semantics and << is an ordinary key. | +| `source` | yes | string | Required source alias, or . for the current declaring source. Source resolution occurs only in the consuming operation. | +| `select` | | one of: `all`, sequence of string (at most 10000 items) | all or omission selects all discovered skills; a name sequence selects those skills. An empty sequence selects none. Selection is combined with exclude and per-skill overrides. | +| `exclude` | | sequence of string (at most 10000 items) | Skill names removed from the selection. Omission or an empty sequence excludes none. | +| `mode` | | `link` / `copy` / `edit` | link shares cached content, copy creates an installed directory, and edit links live local content. Omission defaults to link. edit requires a local source without a requirement or pin. | +| `overrides` | | name → override (at most 10000 properties) | Skill names mapped to recipient/mode overrides. Omission or an empty mapping supplies none; omitted override fields inherit the component settings. | +| `path` | | string | Optional discovery path relative to the selected filesystem source view. Narrows discovery without changing containment. Not supported for index sources. | + +## component_instructions + +Compose instruction targets and named ChatGPT prompts from ordered section references. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `kind` | yes | `instructions` | Selects the instructions component shape. | +| `agents` | | sequence of agent (at most 10000 items) | Explicit component recipients. Omission inherits the declaring document's defaultAgents; an empty list selects none. Conditions further restrict effective recipients. | +| `condition` | | condition | Additional restrictions intersected with enclosing group/use conditions. Omission imposes no additional restriction; inactive components remain validated and preserved. | +| `native` | | name → name → NativeValue (at most 10000 properties) (at most 10000 properties) | Client-schema identifiers mapped to native field mappings. Omission or an empty mapping supplies no native fields. Values are data, never environment/secret bindings: strings, representable integers, finite decimals, booleans, null, arrays and objects. Core preserves integer/decimal kind and exact decimal text; !!float "1.00" explicitly retains decimal identity, which general JSON Schema cannot validate. Objects have unordered domain semantics and << is an ordinary key. | +| `sections` | | sequence of section (at most 10000 items) | Instruction sections in rendering order. Omission or an empty sequence supplies none; repeated references retain their occurrences. | +| `chatgpt` | | name → promptDeclaration (at most 10000 properties) | Named ChatGPT prompts retained in declaration order, separate from agent-targeted sections. Omission or an empty mapping declares none. | + +## mcpRegistry + +The captured registry server version and selected executable package or endpoint. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `registry` | yes | string | Registry base URL as observed at selection. | +| `server` | yes | string | Full server name in the registry. | +| `version` | yes | string | Exact version of the server definition. | +| `origin` | yes | string | Canonical HTTP origin of the selected endpoint or artifact registry. | +| `package` | | string | Exact package or image coordinate for a stdio selection. | +| `invocationDigest` | | string | Digest binding the captured registry selection to its typed invocation. | +| `portableBindings` | | name → string (at most 10000 properties) | Digests of non-secret registry literals eligible for portable export. | + +## component_mcpServer + +Declare a named MCP server connection without starting or contacting it. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `kind` | yes | `mcpServer` | Selects the mcpServer component shape. | +| `agents` | | sequence of agent (at most 10000 items) | Explicit component recipients. Omission inherits the declaring document's defaultAgents; an empty list selects none. Conditions further restrict effective recipients. | +| `condition` | | condition | Additional restrictions intersected with enclosing group/use conditions. Omission imposes no additional restriction; inactive components remain validated and preserved. | +| `native` | | name → name → NativeValue (at most 10000 properties) (at most 10000 properties) | Client-schema identifiers mapped to native field mappings. Omission or an empty mapping supplies no native fields. Values are data, never environment/secret bindings: strings, representable integers, finite decimals, booleans, null, arrays and objects. Core preserves integer/decimal kind and exact decimal text; !!float "1.00" explicitly retains decimal identity, which general JSON Schema cannot validate. Objects have unordered domain semantics and << is an ordinary key. | +| `name` | yes | string | Required relative component name, retained as its symbolic identity. Nested names use / separators; empty, . and .. segments are not allowed. | +| `registry` | | mcpRegistry | Origin and version of a registry-selected MCP definition. | +| `transport` | yes | transport | Required MCP transport and its unresolved connection settings. | + +## component_hook + +Declare a named event-triggered invocation without executing it. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `kind` | yes | `hook` | Selects the hook component shape. | +| `agents` | | sequence of agent (at most 10000 items) | Explicit component recipients. Omission inherits the declaring document's defaultAgents; an empty list selects none. Conditions further restrict effective recipients. | +| `condition` | | condition | Additional restrictions intersected with enclosing group/use conditions. Omission imposes no additional restriction; inactive components remain validated and preserved. | +| `native` | | name → name → NativeValue (at most 10000 properties) (at most 10000 properties) | Client-schema identifiers mapped to native field mappings. Omission or an empty mapping supplies no native fields. Values are data, never environment/secret bindings: strings, representable integers, finite decimals, booleans, null, arrays and objects. Core preserves integer/decimal kind and exact decimal text; !!float "1.00" explicitly retains decimal identity, which general JSON Schema cannot validate. Objects have unordered domain semantics and << is an ordinary key. | +| `name` | yes | string | Required relative component name, retained as its symbolic identity. Nested names use / separators; empty, . and .. segments are not allowed. | +| `event` | yes | event | Required portable or native hook event. Native events require exactly one explicit component recipient. | +| `run` | yes | run | Required invocation performed when the target client triggers this hook. Declaration reads never execute it. | +| `matcher` | | string | Optional target-client matcher text. Omission leaves matching unspecified; support and interpretation belong to the adapter. | +| `timeoutSeconds` | | integer ≥ 1 | Positive plain integer timeout in seconds. Omission leaves the timeout unspecified. Core rejects decimal spellings such as 1.0 and out-of-range integers. | + +## component_subagent + +Declare a named subagent with a description and prompt body. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `kind` | yes | `subagent` | Selects the subagent component shape. | +| `agents` | | sequence of agent (at most 10000 items) | Explicit component recipients. Omission inherits the declaring document's defaultAgents; an empty list selects none. Conditions further restrict effective recipients. | +| `condition` | | condition | Additional restrictions intersected with enclosing group/use conditions. Omission imposes no additional restriction; inactive components remain validated and preserved. | +| `native` | | name → name → NativeValue (at most 10000 properties) (at most 10000 properties) | Client-schema identifiers mapped to native field mappings. Omission or an empty mapping supplies no native fields. Values are data, never environment/secret bindings: strings, representable integers, finite decimals, booleans, null, arrays and objects. Core preserves integer/decimal kind and exact decimal text; !!float "1.00" explicitly retains decimal identity, which general JSON Schema cannot validate. Objects have unordered domain semantics and << is an ordinary key. | +| `name` | yes | string | Required relative component name, retained as its symbolic identity. Nested names use / separators; empty, . and .. segments are not allowed. | +| `description` | yes | string | User-facing explanation of when to use this subagent. | +| `prompt` | yes | prompt | Required inline prompt or prompt-file reference. File contents are not read during declaration parsing. | +| `model` | | string | Optional target-client model identifier. Omission leaves model selection unspecified. | +| `tools` | | sequence of string (at most 10000 items) | Optional target-client tool names. Omission leaves the tool list unspecified; an empty sequence is an explicit empty list. | + +## component_command + +Declare a named prompt command and its input parameters. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `kind` | yes | `command` | Selects the command component shape. | +| `agents` | | sequence of agent (at most 10000 items) | Explicit component recipients. Omission inherits the declaring document's defaultAgents; an empty list selects none. Conditions further restrict effective recipients. | +| `condition` | | condition | Additional restrictions intersected with enclosing group/use conditions. Omission imposes no additional restriction; inactive components remain validated and preserved. | +| `native` | | name → name → NativeValue (at most 10000 properties) (at most 10000 properties) | Client-schema identifiers mapped to native field mappings. Omission or an empty mapping supplies no native fields. Values are data, never environment/secret bindings: strings, representable integers, finite decimals, booleans, null, arrays and objects. Core preserves integer/decimal kind and exact decimal text; !!float "1.00" explicitly retains decimal identity, which general JSON Schema cannot validate. Objects have unordered domain semantics and << is an ordinary key. | +| `name` | yes | string | Required relative component name, retained as its symbolic identity. Nested names use / separators; empty, . and .. segments are not allowed. | +| `description` | yes | string | User-facing explanation of this prompt command. | +| `prompt` | yes | prompt | Required inline prompt or prompt-file reference. ${input:name} refers to a declared parameter; $${input:name} is literal text. | +| `parameters` | | sequence of parameter (at most 10000 items) | Inputs in declaration order. Omission or an empty sequence declares none. Names must be unique and inline prompt tokens must refer to these names. | + +## component_lspServer + +Declare a named language server invocation and extension-to-language mapping. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `kind` | yes | `lspServer` | Selects the lspServer component shape. | +| `agents` | | sequence of agent (at most 10000 items) | Explicit component recipients. Omission inherits the declaring document's defaultAgents; an empty list selects none. Conditions further restrict effective recipients. | +| `condition` | | condition | Additional restrictions intersected with enclosing group/use conditions. Omission imposes no additional restriction; inactive components remain validated and preserved. | +| `native` | | name → name → NativeValue (at most 10000 properties) (at most 10000 properties) | Client-schema identifiers mapped to native field mappings. Omission or an empty mapping supplies no native fields. Values are data, never environment/secret bindings: strings, representable integers, finite decimals, booleans, null, arrays and objects. Core preserves integer/decimal kind and exact decimal text; !!float "1.00" explicitly retains decimal identity, which general JSON Schema cannot validate. Objects have unordered domain semantics and << is an ordinary key. | +| `name` | yes | string | Required relative component name, retained as its symbolic identity. Nested names use / separators; empty, . and .. segments are not allowed. | +| `run` | yes | run | Required language server invocation, retained as data until used by the consuming operation. | +| `languages` | yes | name → string (at most 10000 properties) | File extensions, including a leading dot, mapped to nonempty language identifiers. An empty mapping declares no extension associations.
Examples: {".swift": "swift"} | +| `initializationOptions` | | name → NativeValue (at most 10000 properties) | Native values passed as language server initialization options. Omission or an empty mapping supplies none. Values retain Core integer/decimal kind and exact decimal text; !!float "1.00" explicitly marks a decimal. Null and nested arrays/objects are data, not runtime bindings. | + +## component_permissions + +Declare a named ordered collection of client permission rules. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `kind` | yes | `permissions` | Selects the permissions component shape. | +| `agents` | | sequence of agent (at most 10000 items) | Explicit component recipients. Omission inherits the declaring document's defaultAgents; an empty list selects none. Conditions further restrict effective recipients. | +| `condition` | | condition | Additional restrictions intersected with enclosing group/use conditions. Omission imposes no additional restriction; inactive components remain validated and preserved. | +| `native` | | name → name → NativeValue (at most 10000 properties) (at most 10000 properties) | Client-schema identifiers mapped to native field mappings. Omission or an empty mapping supplies no native fields. Values are data, never environment/secret bindings: strings, representable integers, finite decimals, booleans, null, arrays and objects. Core preserves integer/decimal kind and exact decimal text; !!float "1.00" explicitly retains decimal identity, which general JSON Schema cannot validate. Objects have unordered domain semantics and << is an ordinary key. | +| `name` | yes | string | Required relative component name, retained as its symbolic identity. Nested names use / separators; empty, . and .. segments are not allowed. | +| `rules` | yes | sequence of rule (at most 10000 items) | Permission rules in declaration order. An empty sequence declares no rules. Enforcement belongs to the target client. | + +## component_ignore + +Declare a named collection of context or indexing ignore patterns. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `kind` | yes | `ignore` | Selects the ignore component shape. | +| `agents` | | sequence of agent (at most 10000 items) | Explicit component recipients. Omission inherits the declaring document's defaultAgents; an empty list selects none. Conditions further restrict effective recipients. | +| `condition` | | condition | Additional restrictions intersected with enclosing group/use conditions. Omission imposes no additional restriction; inactive components remain validated and preserved. | +| `native` | | name → name → NativeValue (at most 10000 properties) (at most 10000 properties) | Client-schema identifiers mapped to native field mappings. Omission or an empty mapping supplies no native fields. Values are data, never environment/secret bindings: strings, representable integers, finite decimals, booleans, null, arrays and objects. Core preserves integer/decimal kind and exact decimal text; !!float "1.00" explicitly retains decimal identity, which general JSON Schema cannot validate. Objects have unordered domain semantics and << is an ordinary key. | +| `name` | yes | string | Required relative component name, retained as its symbolic identity. Nested names use / separators; empty, . and .. segments are not allowed. | +| `patterns` | yes | sequence of string (at most 10000 items) | Ignore patterns in declaration order, interpreted by the target client for the selected purpose. An empty sequence declares none. | +| `purpose` | | `context` / `indexing` | context excludes content from model context; indexing excludes it from indexing. Omission defaults to context; support is checked by the consuming adapter. | + +## component_plugin + +Declare a plugin resource for native installation or component expansion. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `kind` | yes | `plugin` | Selects the plugin component shape. | +| `agents` | | sequence of agent (at most 10000 items) | Explicit component recipients. Omission inherits the declaring document's defaultAgents; an empty list selects none. Conditions further restrict effective recipients. | +| `condition` | | condition | Additional restrictions intersected with enclosing group/use conditions. Omission imposes no additional restriction; inactive components remain validated and preserved. | +| `native` | | name → name → NativeValue (at most 10000 properties) (at most 10000 properties) | Client-schema identifiers mapped to native field mappings. Omission or an empty mapping supplies no native fields. Values are data, never environment/secret bindings: strings, representable integers, finite decimals, booleans, null, arrays and objects. Core preserves integer/decimal kind and exact decimal text; !!float "1.00" explicitly retains decimal identity, which general JSON Schema cannot validate. Objects have unordered domain semantics and << is an ordinary key. | +| `name` | yes | string | Required relative component name, retained as its symbolic identity. Nested names use / separators; empty, . and .. segments are not allowed. | +| `source` | yes | string | Required source alias, or . for the declaring source, containing the plugin resource. | +| `path` | yes | string | Required safe relative plugin resource path within the selected source. | +| `mode` | | `native` / `components` | components (the default) expands plugin members. native installs the vendor plugin for exactly one explicit recipient and forbids select and nonempty exclude. | +| `select` | | sequence of `skills` / `instructions` / `mcpServer` / `hook` / `subagent` / `command` / `lspServer` / `permissions` / `ignore` / `plugin` (at most 10000 items) | Component kinds to include during components-mode expansion. Omission leaves kinds unrestricted; an empty sequence selects none. Duplicate kinds are errors. | +| `exclude` | | sequence of componentReference (at most 10000 items) | Typed individual members removed from components-mode expansion. Omission or an empty sequence excludes none. Each kind/name pair must be unique. | + +## component + +One component declaration, selected by its required kind. All fields are checked even when the component is inactive; target-client support is evaluated by the consuming operation. + +### Alternative 1 + +component_skills + +### Alternative 2 + +component_instructions + +### Alternative 3 + +component_mcpServer + +### Alternative 4 + +component_hook + +### Alternative 5 + +component_subagent + +### Alternative 6 + +component_command + +### Alternative 7 + +component_lspServer + +### Alternative 8 + +component_permissions + +### Alternative 9 + +component_ignore + +### Alternative 10 + +component_plugin + +## use + +Activate a local group or an exported group from a source. Uses retain order and occurrences; nested conditions intersect and source aliases remain local to their declaring document. + +Examples: {"group": "checks"}, {"group": "checks", "source": "team"} + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `group` | yes | string | Required group name. Without source it must name a local group; a named source must export the group before linking can use it. | +| `source` | | string | Alias of the producer exporting this group. Omission selects a local group; . addresses the current source. Remote source aliases are not rebound in the importing document. | +| `condition` | | condition | Additional restrictions for this expansion, intersected with group and enclosing conditions. Omission imposes no additional restriction. | + +## group + +A reusable group of direct components and nested uses. Definition alone does not activate it. Local use cycles are rejected, and unused or inactive contents are still validated. + +| Field | Required | Shape | Description | +| --- | --- | --- | --- | +| `components` | | sequence of component (at most 10000 items) | Direct components retained in declaration order. Omission or an empty sequence contributes none. | +| `uses` | | sequence of use (at most 10000 items) | Nested group uses expanded in declaration order. Omission or an empty sequence references none. | +| `condition` | | condition | Restrictions intersected with each importing use and nested component/section condition. Omission imposes no additional restriction. | diff --git a/Documentation/Reference/Marketplace.md b/Documentation/Reference/Marketplace.md new file mode 100644 index 0000000..41734c2 --- /dev/null +++ b/Documentation/Reference/Marketplace.md @@ -0,0 +1,178 @@ +# Team marketplace + +Teams distribute versioned bundles from local directories, Git snapshots or +static HTTPS indexes. CLI and App share named marketplaces through +`MarketplaceDirectory`. + +Project registrations live in `.agent/marketplaces.yaml`. User registrations +live in `~/.agents/marketplaces.yaml`. Each name maps to a directory, a Git +repository with an optional ref and subpath, or an HTTPS index URL. A project entry takes precedence +over a user entry of the same name. Relative filesystem addresses are anchored +to the project root or the user's home, according to the scope that owns them. + +```yaml +team: + git: https://github.com/example/team-catalog.git + ref: stable + subpath: packages +local: + directory: ./team-market +hosted-team: + hosted: https://packages.example.org/team/marketplace.json +``` + +Registering a name saves its address. Browsing reads the catalog. Installation +records the selected origin in `agents.yaml`, so subsequent changes to the +registration leave existing package pins intact. + +## Publish and browse + +Import `AgentsCore` and `AgentsUpdates`. Call +`MarketplaceOperations.publishBundle` with the Agents archive bytes, an +existing catalog directory, and the selected `scope` and +`RuntimeEnvironment`. The publisher checks current source and organization +policy for both the archive and the destination, and revalidates the policy +before the final rename. See [Author project packaging](AuthorPackaging.md) +for how the publisher verifies public MCP inputs. + +For another archive format, use `MarketplaceOperations.publish` with that +format's inspection function. It validates the archive and returns its +package ID and version. Formats without portable source evidence are +evaluated as unknown sources. IDs are lowercase ASCII names using letters, +digits, periods, underscores and hyphens. Versions use canonical SemVer. + +```text +releases/ + review-kit/ + 1.0.0/ + release.json + package.bundle +``` + +`release.json` declares `formatVersion` (1), `coordinate` (`package` and +`version`), `archiveDigest` (SHA-256), `archiveByteCount` and optional +`summary`. Publication syncs the two files and exposes the directory with +an exclusive rename. An identical retry verifies the published archive. +A different record at the same coordinate conflicts. Browsing ignores +hidden staging directories. A process interrupted before the rename may +leave a hidden staging directory. The catalog owner can remove an abandoned +stage after confirming its publisher has stopped. + +Create a `MarketplaceRegistration` with a display name and +`MarketplaceOrigin`. The origin can be a directory or a Git repository. +Git supports full HTTP(S) and SSH URLs, host/repository shorthand and +explicit filesystem paths. A Git origin can select a ref and a catalog +subdirectory within the tree. Filesystem locations are absolute or relative +to the consumer project directory. Directory writes appear immediately. +For distribution through Git, commit the release files using the team's +repository workflow. + +`MarketplaceOperations.browse` returns one observation. Use `search` to +filter by package or summary and `select(package:version:)` to choose an +exact release or the highest available SemVer. `updates(for:)` compares +available versions with a committed pin from the same origin. Git +observations carry a full commit. Several packages from the same catalog +can be installed from different commits. + +## Hosted HTTPS indexes + +Use `MarketplaceOrigin(hostedIndex:)` or `MarketplaceOrigin(kind: .hosted, +location:)` with an absolute HTTPS index URL. The canonical URL, including its +path, identifies the catalog across registration names. Browse, search and +`verifyCatalog` are read-only. Use `acquire` to verify an individual release. + +`MarketplaceOperations.exportHostedBundle(_:to:summary:)` takes the bytes of a +verified native bundle and an existing staging directory. It returns the local +`marketplace.json` URL. Publish the index and the referenced archive paths using +your static host. The index contains `formatVersion: 1` and a `releases` array. +Each release contains `coordinate`, `archiveDigest`, `archiveByteCount`, an +optional `summary` and `archivePath` relative to the index directory. An index can +contain up to 4,096 releases and occupy up to 8 MiB. Archives can occupy up to +128 MiB each, subject to the install lock's aggregate byte budget. Publish +referenced archives before replacing a live index. A staged export uses immutable +archives, an atomic index replacement and a hidden writer lock. The index and its +archives use the same layout across exports. Native hosted indexes and APM JSON +file imports have separate formats. + +For private hosting, supply `HostedMarketplaceAccess` to `browse`, +`verifyCatalog`, release `acquire`, `resolve` or `previewResolution`. The +credential provider receives the canonical index URL only for an exact matching +user registration. A CLI can look up a host-selected environment variable, and +an app can provide a session-only token. The provider returns the bearer token +itself. Source and organization policies apply before every request. Index +redirects stay in the admitted HTTPS directory. Archive redirects to another +origin require explicit `trustedDownloadOrigins` and permanently discard the +credential for that request chain. + +Install hosted releases with `MarketplaceRoot`, `previewResolution` and +`withPreparedResolution` or `performResolution`. Bundle dependencies may use +relative package coordinates or an independently user-registered hosted index +URL. The hosted preview captures the exact archive bytes and request provenance. +Apply revalidates policy and destination state and uses the captured marketplace +closure. The graph lock records the index digest, archive digest and redirect +provenance, plus the archive bytes in `contentObjects`. Frozen restore verifies +the locked archives and replays selected components in an independent project +without hosted access or credentials. + +## Acquire, preview and apply + +`MarketplaceOperations.acquire` takes a release observation or a committed +pin. It verifies the exact byte count and digest and returns a +`VerifiedMarketplacePackage` with the archive. An old Git observation +reads its selected commit after the discovery ref advances. Pass the consuming +scope and environment to browse and acquire. The effective source policy checks +the catalog origin before opening it. + +Pass the archive to its format owner for inspection and match its declared +package ID and version with the release coordinate. The archive importer +builds a full-scope update request and reports the source aliases of its +imported producer groups. Bind that request with +`package.bindingImport(_:as:sourceAliases:)`. Those aliases are owned by +the dependency. They must have exported group uses in the candidate and +provide replayable locked resources. Keep borrowed archive extraction +under the importer's staging scope. + +Preview and reprepare with `UpdateOperations`, using the displayed +fingerprint to apply. `CombinedUpdateReport.marketplaceChanges` includes +the previous and proposed pins. Updating a dependency keeps its catalog +and package ID and replaces its owned contributions with the selected +release. `MarketplaceOperations.removalRequest(for:)` previews and +removes the dependency's declarations and deployments in the same +transaction. Other dependencies retain their pins. + +The project declaration records stable intent alongside the generated +producer sources and group uses. + +```yaml +version: 1 +packages: + review: + package: review-kit + version: "1.0.0" + catalog: + kind: git + location: "https://github.com/example/team-catalog.git" + ref: main +``` + +Commit both `.agent/agents.yaml` and `.agent/agents.resolved`. The ledger +pins the catalog origin, selected archive digest, Git commit when applicable, +and imported component and resource closure. Portable bundles retain original +producer and resource origins. A re-export also carries the catalog origin of a +marketplace-installed component. Applicable policies check those origins at +import, update, restore and audit. The bundle store is a materialization of +these inputs. A local producer with no portable coordinates requires an +explicit `missing` allowance in each configured layer. Restore checks the +declared selection and recorded contributions before rendering. It replays the +committed closure from ledger bytes without consulting the catalog or +authoring tree. Use `MarketplaceOperations.installed` to read admitted +pins. `ScopeInspection` exposes pins and any intent mismatch for read-only +audit. Its CycloneDX and SPDX inventories include admitted release versions, +archive digests and references to the imported components. + +The workflow reference is APM v0.11.0's catalog registration, discovery +and locked package selection. Core uses the release-directory format and +Swift APIs described here. +[Release v0.11.0](https://github.com/microsoft/apm/releases/tag/v0.11.0) · +[Marketplace reference](https://microsoft.github.io/apm/reference/cli/marketplace/) · +[Consumer behavior](https://microsoft.github.io/apm/consumer/installing-from-marketplaces/) diff --git a/Documentation/Reference/OrganizationPolicy.md b/Documentation/Reference/OrganizationPolicy.md new file mode 100644 index 0000000..8d87277 --- /dev/null +++ b/Documentation/Reference/OrganizationPolicy.md @@ -0,0 +1,152 @@ +# Organization install policy + +Applications select policies through `RuntimeEnvironment.userOrganizationPolicy` +and `projectOrganizationPolicy`. The user selection also governs project +installs. A project selection adds a separate authority for project installs. +The consumer manifest and imported packages have no policy selector. The +existing user, project and explicitly configured organization source +allowlists remain hard gates. + +The host can set `AGENTS_USER_ORGANIZATION_POLICY` and +`AGENTS_PROJECT_ORGANIZATION_POLICY` to an absolute file path, an HTTPS +document URL, or `github:OWNER/REPO` for organization discovery. Each +configured selection is required. An invalid location appears as a blocking +finding for that scope. An explicit Swift selection takes precedence for +its scope. + +```swift +import AgentsCore +import AgentsUpdates +import Foundation + +var environment = RuntimeEnvironment() +environment.userOrganizationPolicy = OrganizationPolicySelection( + .local(URL(fileURLWithPath: "/etc/agents/agents-policy.yaml"))) +let status = try OrganizationPolicyOperations.status(environment: environment) +let audit = try OrganizationPolicyOperations.audit( + environment: environment, requireOrganizationPolicy: true) +``` + +Use `OrganizationPolicyReport.isBlocked` for status and +`OrganizationPolicyAudit.isBlocked` for CI. The audit also exposes hard +source violations and detects a marketplace declaration that differs from its +locked graph. It uses recorded lock data and passive workspace checks. Policy retrieval +is its only network operation. The CI presence option requires a loaded policy. + +Successful install previews expose `CombinedUpdateReport.organizationPolicy`. +A policy refusal throws `OrganizationPolicyFailure` with the same report +shape. Each finding has its rule, subject, authority, effective outcome and +document digest. Dependency findings can include the path and the matched +rule. Preview clients should verify the displayed fingerprint at apply. +Policy evidence participates in the fingerprint and local bytes are +revalidated before publication. + +## Policy documents + +This example is a native Core policy document. + +```yaml +name: team-baseline +version: "2026.1" +extends: common-policy.yaml +enforcement: block +dependencies: + allow: ["github.com/example/**"] + deny: ["**/retired"] + require: + - identity: "github.com/example/catalog#review-tools" + from: "2.1.0" + require_resolution: block + require_pinned_constraint: true + max_depth: 6 +mcp: + require: ["inline/team-docs"] + transport: {allow: [streamable-http]} +executables: + deny: ["github.com/example/catalog#review-tools"] +unmanaged_files: + action: warn + directories: [.agents/skills] +security: + integrity: {require_hashes: true} + audit: {fail_on_drift: true} +``` + +- `off` reports loaded policy. `warn` reports violations with advisory + severity. `block` refuses violations before publication. Required policy + availability is independent of the rule mode. +- Inheritance allows up to five documents. Policy findings retain the + document that supplied the rule. Each allow list must match, explicit + `[]` admits no identities, and `null` adds no restriction. Denies and + requirements add across documents. Depth limits tighten. A child cannot + lower the enforcement mode or weaken required version conflict handling. +- Package rules accept Git repository coordinates such as + `github.com/example/repo` with an optional discovery subpath. Marketplace + coordinates append `#package` to the catalog coordinate. Local catalog + coordinates use `local:/absolute/path#package`. Standalone bundles have a + deny identity of `_local/package`. Bundle acquisitions also check recorded + producer origins. `sources` applies to source origins and `marketplace.allow` + applies to catalog origins. Globs use `*` for a segment and `**` for zero or + more segments. Hostless Git patterns match any host. Hostless exact Git + requirements identify `github.com`. GitHub owner and repository names + compare case-insensitively. Subpaths, package names and MCP names retain + case. +- Package requirements verify both authored intent and selected deployment. + `project-wins` honors a project constraint when present. `policy-wins` + selects using the policy bounds for that package and records the override. + `block` requires a version satisfying both. Override records require matching + active policy for frozen replay. Audit never injects requirements. +- A marketplace root has depth one. A shared node uses the longest path + among the selected roots. External component-group links count producer + transitions. Pinned-constraint checks use the authored Git selector, + including recognized release tags and full commit IDs. +- MCP rules use `inline/name`, qualified producer coordinates with + `#server`, or the selected registry and server coordinate. The + `mcp.require` extension uses exact identities. `mcp.self_defined` accepts + `allow`, `warn`, or `deny`. Setting `trust_transitive: false` requires + an explicit allow match. Transport restrictions check symbolic effective + transport. Executable ceilings cover deployed hooks, LSP, self-defined MCP, + executable resource entries and detected executable plugin contents. + Opaque executable evidence is reported when a matching ceiling cannot be + verified. `executables.require` verifies deployment evidence. Recommendations + are reported as advisory metadata and grant no trust. +- `manifest.required_fields` checks admitted top-level keys. + `require_explicit_includes` requires named skill selection where Core has + an authored skill selector. `content_types.allow` uses Core component kind + names. `scripts: deny` checks the presence of a top-level scripts field. + Drift uses the lock and passive target evidence. A native layout that needs + replay reports unverified drift when passive evidence is insufficient. + Unmanaged checks cover registered skill and Antigravity rule directories + by default. A policy can supply relative workspace directories and exclude + path globs from the resulting findings. + +## Availability and cache + +A selection uses `.local(URL)`, `.https(URL)` or +`.organization(gitRemote: String)`. Supply the already identified GitHub +remote for organization discovery. Core tries `.github-private`, `.github`, +`.apm`, then `_apm` for `agents-policy.yaml`. Discovery uses public GitHub +raw HTTPS endpoints. A caller can select another provider through its +explicit HTTPS policy URL. + +A local document can select a relative local parent or an explicit HTTPS +parent. Remote parents use the +same origin as the first HTTPS document, including the effective port. GitHub raw +documents also accept `owner/repository` parent shorthand. An organization +discovery selection can refer to its discovery chain using `extends: org`. +Remote URLs exclude credentials, queries and fragments. Redirects stay on +the same HTTPS origin. Authentication or origin violations and incomplete +inheritance fail closed. + +The caller decides whether a selection is required. Remote documents use the +chain's minimum freshness TTL, capped at one day. Verified bytes can be used +up to seven days after a transient offline failure. The loader reports stale +evidence, including its age. Once a known chain sets `fetch_failure: block`, +its cached metadata preserves that outage behavior after the bytes expire. +An admitted install can refresh the disposable cache in the supplied home. +Status, CI, previews and refusals leave it unchanged. + +Native Core policy uses the APM governance reference for scope, outcomes, +inheritance and trust semantics. Complete `apm-policy.yml` import, authenticated +provider discovery, external scanners and experimental registry requirements +are separate integrations. [APM policy reference](https://microsoft.github.io/apm/reference/policy-schema/) diff --git a/Documentation/Reference/Presentation.md b/Documentation/Reference/Presentation.md index c712406..9fd7909 100644 --- a/Documentation/Reference/Presentation.md +++ b/Documentation/Reference/Presentation.md @@ -51,7 +51,7 @@ containing the skill fixture above. Unset `CODEX_HOME`, `CLAUDE_CONFIG_DIR`, The expected stdout is `review` followed by a newline. Verify that `.agents/skills/review` in the scratch project links to `skills/review` and that -`.agent/agents.json` and `.agent/agents.resolved` record the selection. Remove +`.agent/agents.yaml` and `.agent/agents.resolved` record the selection. Remove `.build/presentation/` after validation. [design]: https://github.com/agents-tools/.github/blob/master/DESIGN.md diff --git a/Documentation/Reference/README.md b/Documentation/Reference/README.md index a54c772..f289c52 100644 --- a/Documentation/Reference/README.md +++ b/Documentation/Reference/README.md @@ -4,6 +4,13 @@ This directory holds supporting reference material for `core`. ## Guides +- [Agent client inspection](AgentClients.md): passive observations and schema evidence through the public API. +- [MCP registry](MCPRegistry.md) covers browsing, selecting, and deploying registry servers through the public API. +- [APM file import](APMImport.md) describes the supported manifest and lock inputs. +- [Agents manifest language](Manifest.md): YAML field shapes, scalar semantics, limits, source edits, dump and diagnostics. +- [Team marketplace](Marketplace.md) covers local publication, Git catalogs and locked package selection. +- [Author project packaging](AuthorPackaging.md) covers read-only review, exact + archive publication, and native plugin layouts. - [Repository presentation](Presentation.md): the README Quick look fixture and standalone consumer validation. - [Release checklist](Release.md): preflight, signed version tags, GitHub diff --git a/Documentation/Reference/SourceAccess.md b/Documentation/Reference/SourceAccess.md new file mode 100644 index 0000000..27267af --- /dev/null +++ b/Documentation/Reference/SourceAccess.md @@ -0,0 +1,101 @@ +# Package source access + +Source routing uses the operator's [user settings](UserSourceAccess.md). +A Swift host may supply a typed `RuntimeEnvironment.sourceAccess` override. +Project declarations select a source and a ref. + +## Credential status + +Pass the workspace's declaration, install selector, runtime environment, and +current `EffectiveSourcePolicy` to `SourceCredentialOperations.inspect`. +Consumers can read the local user and project policy through +`SourcePolicyOperations.inspect`. Source aliases and selectors resolve the +same way as installation. For example, `team@tag:release/v1` means the +literal tag `release/v1`. + +A report gives the provider, effective host and port, transport, credential +category, availability, and optional validation status. Inspection makes +no requests and never invokes a credential resolver. Host-only inspection +considers host-wide bindings. SSH credentials are managed by SSH. +An explicitly delegated Git host reports `delegated/unverified`. + +Use `SourceAuthority` to identify an exact host and port, with 443 as the +default. Core classifies GitHub and GitLab on their standard authorities. +Register enterprise authorities in `SourceAccessConfiguration.providers`. +A `SourceCredentialBinding` authorizes either a direct HTTPS repository or +a mirror. A path-scoped direct binding names the repository. A path-scoped +mirror binding names the configured base path followed by the logical +repository namespace, such as `/proxy/org/repo`. A matching repository +binding takes precedence over a host-wide binding. Duplicate matching +bindings fail the operation. + +`SourceCredentialOperations.validate` sends the selected credential only +to its configured provider identity endpoint after policy admits that +endpoint. The supported identity requests are GitHub's +`https://api.github.com/user`, GitHub Enterprise's `/api/v3/user`, and +GitLab's `/api/v4/user`. HTTP 200 is accepted and HTTP 401 is refused. +A mirror route, an unauthorized validation endpoint, or an inconclusive +response gives `indeterminate`. Reports contain status and omit provider +response bodies and Git subprocess diagnostics. + +`SourceCredentialOperations.export` explicitly writes one selected, +exportable value to a writable pipe. A shell can capture the pipe through +command substitution. Opaque bindings and non-pipe output are refused. +The caller controls what the pipe recipient does with the value. + +## Egress and archive selection + +`SourceAccessConfiguration.Egress.proxyOnly` requires an admitted archive +profile for a network repository. The logical repository and effective +HTTPS destination each need admission under the current source policies. +For MCP Registry requests, set `MCP_REGISTRY_URL` to the team's HTTPS registry. +In proxy-only mode, registry searches and locked installations require the +configured host, port and base path. Well-known indexes and hosted marketplaces +require direct HTTP egress. Organization policy continues to use its separately +configured discovery location, policy file, or HTTPS endpoint. Offline +restore uses eligible previously verified governance evidence. + +A mirror profile defines one source authority, HTTPS base path, and archive +flavor. The client makes one GET and refuses redirects. + +| Profile | Request relative to the configured base | +| --- | --- | +| GitHub archive reverse proxy | `owner/repo/archive/refs/tags/release/v1.zip`, the corresponding `refs/heads/` path, or `owner/repo/archive/.zip` | +| GitLab repository API | `api/v4/projects/group%2Fsub%2Frepo/repository/archive.zip?sha=` | + +GitLab accepts full commit IDs. A profile whose endpoint supports qualified +refs can opt in to a `refs/tags/` or `refs/heads/` query value. +The client supports typed tags, branches, and full commits. A selection +that needs discovery fails on archive-only routes. A locked version +selection can replay its recorded ref when the version still meets the +current requirements. History operations, including Git watch, require +Git objects. Artifactory VCS profiles are unsupported. + +The request shapes describe the Swift client's contract. Local fixture +results do not establish interoperability with any live enterprise host +or other package manager. + +## Restore and private publication + +A resolved source's optional `archive` object records `effectiveURL`, +`flavor`, a `ref` with `kind` and `name`, `treeDigest`, +`observedArchiveDigest`, and, for strict profiles, `requiredArchiveDigest`. +The source's revision is the normalized tree digest. A resource with +`kind: archive` names verified tree paths and digests. Frozen replay +admits the recorded route before using a retained ZIP or reacquiring it. + +Recompression can satisfy a tree-authoritative lock. A strict pin also +requires its recorded ZIP digest. An update preview can report changed ZIP +bytes with the same tree through `archiveRepresentationChanges`. + +Verified archive recovery is kept under the runtime home in an owner-only +store. Scope reservations protect committed and in-flight generations. +Archive bytes become durable before a lock or deployment names them. +A copied lock supplies request coordinates and digests. Offline restore +requires eligible local recovery bytes. Public packages and shared +acquisition caches omit private archive payloads. + +Private copies and rendered files use owner-only permissions. Directory +and link targets require controlled filesystem ancestry. Core checks +ownership, permissions, and ACLs during preview and publication. Native +configuration that would place archive content in the lock is refused. diff --git a/Documentation/Reference/UserSourceAccess.md b/Documentation/Reference/UserSourceAccess.md new file mode 100644 index 0000000..2a9c413 --- /dev/null +++ b/Documentation/Reference/UserSourceAccess.md @@ -0,0 +1,103 @@ +# User source access settings + +Swift hosts, including the CLI and App, use the operator's +`~/.agents/source-access.yaml` for source routing. The file applies to user +and project operations. Project declarations and locks select sources and +revisions. Trust settings come from the operator profile or an explicit +configuration supplied by a trusted Swift host. + +The file is optional. With no file, the runtime uses ordinary direct egress. +`version: 1` and `egress` are required in a configured file. The egress +values are `directAllowed` and `proxyOnly`. The latter admits network +repositories through configured archive mirrors and denies direct indexes, +registries and hosted marketplaces. The logical source and destination +also remain subject to the applicable source policies. + +## GitHub archive mirror + +```yaml +version: 1 +egress: proxyOnly +mirrors: + - source: + host: github.com + base: https://archives.example.test/github + flavor: github +credentials: + - route: mirror + host: archives.example.test + path: /github/team/package + environmentVariable: TEAM_ARCHIVE_TOKEN +``` + +For `team/package@tag:release/v1`, this selects +`https://archives.example.test/github/team/package/archive/refs/tags/release/v1.zip`. +The exact credential scope is the mirror base path plus the logical +repository path. Omit `path` only to authorize that binding for the whole +authority on the selected route. + +## Enterprise direct HTTPS + +```yaml +version: 1 +egress: directAllowed +providers: + - host: code.example.test + port: 8443 + provider: gitlab +credentials: + - route: direct + host: code.example.test + port: 8443 + path: /division/tools/package + environmentVariable: PACKAGE_GIT_TOKEN + validationEndpoint: https://code.example.test:8443/api/v4/user +``` + +The host and port identify the exact authority. Omitted ports mean 443. +`provider` is `github` or `gitlab`. Their public services are recognized +on standard ports. A direct binding matches the HTTPS repository path with +the optional transport suffix `.git` removed. A repository binding takes +precedence over an authority-wide binding. The selected program must receive +the named variable in its process environment. An absent or invalid value +reports an unavailable credential. The settings store only the variable name. + +The optional `validationEndpoint` enables explicit provider validation for +a direct binding. The URL must be the admitted provider identity endpoint. +The optional `exportable: true` allows the explicit pipe-backed export +operation. Both are off by default. + +A mirror's `source` contains `host` and optional `port`. Its `base` is +HTTPS with a fixed path. Supported flavors are `github` and `gitlab`. +For a GitLab API mirror, set `supportsQualifiedGitLabRefs: true` only when +its endpoint supports qualified tag and branch refs. A mirror can set +`requiresExactArchiveBytes: true` to require matching ZIP bytes on replay. +Both flags default to false. + +## Diagnostics and editing + +Use an owner-controlled home and `.agents` directory. The profile must be +a regular file owned by the current user, with one link and without external +write or control access. The editor saves new content with mode `0600`. +Unsafe locations and malformed profiles fail closed. A malformed profile +in a safe location can be opened and repaired in the editor. + +```swift +import AgentsCore +import Foundation + +var runtime = RuntimeEnvironment() +let editor = try SourceAccessSettingsEditor(environment: runtime) +let proposal = try editor.preview(Data("version: 1\negress: proxyOnly\n".utf8)) +try editor.save(proposal) +runtime.reloadSourceAccessSettings() +``` + +Pass the same runtime to subsequent operations. To reset, open a fresh +editor and save `editor.preview(nil)`. A saved preview becomes stale when +its captured profile changes, even when another editor writes the change. +A runtime that already captured a profile fails its source access checks if +the file changes. Rebuild the runtime or call `reloadSourceAccessSettings()` +and start a fresh operation after the operator chooses to reload. +`RuntimeEnvironment(sourceAccess: configuration)` uses an explicitly +supplied typed configuration for embedding and isolated tests. diff --git a/Package.resolved b/Package.resolved index e22904f..0438c2e 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,6 +1,33 @@ { - "originHash" : "ae0e3d7c64e7b90b867d3dcc9ced8ade57036f06db9caea7e98ebe08898ef86a", + "originHash" : "e52552c8d5747be8dcb02a8ace8ba7f8b39ac4605c24605c1811b3ccd827f09d", "pins" : [ + { + "identity" : "eventsource", + "kind" : "remoteSourceControl", + "location" : "https://github.com/mattt/eventsource.git", + "state" : { + "revision" : "bb4b61273b5a976bb571859c17f903ebc3439df1", + "version" : "1.6.0" + } + }, + { + "identity" : "swift-asn1", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-asn1.git", + "state" : { + "revision" : "3b6410f7dee09eb33cdd26260c5fd47fda19b0e2", + "version" : "1.7.3" + } + }, + { + "identity" : "swift-atomics", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-atomics.git", + "state" : { + "revision" : "0442cb5a3f98ab802acb777929fdb446bda11a34", + "version" : "1.3.1" + } + }, { "identity" : "swift-cmark", "kind" : "remoteSourceControl", @@ -10,6 +37,33 @@ "version" : "0.9.0" } }, + { + "identity" : "swift-collections", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-collections.git", + "state" : { + "revision" : "88754449ab766a739610b660e117762115fabc9c", + "version" : "1.7.6" + } + }, + { + "identity" : "swift-crypto", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-crypto.git", + "state" : { + "revision" : "c2cbadd7263439d8015189668f96ff5b5be565ce", + "version" : "5.0.3" + } + }, + { + "identity" : "swift-log", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-log.git", + "state" : { + "revision" : "e3da04078777e6a1b72ce19981fbd6539b0847d8", + "version" : "1.17.0" + } + }, { "identity" : "swift-markdown", "kind" : "remoteSourceControl", @@ -19,6 +73,41 @@ "version" : "0.9.0" } }, + { + "identity" : "swift-nio", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-nio.git", + "state" : { + "revision" : "2f58d8ef84438d6517fc78bcea2f8527e3c72936", + "version" : "2.105.0" + } + }, + { + "identity" : "swift-sdk", + "kind" : "remoteSourceControl", + "location" : "https://github.com/modelcontextprotocol/swift-sdk.git", + "state" : { + "revision" : "a0ae212ebf6eab5f754c3129608bc5557637e605" + } + }, + { + "identity" : "swift-system", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-system.git", + "state" : { + "revision" : "640e5755b5826f4437eaeedd366fd776737db62c", + "version" : "1.9.0" + } + }, + { + "identity" : "tree-sitter", + "kind" : "remoteSourceControl", + "location" : "https://github.com/tree-sitter/tree-sitter", + "state" : { + "revision" : "da6fe9beb4f7f67beb75914ca8e0d48ae48d6406", + "version" : "0.25.10" + } + }, { "identity" : "yams", "kind" : "remoteSourceControl", diff --git a/Package.swift b/Package.swift index 7a801f8..77e0500 100644 --- a/Package.swift +++ b/Package.swift @@ -9,35 +9,129 @@ let package = Package( .macOS(.v15) ], products: [ + .library(name: "AgentsManifest", targets: ["AgentsManifest"]), .library(name: "AgentsCore", targets: ["AgentsCore"]), .library(name: "AgentsSkills", targets: ["AgentsSkills"]), .library(name: "AgentsInstructions", targets: ["AgentsInstructions"]), .library(name: "AgentsUpdates", targets: ["AgentsUpdates"]), ], dependencies: [ - .package(url: "https://github.com/jpsim/Yams", from: "6.0.0"), + .package( + url: "https://github.com/modelcontextprotocol/swift-sdk.git", + revision: "a0ae212ebf6eab5f754c3129608bc5557637e605"), + .package(url: "https://github.com/apple/swift-crypto.git", from: "5.0.0"), + .package(url: "https://github.com/jpsim/Yams", exact: "6.2.2"), .package(url: "https://github.com/swiftlang/swift-markdown.git", from: "0.9.0"), + .package(url: "https://github.com/tree-sitter/tree-sitter", exact: "0.25.10"), ], targets: [ - .target(name: "AgentsCore"), + .target( + name: "TOMLSemantics", + exclude: ["LICENSE", "provenance.json", "PATCHES.md", "upstream.patch"]), + .target( + name: "TreeSitterTOML", exclude: ["LICENSE", "provenance.json"], + sources: ["parser.c", "scanner.c"], publicHeadersPath: "include", + cSettings: [.headerSearchPath(".")]), + .target( + name: "NativeDocuments", + dependencies: [ + "AgentsCore", "TOMLSemantics", "TreeSitterTOML", + .product(name: "TreeSitter", package: "tree-sitter"), + ]), + .testTarget( + name: "NativeDocumentsTests", + dependencies: ["NativeDocuments", "TOMLSemantics", "AgentsCore"]), + .target(name: "CPlatform", linkerSettings: [.linkedLibrary("z")]), + .target(name: "CSQLite", linkerSettings: [.linkedLibrary("sqlite3")]), + .target( + name: "TreeSitterYAML", exclude: ["LICENSE", "provenance.json"], + sources: ["parser.c", "scanner.c"], publicHeadersPath: "include", + cSettings: [.headerSearchPath(".")]), + .target( + name: "AgentsManifest", + dependencies: [ + "AgentsCore", "TreeSitterYAML", "Yams", + .product(name: "TreeSitter", package: "tree-sitter"), + ], exclude: ["Resources/agents.schema.json"]), + .target( + name: "AgentsCore", + dependencies: [ + "CPlatform", "CSQLite", "TOMLSemantics", .product(name: "Crypto", package: "swift-crypto"), + .product(name: "Markdown", package: "swift-markdown"), "Yams", + ] + ), .target( name: "AgentsInstructions", - dependencies: ["AgentsCore", .product(name: "Markdown", package: "swift-markdown")] + dependencies: [ + "AgentsCore", "AgentsManifest", .product(name: "Markdown", package: "swift-markdown"), + ] ), - .target(name: "AgentsSkills", dependencies: ["AgentsCore", "Yams"]), + .target(name: "AgentsSkills", dependencies: ["AgentsCore", "AgentsManifest", "Yams"]), .target( - name: "AgentsUpdates", dependencies: ["AgentsCore", "AgentsSkills", "AgentsInstructions"]), + name: "AgentsUpdates", + dependencies: [ + "AgentsCore", "AgentsManifest", "AgentsSkills", "AgentsInstructions", "CPlatform", + "Components", "NativeDocuments", + ]), + .target( + name: "Components", + dependencies: [ + "AgentsCore", "AgentsManifest", "AgentsSkills", "AgentsInstructions", "NativeDocuments", + .product(name: "MCP", package: "swift-sdk"), + ]), + .testTarget( + name: "ComponentsTests", + dependencies: [ + "Components", "AgentsCore", "AgentsManifest", "AgentsSkills", "AgentsInstructions", + "StateTestProcess", "StateTestSupport", "MCPTestProcess", + ], resources: [.copy("Fixtures")]), + .executableTarget( + name: "MCPTestProcess", dependencies: ["CPlatform"], path: "Tests/MCPTestProcess"), + .target( + name: "StateTestSupport", dependencies: ["AgentsCore", "AgentsManifest"], + path: "Tests/StateTestSupport"), .executableTarget( name: "StateTestProcess", - dependencies: ["AgentsCore", "AgentsInstructions", "AgentsSkills", "AgentsUpdates"], + dependencies: [ + "AgentsCore", "AgentsManifest", "AgentsInstructions", "AgentsSkills", "AgentsUpdates", + "CPlatform", "StateTestSupport", "Components", + ], path: "Tests/StateTestProcess"), - .testTarget(name: "AgentsCoreTests", dependencies: ["AgentsCore", "StateTestProcess"]), - .testTarget(name: "AgentsInstructionsTests", dependencies: ["AgentsInstructions"]), - .testTarget(name: "AgentsUpdatesTests", dependencies: ["AgentsUpdates", "StateTestProcess"]), + .testTarget( + name: "AgentsCoreTests", + dependencies: [ + "AgentsCore", "AgentsManifest", "StateTestProcess", "StateTestSupport", "CPlatform", + ]), + .testTarget( + name: "AgentsInstructionsTests", + dependencies: [ + "AgentsInstructions", "AgentsSkills", "AgentsManifest", "AgentsUpdates", "StateTestSupport", + ]), + .target( + name: "ManifestTestSupport", dependencies: ["AgentsManifest"], + path: "Tests/ManifestTestSupport"), + .executableTarget( + name: "ManifestTestProcess", + dependencies: ["AgentsManifest", "AgentsCore", "ManifestTestSupport"], + path: "Tests/ManifestTestProcess"), + .testTarget( + name: "AgentsManifestTests", + dependencies: [ + "AgentsManifest", "AgentsCore", "ManifestTestProcess", + "ManifestTestSupport", + ]), + .testTarget( + name: "AgentsUpdatesTests", + dependencies: [ + "AgentsUpdates", "AgentsManifest", "StateTestProcess", "StateTestSupport", "CPlatform", + "MCPTestProcess", + ]), .testTarget( name: "AgentsSkillsTests", dependencies: [ - "AgentsSkills", "AgentsCore", "AgentsInstructions", "Yams", "StateTestProcess", + "AgentsSkills", "AgentsCore", "AgentsManifest", "AgentsInstructions", "AgentsUpdates", + "Yams", + "StateTestProcess", "StateTestSupport", "CPlatform", ]), ], swiftLanguageModes: [.v6] diff --git a/README.md b/README.md index d680f05..b38e950 100644 --- a/README.md +++ b/README.md @@ -22,8 +22,8 @@ alt="Swift 6.3+"> - Platforms: macOS 15+ + Platforms: macOS 15+ and Linux License: MIT @@ -51,19 +51,25 @@ Both [agents](https://github.com/agents-tools/cli) and [skill](https://github.com/skill-cli/cli) consume this package. Consumers own command parsing, terminal output and executable distribution. +- **AgentsManifest**: reads and edits `agents.yaml`, validates complete symbolic + declaration intent and prepares byte-preserving changes. It supplies read-only + `loadDeclaration()` and `loadManifest()` access and declaration writes for the + domain modules. - **AgentsCore**: source parsing and identity, Git requirements, declaration and resolved-state models, atomic state storage, bare mirrors and immutable source materializations, watch subscriptions, hashing, path safety, process execution and agent locations. - **AgentsSkills**: `SKILL.md` discovery and frontmatter, well-known artifacts, installation, updates, removal, listing, initialization and diagnostics. It - depends on `AgentsCore` and Yams. + depends on `AgentsCore`, `AgentsManifest` and Yams. - **AgentsInstructions**: instruction discovery, lifecycle operations, audits, managed Markdown blocks, Claude forwarding and named ChatGPT prompts. It uses - `AgentsCore` for sources, state and transactions, and `swift-markdown` for - CommonMark structure. Pure text APIs remain available separately. -- **AgentsUpdates**: shared preparation, reporting and one recoverable apply - for all declared skills and instructions in a scope. + `AgentsCore` for sources, state and transactions, `AgentsManifest` for the + declaration, and `swift-markdown` for CommonMark structure. Pure text APIs + remain available separately. +- **AgentsUpdates**: previews and applies the declared configuration in one + recoverable transaction. It also exposes source import, component inspection + and explicit MCP connection tests to CLI and GUI consumers. ## Quick look @@ -73,6 +79,7 @@ the live source for Codex and list the installed skills: ```swift import AgentsCore import AgentsSkills +import AgentsUpdates let environment = RuntimeEnvironment() _ = try SkillOperations.add(AddOptions( @@ -97,6 +104,7 @@ targets: [ .executableTarget( name: "YourCLI", dependencies: [ + .product(name: "AgentsManifest", package: "core"), .product(name: "AgentsCore", package: "core"), .product(name: "AgentsSkills", package: "core"), .product(name: "AgentsInstructions", package: "core"), @@ -115,28 +123,64 @@ requirement. Pin a reviewed revision when reproducibility is required. Use ### State and lifecycle -Project state lives in `.agent/agents.json`, `.agent/agents.resolved` and +Project state lives in `.agent/agents.yaml`, `.agent/agents.resolved` and `.agent/agents.watch`. User state uses the same filenames under `~/.agents/`. -The respective `cache/` directory holds source mirrors and exact content. A -project commits its `agents.json` declaration and `agents.resolved` lock; keep +The respective `cache/` directory holds scope-owned mirrors and exact +materializations needed for restoration. A +project commits its `agents.yaml` declaration and `agents.resolved` lock; keep `agents.watch`, `cache/`, `.agents.lock` and `transaction.json` out of version control. The declaration records source aliases, requirements, skill selections and -recipients. The version 1 lock records each skill's independent revision or -artifact digest, content hash and agent-to-mode mapping. `link` uses shared -cached content, `copy` writes a directory, and `edit` links a live local source -with no requirement or pin. Local Git installs in `link` and `copy` use -committed content. - -`AgentsCore` defines the instruction declaration and lock models. Skill -operations preserve the instruction and watch declarations and the locked -instruction records. +recipients in the [manifest language](Documentation/Reference/Manifest.md). +Tool writes edit only the changed source ranges and keep comments. The version 2 +ledger records the full linked graph, independent pins, resources, ownership and +versioned deployments. `link` points to scope-owned materializations, `copy` +writes a directory, and `edit` links a live local source with no requirement or pin. +Local Git installs in `link` and `copy` use committed content. + +`AgentsCore` defines the complete typed declaration and the skill and instruction +lock models. +`loadDeclaration()` preserves all component families, conditions and symbolic +groups; deployment support is checked by the owning operation. Skill +operations use the shared composition layer and preserve recorded other-domain +semantics and watch state. Import `AgentsUpdates` for domain lifecycle methods. Mutating state operations recover interrupted transactions before proceeding and report `CoreError.transactionRecovered` when the command should be retried. The durable scope journal covers installations, declaration, lock, watch state and cache pruning. Corrupt watch state stops scope mutations before any replacement. +Read-only access, including `loadResolved()`, `loadWatch()` and, with `import +AgentsManifest`, `loadDeclaration()` and `loadManifest()`, never recovers and +reports a pending transaction with `CoreError.recoveryPending`. A scope with a +lock or watch state but no `agents.yaml` reports +`CoreError.missingDeclaration`. + +### Acquisition cache + +`AcquisitionCache(environment:)` manages disposable acquisitions across projects. +`RuntimeEnvironment` resolves its location from an explicit cache root, +`AGENTS_CACHE_DIR`, or the provided home's platform cache directory. Call +`inspect()` for per-store bytes and hazards, `preview(.clean)` or +`preview(.prune(days:))` to review removals, and `apply(_:)` for the results +of that preview. Prune defaults to 30 days. A removal result reports completed, +skipped and failed entries and the bytes actually reclaimed. + +Git groups are keyed by the exact anonymous HTTPS transport and commit. +Credentialed Git stays in scope-owned storage. Registry GETs honor origin +policy and HTTP freshness and validators. Only verified public bytes from a +completed deployment can enter the deployed-byte store. Scope-owned lock +closure and installed links survive shared-cache cleanup. Call +`UpdateOperations.restore(environment:offline:)` with `offline: true` to +prohibit remote Git reacquisition during restore. + +### Package source access + +Trusted hosts can configure repository credentials, direct egress and +enterprise archive routes in `RuntimeEnvironment.sourceAccess`. Source +inspection is status-only by default. Archive pins retain verified private +recovery bytes independently of disposable acquisitions. See +[package source access](Documentation/Reference/SourceAccess.md). ### Skills @@ -147,7 +191,7 @@ cache pruning. Corrupt watch state stops scope mutations before any replacement. choice. `listOnly` and `fullDepth` support source inspection. - `updateInstalled(...)` previews declared changes. With `apply: true`, its `beforeApply` callback receives differences before targets and state change. - Unnamed updates reconcile `select: "all"`; named updates affect only the + Unnamed updates reconcile all-member selections; named updates affect only the requested members. - `installResolvedReport(...)` restores the lock's pins, agents and modes. Missing pins and digest mismatches fail the operation. @@ -159,7 +203,7 @@ cache pruning. Corrupt watch state stops scope mutations before any replacement. Pass `RuntimeEnvironment` to select the project, home directory and environment. Default recipients for additions are Codex and Claude Code. Supported agents -also include Cursor, Gemini CLI and OpenCode. Listing and removal without an +also include Cursor, Gemini CLI, OpenCode and Antigravity. Listing and removal without an agent filter cover every recipient. Update previews include physical removals, entry types and symbolic link destinations. Installed inventory validates skill metadata and excludes missing entries; managed inventory retains those records @@ -180,7 +224,7 @@ diff leave declaration, lock, watch state and installed content unchanged. ### Combined updates -`UpdateOperations.preview(...)` returns both kinds under one shared scope lock. +`UpdateOperations.preview(...)` returns the selected configuration under existing shared locks with temporary source acquisition. For application, `withPreparedUpdate(...)` prepares both kinds and holds the writer lock while the consumer renders `update.report` and calls `update.apply()`. Apply commits both kinds, changed state and pruning together. @@ -215,7 +259,7 @@ by bare name. `InstructionOperations` generates whole target files from them: deletes a target that no longer receives sections while it still equals its locked rendering. - `renderChatGPT(prompt:...)` renders locked sections plus a custom append file. - Prompts live in `instructions.chatgpt`. + Prompts are declared in an instructions component’s `chatgpt` mapping. - `doctor(...)` checks missing, drifted and unowned locked targets, changed own files, links, scope duplication, Claude forwarding, Codex overrides and the project size budget, newer matching source revisions and uncommitted sources. @@ -225,10 +269,11 @@ by bare name. `InstructionOperations` generates whole target files from them: - `initializeInstructions(named:environment:)` creates a valid file skeleton in the project's `.agent/instructions/`. -A target is a notice line followed by the sections in declared order. A section +A combined Markdown target is a notice line followed by the sections in declared order. A section with `paths` gets a line naming its patterns and, in project scope, is written -to the `AGENTS.md` of the directory the patterns share. Project recipients -share `AGENTS.md` except Gemini CLI, which uses `GEMINI.md`. Claude project +to the `AGENTS.md` of the directory the patterns share. Codex, Claude Code, +Cursor and OpenCode share project `AGENTS.md`. Gemini CLI uses `GEMINI.md`. +Claude project files receive only a managed import when forwarding is needed. User locations honor `CODEX_HOME`, `CLAUDE_CONFIG_DIR` and `XDG_CONFIG_HOME`; Codex and Claude use separate files. Codex diagnostics accept effective discovery settings from @@ -239,13 +284,29 @@ that project's `AGENTS.md` outside code and HTML, including managed import blocks. Inline mentions do not suppress the caller's managed import block; a duplicate import is acceptable to ensure the instructions load. +Antigravity installs one native rule per selected instruction section in +`.agents/rules/` for a project or `~/.gemini/config/rules/` for a user. +Project sections with `paths` become scoped glob rules. The +[manifest reference](Documentation/Reference/Manifest.md#antigravity) lists +Antigravity's skill, MCP and hook targets. + See [instruction lifecycle](Documentation/Architecture/Instructions.md) for API contracts, target paths, read-only inspection and deletion rules. ## Requirements - Swift 6.3 or newer, using Swift 6 language mode. -- macOS 15 or newer, as declared in [Package.swift](Package.swift). +- macOS 15 or newer, as declared in [Package.swift](Package.swift), or Linux + with glibc 2.34 or newer, `/proc` mounted and a filesystem supporting file + `flock`, atomic directory exchange, POSIX ACLs and extended attributes. +- Linux builds require SQLite 3 headers and library (`libsqlite3-dev` on Ubuntu). +- Relocating a project with compressed Codex rollouts requires `zstd`. +- Git and `tar`; ZIP artifacts also require `unzip` (including `zipinfo`). +- Directory permissions, inherited/default ACLs and other filesystem policy must + allow the owner to read/write created files and read/write/search created + directories. Core does not repair access policy; denied operations stop with + the affected path and a permission diagnostic. Correct the environment before + retrying. ## Documentation @@ -259,6 +320,8 @@ contracts, target paths, read-only inspection and deletion rules. instructions files, generated targets, prompts and diagnostics. - [Watch API](Documentation/Architecture/Watch.md): subscriptions, comparisons and seen baselines. +- [Organization install policy](Documentation/Reference/OrganizationPolicy.md): policy selection, + install checks and read-only CI auditing. - [Combined updates](Documentation/Architecture/Updates.md): reports, preparation, one-use handles and transaction outcomes. - [Release checklist](Documentation/Reference/Release.md): package releases and @@ -273,24 +336,47 @@ Read the [organization contributing guide][contributing] and the ### Development -Run the package's build, test, release and formatting checks: +The generation commands in `.github/swift-package.json` run on the last +compiler entry's runner, using `python3` and the toolchain's `swift format`. +They regenerate into temporary directories and compare committed bytes. +`swift test` checks YAML admission, complete domain round trips, source maps, +lossless edits and the existing lifecycle contracts. + +Run the package's build, test, generation and formatting checks: ```bash swift build env -u CODEX_HOME -u CLAUDE_CONFIG_DIR -u XDG_CONFIG_HOME \ -u XDG_STATE_HOME -u XDG_CACHE_HOME swift test swift build -c release +python3 Scripts/generate-manifest-schema.py --check swift format lint --strict --configuration .swift-format \ --recursive Package.swift Sources Tests ``` +By default, publication tests kill each operation at representative points, and +kill recovery at durable steps from each seeded interruption. When changing the +transaction protocol, also kill at every recorded point: + +```bash +env -u CODEX_HOME -u CLAUDE_CONFIG_DIR -u XDG_CONFIG_HOME \ + -u XDG_STATE_HOME -u XDG_CACHE_HOME AGENTS_PUBLICATION_MATRIX=full \ + swift test --filter PublicationTests +``` + The required checks are `policy / policy` and `validate / result`, provided by full-SHA-pinned reusable workflows from `agents-tools/github-workflows`. Source policy validates PR titles, new commit messages and added lines. -[Package validation configuration](.github/swift-package.json) selects one -compiler: the latest stable Xcode, 26.6, on `macos-26`. Validation runs tests -and a release build, plus strict formatting with `.swift-format` over -`Package.swift`, `Sources` and `Tests`. +[Package validation configuration](.github/swift-package.json) selects Xcode +26.6 on `macos-26` and a digest-pinned official Swift Linux container. macOS and +Linux validation run the Debug and Release test suites with the default +publication matrix; the full publication matrix is not part of CI. macOS also +runs a release build and strict formatting with `.swift-format` over +`Package.swift`, `Sources` and `Tests`. The test suites include subprocess +recovery tests. The configuration owns the Linux compiler version and image +digest. The suites run serially so other test cases cannot starve subprocess +deadlines. Linux uses the checkout owner to exercise kernel permission checks, +with Python 3 for the loopback HTTP fixture and Perl through Git. Render and check the committed [social preview](.github/assets/social-preview/social-preview.png) locally with diff --git a/Scripts/generate-manifest-schema.py b/Scripts/generate-manifest-schema.py new file mode 100644 index 0000000..4235712 --- /dev/null +++ b/Scripts/generate-manifest-schema.py @@ -0,0 +1,217 @@ +#!/usr/bin/env python3 +"""Compile the finite field shapes used by the shipped manifest schema.""" +import argparse +import json +import subprocess +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +ANNOTATIONS = {'title', 'description', 'examples'} +INTEGER_MIN = -(2 ** 63) +INTEGER_MAX = 2 ** 63 - 1 + + +def q(value): + escapes = {'"': '\\"', '\\': '\\\\', '\n': '\\n', '\r': '\\r', '\t': '\\t'} + return '"' + ''.join(escapes.get(c, '\\u{' + format(ord(c), 'x') + '}' if ord(c) < 32 else c) + for c in value) + '"' + + +def integer(value, name, minimum=INTEGER_MIN): + if type(value) is not int or not minimum <= value <= INTEGER_MAX: + raise ValueError(f'{name} must be an integer in {minimum}...{INTEGER_MAX}') + return str(value) + + +def emit(value, definitions, *, root=False): + if not isinstance(value, dict): + raise ValueError('field shapes must be schema objects') + + def allow(keys): + accepted = set(keys) | ANNOTATIONS + if root: + accepted |= {'$schema', '$id', '$defs'} + unsupported = set(value) - accepted + if unsupported: + raise ValueError('unsupported schema keywords or combination: ' + ', '.join(sorted(unsupported))) + + for key in ('title', 'description', '$schema', '$id'): + if key in value and not isinstance(value[key], str): + raise ValueError(key + ' must be a string') + if 'examples' in value and not isinstance(value['examples'], list): + raise ValueError('examples must be an array') + if '$ref' in value: + allow({'$ref'}) + ref = value['$ref'] + if not isinstance(ref, str) or not ref.startswith('#/$defs/') or ref[8:] not in definitions: + raise ValueError('expected a reference to a bundled definition') + return '.named(' + q(ref[8:]) + ')' + if 'x-agents-native-value' in value: + allow({'x-agents-native-value'}) + if value['x-agents-native-value'] is not True: + raise ValueError('x-agents-native-value must be true') + return '.native' + if 'oneOf' in value: + allow({'oneOf'}) + choices = value['oneOf'] + if not isinstance(choices, list) or not choices: + raise ValueError('oneOf must contain field shapes') + return '.oneOf([' + ', '.join(emit(x, definitions) for x in choices) + '])' + if 'const' in value: + allow({'const', 'type', 'x-agents-scalar-kind'}) + literal = value['const'] + if isinstance(literal, str) and value.get('type', 'string') == 'string': + if 'x-agents-scalar-kind' in value: + raise ValueError('scalar-kind is supported only on integers') + return '.constant(' + q(literal) + ')' + if type(literal) is int and value.get('type') == 'integer': + if value.get('x-agents-scalar-kind', 'integer') != 'integer': + raise ValueError('unsupported scalar-kind') + return '.integerConstant(' + integer(literal, 'const') + ')' + raise ValueError('const supports strings and typed integers') + if 'enum' in value: + allow({'enum', 'type'}) + choices = value['enum'] + if (value.get('type', 'string') != 'string' or not isinstance(choices, list) + or not choices or any(not isinstance(x, str) for x in choices) + or len(set(choices)) != len(choices)): + raise ValueError('enum must contain unique strings') + return '.enumeration([' + ', '.join(q(x) for x in choices) + '])' + kind = value.get('type') + if kind == 'string': + allow({'type'}) + return '.string' + if kind == 'integer': + allow({'type', 'minimum', 'maximum', 'x-agents-scalar-kind'}) + if value.get('x-agents-scalar-kind', 'integer') != 'integer': + raise ValueError('unsupported scalar-kind') + bounds = 'minimum: ' + integer(value.get('minimum', INTEGER_MIN), 'minimum') + if 'maximum' in value: + bounds += ', maximum: ' + integer(value['maximum'], 'maximum') + return '.integer(' + bounds + ')' + if kind == 'array': + allow({'type', 'items', 'maxItems'}) + if 'items' not in value: + raise ValueError('arrays require an item shape') + maximum = integer(value['maxItems'], 'maxItems', 0) if 'maxItems' in value else 'nil' + return '.array(' + emit(value['items'], definitions) + ', maximum: ' + maximum + ')' + if kind == 'object': + allow({'type', 'properties', 'required', 'additionalProperties', 'maxProperties'}) + maximum = integer(value['maxProperties'], 'maxProperties', 0) if 'maxProperties' in value else 'nil' + additional = value.get('additionalProperties') + if isinstance(additional, dict): + if 'properties' in value or 'required' in value: + raise ValueError('dictionary shapes cannot also declare fixed fields or required keys') + return '.dictionary(' + emit(additional, definitions) + ', maximum: ' + maximum + ')' + if additional is not False: + raise ValueError('objects require false or a field shape for additionalProperties') + properties = value.get('properties', {}) + required = value.get('required', []) + if not isinstance(properties, dict) or any(not isinstance(x, str) for x in properties): + raise ValueError('properties must map field names to shapes') + if (not isinstance(required, list) or any(not isinstance(x, str) for x in required) + or len(set(required)) != len(required) or not set(required) <= set(properties)): + raise ValueError('required must contain unique declared field names') + fields = ', '.join(q(k) + ': ' + emit(v, definitions) for k, v in properties.items()) + return ('.object([' + (fields or ':') + '], required: [' + ', '.join(q(x) for x in required) + + '], maximum: ' + maximum + ')') + raise ValueError('unsupported field shape: ' + str(kind)) + + +def describe(value): + if '$ref' in value: + return value['$ref'].removeprefix('#/$defs/') + if 'x-agents-native-value' in value: + return 'NativeValue' + if 'const' in value: + return '`' + str(value['const']) + '`' + if 'enum' in value: + return ' / '.join('`' + str(x) + '`' for x in value['enum']) + if 'oneOf' in value: + return 'one of: ' + ', '.join(describe(x) for x in value['oneOf']) + kind = value['type'] + if kind == 'array': + shape = 'sequence of ' + describe(value['items']) + return shape + (f" (at most {value['maxItems']} items)" if 'maxItems' in value else '') + if kind == 'object': + shape = ('name → ' + describe(value['additionalProperties']) + if isinstance(value['additionalProperties'], dict) else 'mapping') + return shape + (f" (at most {value['maxProperties']} properties)" if 'maxProperties' in value else '') + if kind == 'integer' and 'minimum' in value: + return 'integer ≥ ' + str(value['minimum']) + return kind + + +def table_text(text): + return text.replace('&', '&').replace('|', '|').replace('`', '`').replace('\n', '
') + + +def examples(value): + return ', '.join('' + table_text(json.dumps(example, ensure_ascii=False)).replace('<', '<') + .replace('>', '>') + '' for example in value.get('examples', [])) + + +def field_help(value, level=3): + text = value.get('description', '') + text = text + '\n\n' if text else '' + if value.get('examples'): + text += 'Examples: ' + examples(value) + '\n\n' + if 'properties' in value: + if 'maxProperties' in value: + text += describe(value) + '\n\n' + text += '| Field | Required | Shape | Description |\n| --- | --- | --- | --- |\n' + for key, field in value['properties'].items(): + details = table_text(field.get('description', '')) + if field.get('examples'): + details += ('
' if details else '') + 'Examples: ' + examples(field) + text += ('| `' + key + '` | ' + ('yes' if key in value.get('required', []) else '') + + ' | ' + describe(field) + ' | ' + details + ' |\n') + elif 'oneOf' not in value: + text += describe(value) + '\n' + for index, branch in enumerate(value.get('oneOf', []), 1): + text = text.rstrip('\n') + '\n\n' + '#' * level + ' Alternative ' + str(index) + '\n\n' + text += field_help(branch, level + 1) + return text + + +def compile_schema(schema): + if not isinstance(schema, dict) or not isinstance(schema.get('$defs'), dict): + raise ValueError('the bundled schema requires named definitions') + if schema.get('$schema', 'https://json-schema.org/draft/2020-12/schema') != 'https://json-schema.org/draft/2020-12/schema': + raise ValueError('the bundled schema uses the 2020-12 dialect') + definitions = schema['$defs'] + if any(not isinstance(name, str) or not name or '/' in name or '~' in name for name in definitions): + raise ValueError('definition names must be nonempty, unescaped pointer segments') + text = ('// Generated by Scripts/generate-manifest-schema.py.\n\nenum ManifestSchema {\n' + + ' static let root: YAMLRule = ' + emit(schema, definitions, root=True) + + '\n static let definitions: [String: YAMLRule] = [\n') + text += ''.join(' ' + q(k) + ': ' + emit(v, definitions) + ',\n' for k, v in definitions.items()) + text += ' ]\n}\n' + help_text = ('# Manifest Field Shapes\n\n' + 'Generated from `Sources/AgentsManifest/Resources/agents.schema.json`.\n') + for name, definition in [('Declaration', schema)] + list(definitions.items()): + help_text += '\n## ' + name + '\n\n' + help_text += field_help(definition) + return text, help_text + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--check', action='store_true') + args = parser.parse_args() + schema = json.loads((ROOT / 'Sources/AgentsManifest/Resources/agents.schema.json').read_text()) + text, help_text = compile_schema(schema) + text = subprocess.run(['xcrun', 'swift-format', 'format', '--configuration', str(ROOT / '.swift-format')], + input=text, text=True, capture_output=True, check=True).stdout + outputs = {ROOT / 'Sources/AgentsManifest/ManifestSchema.swift': text, + ROOT / 'Documentation/Reference/ManifestSchema.md': help_text} + for path, contents in outputs.items(): + if args.check: + if not path.exists() or path.read_text() != contents: + raise SystemExit('generated manifest schema/help is stale: ' + str(path)) + else: + path.write_text(contents) + + +if __name__ == '__main__': + main() diff --git a/Scripts/test-linux.py b/Scripts/test-linux.py new file mode 100644 index 0000000..ed54d51 --- /dev/null +++ b/Scripts/test-linux.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python3 +"""Run the package tests in the pinned Linux toolchain as the checkout owner.""" + +import json +import os +from pathlib import Path +import subprocess +import sys + + +def main(image): + root = Path(__file__).resolve().parents[1] + config = json.loads((root / ".github/swift-package.json").read_text()) + if os.getuid() == 0: + raise SystemExit("Run Linux validation as a regular user for filesystem permission tests.") + + dockerfile = root / ".github/ci/linux-tests.Dockerfile" + test_image = subprocess.check_output( + [ + "docker", "build", "--quiet", "--file", str(dockerfile), + "--build-arg", f"SWIFT_IMAGE={image}", + "--build-arg", f"TEST_UID={os.getuid()}", + "--build-arg", f"TEST_GID={os.getgid()}", + str(dockerfile.parent), + ], + text=True, + ).strip() + for configuration in config["test_configurations"]: + subprocess.run( + [ + "docker", "run", "--rm", "--init", "--volume", f"{root}:/workspace", + test_image, "swift", "test", "-c", configuration, "--jobs", "2", "--no-parallel", + ], + check=True, + ) + + +if __name__ == "__main__": + main(sys.argv[1]) diff --git a/Scripts/test_manifest_schema.py b/Scripts/test_manifest_schema.py new file mode 100644 index 0000000..78dc5b7 --- /dev/null +++ b/Scripts/test_manifest_schema.py @@ -0,0 +1,86 @@ +#!/usr/bin/env python3 +"""Guard the bundled schema compiler's accepted validation semantics.""" +import copy +import importlib.util +import unittest +from pathlib import Path + +spec = importlib.util.spec_from_file_location('manifest_schema', Path(__file__).with_name('generate-manifest-schema.py')) +compiler = importlib.util.module_from_spec(spec) +spec.loader.exec_module(compiler) + + +class SchemaCompilerTests(unittest.TestCase): + def test_annotations_reach_help_without_changing_runtime_rules(self): + schema = { + 'type': 'object', 'additionalProperties': False, '$defs': { + 'choice': {'oneOf': [ + {'type': 'object', 'additionalProperties': False, + 'properties': {'description': {'type': 'string'}}, 'required': ['description']}, + {'type': 'string'}, + ]}, + }, + 'properties': {'examples': {'$ref': '#/$defs/choice'}}, + } + annotated = copy.deepcopy(schema) + annotated['description'] = 'Declaration documentation.' + annotated['properties']['examples']['description'] = 'A field with a schema reference.' + branch = annotated['$defs']['choice']['oneOf'][0] + branch['description'] = 'Mapping alternative documentation.' + branch['properties']['description']['description'] = 'First line | `text`\nSecond line.' + branch['properties']['description']['examples'] = ['a | b', ''] + swift, help_text = compiler.compile_schema(annotated) + self.assertEqual(swift, compiler.compile_schema(schema)[0]) + for expected in ['Declaration documentation.', 'A field with a schema reference.', + 'Mapping alternative documentation.', 'First line | `text`
Second line.', + '"a | b"', '"<value>"', + '| `description` | yes | string |', '| `examples` | | choice |']: + self.assertIn(expected, help_text) + + def test_schema_values_drive_runtime_constraints_and_help(self): + schema = { + 'type': 'object', 'additionalProperties': False, '$defs': {}, + 'properties': { + 'version': {'type': 'integer', 'const': 2}, + 'items': {'type': 'array', 'items': {'type': 'string'}, 'maxItems': 3}, + 'names': {'type': 'object', 'additionalProperties': {'type': 'string'}, 'maxProperties': 4}, + 'record': {'type': 'object', 'additionalProperties': False, 'maxProperties': 0}, + 'count': {'type': 'integer', 'minimum': 5}, + }, + } + swift, help_text = compiler.compile_schema(schema) + for expected in ['.integerConstant(2)', '.array(.string, maximum: 3)', + '.dictionary(.string, maximum: 4)', '.object([:], required: [], maximum: 0)', + '.integer(minimum: 5)']: + self.assertIn(expected, swift) + for expected in ['`2`', 'at most 3 items', 'at most 4 properties', 'at most 0 properties', 'integer ≥ 5']: + self.assertIn(expected, help_text) + + def test_validation_siblings_are_not_discarded(self): + for shape in [{'$ref': '#/$defs/string'}, {'oneOf': [{'type': 'string'}]}, + {'x-agents-native-value': True}, {'const': 'a'}, {'enum': ['a']}]: + with self.subTest(shape=shape), self.assertRaises(ValueError): + compiler.emit({**shape, 'maxItems': 1}, {'string': {'type': 'string'}}) + for shape in [{'type': 'string', 'minimum': 1}, {'type': 'array', 'items': {'type': 'string'}, 'maxProperties': 1}, + {'type': 'object', 'additionalProperties': {'type': 'string'}, 'properties': {}}]: + with self.subTest(shape=shape), self.assertRaises(ValueError): + compiler.emit(shape, {}) + + def test_unsupported_values_are_rejected(self): + for shape in [{'const': True}, {'const': 2.5}, {'type': 'integer', 'const': 2 ** 63}, + {'const': 'a', 'type': 'integer'}, {'enum': [1]}, {'enum': []}, + {'type': 'object', 'additionalProperties': True}, {'type': 'object'}, + {'x-agents-native-value': False}, {'oneOf': []}, {'$ref': 'external'}, + {'$ref': '#/$defs/missing'}, {'type': 'integer', 'x-agents-scalar-kind': 'float'}, + {'type': 'object', 'additionalProperties': False, 'required': ['absent']}]: + with self.subTest(shape=shape), self.assertRaises(ValueError): + compiler.emit(shape, {}) + for maximum in [-1, True, 1.5, 2 ** 63]: + for shape in [{'type': 'array', 'items': {'type': 'string'}, 'maxItems': maximum}, + {'type': 'object', 'additionalProperties': False, 'maxProperties': maximum}]: + with self.subTest(shape=shape), self.assertRaises(ValueError): + compiler.emit(shape, {}) + + +if __name__ == '__main__': + unittest.main() diff --git a/Sources/AgentsCore/AcquisitionCache/AcquisitionCache.swift b/Sources/AgentsCore/AcquisitionCache/AcquisitionCache.swift new file mode 100644 index 0000000..cb4a952 --- /dev/null +++ b/Sources/AgentsCore/AcquisitionCache/AcquisitionCache.swift @@ -0,0 +1,155 @@ +import Foundation + +public enum AcquisitionCacheStore: String, CaseIterable, Codable, Sendable { + case git + case http + case deployed +} + +public enum AcquisitionCacheMaintenance: Equatable, Sendable { + case clean + case prune(days: Int = 30) +} + +public enum AcquisitionCacheError: LocalizedError, Equatable, Sendable { + case unsafeRoot(String) + case rootChanged + case invalidAge + case busy + case invalidEntry + + public var errorDescription: String? { + switch self { + case .unsafeRoot(let path): "Unsafe acquisition cache root: \(path)" + case .rootChanged: "The acquisition cache root changed after review." + case .invalidAge: "The acquisition cache prune age must be nonnegative." + case .busy: "The acquisition cache entry is in use." + case .invalidEntry: "The acquisition cache entry has invalid or unsafe contents." + } + } +} + +public struct AcquisitionCacheEntry: Equatable, Sendable { + public let store: AcquisitionCacheStore + public let id: String + public let object: String + public let lastUsed: Date + public let bytes: Int64 + public let pendingDisposal: Bool + /// Reference indexes are attributed to Git, but do not count as immutable commit groups. + public var isGitObservation: Bool { store == .git && object.hasPrefix("ref:") } + let generation: UUID + let identities: [String: FileObjectIdentity] + let files: [String: AcquisitionFileGeneration] +} + +public struct AcquisitionCacheIssue: Equatable, Sendable { + public let path: String + public let reason: String +} + +public struct AcquisitionCacheInventory: Sendable { + public let root: URL + public let entries: [AcquisitionCacheEntry] + public let issues: [AcquisitionCacheIssue] + + public var totalBytes: Int64 { entries.reduce(0) { $0 + $1.bytes } } + + public func bytes(in store: AcquisitionCacheStore) -> Int64 { + entries.lazy.filter { $0.store == store }.reduce(0) { $0 + $1.bytes } + } +} + +/// An in-memory review tied to the opened cache root and the listed generations. +public struct AcquisitionCachePreview: Sendable { + public let root: URL + public let operation: AcquisitionCacheMaintenance + public let candidates: [AcquisitionCacheEntry] + public let issues: [AcquisitionCacheIssue] + public var totalBytes: Int64 { candidates.reduce(0) { $0 + $1.bytes } } + let rootIdentity: FileObjectIdentity? + let cutoff: Date? +} + +public struct AcquisitionCacheRemoval: Sendable { + public let removed: [AcquisitionCacheEntry] + public let skipped: [AcquisitionCacheEntry] + public let failures: [AcquisitionCacheIssue] + public let reclaimedBytes: Int64 + public var isComplete: Bool { failures.isEmpty } +} + +/// Disposable public acquisition storage shared by consumers of the Swift runtime. +public struct AcquisitionCache: Sendable { + package static let registryResponseLimit = 8 * 1024 * 1024 + + public let root: URL + let environment: RuntimeEnvironment + + public init(environment: RuntimeEnvironment = RuntimeEnvironment()) { + self.environment = environment + root = environment.acquisitionCacheDirectory + } + + /// Reads the inventory without creating or recovering anything. + public func inspect() throws -> AcquisitionCacheInventory { + try withRoot { directory in + try inventory(directory).report + } + } + + public func preview( + _ operation: AcquisitionCacheMaintenance, now: Date = Date() + ) throws -> AcquisitionCachePreview { + let cutoff: Date? + switch operation { + case .clean: cutoff = nil + case .prune(let days): + guard days >= 0 else { throw AcquisitionCacheError.invalidAge } + cutoff = now.addingTimeInterval(-Double(days) * 86_400) + } + return try withRoot { directory in + let scan = try inventory(directory) + let candidates = scan.report.entries.filter { entry in + guard let cutoff else { return true } + return entry.store == .git + && (entry.pendingDisposal || (!entry.isGitObservation && entry.lastUsed < cutoff)) + } + return AcquisitionCachePreview( + root: root, operation: operation, candidates: candidates, issues: scan.report.issues, + rootIdentity: scan.identity, cutoff: cutoff) + } + } + + /// Applies the reviewed candidates independently. Reused or replaced entries are skipped. + public func apply(_ preview: AcquisitionCachePreview) throws -> AcquisitionCacheRemoval { + try apply(preview, afterDetach: {}) + } +} + +extension RuntimeEnvironment { + public var acquisitionCacheDirectory: URL { + if let root = acquisitionCacheRoot { return root.standardizedFileURL } + if let configured = environment["AGENTS_CACHE_DIR"], !configured.isEmpty { + let project = URL(fileURLWithPath: projectDirectory.path, isDirectory: true) + return URL(fileURLWithPath: configured, relativeTo: project).standardizedFileURL + } + #if os(macOS) + let base = homeDirectory.appendingPathComponent("Library/Caches") + #else + let base = + environment["XDG_CACHE_HOME"].flatMap { + $0.hasPrefix("/") ? URL(fileURLWithPath: $0) : nil + } ?? homeDirectory.appendingPathComponent(".cache") + #endif + return base.appendingPathComponent("agents") + } +} + +struct AcquisitionFileGeneration: Equatable, Sendable { + let info: stat + + static func == (lhs: Self, rhs: Self) -> Bool { + DirectoryHandle.sameGeneration(lhs.info, rhs.info) + } +} diff --git a/Sources/AgentsCore/AcquisitionCache/AcquisitionStorage.swift b/Sources/AgentsCore/AcquisitionCache/AcquisitionStorage.swift new file mode 100644 index 0000000..cc7c07b --- /dev/null +++ b/Sources/AgentsCore/AcquisitionCache/AcquisitionStorage.swift @@ -0,0 +1,702 @@ +import CPlatform +import Foundation + +extension AcquisitionCache { + package struct Value: Sendable { + package let data: Data + package let metadata: Data + package let publication: UUID + } + + package enum WriteCondition: Sendable { + case absent + case publication(UUID) + } + + private struct Record: Codable { + let store: AcquisitionCacheStore + let key: String + let object: String + let digest: String + let size: Int + let metadata: Data + var publication: UUID + let created: Date + var revoked: Bool? + } + + private struct Access: Codable { + let generation: UUID + let time: Date + } + + private struct Entry { + let directory: DirectoryHandle + let record: Record + let payload: stat + let summary: AcquisitionCacheEntry + } + + private struct Receipt: Codable { + let id: UUID + let record: Record + let access: Access + let identities: [String: FileObjectIdentity] + } + + private static let marker = ".agents-acquisition-cache" + private static let markerContents = Data("agents acquisition cache 1\n".utf8) + private static let trash = ".trash" + private static let leases = ".leases" + private static let payload = "bytes" + private static let manifest = "record.json" + private static let nextManifest = "record.next" + private static let access = "access.json" + private static let nextAccess = "access.next" + private static let recordLimit = 64 * 1024 + private static let typedFiles: Set = [ + payload, manifest, nextManifest, access, nextAccess, + ] + + package static func key(_ records: [(String, Data)]) -> String { + FileHash.hashRecords(records) + } + + package func read( + _ store: AcquisitionCacheStore, key: String, maximumBytes: Int, + now: Date = Date(), touching: Bool = true, _ body: (Value) throws -> T + ) throws -> T? { + func openEntry(in root: DirectoryHandle?) throws -> (Entry, Lease)? { + guard let root, + let parent = try directory(store.rawValue, in: root), + let entry = try entry(store, key: key, in: parent), entry.record.revoked != true, + entry.record.size <= maximumBytes + else { return nil } + let lease = try entryLease(store, key: key, root: root, create: false, exclusive: false) + return (entry, lease) + } + + func verified(_ entry: Entry) throws -> Value { + let data = try entry.directory.read( + Self.payload, matching: entry.payload, maximumBytes: maximumBytes) + guard data.count == entry.record.size, + FileHash.sha256Hex(data: data) == entry.record.digest + else { throw AcquisitionCacheError.invalidEntry } + return .init( + data: data, metadata: entry.record.metadata, publication: entry.record.publication) + } + + // Registry reads copy their bounded response under root coordination. This keeps conditional + // invalidation from racing a lease associated only with an in-memory HTTP representation. + if store == .http { + let value = try withRoot(exclusive: touching) { root in + guard let (entry, lease) = try openEntry(in: root) else { return nil as Value? } + return try withExtendedLifetime(lease) { + let value = try verified(entry) + if touching { try touch(entry, now: now) } + return value + } + } + return try value.map(body) + } + + let found = try withRoot(exclusive: touching) { root in + let found = try openEntry(in: root) + if touching, let (entry, _) = found { try touch(entry, now: now) } + return found + } + guard let (entry, lease) = found else { return nil } + return try withExtendedLifetime(lease) { try body(verified(entry)) } + } + + private func touch(_ entry: Entry, now: Date) throws { + let access = Access(generation: UUID(), time: max(now, entry.summary.lastUsed)) + try entry.directory.replaceFile( + Self.access, through: Self.nextAccess, with: Self.encode(access), + afterWrite: {}, afterRename: {}) + } + + package func publication(_ store: AcquisitionCacheStore, key: String) throws -> UUID? { + try withRoot { root in + guard let root, let parent = try directory(store.rawValue, in: root) else { return nil } + return try entry(store, key: key, in: parent)?.record.publication + } + } + + /// Retains the previous generation if another request already advanced it. + @discardableResult + package func write( + _ data: Data, store: AcquisitionCacheStore, key: String, object: String, + metadata: Data = Data(), condition: WriteCondition = .absent, now: Date = Date(), + totalLimit: Int64? = nil + ) throws -> Bool { + try withRoot(mutate: true) { root in + guard let root else { throw AcquisitionCacheError.rootChanged } + try Self.requireKey(key) + let parent = try directory(store.rawValue, in: root, create: true)! + let previous = try entry(store, key: key, in: parent) + guard matches(previous, condition: condition) else { return false } + let lease = try entryLease(store, key: key, root: root, create: true, exclusive: true) + return try withExtendedLifetime(lease) { + let record = Record( + store: store, key: key, object: object, digest: FileHash.sha256Hex(data: data), + size: data.count, metadata: metadata, publication: UUID(), created: now) + try Self.validate(record, store: store, key: key) + let encoded = try Self.encode(record) + guard encoded.count <= Self.recordLimit else { throw AcquisitionCacheError.invalidEntry } + if let totalLimit { + try makeRoom( + in: parent, root: root, store: store, keeping: key, + incoming: Int64(data.count + encoded.count), limit: totalLimit) + } + if let previous { + let detached = try detach(previous, parent: parent, root: root) + _ = try dispose(detached, root: root) + } + try requireRootIdentity(root) + return try parent.publishDirectory( + named: key, files: [Self.manifest: encoded, Self.payload: data]) + } + } + } + + package func invalidate( + _ store: AcquisitionCacheStore, key: String, publication: UUID + ) throws { + try withRoot(exclusive: true) { root in + guard let root, let parent = try directory(store.rawValue, in: root), + let current = try entry(store, key: key, in: parent), + current.record.publication == publication + else { return } + let lease = try entryLease(store, key: key, root: root, create: false, exclusive: true) + try withExtendedLifetime(lease) { + // Revocation precedes reclamation. A permission error in trash must not leave a + // reusable response or allow a concurrent validator to renew the retired publication. + var revoked = current.record + revoked.revoked = true + revoked.publication = UUID() + try current.directory.replaceFile( + Self.manifest, through: Self.nextManifest, with: Self.encode(revoked), + afterWrite: {}, afterRename: {}) + guard let retired = try entry(store, key: key, in: parent) else { return } + if let detached = try? detach(retired, parent: parent, root: root) { + _ = try? dispose(detached, root: root) + } + } + } + } + + private func matches(_ entry: Entry?, condition: WriteCondition) -> Bool { + switch condition { + case .absent: entry == nil + case .publication(let old): entry?.record.publication == old + } + } + + private func makeRoom( + in parent: DirectoryHandle, root: DirectoryHandle, store: AcquisitionCacheStore, + keeping key: String, incoming: Int64, limit: Int64 + ) throws { + guard incoming <= limit else { throw AcquisitionCacheError.invalidEntry } + var remaining = try disposalBytes(store, root: root) + incoming + let entries = try parent.names().filter { $0 != key }.compactMap { + try entry(store, key: $0, in: parent) + }.sorted { $0.summary.lastUsed < $1.summary.lastUsed } + remaining += entries.reduce(0) { $0 + $1.summary.bytes } + for entry in entries where remaining > limit { + guard + let lease = try? entryLease( + store, key: entry.record.key, root: root, create: false, exclusive: true) + else { continue } + remaining -= try withExtendedLifetime(lease) { + let detached = try detach(entry, parent: parent, root: root) + return try dispose(detached, root: root) + } + } + guard remaining <= limit else { throw AcquisitionCacheError.busy } + } + + private func disposalBytes(_ store: AcquisitionCacheStore, root: DirectoryHandle) throws -> Int64 + { + guard let trash = try directory(Self.trash, in: root) else { return 0 } + return try trash.names().filter { $0.hasSuffix(".json") }.reduce(into: Int64(0)) { + total, name in + let entry = try pending(String(name.dropLast(5)), in: trash) + if entry.store == store { total += entry.bytes } + } + } + + package func apply( + _ preview: AcquisitionCachePreview, afterDetach: () throws -> Void + ) throws -> AcquisitionCacheRemoval { + guard root.path.utf8.elementsEqual(preview.root.path.utf8) else { + throw AcquisitionCacheError.rootChanged + } + return try withRoot(exclusive: true) { root in + guard try root?.objectIdentity == preview.rootIdentity else { + throw AcquisitionCacheError.rootChanged + } + var removed: [AcquisitionCacheEntry] = [] + var skipped: [AcquisitionCacheEntry] = [] + var failed = preview.issues + var reclaimed: Int64 = 0 + for candidate in preview.candidates { + guard let root else { break } + let path = candidate.pendingDisposal ? Self.trash : candidate.store.rawValue + do { + if candidate.pendingDisposal { + guard let trash = try directory(Self.trash, in: root), + try trash.info(candidate.id + ".json") != nil, + try pending(candidate.id, in: trash) == candidate + else { + skipped.append(candidate) + continue + } + try dispose(candidate.id, root: root, reclaimed: &reclaimed) + } else { + guard let parent = try directory(path, in: root), + let entry = try entry(candidate.store, key: candidate.id, in: parent), + entry.summary == candidate, + preview.cutoff.map({ candidate.lastUsed < $0 && candidate.store == .git }) ?? true + else { + skipped.append(candidate) + continue + } + let lease = try entryLease( + candidate.store, key: candidate.id, root: root, create: false, exclusive: true) + let name = try withExtendedLifetime(lease) { + try detach(entry, parent: parent, root: root) + } + try afterDetach() + try dispose(name, root: root, reclaimed: &reclaimed) + } + removed.append(candidate) + } catch { + failed.append(issue(path + "/" + candidate.id, error)) + } + } + return AcquisitionCacheRemoval( + removed: removed, skipped: skipped, failures: failed, reclaimedBytes: reclaimed) + } + } + + func inventory(_ root: DirectoryHandle?) throws -> ( + report: AcquisitionCacheInventory, identity: FileObjectIdentity? + ) { + var entries: [AcquisitionCacheEntry] = [] + var issues: [AcquisitionCacheIssue] = [] + if let root, try root.info(Self.marker) != nil { + func scan(_ name: String, _ inspect: (DirectoryHandle, String) throws -> Void) { + do { + guard let directory = try directory(name, in: root) else { return } + for key in try directory.names() { + do { try inspect(directory, key) } catch { + issues.append(issue(name + "/" + key, error)) + } + } + } catch { issues.append(issue(name, error)) } + } + for store in AcquisitionCacheStore.allCases { + scan(store.rawValue) { parent, key in + if let entry = try entry(store, key: key, in: parent) { entries.append(entry.summary) } + } + } + scan(Self.trash) { parent, key in + if key.hasSuffix(".json") { + entries.append(try pending(String(key.dropLast(5)), in: parent)) + } else { + guard key.hasSuffix(".entry"), + try parent.info(String(key.dropLast(6)) + ".json") != nil + else { throw AcquisitionCacheError.invalidEntry } + } + } + scan(Self.leases) { parent, key in + let fields = key.split(separator: "-", omittingEmptySubsequences: false) + guard fields.count == 2, AcquisitionCacheStore(rawValue: String(fields[0])) != nil, + let info = try parent.info(key), Self.owned(info, kind: S_IFREG) + else { throw AcquisitionCacheError.invalidEntry } + try Self.requireKey(String(fields[1])) + } + let known = Set(AcquisitionCacheStore.allCases.map(\.rawValue)) + .union([Self.marker, Self.leases, Self.trash]) + for name in try root.names() where !known.contains(name) { + issues.append(issue(name, AcquisitionCacheError.invalidEntry)) + } + } + return (.init(root: self.root, entries: entries, issues: issues), try root?.objectIdentity) + } + + private func issue(_ path: String, _ error: any Error) -> AcquisitionCacheIssue { + .init(path: path, reason: error.localizedDescription) + } + + private func entry( + _ store: AcquisitionCacheStore, key: String, in parent: DirectoryHandle + ) throws -> Entry? { + try Self.requireKey(key) + guard let directory = try directory(key, in: parent) else { return nil } + let record = try Self.decode(Record.self, in: directory, named: Self.manifest) + try Self.validate(record, store: store, key: key) + let access = + try directory.info(Self.access) == nil + ? Access(generation: record.publication, time: record.created) + : Self.decode(Access.self, in: directory, named: Self.access) + let files = try members(directory) + guard let payload = files.stats[Self.payload], payload.st_size == record.size, + files.stats[Self.manifest] != nil + else { throw AcquisitionCacheError.invalidEntry } + let summary = AcquisitionCacheEntry( + store: store, id: key, object: record.object, lastUsed: access.time, bytes: files.bytes, + pendingDisposal: false, generation: access.generation, identities: files.identities, + files: files.stats.mapValues { AcquisitionFileGeneration(info: $0) }) + return Entry(directory: directory, record: record, payload: payload, summary: summary) + } + + private func detach( + _ entry: Entry, parent: DirectoryHandle, root: DirectoryHandle + ) throws -> String { + try requireRootIdentity(root) + let trash = try directory(Self.trash, in: root, create: true)! + let id = UUID() + let access = Access(generation: entry.summary.generation, time: entry.summary.lastUsed) + let receipt = Receipt( + id: id, record: entry.record, access: access, identities: entry.summary.identities) + let bytes = try Self.encode(receipt) + guard bytes.count <= Self.recordLimit * 2 else { throw AcquisitionCacheError.invalidEntry } + try trash.write(id.uuidString + ".json", data: bytes) + let key = entry.record.key + guard try parent.info(key).map(FileObjectIdentity.init) == receipt.identities["."] else { + throw AcquisitionCacheError.invalidEntry + } + try parent.move(key, to: trash, named: id.uuidString + ".entry", mode: .exclusive) + return id.uuidString + } + + private func pending(_ name: String, in trash: DirectoryHandle) throws -> AcquisitionCacheEntry { + let receipt = try disposal(name, in: trash) + var identities: [String: FileObjectIdentity] = [:] + var files: [String: AcquisitionFileGeneration] = [:] + var bytes: Int64 = 0 + if let entry = try directory(name + ".entry", in: trash) { + let remaining = try members(entry) + guard remaining.identities.allSatisfy({ receipt.identities[$0.key] == $0.value }) else { + throw AcquisitionCacheError.invalidEntry + } + identities = remaining.identities + files = remaining.stats.mapValues { AcquisitionFileGeneration(info: $0) } + bytes = remaining.bytes + } + let receiptName = name + ".json" + identities["receipt"] = try trash.info(receiptName).map(FileObjectIdentity.init) + return .init( + store: receipt.record.store, id: name, object: receipt.record.object, + lastUsed: receipt.access.time, bytes: bytes, pendingDisposal: true, + generation: receipt.access.generation, identities: identities, files: files) + } + + private func disposal(_ name: String, in trash: DirectoryHandle) throws -> Receipt { + guard let id = UUID(uuidString: name), id.uuidString == name else { + throw AcquisitionCacheError.invalidEntry + } + let receipt = try Self.decode( + Receipt.self, in: trash, named: name + ".json", maximumBytes: Self.recordLimit * 2) + guard receipt.id == id, receipt.identities["."]?.isDirectory == true, + Set(receipt.identities.keys).isSubset(of: Self.typedFiles.union(["."])) + else { throw AcquisitionCacheError.invalidEntry } + try Self.validate(receipt.record, store: receipt.record.store, key: receipt.record.key) + return receipt + } + + private func dispose(_ name: String, root: DirectoryHandle) throws -> Int64 { + var reclaimed: Int64 = 0 + try dispose(name, root: root, reclaimed: &reclaimed) + return reclaimed + } + + private func dispose(_ name: String, root: DirectoryHandle, reclaimed: inout Int64) throws { + try requireRootIdentity(root) + guard let trash = try directory(Self.trash, in: root) else { + throw AcquisitionCacheError.invalidEntry + } + let expected = try pending(name, in: trash) + let entryName = name + ".entry" + if let entry = try directory(entryName, in: trash) { + for file in try entry.names() { + guard let info = try entry.info(file), + FileObjectIdentity(info) == expected.identities[file], + try entry.objectIdentity == expected.identities["."] + else { throw AcquisitionCacheError.invalidEntry } + guard unlinkat(entry.descriptor, file, 0) == 0 else { + throw FileSystem.posixError( + errno, at: entry.url.appendingPathComponent(file), + otherwise: .invalidState("cannot remove cache file")) + } + reclaimed += info.st_size + } + try entry.sync() + guard try trash.info(entryName).map(FileObjectIdentity.init) == expected.identities["."] + else { + throw AcquisitionCacheError.invalidEntry + } + try trash.removeEmptyDirectory(entryName) + } + try trash.remove(name + ".json", identity: expected.identities["receipt"]) + } + + private func members(_ directory: DirectoryHandle) throws -> ( + stats: [String: stat], identities: [String: FileObjectIdentity], bytes: Int64 + ) { + var stats: [String: stat] = [:] + var identities = [".": try directory.objectIdentity] + var bytes: Int64 = 0 + for name in try directory.names() { + guard Self.typedFiles.contains(name), + let info = try directory.info(name), Self.owned(info, kind: S_IFREG), info.st_size >= 0 + else { throw AcquisitionCacheError.invalidEntry } + if name != Self.payload, info.st_size > Self.recordLimit { + throw AcquisitionCacheError.invalidEntry + } + stats[name] = info + identities[name] = FileObjectIdentity(info) + let sum = bytes.addingReportingOverflow(info.st_size) + guard !sum.overflow else { throw AcquisitionCacheError.invalidEntry } + bytes = sum.partialValue + } + return (stats, identities, bytes) + } + + private func directory( + _ name: String, in parent: DirectoryHandle, create: Bool = false + ) throws -> DirectoryHandle? { + guard let info = try parent.info(name) else { + return try create ? parent.makeDirectory(name) : nil + } + guard Self.owned(info, kind: S_IFDIR) else { throw AcquisitionCacheError.invalidEntry } + let opened = try parent.child(name) + guard try opened.objectIdentity == FileObjectIdentity(info) else { + throw AcquisitionCacheError.invalidEntry + } + return opened + } + + func withRoot( + mutate: Bool = false, exclusive: Bool = false, _ body: (DirectoryHandle?) throws -> T + ) throws -> T { + try requireSafeRoot() + guard let handle = try existingRoot(create: mutate) else { return try body(nil) } + let lock = try Lease(handle.descriptor, exclusive: mutate || exclusive) + return try withExtendedLifetime(lock) { + try requireRootIdentity(handle) + var info = stat() + guard fstat(handle.descriptor, &info) == 0, Self.owned(info, kind: S_IFDIR) else { + throw AcquisitionCacheError.unsafeRoot(root.path) + } + if let marker = try handle.info(Self.marker) { + guard Self.owned(marker, kind: S_IFREG), + try handle.read(Self.marker, matching: marker, maximumBytes: 128) == Self.markerContents + else { throw AcquisitionCacheError.unsafeRoot(root.path) } + } else { + guard try handle.names().isEmpty else { throw AcquisitionCacheError.unsafeRoot(root.path) } + if mutate { try handle.write(Self.marker, data: Self.markerContents) } + } + return try body(handle) + } + } + + private func existingRoot(create: Bool = false) throws -> DirectoryHandle? { + var parent = try DirectoryHandle(at: URL(fileURLWithPath: "/")) + for (index, name) in root.pathComponents.dropFirst().enumerated() { + if create, try parent.info(name) == nil { + do { _ = try parent.makeDirectory(name) } catch { + if try parent.info(name) == nil { throw error } + } + } + guard let info = try parent.info(name) else { return nil } + if index == 0 && platform_system_alias(name) { + parent = try DirectoryHandle(at: parent.url.appendingPathComponent(name)) + } else { + guard info.st_mode & S_IFMT == S_IFDIR else { + throw AcquisitionCacheError.unsafeRoot(root.path) + } + let child = try parent.child(name) + guard try child.objectIdentity == FileObjectIdentity(info) else { + throw AcquisitionCacheError.rootChanged + } + parent = child + } + } + return parent + } + + private func requireRootIdentity(_ handle: DirectoryHandle) throws { + try requireSafeRoot() + guard try existingRoot()?.objectIdentity == handle.objectIdentity else { + throw AcquisitionCacheError.rootChanged + } + } + + private func requireSafeRoot() throws { + guard root.isFileURL, root.path.hasPrefix("/"), !root.path.utf8.contains(0) else { + throw AcquisitionCacheError.unsafeRoot(root.path) + } + let home = environment.homeDirectory + let project = environment.projectDirectory + var protected = environment.protectedAcquisitionPaths + for scope in [InstallScope.project, .user] { + protected.append(StateStore(scope: scope, environment: environment).directory) + protected.append( + AgentRegistry.canonicalSkillsDirectory(scope: scope, environment: environment)) + protected += AgentID.allCases.map { + AgentRegistry.skillsDirectory(for: $0, scope: scope, environment: environment) + } + } + let clientRoots = [ + ".agents", ".codex", ".claude", ".gemini", ".cursor", ".opencode", ".antigravity", + ] + protected += clientRoots.flatMap { + [home.appendingPathComponent($0), project.appendingPathComponent($0)] + } + for name in ["CODEX_HOME", "CODEX_SQLITE_HOME", "CLAUDE_CONFIG_DIR"] { + if let path = environment.environment[name], path.hasPrefix("/") { + protected.append(URL(fileURLWithPath: path)) + } + } + if let path = environment.environment["GEMINI_CLI_HOME"], path.hasPrefix("/") { + let gemini = URL(fileURLWithPath: path) + protected += [ + gemini.appendingPathComponent(".gemini"), gemini.appendingPathComponent(".agents"), + ] + } + let roots = Self.pathSpellings(root) + guard + !roots.contains(where: { candidate in + candidate == "/" + || Self.pathSpellings(home).contains(where: { Self.contains(candidate, $0) }) + || protected.contains(where: { url in + Self.pathSpellings(url).contains { + Self.contains(candidate, $0) || Self.contains($0, candidate) + } + }) + }) + else { throw AcquisitionCacheError.unsafeRoot(root.path) } + } + + private static func pathSpellings(_ url: URL) -> [String] { + let original = url.standardizedFileURL + var existing = original + var tail: [String] = [] + if let path = PathSafety.realPath(existing.path) { return [original.path, path] } + while existing.path != "/" { + tail.append(existing.lastPathComponent) + existing.deleteLastPathComponent() + if let path = PathSafety.realPath(existing.path) { + return [ + original.path, + tail.reversed().reduce(URL(fileURLWithPath: path)) { + $0.appendingPathComponent($1) + }.path, + ] + } + } + return [original.path] + } + + private static func contains(_ root: String, _ path: String) -> Bool { + #if os(macOS) + let root = root.lowercased() + let path = path.lowercased() + #endif + return root == path || path.hasPrefix(root == "/" ? root : root + "/") + } + + private func entryLease( + _ store: AcquisitionCacheStore, key: String, root: DirectoryHandle, create: Bool, + exclusive: Bool + ) throws -> Lease { + guard let leases = try directory(Self.leases, in: root, create: create) else { + throw AcquisitionCacheError.invalidEntry + } + let name = store.rawValue + "-" + key + let descriptor = openat( + leases.descriptor, name, + (create ? O_RDWR | O_CREAT : O_RDONLY) | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC, 0o600) + guard descriptor >= 0 else { + throw FileSystem.posixError( + errno, at: leases.url.appendingPathComponent(name), otherwise: .unsafePath("cache lease")) + } + defer { close(descriptor) } + var info = stat() + guard fstat(descriptor, &info) == 0, Self.owned(info, kind: S_IFREG), + try leases.info(name).map(FileObjectIdentity.init) == FileObjectIdentity(info) + else { throw AcquisitionCacheError.invalidEntry } + if create { try leases.sync() } + return try Lease(descriptor, exclusive: exclusive, nonblocking: true) + } + + private final class Lease { + private let descriptor: Int32 + + init(_ original: Int32, exclusive: Bool, nonblocking: Bool = false) throws { + descriptor = fcntl(original, F_DUPFD_CLOEXEC, 3) + guard descriptor >= 0 else { throw AcquisitionCacheError.invalidEntry } + let operation = (exclusive ? LOCK_EX : LOCK_SH) | (nonblocking ? LOCK_NB : 0) + while flock(descriptor, operation) != 0 { + let code = errno + if code == EINTR { continue } + close(descriptor) + if code == EWOULDBLOCK { throw AcquisitionCacheError.busy } + throw AcquisitionCacheError.invalidEntry + } + } + + deinit { + flock(descriptor, LOCK_UN) + close(descriptor) + } + } + + private static func requireKey(_ key: String) throws { + guard key.utf8.count == 64, + key.utf8.allSatisfy({ + (48...57).contains($0) || (97...102).contains($0) + }) + else { throw AcquisitionCacheError.invalidEntry } + } + + private static func validate( + _ record: Record, store: AcquisitionCacheStore, key: String + ) throws { + try requireKey(key) + try requireKey(record.digest) + let limit: Int + switch store { + case .git: limit = record.object.hasPrefix("ref:") ? 1024 : GitAcquisition.packLimit + case .http: limit = registryResponseLimit + case .deployed: limit = deployedFileLimit + } + guard record.store == store, record.key == key, (0...limit).contains(record.size), + !record.object.isEmpty, record.object.utf8.count <= 256, + record.created.timeIntervalSinceReferenceDate.isFinite + else { throw AcquisitionCacheError.invalidEntry } + } + + private static func owned(_ info: stat, kind: mode_t) -> Bool { + info.st_mode & S_IFMT == kind && info.st_uid == geteuid() + && info.st_mode & (S_IWGRP | S_IWOTH) == 0 && (kind != S_IFREG || info.st_nlink == 1) + } + + private static func encode(_ value: some Encodable) throws -> Data { + try JSONEncoder().encode(value) + } + + private static func decode( + _ type: T.Type, in parent: DirectoryHandle, named name: String, + maximumBytes: Int = recordLimit + ) throws -> T { + guard let info = try parent.info(name), owned(info, kind: S_IFREG) else { + throw AcquisitionCacheError.invalidEntry + } + return try JSONDecoder().decode( + type, from: parent.read(name, matching: info, maximumBytes: maximumBytes)) + } +} diff --git a/Sources/AgentsCore/AcquisitionCache/DeployedAcquisition.swift b/Sources/AgentsCore/AcquisitionCache/DeployedAcquisition.swift new file mode 100644 index 0000000..6b31bb7 --- /dev/null +++ b/Sources/AgentsCore/AcquisitionCache/DeployedAcquisition.swift @@ -0,0 +1,36 @@ +import Foundation + +extension AcquisitionCache { + package static let deployedFileLimit = 4 * 1024 * 1024 + private static let deployedStoreLimit: Int64 = 256 * 1024 * 1024 + + /// Reads a disposable copy of bytes addressed by a digest the caller already trusts. + /// Absence or an integrity mismatch requires recovery from the caller's authoritative state. + public func verifiedDeployedBytes(sha256 digest: String) throws -> Data? { + let hash = digest.hasPrefix("sha256:") ? String(digest.dropFirst(7)) : digest + guard hash.utf8.count == 64, + hash.utf8.allSatisfy({ + (48...57).contains($0) || (97...102).contains($0) + }) + else { throw AcquisitionCacheError.invalidEntry } + return try? read(.deployed, key: hash, maximumBytes: Self.deployedFileLimit) { + guard FileHash.sha256Hex(data: $0.data) == hash else { + throw AcquisitionCacheError.invalidEntry + } + return $0.data + } + } + + /// The installation owner must verify these bytes against its anonymous source and + /// the completed deployment before publication. + package func rememberDeployedBytes(_ data: Data) throws { + guard data.count <= Self.deployedFileLimit else { return } + let key = FileHash.sha256Hex(data: data) + if try verifiedDeployedBytes(sha256: key) != nil { return } + let current = try publication(.deployed, key: key) + try write( + data, store: .deployed, key: key, object: key, + condition: current.map(WriteCondition.publication) ?? .absent, + totalLimit: Self.deployedStoreLimit) + } +} diff --git a/Sources/AgentsCore/AcquisitionCache/GitAcquisition.swift b/Sources/AgentsCore/AcquisitionCache/GitAcquisition.swift new file mode 100644 index 0000000..c9f9035 --- /dev/null +++ b/Sources/AgentsCore/AcquisitionCache/GitAcquisition.swift @@ -0,0 +1,331 @@ +import Foundation + +/// Exact packs borrowed by one synchronous operation and retained independently of the shared +/// cache. The update owns this workspace through apply, including a reviewed pause. +package final class GitAcquisitionCaptures { + private var directory: DirectoryHandle? + private var packs = Set() + private var archives: [String: String] = [:] + var archiveSelections: [String: SourceRevision] = [:] + + package init() {} + + deinit { + if let directory { try? FileManager.default.removeItem(at: directory.url) } + } + + fileprivate func read(_ key: String) throws -> Data? { + guard packs.contains(key), let directory else { return nil } + return try directory.read(key, maximumBytes: GitAcquisition.packLimit) + } + + fileprivate func retain(_ data: Data, key: String) throws { + guard !packs.contains(key) else { return } + if directory == nil { + directory = try PrivateSourceRecovery.makeWorkspace(prefix: "agents-acquisition-captures-") + } + guard let directory else { throw AcquisitionCacheError.invalidEntry } + try directory.write(key, data: data) + packs.insert(key) + } + + func readArchive(_ reference: PrivateSourceRecovery.Reference) throws -> Data? { + guard let directory, let digest = archives[reference.key] else { return nil } + let data = try directory.read( + "archive-" + reference.key, maximumBytes: VerifiedVCSArchive.compressedLimit) + guard "sha256:" + FileHash.sha256Hex(data: data) == digest else { + throw SourceAccessError.invalidArchive + } + return data + } + + func captureArchive( + _ data: Data, verified: VerifiedVCSArchive, reference: PrivateSourceRecovery.Reference + ) throws { + guard archives[reference.key] == nil else { return } + if directory == nil { + directory = try PrivateSourceRecovery.makeWorkspace(prefix: "agents-acquisition-captures-") + } + guard let directory else { throw SourceAccessError.recoveryUnavailable } + let file = try directory.createPrivateFile("archive-" + reference.key) + try file.write(data) + archives[reference.key] = verified.byteDigest + } + + package func containsAnonymousCommit( + _ source: SourceDeclaration, revision: String, + environment: RuntimeEnvironment + ) -> Bool { + guard let acquisition = GitAcquisition(source, environment: environment) else { return false } + return packs.contains(acquisition.key(revision)) + } +} + +struct GitAcquisition { + struct Pack { + let revision: String + let bytes: Data + } + + struct Advertisement { + let catalog: SourceCatalog + let time: Date + } + + private struct Observation: Codable { + let revision: String + let time: Date + } + + // A fixture may trust its own CA without changing the OS trust store or Git's ambient config. + @TaskLocal static var fixtureCertificateAuthority: URL? + static let packLimit = 128 * 1024 * 1024 + private static let fetchedRef = "refs/agents/acquired" + + let url: String + let cache: AcquisitionCache + private let captures: GitAcquisitionCaptures? + private let access: SourceAccessConfiguration + + init?( + _ source: SourceDeclaration, environment: RuntimeEnvironment, + captures: GitAcquisitionCaptures? = nil + ) { + guard source.kind == .git, + let route = try? SourceRoute(source, environment: environment, policy: .init()), + case .git = route, Self.isAnonymous(route, environment: environment), + let parts = URLComponents(string: source.gitURL), + parts.scheme?.lowercased() == "https", + let host = parts.host, !host.isEmpty, parts.user == nil, parts.password == nil, + parts.query == nil, parts.fragment == nil, + (try? SourceOrigin.git(source.gitURL)) != nil + else { return nil } + let dnsName = host.lowercased().trimmingCharacters(in: CharacterSet(charactersIn: ".")) + guard + !environment.credentialedGitHosts.contains(where: { + $0.lowercased().trimmingCharacters(in: CharacterSet(charactersIn: ".")) == dnsName + }) + else { return nil } + // Keep the exact transport URL. Policy and declaration identities may coalesce spellings. + url = source.gitURL + cache = AcquisitionCache(environment: environment) + self.captures = captures + access = environment.sourceAccess + } + + private static func isAnonymous(_ route: SourceRoute, environment: RuntimeEnvironment) -> Bool { + do { return try route.credential(environment.sourceAccess) == nil } catch { return false } + } + + func key(_ revision: String) -> String { + AcquisitionCache.key([("transport", Data(url.utf8)), ("commit", Data(revision.utf8))]) + } + + func discover() throws -> Advertisement { + let time = Date() + let advertised = try workspace { root in + try git(["ls-remote", "--symref", "--", url], in: root, .listRemoteReferences, network: true) + } + var raw: [String: String] = [:] + for line in advertised.split(separator: "\n") { + let fields = line.split(separator: "\t", maxSplits: 1).map(String.init) + guard fields.count == 2, SourceCache.isObjectID(fields[0]), + fields[1] == "HEAD" || fields[1].hasPrefix("refs/") + else { continue } + guard raw.updateValue(fields[0], forKey: fields[1]) == nil else { + throw CoreError.invalidSource("duplicate Git reference in remote advertisement") + } + } + var references = raw + var tags: [String: String] = [:] + for (ref, object) in raw where ref.hasPrefix("refs/tags/") && !ref.hasSuffix("^{}") { + let commit = raw[ref + "^{}"] ?? object + references[ref] = commit + tags[String(ref.dropFirst("refs/tags/".count))] = commit + } + return Advertisement(catalog: .init(tags: tags, references: references), time: time) + } + + /// Accepts only expressions whose result is determined by the current advertisement. + static func reference(_ expression: String, in catalog: SourceCatalog) -> (String, String)? { + if let revision = catalog.references[expression] { return (expression, revision) } + let matches = ["refs/tags/", "refs/heads/", "refs/remotes/"].compactMap { prefix in + catalog.references[prefix + expression].map { (prefix + expression, $0) } + } + return matches.count == 1 ? matches.first : nil + } + + func exact(_ requested: String, offline: Bool = false) throws -> Pack? { + guard SourceCache.isObjectID(requested) else { return nil } + let key = key(requested) + if let bytes = try captures?.read(key) { + return Pack(revision: requested, bytes: bytes) + } + if let pack = try? cache.read( + .git, key: key, maximumBytes: Self.packLimit, + { value in + let pack = Pack(revision: requested, bytes: value.data) + try withVerifiedRepository(pack) { _, _ in } + try captures?.retain(pack.bytes, key: key) + return pack + }) + { + return pack + } + guard !offline else { return nil } + try Task.checkCancellation() + let pack = try download(requested) + try captures?.retain(pack.bytes, key: self.key(pack.revision)) + return pack + } + + /// Publication is optional. The caller may continue with the verified, owned bytes. + func remember(_ pack: Pack) { + _ = try? cache.write(pack.bytes, store: .git, key: key(pack.revision), object: pack.revision) + } + + func note(_ ref: String, pack: Pack, observedAt time: Date) { + let key = observationKey(ref) + let observation = Observation(revision: pack.revision, time: time) + guard let bytes = try? JSONEncoder().encode(observation) else { return } + for _ in 0..<4 { + let previous = try? cache.read(.git, key: key, maximumBytes: 1024, touching: false) { value in + (try JSONDecoder().decode(Observation.self, from: value.data), value.publication) + } + if let previous, previous.0.time >= time { return } + let condition = previous.map { AcquisitionCache.WriteCondition.publication($0.1) } ?? .absent + guard + let written = try? cache.write( + bytes, store: .git, key: key, + object: "ref:" + String(decoding: ref.utf8.prefix(120), as: UTF8.self), + condition: condition, now: time) + else { return } + if written { return } + } + } + + func observedRevision(_ ref: String) throws -> String? { + try cache.read(.git, key: observationKey(ref), maximumBytes: 1024, touching: false) { + try JSONDecoder().decode(Observation.self, from: $0.data).revision + } + } + + private func observationKey(_ ref: String) -> String { + AcquisitionCache.key([("transport", Data(url.utf8)), ("ref", Data(ref.utf8))]) + } + + private func download(_ object: String) throws -> Pack { + try workspace { root in + let repository = try initialize(in: root, object: object) + _ = try git( + [ + "-C", repository.path, "fetch", "--no-tags", "--no-recurse-submodules", "--", url, + "+" + object + ":" + Self.fetchedRef, + ], + in: root, .fetch, network: true) + let received = try git( + ["-C", repository.path, "rev-parse", "--verify", Self.fetchedRef], + in: root, .resolveRevision(revision: object)) + guard received == object else { throw AcquisitionCacheError.invalidEntry } + let revision = try git( + ["-C", repository.path, "rev-parse", "--verify", Self.fetchedRef + "^{commit}"], + in: root, .resolveRevision(revision: object)) + guard SourceCache.isObjectID(revision) else { throw AcquisitionCacheError.invalidEntry } + _ = try git( + ["-C", repository.path, "repack", "-a", "-d"], in: root, .extractRevision) + let packs = try DirectoryHandle(at: repository).child("objects").child("pack") + let files = try packs.names().filter { $0.hasSuffix(".pack") } + guard files.count == 1 else { throw AcquisitionCacheError.invalidEntry } + let pack = Pack( + revision: revision, bytes: try packs.read(files[0], maximumBytes: Self.packLimit)) + try withVerifiedRepository(pack) { _, _ in } + return pack + } + } + + /// Rebuilds the object database from the same verified bytes consumed from the entry. + /// The callback receives a private repository and the Git pack stem in its objects/pack. + func withVerifiedRepository( + _ pack: Pack, _ body: (URL, String) throws -> T + ) throws -> T { + try workspace { root in + let repository = try initialize(in: root, object: pack.revision) + let temp = root.appendingPathComponent("incoming.pack") + try DirectoryHandle(at: root).write("incoming.pack", data: pack.bytes) + let digest = try git( + ["-C", repository.path, "index-pack", "--strict", temp.path], in: root, .extractRevision) + guard SourceCache.isObjectID(digest), digest.utf8.count == pack.revision.utf8.count + else { throw AcquisitionCacheError.invalidEntry } + let stem = "pack-" + digest + let objects = repository.appendingPathComponent("objects/pack") + try FileManager.default.moveItem( + at: temp, to: objects.appendingPathComponent(stem + ".pack")) + try FileManager.default.moveItem( + at: root.appendingPathComponent("incoming.idx"), + to: objects.appendingPathComponent(stem + ".idx")) + let actual = try git( + ["-C", repository.path, "rev-parse", "--verify", pack.revision + "^{commit}"], + in: root, .resolveRevision(revision: pack.revision)) + guard actual == pack.revision else { throw AcquisitionCacheError.invalidEntry } + _ = try git( + [ + "-C", repository.path, "fsck", "--full", "--strict", "--no-reflogs", + "--no-dangling", pack.revision, + ], in: root, .extractRevision) + return try body(repository, stem) + } + } + + func initializeMirror(at repository: URL, object: String) throws { + 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) + _ = try git( + ["-C", repository.path, "config", "remote.origin.url", url], in: clean, .readOrigin) + _ = try git( + ["-C", repository.path, "config", "remote.origin.fetch", "+refs/*:refs/*"], + in: clean, .readOrigin) + _ = try git( + ["-C", repository.path, "config", "remote.origin.mirror", "true"], in: clean, .readOrigin) + } + 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 + { + 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 + } + + private func workspace(_ body: (URL) throws -> T) throws -> T { + let parent = try DirectoryHandle(at: FileManager.default.temporaryDirectory) + let directory = try parent.makeDirectory("agents-acquisition-git-" + UUID().uuidString) + defer { + try? parent.remove(directory.url.lastPathComponent, identity: directory.objectIdentity) + } + return try body(directory.url) + } + + private func git( + _ args: [String], in root: URL, _ operation: GitError.Operation, network: Bool = false + ) throws -> String { + if network { try access.requireCurrentSettings() } + return try ProcessRunner.isolatedGit( + args, in: root, operation: operation, source: url, network: network, + certificateAuthority: Self.fixtureCertificateAuthority) + } +} diff --git a/Sources/AgentsCore/AgentClientApplications.swift b/Sources/AgentsCore/AgentClientApplications.swift new file mode 100644 index 0000000..5160770 --- /dev/null +++ b/Sources/AgentsCore/AgentClientApplications.swift @@ -0,0 +1,37 @@ +import Foundation + +#if os(macOS) + import AppKit +#endif + +package struct ClientApplicationObservation: Sendable { + package let bundleIdentifier: String? + package let location: URL? + package let state: ClientObservationState + package let version: ClientVersionObservation +} + +package enum AgentClientApplications { + package static func inspect(agent: AgentID) -> ClientApplicationObservation { + guard let identifier = AgentRegistry.clientBundleIdentifier(for: agent) else { + return .init( + bundleIdentifier: nil, location: nil, state: .unavailable, + version: .unknown(.unrecognizedLayout)) + } + #if os(macOS) + guard let location = NSWorkspace.shared.urlForApplication(withBundleIdentifier: identifier) + else { + return .init( + bundleIdentifier: identifier, location: nil, state: .notFound, + version: .unknown(.artifactNotFound)) + } + let (state, version) = AgentClientObservation.bundleVersion( + at: location, identifier: identifier) + return .init(bundleIdentifier: identifier, location: location, state: state, version: version) + #else + return .init( + bundleIdentifier: identifier, location: nil, state: .unavailable, + version: .unknown(.unavailable)) + #endif + } +} diff --git a/Sources/AgentsCore/AgentClientObservation.swift b/Sources/AgentsCore/AgentClientObservation.swift new file mode 100644 index 0000000..fc1ed44 --- /dev/null +++ b/Sources/AgentsCore/AgentClientObservation.swift @@ -0,0 +1,181 @@ +import CPlatform +import Foundation + +package enum ClientObservationState: String, Sendable { + case present, notFound, inaccessible, invalid, unavailable +} + +package enum ClientVersionUnknown: String, Sendable { + case artifactNotFound, unrecognizedLayout, missingMetadata, unreadableMetadata + case malformedMetadata, oversizedMetadata, nonRegularMetadata, missingVersion, unavailable +} + +package struct ClientVersionObservation: Sendable { + package let version: String? + package let build: String? + package let metadata: URL? + package let key: String? + package let unknown: ClientVersionUnknown? + + package static func unknown(_ reason: ClientVersionUnknown, at metadata: URL? = nil) -> Self { + .init(version: nil, build: nil, metadata: metadata, key: nil, unknown: reason) + } +} + +package struct ClientPathIssue: Sendable { + package let path: String + package let state: ClientObservationState + package let reason: String +} + +package struct ClientPathCoverage: Sendable { + package let supplied: Bool + package let directories: [URL] + package let excluded: [String] + + package init(environment: RuntimeEnvironment) { + supplied = environment.environment["PATH"] != nil + let entries = environment.environment["PATH"]?.components(separatedBy: ":") ?? [] + directories = entries.filter { $0.hasPrefix("/") && !$0.contains("\0") } + .map { URL(fileURLWithPath: $0, isDirectory: true) } + excluded = entries.filter { !$0.hasPrefix("/") || $0.contains("\0") } + } +} + +package struct ClientCommandObservation: Sendable { + package let command: String + package let role: String + package let location: URL? + package let resolvedLocation: URL? + package let state: ClientObservationState + package let issues: [ClientPathIssue] + package let version: ClientVersionObservation +} + +package enum AgentClientObservation { + package static func failureState(_ code: Int32) -> ClientObservationState { + switch code { + case ENOENT, ENOTDIR: .notFound + case EACCES, EPERM: .inaccessible + default: .invalid + } + } + + package static func presence(_ url: URL, directory: Bool) -> ClientObservationState { + guard url.isFileURL, !url.path.contains("\0") else { return .invalid } + var info = stat() + guard stat(url.path, &info) == 0 else { return failureState(errno) } + let kind = info.st_mode & mode_t(CPlatform.S_IFMT) + return kind == mode_t(directory ? CPlatform.S_IFDIR : CPlatform.S_IFREG) ? .present : .invalid + } + + package static func command( + _ candidate: AgentRegistry.ClientCommand, coverage: ClientPathCoverage + ) -> ClientCommandObservation { + var issues: [ClientPathIssue] = [] + for directory in coverage.directories { + let url = directory.appendingPathComponent(candidate.name) + var info = stat() + if stat(url.path, &info) != 0 { + let code = errno + if code != ENOENT && code != ENOTDIR { + issues.append( + .init(path: url.path, state: failureState(code), reason: "executable lookup failed")) + } + continue + } + guard info.st_mode & mode_t(CPlatform.S_IFMT) == mode_t(CPlatform.S_IFREG) else { continue } + guard access(url.path, X_OK) == 0 else { + issues.append( + .init(path: url.path, state: failureState(errno), reason: "executable access denied")) + continue + } + let resolved = url.resolvingSymlinksInPath() + let version: ClientVersionObservation + if let bundle = AgentRegistry.clientBundle(for: candidate.name, resolvedExecutable: resolved), + let identifier = AgentRegistry.clientBundleIdentifier(for: .cursor) + { + version = bundleVersion(at: bundle, identifier: identifier).1 + } else { + version = .unknown(.unrecognizedLayout) + } + return .init( + command: candidate.name, role: candidate.role, location: url, resolvedLocation: resolved, + state: .present, issues: issues, version: version) + } + return .init( + command: candidate.name, role: candidate.role, location: nil, resolvedLocation: nil, + state: coverage.directories.isEmpty + ? .unavailable : issues.first?.state ?? .notFound, + issues: issues, + version: .unknown( + coverage.directories.isEmpty || !issues.isEmpty ? .unavailable : .artifactNotFound)) + } + + /// Follows installation symlinks, validates the opened object, and bounds even growing files. + package static func metadata(_ url: URL) throws -> Data { + guard url.isFileURL, !url.path.contains("\0") else { + throw ClientVersionUnknownError(.unreadableMetadata) + } + let fd = open(url.path, O_RDONLY | O_CLOEXEC | O_NONBLOCK) + guard fd >= 0 else { + throw ClientVersionUnknownError( + errno == ENOENT || errno == ENOTDIR ? .missingMetadata : .unreadableMetadata) + } + defer { close(fd) } + var info = stat() + guard fstat(fd, &info) == 0 else { throw ClientVersionUnknownError(.unreadableMetadata) } + guard info.st_mode & mode_t(CPlatform.S_IFMT) == mode_t(CPlatform.S_IFREG) else { + throw ClientVersionUnknownError(.nonRegularMetadata) + } + let limit = 1_048_576 + guard info.st_size >= 0, info.st_size <= limit else { + throw ClientVersionUnknownError(.oversizedMetadata) + } + var result = Data() + var buffer = [UInt8](repeating: 0, count: 16_384) + while true { + let count = read(fd, &buffer, min(buffer.count, limit + 1 - result.count)) + if count < 0 { + if errno == EINTR { continue } + throw ClientVersionUnknownError(.unreadableMetadata) + } + if count == 0 { return result } + result.append(contentsOf: buffer.prefix(count)) + guard result.count <= limit else { throw ClientVersionUnknownError(.oversizedMetadata) } + } + } + + package static func bundleVersion(at bundle: URL, identifier: String) + -> (ClientObservationState, ClientVersionObservation) + { + let url = bundle.appendingPathComponent("Contents/Info.plist") + do { + let bytes = try metadata(url) + guard + let plist = try? PropertyListSerialization.propertyList(from: bytes, format: nil) + as? [String: Any], + plist["CFBundleIdentifier"] as? String == identifier + else { return (.invalid, .unknown(.malformedMetadata, at: url)) } + let version = (plist["CFBundleShortVersionString"] as? String).flatMap { + $0.isEmpty ? nil : $0 + } + let build = (plist["CFBundleVersion"] as? String).flatMap { $0.isEmpty ? nil : $0 } + return ( + .present, + .init( + version: version, build: build, metadata: url, + key: "CFBundleShortVersionString", unknown: version == nil ? .missingVersion : nil) + ) + } catch let error as ClientVersionUnknownError { + let state: ClientObservationState = + error.reason == .unreadableMetadata ? .inaccessible : .invalid + return (state, .unknown(error.reason, at: url)) + } catch { return (.invalid, .unknown(.malformedMetadata, at: url)) } + } +} + +package struct ClientVersionUnknownError: Error { + package let reason: ClientVersionUnknown + package init(_ reason: ClientVersionUnknown) { self.reason = reason } +} diff --git a/Sources/AgentsCore/AgentRegistry.swift b/Sources/AgentsCore/AgentRegistry.swift index 2f02b7f..7ae8bc0 100644 --- a/Sources/AgentsCore/AgentRegistry.swift +++ b/Sources/AgentsCore/AgentRegistry.swift @@ -6,6 +6,7 @@ public enum AgentID: String, Codable, CaseIterable, Sendable { case cursor case geminiCLI = "gemini-cli" case opencode + case antigravity public var displayName: String { switch self { @@ -19,9 +20,17 @@ public enum AgentID: String, Codable, CaseIterable, Sendable { return "Gemini CLI" case .opencode: return "OpenCode" + case .antigravity: + return "Antigravity" } } + public var supportsSkills: Bool { true } + + public func supportsInstructions(in scope: InstallScope) -> Bool { + scope == .project || self != .cursor + } + public static func parse(_ raw: String) throws -> AgentID { if raw == "claude" || raw == "claude-code" { return .claudeCode @@ -54,13 +63,35 @@ public enum InstallMode: String, Codable, Sendable { public struct RuntimeEnvironment: Sendable { public var projectDirectory: URL - public var homeDirectory: URL - public var environment: [String: String] + public var homeDirectory: URL { + didSet { if sourceAccess.usesUserSettings { reloadSourceAccessSettings() } } + } + public var environment: [String: String] { + didSet { if sourceAccess.usesUserSettings { reloadSourceAccessSettings() } } + } + /// A trusted caller may select a shared local policy, independently of project declarations. + public var organizationSourcePolicyURL: URL? + public var userOrganizationPolicy: OrganizationPolicySelection? + public var projectOrganizationPolicy: OrganizationPolicySelection? + /// An explicit cache root supplied by the trusted host, typically for an isolated fixture. + public var acquisitionCacheRoot: URL? + /// Hosts the caller has selected for credentialed Git, matched case-insensitively. + public var credentialedGitHosts: Set + /// Additional deployment or backup roots owned by the caller. + public var protectedAcquisitionPaths: [URL] + /// Trusted source access captured at construction or explicit reload. + /// Use resolvedSourceAccess() to check whether a captured user profile is still valid. + public var sourceAccess: SourceAccessConfiguration public init( projectDirectory: URL = URL(fileURLWithPath: FileManager.default.currentDirectoryPath), homeDirectory: URL? = nil, - environment: [String: String] = ProcessInfo.processInfo.environment + environment: [String: String] = ProcessInfo.processInfo.environment, + organizationSourcePolicyURL: URL? = nil, + userOrganizationPolicy: OrganizationPolicySelection? = nil, + projectOrganizationPolicy: OrganizationPolicySelection? = nil, + acquisitionCacheRoot: URL? = nil, credentialedGitHosts: Set = [], + protectedAcquisitionPaths: [URL] = [], sourceAccess: SourceAccessConfiguration? = nil ) { self.projectDirectory = projectDirectory.standardizedFileURL let resolvedHome = @@ -69,10 +100,30 @@ public struct RuntimeEnvironment: Sendable { ?? FileManager.default.homeDirectoryForCurrentUser self.homeDirectory = resolvedHome.standardizedFileURL self.environment = environment + self.acquisitionCacheRoot = acquisitionCacheRoot + self.credentialedGitHosts = credentialedGitHosts + self.protectedAcquisitionPaths = protectedAcquisitionPaths + self.sourceAccess = + sourceAccess ?? .loadUserSettings(home: self.homeDirectory, environment: environment) + self.userOrganizationPolicy = + userOrganizationPolicy + ?? environment["AGENTS_USER_ORGANIZATION_POLICY"].map( + OrganizationPolicySelection.init(location:)) + self.projectOrganizationPolicy = + projectOrganizationPolicy + ?? environment["AGENTS_PROJECT_ORGANIZATION_POLICY"].map( + OrganizationPolicySelection.init(location:)) + self.organizationSourcePolicyURL = + organizationSourcePolicyURL + ?? environment["AGENTS_ORGANIZATION_SOURCE_POLICY"].map { + URL(fileURLWithPath: $0, relativeTo: resolvedHome) + } } } package enum AgentRegistry { + package static var skillAgents: [AgentID] { AgentID.allCases.filter(\.supportsSkills) } + package static func canonicalSkillsDirectory( scope: InstallScope, environment: RuntimeEnvironment ) -> URL { @@ -94,7 +145,8 @@ package enum AgentRegistry { return projectSkillsDirectory(for: agent, environment: environment).standardizedFileURL.path == canonical case .user: - return usesUniversalProjectSkillsDirectory(for: agent, environment: environment) + return agent != .antigravity + && usesUniversalProjectSkillsDirectory(for: agent, environment: environment) } } @@ -113,7 +165,7 @@ package enum AgentRegistry { switch agent { case .claudeCode: return environment.projectDirectory.appendingPathComponent(".claude/skills") - case .codex, .cursor, .geminiCLI, .opencode: + case .codex, .cursor, .geminiCLI, .opencode, .antigravity: return environment.projectDirectory.appendingPathComponent(".agents/skills") } } @@ -144,6 +196,8 @@ package enum AgentRegistry { environment.environment["XDG_CONFIG_HOME"].flatMap { $0.isEmpty ? nil : $0 } ?? environment.homeDirectory.appendingPathComponent(".config").path return URL(fileURLWithPath: configHome).appendingPathComponent("opencode/skills") + case .antigravity: + return environment.homeDirectory.appendingPathComponent(".gemini/config/skills") } } @@ -158,18 +212,21 @@ package enum AgentRegistry { ] case .claudeCode: return [userSkillsDirectory(for: agent, environment: environment)] + case .antigravity: + return [userSkillsDirectory(for: agent, environment: environment)] } } package static func projectScanDirectories( for agent: AgentID, environment: RuntimeEnvironment ) -> [URL] { + guard agent.supportsSkills else { return [] } let primary = projectSkillsDirectory(for: agent, environment: environment) let additional: [URL] switch agent { case .geminiCLI: additional = [environment.projectDirectory.appendingPathComponent(".gemini/skills")] - case .codex, .claudeCode, .cursor, .opencode: + case .codex, .claudeCode, .cursor, .opencode, .antigravity: additional = [] } return uniqueDirectories([primary] + additional) @@ -200,3 +257,69 @@ package enum AgentRegistry { } } + +extension AgentRegistry { + package struct ClientCommand: Sendable { + package let name: String + package let role: String + } + + package static func clientCommands(for agent: AgentID) -> [ClientCommand] { + switch agent { + case .codex: [.init(name: "codex", role: "agentCLI")] + case .claudeCode: [.init(name: "claude", role: "agentCLI")] + case .geminiCLI: [.init(name: "gemini", role: "agentCLI")] + case .antigravity: [.init(name: "agy", role: "agentCLI")] + case .opencode: [.init(name: "opencode", role: "agentCLI")] + case .cursor: + [ + .init(name: "cursor", role: "editorLauncher"), + .init(name: "cursor-agent", role: "agentCLI"), + ] + } + } + + // Registered editor bundle identity; the agent CLI has independent metadata. + package static func clientBundleIdentifier(for agent: AgentID) -> String? { + agent == .cursor ? "com.todesktop.230313mzl4w4u92" : nil + } + + package static func clientSkillLocations( + for agent: AgentID, scope: InstallScope, environment: RuntimeEnvironment + ) -> [(String, URL)] { + guard agent.supportsSkills else { return [] } + let scans = + scope == .user + ? nativeUserScanDirectories(for: agent, environment: environment) + : projectScanDirectories(for: agent, environment: environment) + return [ + ("skills.install", installSkillsDirectory(for: agent, scope: scope, environment: environment)) + ] + + scans.enumerated().map { ("skills.scan.\($0.offset)", $0.element) } + } +} + +extension AgentRegistry { + /// Only the bundled editor launcher carries this bundle metadata association. + package static func clientBundle(for command: String, resolvedExecutable: URL) -> URL? { + guard command == "cursor", + resolvedExecutable.path.hasSuffix("/Contents/Resources/app/bin/cursor") + else { return nil } + var bundle = resolvedExecutable + for _ in 0..<5 { bundle.deleteLastPathComponent() } + return bundle + } +} + +extension RuntimeEnvironment { + /// Checks the captured user settings generation without changing the selected configuration. + public func resolvedSourceAccess() throws -> SourceAccessConfiguration { + try sourceAccess.requireCurrentSettings() + return sourceAccess + } + + /// Select the current operator profile for subsequent operations. + public mutating func reloadSourceAccessSettings() { + sourceAccess = .loadUserSettings(home: homeDirectory, environment: environment) + } +} diff --git a/Sources/AgentsCore/ArchiveDeploymentAccess.swift b/Sources/AgentsCore/ArchiveDeploymentAccess.swift new file mode 100644 index 0000000..027becf --- /dev/null +++ b/Sources/AgentsCore/ArchiveDeploymentAccess.swift @@ -0,0 +1,63 @@ +import Foundation + +/// Archive outputs carry the same per-identity boundary through preview and the publication +/// journal. A link carries coordinates only. Copies and rendered bytes require owner-only inodes. +package struct ArchiveDeploymentAccess { + let target: TargetPrecondition + let ancestry: DirectoryAccessEvidence + let beforeAccess: FileAccessEvidence? + let members: [TreeMemberAccess]? + + package init(at destination: URL) throws { + self.target = try TargetPrecondition(destination) + let parentURL = destination.deletingLastPathComponent() + ancestry = try DirectoryAccessEvidence.capture(at: parentURL) + if let snapshot = target.snapshot, snapshot.identity.kind != S_IFLNK { + guard snapshot.isRegular || snapshot.identity.isDirectory else { + throw CoreError.unsafePath("invalid private archive destination") + } + let parent = try DirectoryHandle(at: parentURL) + beforeAccess = try parent.requirePrivateAccess(destination.lastPathComponent) + members = try TreeMemberAccess.capture( + destination.lastPathComponent, in: parent, snapshot: snapshot, requirePrivate: true) + } else { + beforeAccess = nil + members = nil + } + } + + func requirePrivateLinkTarget(_ destination: URL, environment: RuntimeEnvironment) throws { + let recovery = environment.homeDirectory + .appendingPathComponent(".agents-source-recovery").resolvingSymlinksInPath() + let resolved = destination.resolvingSymlinksInPath() + guard PathSafety.isContained(resolved, in: recovery), resolved.path != recovery.path else { + throw CoreError.unsafePath("archive link escapes private recovery") + } + let parts = PathSafety.relativePath(resolved.path, to: recovery.path).split(separator: "/") + guard parts.count >= 2, parts[1] == "tree" else { + throw CoreError.unsafePath("archive link requires a retained tree") + } + _ = try DirectoryAccessEvidence.capture(at: resolved) + let root = try DirectoryHandle(at: recovery) + let target = try DirectoryHandle(at: resolved) + _ = try FileAccessEvidence.requirePrivate(descriptor: root.descriptor) + _ = try FileAccessEvidence.requirePrivate(descriptor: target.descriptor) + } + + package func memberAccessFingerprint() throws -> String? { + try members.map { try ResolvedLedgerCodec.digest($0) } + } + + package func validate() throws { + let parentURL = target.url.deletingLastPathComponent() + try ancestry.validate(at: parentURL) + try target.validate() + if let beforeAccess, let snapshot = target.snapshot { + let parent = try DirectoryHandle(at: parentURL) + _ = try parent.requirePrivateAccess(target.url.lastPathComponent, matching: beforeAccess) + try TreeMemberAccess.verify( + members, snapshot: snapshot, named: target.url.lastPathComponent, in: parent, + requirePrivate: true) + } + } +} diff --git a/Sources/AgentsCore/BundleSourceLocation.swift b/Sources/AgentsCore/BundleSourceLocation.swift new file mode 100644 index 0000000..a422e42 --- /dev/null +++ b/Sources/AgentsCore/BundleSourceLocation.swift @@ -0,0 +1,21 @@ +import Foundation + +/// Transaction-owned, content-addressed producer trees for imported bundles. +package enum BundleSourceLocation { + package static let directory = "bundles" + package static let tree = "source" + + package static func isKey(_ key: String) -> Bool { + key.utf8.count == 64 + && key.utf8.allSatisfy { (48...57).contains($0) || (97...102).contains($0) } + } + + package static func container(of source: URL, in store: StateStore) -> URL? { + let container = source.deletingLastPathComponent() + let root = store.directory.appendingPathComponent(directory) + guard source.lastPathComponent == tree, isKey(container.lastPathComponent), + container.deletingLastPathComponent().path == root.path + else { return nil } + return container + } +} diff --git a/Sources/AgentsCore/BundleStoredSource.swift b/Sources/AgentsCore/BundleStoredSource.swift new file mode 100644 index 0000000..c128b86 --- /dev/null +++ b/Sources/AgentsCore/BundleStoredSource.swift @@ -0,0 +1,73 @@ +import Foundation + +package struct BundleStoredSource: Codable, Sendable { + package struct Coordinate: Codable, Sendable { + package let name: String + package let version: String + + package init(name: String, version: String) { + self.name = name + self.version = version + } + } + + package let package: Coordinate + package let componentID: String + package let sources: [PortableSourceEvidence] + let treeDigest: String + package let marketplaceNode: MarketplaceNodeID? + + package init( + package: Coordinate, componentID: String, sources: [PortableSourceEvidence], treeDigest: String, + marketplaceNode: MarketplaceNodeID? = nil + ) { + self.package = package + self.componentID = componentID + self.sources = sources + self.treeDigest = treeDigest + self.marketplaceNode = marketplaceNode + } + + package func recording(_ source: PortableSourceEvidence) -> Self { + Self( + package: package, componentID: componentID, sources: sources + [source], + treeDigest: treeDigest, marketplaceNode: marketplaceNode) + } + + package static let filename = "bundle-source.json" + + package static func read( + _ container: URL, snapshot: URL? = nil, expectedKey: String? = nil + ) throws -> Self { + let seal = try readMarker(container, expectedKey: expectedKey) + try seal.validateTree(snapshot ?? container.appendingPathComponent(BundleSourceLocation.tree)) + return seal + } + + static func readMarker(_ container: URL, expectedKey: String? = nil) throws -> Self { + let directory = try DirectoryHandle(at: container) + let bytes = try directory.readRegularFile(filename, maximumBytes: 2 * 1024 * 1024) + guard FileHash.sha256Hex(data: bytes) == (expectedKey ?? container.lastPathComponent) + else { throw CoreError.invalidSource("bundle source storage conflicts at " + container.path) } + try LedgerAdmission.check(bytes, limits: .standard) + let marker = try JSONDecoder().decode(Self.self, from: bytes) + guard !marker.sources.isEmpty, + Set(marker.sources).count == marker.sources.count, + try ResolvedLedgerCodec.bytes(marker) == bytes + else { throw CoreError.invalidSource("invalid bundle source evidence") } + for source in marker.sources { try source.validate() } + return marker + } + + func validateTree(_ tree: URL) throws { + guard try treeDigest == Self.digest(tree) else { + throw CoreError.invalidSource("bundle source tree was changed at " + tree.path) + } + } + + package static func digest(_ tree: URL) throws -> String { + try ResolvedLedgerCodec.digest([ + FileHash.folderHash(tree), ResolvedLedgerCodec.digest(FileHash.executableFlags(tree)), + ]) + } +} diff --git a/Sources/AgentsCore/ClientBackups/BackupArchive.swift b/Sources/AgentsCore/ClientBackups/BackupArchive.swift new file mode 100644 index 0000000..efea543 --- /dev/null +++ b/Sources/AgentsCore/ClientBackups/BackupArchive.swift @@ -0,0 +1,183 @@ +import CPlatform +import CSQLite +import Crypto +import Foundation + +struct BackupHeader: Codable, Equatable, Sendable { + let client: BackupClient + let sourceHome: String + let sourceClient: String + let sourceDatabase: String + let projects: [String] +} + +struct BackupEntry: Codable, Equatable, Sendable { + let number: Int64 + let root: String + let path: String + let mode: UInt16 + let digest: BackupDigest +} + +struct BackupManifest: Codable, Equatable, Sendable { + let header: BackupHeader + var entries: [BackupEntry] + + func hash() throws -> String { + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys] + return FileHash.sha256Hex(data: try encoder.encode(self)) + } +} + +final class BackupArchive { + private static let applicationID: Int64 = 0x4147_424b + private static let version: Int64 = 1 + private static let schema = [ + "CREATE TABLE header (id INTEGER PRIMARY KEY CHECK (id=1), json BLOB NOT NULL, digest TEXT NOT NULL)", + "CREATE TABLE files (id INTEGER PRIMARY KEY, root TEXT NOT NULL, path TEXT NOT NULL, mode INTEGER NOT NULL, size INTEGER NOT NULL, digest TEXT NOT NULL)", + "CREATE TABLE chunks (file INTEGER NOT NULL, part INTEGER NOT NULL, bytes BLOB NOT NULL, PRIMARY KEY(file,part)) WITHOUT ROWID", + ] + private let db: BackupSQL + let readGeneration: BackupGeneration? + private(set) var manifest: BackupManifest + + init(writing name: String, in directory: DirectoryHandle, header: BackupHeader) throws { + readGeneration = nil + try BackupIO.write(name, in: directory) { _ in } + db = try BackupSQL(directory.url.appendingPathComponent(name), writable: true) + manifest = BackupManifest(header: header, entries: []) + try db.execute("PRAGMA application_id=\(Self.applicationID)") + try db.execute("PRAGMA user_version=\(Self.version)") + try db.execute("BEGIN IMMEDIATE") + for table in Self.schema { try db.execute(table) } + } + + init(reading url: URL) throws { + _ = try BackupIO.address(url) + guard let parent = try BackupIO.directory(url.deletingLastPathComponent()), + let value = try BackupIO.generation(parent, url.lastPathComponent), + value.value.st_mode & S_IFMT == S_IFREG + else { throw ClientBackupError.invalidPackage } + readGeneration = value + db = try BackupSQL(url, immutable: true) + var applicationID: Int64? + var version: Int64? + try db.rows("PRAGMA application_id") { applicationID = try BackupSQL.integer($0, 0) } + try db.rows("PRAGMA user_version") { version = try BackupSQL.integer($0, 0) } + guard applicationID == Self.applicationID, version == Self.version else { + throw ClientBackupError.invalidPackage + } + var actual: [String] = [] + try db.rows("SELECT sql FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%'") { + actual.append(try BackupSQL.text($0, 0)) + } + guard actual.sorted() == Self.schema.sorted() else { throw ClientBackupError.invalidPackage } + try db.verify() + var header: BackupHeader? + var hash: String? + try db.rows("SELECT json,digest FROM header WHERE id=1") { row in + header = try JSONDecoder().decode( + BackupHeader.self, from: BackupSQL.blob(row, 0, limit: 4 * 1024 * 1024)) + hash = try BackupSQL.text(row, 1) + } + guard let header, + [header.sourceHome, header.sourceClient, header.sourceDatabase].allSatisfy({ + $0 == "/" || BackupIO.originalPath($0) + }), header.projects.allSatisfy(BackupIO.originalPath), + Set(header.projects.map(BackupIO.fold)).count == header.projects.count + else { throw ClientBackupError.invalidPackage } + var entries: [BackupEntry] = [] + var paths = Set() + try db.rows("SELECT id,root,path,mode,size,digest FROM files ORDER BY id") { row in + let number = try BackupSQL.integer(row, 0) + let root = try BackupSQL.text(row, 1) + let path = try BackupSQL.text(row, 2) + let mode = try BackupSQL.integer(row, 3) + let size = try BackupSQL.integer(row, 4) + let digest = try BackupSQL.text(row, 5) + let components = try BackupIO.components(path) + guard number == Int64(entries.count + 1), (0...0o777).contains(mode), size >= 0, + digest.utf8.count == 64, digest.utf8.allSatisfy(Self.isHex), + BackupScope.allows( + header.client, root: root, components: components, projects: header.projects), + paths.insert(root + ":" + BackupIO.fold(path)).inserted + else { throw ClientBackupError.invalidPackage } + entries.append( + BackupEntry( + number: number, root: root, path: path, mode: UInt16(mode), + digest: BackupDigest(size: size, hash: digest))) + } + manifest = BackupManifest(header: header, entries: entries) + guard try manifest.hash() == hash, + try BackupIO.generation(parent, url.lastPathComponent) == value + else { throw ClientBackupError.invalidPackage } + try db.rows( + "SELECT 1 FROM chunks WHERE file<1 OR file>? LIMIT 1", [.integer(Int64(entries.count))] + ) { + _ in throw ClientBackupError.invalidPackage + } + } + + private static func isHex(_ byte: UInt8) -> Bool { + (48...57).contains(byte) || (97...102).contains(byte) + } + + func add( + root: String, path: String, mode: UInt16, parent: DirectoryHandle, name: String, + generation: BackupGeneration + ) throws { + let number = Int64(manifest.entries.count + 1) + var part: Int64 = 0 + let fingerprint = try BackupIO.stream(parent, name, expecting: generation) { bytes in + try db.execute( + "INSERT INTO chunks VALUES (?,?,?)", [.integer(number), .integer(part), .blob(bytes)]) + part += 1 + } + let entry = BackupEntry( + number: number, root: root, path: path, mode: mode, digest: fingerprint.digest) + try db.execute( + "INSERT INTO files VALUES (?,?,?,?,?,?)", + [ + .integer(number), .text(root), .text(path), .integer(Int64(mode)), + .integer(entry.digest.size), .text(entry.digest.hash), + ]) + manifest.entries.append(entry) + } + + func finish() throws { + try db.execute( + "INSERT INTO header VALUES (1,?,?)", + [ + .blob(try JSONEncoder().encode(manifest.header)), .text(try manifest.hash()), + ]) + try db.execute("COMMIT") + } + + func read(_ entry: BackupEntry, _ consume: (Data) throws -> Void = { _ in }) throws { + var hash = SHA256() + var size: Int64 = 0 + var part: Int64 = 0 + try db.rows( + "SELECT part,bytes FROM chunks WHERE file=? ORDER BY part", [.integer(entry.number)] + ) { row in + let bytes = try BackupSQL.blob(row, 1, limit: BackupIO.chunkSize) + guard try BackupSQL.integer(row, 0) == part, + Int64(bytes.count) <= entry.digest.size - size + else { throw ClientBackupError.invalidPackage } + size += Int64(bytes.count) + part += 1 + hash.update(data: bytes) + try consume(bytes) + } + guard size == entry.digest.size, BackupIO.hex(hash.finalize()) == entry.digest.hash else { + throw ClientBackupError.invalidPackage + } + } + + func extract(_ entry: BackupEntry, to parent: DirectoryHandle, named name: String) throws { + try BackupIO.write(name, in: parent) { output in + try read(entry) { try output.write(contentsOf: $0) } + } + } +} diff --git a/Sources/AgentsCore/ClientBackups/BackupClaudeImports.swift b/Sources/AgentsCore/ClientBackups/BackupClaudeImports.swift new file mode 100644 index 0000000..cc4fde5 --- /dev/null +++ b/Sources/AgentsCore/ClientBackups/BackupClaudeImports.swift @@ -0,0 +1,160 @@ +import Foundation +import Markdown + +enum BackupClaudeImports { + static let archivePrefix = "claude-import:" + + struct File: Hashable { + let root: String + let path: String + + init(root: String, path: String) { + self.root = root.hasPrefix(archivePrefix) ? String(root.dropFirst(archivePrefix.count)) : root + self.path = path + } + } + + struct Locations { + let home: URL + let client: URL + let projects: [String: URL] + private let searchRoots: [(key: String, path: String)] + + init(home: URL, client: URL, projects: [String: URL]) { + self.home = home + self.client = client + self.projects = projects + let roots = + projects.map { (key: $0.key, path: $0.value.standardizedFileURL.path) } + + [(key: "client", path: client.standardizedFileURL.path)] + searchRoots = roots.sorted { + if $0.path.count != $1.path.count { return $0.path.count > $1.path.count } + return $0.key < $1.key + } + } + + func url(_ file: File) -> URL? { + let root = file.root == "client" ? client : projects[file.root] + return root?.appendingPathComponent(file.path) + } + + func resolve(_ token: String, from file: File) -> File? { + guard let document = url(file) else { return nil } + let target: URL + if token.hasPrefix("~/") { + target = home.appendingPathComponent(String(token.dropFirst(2))) + } else if token.hasPrefix("/") { + target = URL(fileURLWithPath: token) + } else if !token.hasPrefix("~") { + target = document.deletingLastPathComponent().appendingPathComponent(token) + } else { + return nil + } + let path = target.standardizedFileURL.path + for (key, root) in searchRoots where path.hasPrefix(root + "/") { + let relative = String(path.dropFirst(root.count + 1)) + guard let parts = try? BackupIO.components(relative), allows(parts) else { return nil } + return File(root: key, path: relative) + } + return nil + } + } + + private struct Reference { + let token: String + let range: Range + } + + static func allows(_ parts: [String]) -> Bool { + !parts.isEmpty + && parts.enumerated().allSatisfy { index, part in + !BackupScope.excluded(part) && (!part.hasPrefix(".") || (index == 0 && part == ".claude")) + } + } + + static func isEntry(_ file: File, projects: [String: URL]) -> Bool { + if file.root == "client" { + return ["CLAUDE.md", "CLAUDE.local.md"].contains(file.path) + || (file.path.hasPrefix("rules/") && file.path.hasSuffix(".md")) + } + guard projects[file.root] != nil else { return false } + return BackupScope.projectContextNames(.claudeCode).contains( + file.path.split(separator: "/").last.map(String.init) ?? "") + || (file.path.hasPrefix(".claude/rules/") && file.path.hasSuffix(".md")) + } + + static func closure( + entries: [File], locations: Locations, load: (File) throws -> Data? + ) throws -> Set { + var depths: [File: Int] = [:] + func visit(_ file: File, depth: Int) throws { + if let prior = depths[file], prior <= depth { return } + guard let bytes = try load(file) else { + throw ClientBackupError.invalidLocation(locations.url(file)?.path ?? file.path) + } + depths[file] = depth + guard depth < 4, let source = String(data: bytes, encoding: .utf8) else { return } + for reference in try references(source) { + if let target = locations.resolve(reference.token, from: file) { + try visit(target, depth: depth + 1) + } + } + } + for entry in entries { try visit(entry, depth: 0) } + return Set(depths.keys) + } + + static func relocated( + _ bytes: Data, file: File, source: Locations, destination: Locations + ) throws -> Data? { + guard let document = String(data: bytes, encoding: .utf8) else { return nil } + var edits: [(Range, String)] = [] + for reference in try references(document) { + guard let target = source.resolve(reference.token, from: file), + destination.resolve(reference.token, from: file) != target, + let url = destination.url(target) + else { continue } + edits.append((reference.range, url.path.replacingOccurrences(of: " ", with: "\\ "))) + } + guard !edits.isEmpty else { return nil } + var result = document + for (range, replacement) in edits.reversed() { + result.replaceSubrange(range, with: replacement) + } + return Data(result.utf8) + } + + private static func references(_ source: String) throws -> [Reference] { + var lineStarts = [0] + for (index, byte) in source.utf8.enumerated() where byte == 0x0a { + lineStarts.append(index + 1) + } + var code: [Range] = [] + let document = Document(parsing: source, options: [.disableSmartOpts]) + func visit(_ node: any Markup) { + if node is CodeBlock || node is InlineCode || node is HTMLBlock { + if let range = node.range, lineStarts.indices.contains(range.lowerBound.line - 1), + lineStarts.indices.contains(range.upperBound.line - 1) + { + let lower = lineStarts[range.lowerBound.line - 1] + range.lowerBound.column - 1 + let upper = lineStarts[range.upperBound.line - 1] + range.upperBound.column - 1 + if lower <= upper { code.append(lower..'"\x60\\])+)"#) + let matches = pattern.matches(in: source, range: NSRange(source.startIndex..., in: source)) + return matches.compactMap { match in + guard let whole = Range(match.range, in: source), + let range = Range(match.range(at: 1), in: source) + else { return nil } + let offset = source.utf8.distance(from: source.utf8.startIndex, to: whole.lowerBound) + guard !code.contains(where: { $0.contains(offset) }) else { return nil } + return Reference( + token: source[range].replacingOccurrences(of: "\\ ", with: " "), range: range) + } + } +} diff --git a/Sources/AgentsCore/ClientBackups/BackupGeminiCheckpoints.swift b/Sources/AgentsCore/ClientBackups/BackupGeminiCheckpoints.swift new file mode 100644 index 0000000..2c4e06f --- /dev/null +++ b/Sources/AgentsCore/ClientBackups/BackupGeminiCheckpoints.swift @@ -0,0 +1,176 @@ +import CPlatform +import Foundation + +enum BackupGeminiCheckpoints { + static func isRecord(_ parts: [String]) -> Bool { + parts.count == 4 && parts[0] == "tmp" && parts[2] == "checkpoints" + && parts[3].hasSuffix(".json") + } + + static func isPack(_ parts: [String]) -> Bool { + parts.count == 6 && parts[0] == "history" && parts[2] == ".git" + && parts[3] == "objects" && parts[4] == "pack" && packName(parts[5]) + } + + private static func packName(_ value: String) -> Bool { + value.range(of: #"^pack-[a-f0-9]{40}\.(pack|idx)$"#, options: .regularExpression) != nil + } + + private static func hex(_ value: String, length: ClosedRange) -> Bool { + length.contains(value.utf8.count) + && value.utf8.allSatisfy { + (48...57).contains($0) || (97...102).contains($0) + } + } + + static func commit(in file: URL) throws -> String? { + var result: String? + let reader = try BackupJSONStream(file, selection: [["commitHash"]]) { _, value in + guard result == nil, hex(value, length: 4...40) else { + throw ClientBackupError.unsupportedLayout("Gemini checkpoint " + file.lastPathComponent) + } + result = value + return nil + } + try reader.process() + return result + } + + static func capture( + commits: [String], shadow: URL, scratch: DirectoryHandle, + observe: (URL) throws -> BackupGeneration? + ) throws -> [URL] { + do { + let repo = try repository(in: scratch) + let input = shadow.appendingPathComponent(".git/objects") + guard let objects = try BackupIO.directory(input) else { + throw ClientBackupError.invalidLocation(input.path) + } + _ = try observe(input) + let destination = try repo.child("objects") + for prefix in try objects.names() where prefix == "pack" || hex(prefix, length: 2...2) { + let directory = try objects.child(prefix) + _ = try observe(directory.url) + let target = + try destination.info(prefix) == nil + ? destination.createPrivateDirectory(prefix) : destination.child(prefix) + for file in try directory.names() + where prefix == "pack" ? packName(file) : hex(file, length: 38...38) { + let url = directory.url.appendingPathComponent(file) + guard let current = try observe(url), + try BackupIO.copy(url, to: target, named: file).generation == current + else { throw ClientBackupError.conflict(url.path) } + } + } + let resolved = try commits.map { try resolve($0, in: repo) } + let output = try scratch.createPrivateDirectory("gemini-pack-" + UUID().uuidString) + let inputName = "commits-" + UUID().uuidString + try scratch.write( + inputName, data: Data((Set(resolved).sorted().joined(separator: "\n") + "\n").utf8)) + let prefix = output.url.appendingPathComponent("pack").path + let name = try git( + ["pack-objects", "--quiet", "--revs", "--non-empty", prefix], + in: repo, input: scratch.url.appendingPathComponent(inputName)) + guard hex(name, length: 40...40) else { + throw ClientBackupError.unsupportedLayout(shadow.path) + } + return ["idx", "pack"].map { output.url.appendingPathComponent("pack-" + name + "." + $0) } + } catch { + throw ClientBackupError.unsupportedLayout(shadow.path) + } + } + + struct Prepared { + let commits: [String: String] + let initialFiles: [String: URL] + let references: [String: URL] + } + + static func prepare( + commits: [String], packs: [String: URL], scratch: DirectoryHandle, initialize: Bool + ) throws -> Prepared { + let repo = try repository(in: scratch) + let directory = try repo.child("objects").child("pack") + for (name, payload) in packs { + guard packName(name) else { throw ClientBackupError.invalidPackage } + try BackupIO.copy(payload, to: directory, named: name) + } + for name in packs.keys { + let counterpart = + name.hasSuffix(".pack") + ? String(name.dropLast(5)) + ".idx" : String(name.dropLast(4)) + ".pack" + guard packs[counterpart] != nil else { throw ClientBackupError.invalidPackage } + if name.hasSuffix(".pack") { + _ = try git( + ["index-pack", "--verify", directory.url.appendingPathComponent(name).path], in: repo) + } + } + var resolved: [String: String] = [:] + for commit in commits where resolved[commit] == nil { + resolved[commit] = try resolve(commit, in: repo) + } + var initialFiles: [String: URL] = [:] + if initialize, let latest = commits.last.flatMap({ resolved[$0] }) { + _ = try git(["read-tree", latest], in: repo) + _ = try git(["update-ref", "refs/heads/main", latest], in: repo) + for file in ["HEAD", "config", "index", "refs/heads/main"] { + initialFiles[file] = repo.url.appendingPathComponent(file) + } + } + let refs = try scratch.createPrivateDirectory("gemini-refs-" + UUID().uuidString) + var references: [String: URL] = [:] + for commit in Set(resolved.values) { + try refs.write(commit, data: Data((commit + "\n").utf8)) + references["refs/agents-checkpoints/" + commit] = refs.url.appendingPathComponent(commit) + } + return Prepared(commits: resolved, initialFiles: initialFiles, references: references) + } + + private static func repository(in scratch: DirectoryHandle) throws -> DirectoryHandle { + let folder = try scratch.createPrivateDirectory("gemini-git-" + UUID().uuidString) + _ = try git( + ["init", "--quiet", "--template=", "--initial-branch=main", "--object-format=sha1"], + in: folder) + return try folder.child(".git") + } + + private static func resolve(_ prefix: String, in repo: DirectoryHandle) throws -> String { + guard hex(prefix, length: 4...40) else { throw ClientBackupError.invalidPackage } + let sha = try git(["rev-parse", "--verify", prefix + "^{commit}"], in: repo) + guard hex(sha, length: 40...40), sha.hasPrefix(prefix) else { + throw ClientBackupError.unsupportedLayout("Gemini checkpoint commit") + } + return sha + } + + @discardableResult + static func git(_ arguments: [String], in folder: DirectoryHandle, input: URL? = nil) throws + -> String + { + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/git") + process.currentDirectoryURL = folder.url + process.arguments = + [ + "-c", "core.hooksPath=/dev/null", "-c", "maintenance.auto=false", + "-c", "gc.auto=0", + ] + arguments + process.environment = [ + "PATH": "/usr/bin:/bin", "GIT_CONFIG_GLOBAL": "/dev/null", "GIT_CONFIG_NOSYSTEM": "1", + "GIT_TERMINAL_PROMPT": "0", "GIT_NO_REPLACE_OBJECTS": "1", + ] + let output = Pipe() + process.standardOutput = output + process.standardError = FileHandle.nullDevice + let handle = try input.map(FileHandle.init(forReadingFrom:)) + defer { try? handle?.close() } + process.standardInput = handle ?? FileHandle.nullDevice + try process.run() + let data = try output.fileHandleForReading.readToEnd() ?? Data() + process.waitUntilExit() + guard process.terminationStatus == 0, let text = String(data: data, encoding: .utf8) else { + throw ClientBackupError.unsupportedLayout("Gemini checkpoint Git objects") + } + return text.trimmingCharacters(in: .whitespacesAndNewlines) + } +} diff --git a/Sources/AgentsCore/ClientBackups/BackupJSONStream.swift b/Sources/AgentsCore/ClientBackups/BackupJSONStream.swift new file mode 100644 index 0000000..6c1ba33 --- /dev/null +++ b/Sources/AgentsCore/ClientBackups/BackupJSONStream.swift @@ -0,0 +1,233 @@ +import CPlatform +import Foundation + +/// Copies native JSON while interpreting only the selected metadata strings. Conversation +/// bodies pass through the chunk buffer, including strings that span many chunks. +final class BackupJSONStream { + typealias Rewriter = ([String], String) throws -> String? + + private let source: FileHandle + private let output: FileHandle? + private let file: String + private let selection: Set<[String]> + private let prefixes: Set<[String]> + private let rewrite: Rewriter + // Six JSON bytes can encode one path byte. Larger strings are payload rather than path metadata. + private static let maximumTokenBytes = 6 * Int(PATH_MAX) + 2 + private var input: [UInt8] = [] + private var cursor = 0 + private var buffer = Data() + private(set) var changed = false + + init( + _ source: URL, output: FileHandle? = nil, selection: Set<[String]>, + rewrite: @escaping Rewriter + ) throws { + self.source = try FileHandle(forReadingFrom: source) + self.output = output + file = source.lastPathComponent + self.selection = selection + prefixes = Set( + selection.flatMap { path in + path.indices.map { Array(path.prefix($0)) } + }) + self.rewrite = rewrite + } + + func process(records: Bool = false) throws { + try space() + if records { + while try peek() != nil { + try object([]) + try space() + } + } else { + try object([]) + try space() + guard try peek() == nil else { throw failure } + } + if !buffer.isEmpty { try output?.write(contentsOf: buffer) } + } + + private var failure: ClientBackupError { .unsupportedLayout(file) } + + private func peek() throws -> UInt8? { + if cursor == input.count { + input = Array(try source.read(upToCount: 64 * 1024) ?? Data()) + cursor = 0 + } + return input.isEmpty ? nil : input[cursor] + } + + private func emit(_ byte: UInt8) throws { + guard let output else { return } + buffer.append(byte) + if buffer.count == 64 * 1024 { + try output.write(contentsOf: buffer) + buffer.removeAll(keepingCapacity: true) + } + } + + private func take(copy: Bool = true) throws -> UInt8 { + guard let next = try peek() else { throw failure } + cursor += 1 + if copy { try emit(next) } + return next + } + + private func expect(_ code: UInt8) throws { + guard try take() == code else { throw failure } + } + + private func space() throws { + while let next = try peek(), [0x20, 0x09, 0x0d, 0x0a].contains(next) { _ = try take() } + } + + private func string(copy: Bool) throws -> Data? { + guard try take(copy: copy) == 0x22 else { throw failure } + var raw: Data? = copy ? nil : Data([0x22]) + + func transfer(_ bytes: some Collection) throws { + if let count = raw?.count, count + bytes.count <= Self.maximumTokenBytes { + raw?.append(contentsOf: bytes) + } else { + if let prefix = raw { + buffer.append(prefix) + raw = nil + } + if output != nil { buffer.append(contentsOf: bytes) } + if buffer.count >= 64 * 1024 { + try output?.write(contentsOf: buffer) + buffer.removeAll(keepingCapacity: true) + } + } + } + + while try peek() != nil { + let start = cursor + while cursor < input.count { + let byte = input[cursor] + if byte == 0x22 || byte == 0x5c || byte < 0x20 { break } + cursor += 1 + } + if cursor > start { try transfer(input[start..= 0x20 else { throw failure } + try transfer(CollectionOfOne(next)) + if next == 0x22 { return raw } + try transfer(CollectionOfOne(try take(copy: false))) + } + throw failure + } + + private func text(_ bytes: Data) throws -> String { + guard + let value = try JSONSerialization.jsonObject(with: bytes, options: [.fragmentsAllowed]) + as? String + else { throw failure } + return value + } + + private func metadata(_ path: [String]) throws { + guard let raw = try string(copy: false) else { return } + let original = try text(raw) + let replacement = try rewrite(path, original) + if let replacement, replacement != original { + let encoder = JSONEncoder() + encoder.outputFormatting = [.withoutEscapingSlashes] + for byte in try encoder.encode(replacement) { try emit(byte) } + changed = true + } else { + for byte in raw { try emit(byte) } + } + } + + private func object(_ path: [String]) throws { + try expect(0x7b) + try space() + if try peek() == 0x7d { + try expect(0x7d) + return + } + while true { + let raw = try string(copy: false) + let member: [String]? + if let raw { + for byte in raw { try emit(byte) } + member = try path + [text(raw)] + } else { + member = nil + } + try space() + try expect(0x3a) + try space() + if let member, try prefixes.contains(member) && peek() == 0x7b { + try object(member) + } else if let member, selection.contains(member) { + try field(member) + } else { + try skipValue() + } + try space() + if try peek() == 0x7d { + try expect(0x7d) + return + } + try expect(0x2c) + try space() + } + } + + private func field(_ path: [String]) throws { + switch try peek() { + case 0x22: try metadata(path) + case 0x5b: + try expect(0x5b) + try space() + if try peek() == 0x5d { + try expect(0x5d) + return + } + while true { + if try peek() == 0x22 { try metadata(path) } else { try skipValue() } + try space() + if try peek() == 0x5d { + try expect(0x5d) + return + } + try expect(0x2c) + try space() + } + default: try skipValue() + } + } + + private func skipValue() throws { + guard let first = try peek() else { throw failure } + if first == 0x22 { + _ = try string(copy: true) + } else if first == 0x7b || first == 0x5b { + var closing: [UInt8] = [] + repeat { + guard let next = try peek() else { throw failure } + if next == 0x22 { + _ = try string(copy: true) + continue + } + _ = try take() + switch next { + case 0x7b: closing.append(0x7d) + case 0x5b: closing.append(0x5d) + case 0x7d, 0x5d: + guard closing.popLast() == next else { throw failure } + default: break + } + } while !closing.isEmpty + } else { + let delimiters: Set = [0x20, 0x09, 0x0d, 0x0a, 0x2c, 0x5d, 0x7d] + guard !delimiters.contains(first) else { throw failure } + while let next = try peek(), !delimiters.contains(next) { _ = try take() } + } + } +} diff --git a/Sources/AgentsCore/ClientBackups/BackupNativeData.swift b/Sources/AgentsCore/ClientBackups/BackupNativeData.swift new file mode 100644 index 0000000..3082a55 --- /dev/null +++ b/Sources/AgentsCore/ClientBackups/BackupNativeData.swift @@ -0,0 +1,495 @@ +import CPlatform +import CSQLite +import Foundation + +struct BackupRelocation { + let header: BackupHeader + let roots: BackupRoots + let projectMappings: [(String, String)] + + init(header: BackupHeader, roots: BackupRoots) { + self.header = header + self.roots = roots + projectMappings = roots.projects.map { ($0.key, $0.value.path) }.sorted { + $0.0.count > $1.0.count + } + } + + func projectPath(_ value: String) -> String { + remap(value, from: projectMappings) + } + + func clientPath(_ value: String) -> String { + remap(value, from: [(header.sourceClient, roots.client.path)]) + } + + private func remap(_ value: String, from roots: [(String, String)]) -> String { + for (original, target) in roots { + if value == original { return target } + if value.hasPrefix(original + "/") { return target + value.dropFirst(original.count) } + } + return value + } +} + +enum BackupNativeJSON { + static func object(_ url: URL) throws -> [String: Any] { + guard let object = try value(url) as? [String: Any] else { + throw ClientBackupError.unsupportedLayout(url.lastPathComponent) + } + return object + } + + static func value(_ url: URL) throws -> Any { + let parent = try DirectoryHandle(at: url.deletingLastPathComponent()) + return try JSONSerialization.jsonObject( + with: parent.read(url.lastPathComponent, maximumBytes: 64 * 1024 * 1024)) + } + + static func encode(_ value: Any) throws -> Data { + try JSONSerialization.data( + withJSONObject: value, options: [.sortedKeys, .withoutEscapingSlashes]) + } + + static func mergeMaps( + _ source: [String: Any], into destination: [String: Any], keys: Set + ) throws -> [String: Any] { + var result = destination.merging(source) { _, new in new } + for key in keys where source[key] != nil && destination[key] != nil { + guard let incoming = source[key] as? [String: Any], + let current = destination[key] as? [String: Any] + else { throw ClientBackupError.unsupportedLayout(key) } + result[key] = current.merging(incoming) { _, new in new } + } + return result + } + + static func remappedRecords( + _ records: [String: Any], using mapping: BackupRelocation + ) throws -> [String: Any] { + var result: [String: Any] = [:] + for (path, value) in records { + let target = mapping.projectPath(path) + guard result.updateValue(value, forKey: target) == nil else { + throw ClientBackupError.conflict("project mapping") + } + } + return result + } + + static func pathFields( + _ input: [String: Any], using mapping: BackupRelocation + ) -> (value: [String: Any], changed: Bool) { + var result = input + var changed = false + for key in ["cwd", "projectPath", "originalPath", "rootPath"] { + if let path = input[key] as? String { + let target = mapping.projectPath(path) + if path != target { + result[key] = target + changed = true + } + } + } + for key in ["fullPath", "rollout_path", "rolloutPath"] { + if let path = input[key] as? String { + let target = mapping.clientPath(mapping.projectPath(path)) + if path != target { + result[key] = target + changed = true + } + } + } + for key in ["runtime_workspace_roots", "workspace_roots"] { + if let paths = input[key] as? [String] { + let mapped = paths.map(mapping.projectPath) + if mapped != paths { + result[key] = mapped + changed = true + } + } + } + let type = input["type"] as? String + if let payload = input["payload"] as? [String: Any] { + if type == "session_meta" || type == "turn_context" { + let mapped = pathFields(payload, using: mapping) + if mapped.changed { + result["payload"] = mapped.value + changed = true + } + } + if type == "event_msg", payload["type"] as? String == "thread_settings_applied", + let settings = payload["thread_settings"] as? [String: Any] + { + let mapped = pathFields(settings, using: mapping) + if mapped.changed { + var next = payload + next["thread_settings"] = mapped.value + result["payload"] = next + changed = true + } + } + } + return (result, changed) + } +} + +struct BackupRolloutOffsets { + var thread: String? + var edits: [(range: Range, delta: Int64)] = [] + + func translate(_ offset: Int64) throws -> Int64 { + var diff: Int64 = 0 + for edit in edits { + if offset <= edit.range.lowerBound { break } + guard offset >= edit.range.upperBound else { + throw ClientBackupError.unsupportedLayout("Codex rollout cursor") + } + diff += edit.delta + } + return offset + diff + } +} + +/// JSONL session bodies can be large, so each pass retains just one record. +enum BackupJSONL { + static func lines(_ url: URL, _ visit: (Data, Bool) throws -> Void) throws { + let reader = try FileHandle(forReadingFrom: url) + defer { try? reader.close() } + var remainder = Data() + while let next = try reader.read(upToCount: BackupIO.chunkSize), !next.isEmpty { + var start = next.startIndex + while let end = next[start...].firstIndex(of: 0x0a) { + remainder.append(contentsOf: next[start.. [String: Any] { + guard let value = try JSONSerialization.jsonObject(with: line) as? [String: Any] else { + throw ClientBackupError.unsupportedLayout(path) + } + return value + } + + static func remap( + _ url: URL, to output: FileHandle, + transform: ([String: Any]) throws -> (value: [String: Any], changed: Bool) + ) throws -> BackupRolloutOffsets { + var offsets = BackupRolloutOffsets() + var offset: Int64 = 0 + try lines(url) { bytes, newline in + let end = offset + Int64(bytes.count) + (newline ? 1 : 0) + var rendered = bytes + if !bytes.isEmpty && bytes != Data([0x0d]) { + let record = try record(bytes, path: url.lastPathComponent) + if record["type"] as? String == "session_meta", + let payload = record["payload"] as? [String: Any], let id = payload["id"] as? String + { + offsets.thread = id + } + let remapped = try transform(record) + if remapped.changed { + rendered = try BackupNativeJSON.encode(remapped.value) + if bytes.last == 0x0d { rendered.append(0x0d) } + offsets.edits.append((offset.. String { + if index { + let record = try record(bytes, path: "session_index.jsonl") + guard let id = record["id"] as? String, !id.isEmpty else { + throw ClientBackupError.unsupportedLayout("session_index.jsonl") + } + return id + } + return FileHash.sha256Hex(data: bytes) + } + var incomingKeys = Set() + try lines(incoming) { bytes, _ in + if !bytes.isEmpty { incomingKeys.insert(try key(bytes)) } + } + func write(_ bytes: Data) throws { + try output.write(contentsOf: bytes) + try output.write(contentsOf: Data([0x0a])) + } + try lines(existing) { bytes, _ in + if try !bytes.isEmpty && !incomingKeys.contains(key(bytes)) { + try write(bytes) + } + } + try lines(incoming) { bytes, _ in + guard !bytes.isEmpty else { return } + let value = try record(bytes, path: incoming.lastPathComponent) + let remapped = BackupNativeJSON.pathFields(value, using: mapping) + try write(remapped.changed ? BackupNativeJSON.encode(remapped.value) : bytes) + } + } +} + +enum BackupNativeDatabase { + private static let sharedTables: Set = [ + "threads", "thread_dynamic_tools", "thread_spawn_edges", "thread_sections", + "thread_read_receipts", "thread_attachments", "thread_artifacts", "thread_goals", + "thread_goal_continuation_deferrals", "projects", "project_roots", "stage1_outputs", + "project_idempotency_keys", "session_model_ids", + ] + private static let destinationTables: Set = [ + "_sqlx_migrations", "backfill_state", "rollout_migration_state", "remote_control_enrollments", + "external_agent_config_imports", "sqlite_sequence", "logs", "agent_jobs", "agent_job_items", + "rollout_migration_skipped_rollouts", + "jobs", "state_metadata", "thread_history_metadata", + ] + + private struct Table { + let name: String + let sql: String + let columns: [String] + let primaryKey: [String] + } + + static func adapt( + _ incoming: URL, destination: URL?, name: String, using mapping: BackupRelocation, + rolloutOffsets: [String: BackupRolloutOffsets] + ) throws -> URL { + do { + let source = try BackupSQL(incoming, writable: true) + try source.verify() + try source.disableTriggers() + let tables = try tables(source) + if name.hasPrefix("state") { + guard let threads = tables.first(where: { $0.name == "threads" }), + ["id", "cwd", "rollout_path"].allSatisfy(threads.columns.contains) + else { throw ClientBackupError.unsupportedLayout(name) } + try rewrite(source, table: "threads", column: "rollout_path", mapping.clientPath) + try rewrite(source, table: "threads", column: "cwd", mapping.projectPath) + if tables.contains(where: { $0.name == "project_roots" && $0.columns.contains("path") }) { + try rewrite(source, table: "project_roots", column: "path", mapping.projectPath) + } + } + if name.hasPrefix("thread_history_"), !rolloutOffsets.isEmpty { + for (table, column) in [ + ("thread_history_projection_state", "next_rollout_byte_offset"), + ("thread_turns", "rollout_byte_offset"), + ("thread_turns", "rollout_end_byte_offset"), + ] { + if let schema = tables.first(where: { $0.name == table }) { + guard schema.columns.contains("thread_id"), schema.columns.contains(column) else { + throw ClientBackupError.unsupportedLayout(name) + } + try rewriteOffsets(source, table: table, column: column, offsets: rolloutOffsets) + } + } + } + try source.execute("PRAGMA journal_mode=DELETE") + } + + guard let destination else { return incoming } + let target = try BackupSQL(destination, writable: true) + try target.verify() + try target.disableTriggers() + let attach = BackupSQL.absoluteFileURL(incoming).absoluteString + "?mode=ro" + try target.execute("ATTACH DATABASE ? AS incoming", [.text(attach)]) + let sourceTables = try tables(target, schema: "incoming") + let targetTables = try tables(target) + guard sourceTables.map(\.sql) == targetTables.map(\.sql), + try triggerDefinitions(target, schema: "incoming") + == triggerDefinitions(target, schema: "main") + else { + throw ClientBackupError.unsupportedLayout(name) + } + try target.execute("PRAGMA foreign_keys=ON") + try target.execute("BEGIN IMMEDIATE") + try target.execute("PRAGMA defer_foreign_keys=ON") + for table in sourceTables { + if destinationTables.contains(table.name) { continue } + let identifier = quote(table.name) + let columns = table.columns.map(quote) + let insert = columns.joined(separator: ",") + let key = table.primaryKey.map(quote).joined(separator: ",") + let updates = table.columns.filter { !table.primaryKey.contains($0) }.map { + "\(quote($0))=excluded.\(quote($0))" + }.joined(separator: ",") + guard !key.isEmpty, sharedTables.contains(table.name) || table.columns.contains("thread_id") + else { + try target.rows( + "SELECT 1 FROM (SELECT * FROM incoming.\(identifier) EXCEPT SELECT * FROM main.\(identifier)) LIMIT 1" + ) { _ in throw ClientBackupError.unsupportedLayout(name + "/" + table.name) } + continue + } + if table.columns.contains("thread_id"), !table.primaryKey.contains("thread_id") { + let sameKey = table.primaryKey.map { + "current.\(quote($0))=archived.\(quote($0))" + }.joined(separator: " AND ") + try target.rows( + """ + SELECT 1 FROM main.\(identifier) current JOIN incoming.\(identifier) archived + ON \(sameKey) + WHERE current.thread_id IS NOT archived.thread_id LIMIT 1 + """ + ) { _ in throw ClientBackupError.conflict(name + "/" + table.name) } + } + let differences = table.columns.filter { !table.primaryKey.contains($0) }.map { + "\(identifier).\(quote($0)) IS NOT excluded.\(quote($0))" + }.joined(separator: " OR ") + let update = updates.isEmpty ? "NOTHING" : "UPDATE SET " + updates + " WHERE " + differences + let sql = """ + INSERT INTO main.\(identifier)(\(insert)) + SELECT \(insert) FROM incoming.\(identifier) WHERE true + ON CONFLICT(\(key)) DO \(update) + """ + try target.execute(sql) + } + try target.execute("COMMIT") + try target.rows("PRAGMA foreign_key_check") { _ in + throw ClientBackupError.conflict(name) + } + try target.execute("DETACH DATABASE incoming") + try target.execute("PRAGMA journal_mode=DELETE") + try target.verify() + return destination + } + + static func requireClosed(_ url: URL) throws { + guard let parent = try BackupIO.directory(url.deletingLastPathComponent()) else { return } + for suffix in ["-wal", "-shm", "-journal"] { + guard try parent.info(url.lastPathComponent + suffix) == nil else { + throw ClientBackupError.conflict(url.path + suffix) + } + } + } + + private static func quote(_ value: String) -> String { + "\"" + value.replacingOccurrences(of: "\"", with: "\"\"") + "\"" + } + + private static func tables(_ db: BackupSQL, schema: String = "main") throws -> [Table] { + try db.rows("SELECT 1 FROM \(schema).sqlite_schema WHERE type='view'") { _ in + throw ClientBackupError.unsupportedLayout("Codex SQLite schema") + } + _ = try triggerDefinitions(db, schema: schema) + var tables: [Table] = [] + try db.rows( + "SELECT name,sql FROM \(schema).sqlite_schema WHERE type='table' ORDER BY name" + ) { row in + let name = try BackupSQL.text(row, 0) + let definition = try BackupSQL.text(row, 1) + guard definition.uppercased().hasPrefix("CREATE TABLE ") else { + throw ClientBackupError.unsupportedLayout("Codex SQLite table") + } + var columns: [String] = [] + var key: [Int64: String] = [:] + try db.rows("PRAGMA \(schema).table_xinfo(\(quote(name)))") { column in + guard try BackupSQL.integer(column, 6) == 0 else { + throw ClientBackupError.unsupportedLayout("Codex SQLite column") + } + let name = try BackupSQL.text(column, 1) + columns.append(name) + let rank = try BackupSQL.integer(column, 5) + if rank > 0 { key[rank] = name } + } + tables.append( + Table( + name: name, sql: definition, columns: columns, + primaryKey: key.keys.sorted().compactMap { key[$0] })) + } + return tables + } + + private static func triggerDefinitions(_ db: BackupSQL, schema: String) throws -> [String] { + let supported = [ + "threads_created_at_ms_after_insert": "threads", + "threads_updated_at_ms_after_insert": "threads", + "threads_created_at_ms_after_update": "threads", + "threads_updated_at_ms_after_update": "threads", + "threads_recency_at_after_insert": "threads", + "thread_realtime_items_projection_cleanup": "thread_history_projection_state", + ] + var definitions: [String] = [] + try db.rows( + "SELECT name,tbl_name,sql FROM \(schema).sqlite_schema WHERE type='trigger' ORDER BY name" + ) { row in + let name = try BackupSQL.text(row, 0) + guard try supported[name] == BackupSQL.text(row, 1) else { + throw ClientBackupError.unsupportedLayout("Codex SQLite trigger") + } + definitions.append(try BackupSQL.text(row, 2)) + } + return definitions + } + + private static func rewriteOffsets( + _ db: BackupSQL, table: String, column: String, offsets: [String: BackupRolloutOffsets] + ) throws { + let table = quote(table) + let column = quote(column) + var changes: [[BackupSQL.Value]] = [] + try db.rows("SELECT DISTINCT thread_id,\(column) FROM \(table) WHERE \(column) IS NOT NULL") { + row in + let id = try BackupSQL.text(row, 0) + guard let rollout = offsets[id] else { return } + let old = try BackupSQL.integer(row, 1) + let replacement = try rollout.translate(old) + if replacement != old { changes.append([.text(id), .integer(old), .integer(replacement)]) } + } + if changes.isEmpty { return } + try db.execute( + """ + CREATE TEMP TABLE offset_mapping ( + thread TEXT NOT NULL, old INTEGER NOT NULL, new INTEGER NOT NULL, PRIMARY KEY(thread,old) + ) + """) + for change in changes { try db.execute("INSERT INTO offset_mapping VALUES (?,?,?)", change) } + let match = "thread=\(table).thread_id AND old=\(table).\(column)" + try db.execute( + """ + UPDATE \(table) SET \(column) = (SELECT new FROM offset_mapping WHERE \(match)) + WHERE EXISTS (SELECT 1 FROM offset_mapping WHERE \(match)) + """) + try db.execute("DROP TABLE offset_mapping") + } + + private static func rewrite( + _ db: BackupSQL, table: String, column: String, _ mapping: (String) -> String + ) throws { + let table = quote(table) + let column = quote(column) + var updates: [(String, String)] = [] + try db.rows("SELECT DISTINCT \(column) FROM \(table) WHERE \(column) IS NOT NULL") { row in + let source = try BackupSQL.text(row, 0) + let target = mapping(source) + if source != target { updates.append((source, target)) } + } + if updates.isEmpty { return } + // One UPDATE prevents a destination that is itself an original root from being remapped twice. + try db.execute("CREATE TEMP TABLE path_mapping (old TEXT PRIMARY KEY, new TEXT NOT NULL)") + for (source, target) in updates { + try db.execute("INSERT INTO path_mapping VALUES (?,?)", [.text(source), .text(target)]) + } + try db.execute( + """ + UPDATE \(table) + SET \(column) = (SELECT new FROM path_mapping WHERE old=\(table).\(column)) + WHERE \(column) IN (SELECT old FROM path_mapping) + """) + try db.execute("DROP TABLE path_mapping") + } +} diff --git a/Sources/AgentsCore/ClientBackups/BackupRestoreTransaction.swift b/Sources/AgentsCore/ClientBackups/BackupRestoreTransaction.swift new file mode 100644 index 0000000..c7d8c3b --- /dev/null +++ b/Sources/AgentsCore/ClientBackups/BackupRestoreTransaction.swift @@ -0,0 +1,345 @@ +import CPlatform +import Foundation + +/// Publication uses atomic exchange or exclusive rename on each destination volume. +/// The private journal records intent before every publication and survives process exit. +enum BackupRestoreTransaction { + @TaskLocal static var checkpoint: (@Sendable (String) throws -> Void)? + + private struct Leaf: Codable { + let path: String + let digest: BackupDigest + let mode: UInt16 + } + + private struct Unit: Codable { + let parent: String + let parentIdentity: FileObjectIdentity + let destination: String + let leafs: [Leaf] + let before: FileObjectIdentity? + var staged: FileObjectIdentity? + var after: FileObjectIdentity? + + var isTree: Bool { leafs.first?.path != "" } + var target: URL { URL(fileURLWithPath: parent).appendingPathComponent(destination) } + + func openParent() throws -> DirectoryHandle { + guard BackupIO.safeComponent(destination), BackupIO.originalPath(parent) || parent == "/", + let directory = try BackupIO.directory(URL(fileURLWithPath: parent)), + try BackupIO.identity(directory) == parentIdentity + else { throw ClientBackupError.conflict(target.path) } + return directory + } + } + + private struct Journal: Codable { + var version = 1 + let id: UUID + let client: BackupClient + var phase: Phase = .staging + var units: [Unit] + + enum Phase: String, Codable { case staging, publishing, committed } + + func container(_ index: Int) -> String { + ".agents-backup-" + id.uuidString + "-" + String(index) + } + } + + private struct Group { + let parent: URL + let parentIdentity: FileObjectIdentity + let destination: String + var items: [(String, BackupRestoreItem)] + } + + static func commit(_ plan: BackupRestorePlan) throws { + let home = try DirectoryHandle(at: plan.home) + let rootName = ".agents-backup-transactions" + let changes = plan.items.filter { $0.kind != .unchanged } + if changes.isEmpty, try home.info(rootName) == nil { + try validate(plan) + return + } + let transactionRoot: DirectoryHandle + if try home.info(rootName) != nil { + transactionRoot = try home.child(rootName) + } else { + do { + transactionRoot = try home.createPrivateDirectory(rootName) + } catch { + // Another restore can establish the journal directory before this one locks it. + transactionRoot = try home.child(rootName) + } + } + try FileAccessEvidence.requirePrivate(descriptor: transactionRoot.descriptor) + let name = plan.client.rawValue + ".json" + try FileLock.withDescriptor(in: transactionRoot, name: plan.client.rawValue + ".lock") { _ in + if try transactionRoot.info(name) != nil { + try recover(in: transactionRoot, named: name, client: plan.client) + throw ClientBackupError.conflict("previous restore recovered; preview again") + } + try validate(plan) + if !changes.isEmpty { + try publish(changes, plan: plan, journalRoot: transactionRoot, name: name) + } + } + } + + private static func validate(_ plan: BackupRestorePlan) throws { + try plan.package.validate() + for before in plan.dependencies { try before.validate() } + for item in plan.items where item.isDatabase { + try BackupNativeDatabase.requireClosed(item.target) + } + } + + private static func group(_ items: [BackupRestoreItem]) throws -> [Group] { + var groups: [String: Group] = [:] + for item in items { + var cursor = item.before.link == nil ? item.target : item.before.target + var parentURL = cursor.deletingLastPathComponent() + while try BackupIO.directory(parentURL) == nil { + cursor = parentURL + parentURL = parentURL.deletingLastPathComponent() + } + let parent = try DirectoryHandle(at: parentURL) + let relative: String + if cursor.path == item.target.path { + relative = "" + } else { + relative = String(item.target.path.dropFirst(cursor.path.count + 1)) + } + if groups[cursor.path] == nil { + groups[cursor.path] = Group( + parent: parent.url, parentIdentity: try BackupIO.identity(parent), + destination: cursor.lastPathComponent, items: []) + } + groups[cursor.path]?.items.append((relative, item)) + } + // Install session files before publishing indexes that refer to them. + return groups.values.sorted { + func priority(_ group: Group) -> Int { + group.items.contains { + $0.1.isDatabase + || [ + "projects.json", "session_index.jsonl", + "sessions-index.json", ".claude.json", + ].contains($0.1.target.lastPathComponent) + } ? 1 : 0 + } + let left = priority($0) + let right = priority($1) + if left != right { return left < right } + let lhs = $0.parent.appendingPathComponent($0.destination).path + let rhs = $1.parent.appendingPathComponent($1.destination).path + return lhs < rhs + } + } + + private static func publish( + _ changes: [BackupRestoreItem], plan: BackupRestorePlan, journalRoot: DirectoryHandle, + name: String + ) throws { + let groups = try group(changes) + var units: [Unit] = [] + for group in groups { + let old = + group.items.first?.1.before.link?.identity + ?? group.items.first { $0.0.isEmpty }?.1.before.before?.generation.identity + units.append( + Unit( + parent: group.parent.path, parentIdentity: group.parentIdentity, + destination: group.destination, + leafs: group.items.map { Leaf(path: $0.0, digest: $0.1.digest, mode: $0.1.mode) }, + before: old)) + } + var journal = Journal(id: UUID(), client: plan.client, units: units) + try persist(journal, in: journalRoot, name: name) + do { + for (index, group) in groups.enumerated() { + let unit = journal.units[index] + let parent = try unit.openParent() + let stage = try parent.createPrivateDirectory(journal.container(index)) + journal.units[index].staged = try BackupIO.identity(stage) + try construct(group.items, isTree: unit.isTree, in: stage) + guard let after = try stage.info("payload") else { + throw ClientBackupError.conflict(unit.target.path) + } + journal.units[index].after = FileObjectIdentity(after) + } + try validate(plan) + journal.phase = .publishing + try persist(journal, in: journalRoot, name: name) + try checkpoint?("publishing") + for (index, group) in groups.enumerated() { + let unit = journal.units[index] + let parent = try unit.openParent() + let stage = try openStage(in: parent, journal: journal, index: index) + guard let stage, let after = unit.after, + try stage.info("payload").map(FileObjectIdentity.init) == after + else { throw ClientBackupError.conflict(unit.target.path) } + try validateSpelling(unit.destination, in: parent) + for (_, item) in group.items { + // Prior publications may have populated an unrelated child in the same ancestor. + try item.before.validate() + if item.isDatabase { try BackupNativeDatabase.requireClosed(item.target) } + } + try stage.move( + "payload", to: parent, named: unit.destination, + mode: unit.before == nil ? .exclusive : .exchange) + guard try parent.info(unit.destination).map(FileObjectIdentity.init) == after, + try stage.info("payload").map(FileObjectIdentity.init) == unit.before + else { throw ClientBackupError.conflict(unit.target.path) } + if let before = group.items.first?.1.before.before, !unit.isTree { + guard let exchanged = try BackupIO.generation(stage, "payload") else { + throw ClientBackupError.conflict(unit.target.path) + } + let current = try BackupIO.stream(stage, "payload", expecting: exchanged) { _ in } + guard current.digest == before.digest, current.mode == before.mode else { + throw ClientBackupError.conflict(unit.target.path) + } + } + _ = try unit.openParent() + try checkpoint?("published") + } + journal.phase = .committed + try persist(journal, in: journalRoot, name: name) + try checkpoint?("committed") + } catch { + let original = error + do { + try checkpoint?("recovering") + try recover(in: journalRoot, named: name, client: plan.client) + } catch { + throw ClientBackupError.storageFailure( + "restore recovery; journal retained at " + journalRoot.url.path) + } + throw original + } + try recover(in: journalRoot, named: name, client: plan.client) + } + + private static func construct( + _ items: [(String, BackupRestoreItem)], isTree: Bool, in stage: DirectoryHandle + ) throws { + let root = isTree ? try stage.createPrivateDirectory("payload") : stage + for (path, item) in items { + let parts = isTree ? try BackupIO.components(path) : ["payload"] + guard let name = parts.last else { throw ClientBackupError.invalidPackage } + var directory = root + for subdirectory in parts.dropLast() { + if try directory.info(subdirectory) == nil { + directory = try directory.createPrivateDirectory(subdirectory) + } else { + directory = try directory.child(subdirectory) + } + } + let copied = try BackupIO.copy(item.payload, to: directory, named: name, mode: item.mode) + guard copied.digest == item.digest else { throw ClientBackupError.conflict(item.target.path) } + try directory.sync() + } + try stage.sync() + } + + private static func persist(_ journal: Journal, in root: DirectoryHandle, name: String) throws { + let bytes = try JSONEncoder().encode(journal) + try root.replaceFile(name, through: name + ".new", with: bytes, afterWrite: {}, afterRename: {}) + try root.requirePrivateAccess(name) + } + + private static func recover(in root: DirectoryHandle, named name: String, client: BackupClient) + throws + { + try root.requirePrivateAccess(name) + let data = try root.read(name, maximumBytes: 64 * 1024 * 1024) + let journal = try JSONDecoder().decode(Journal.self, from: data) + guard journal.version == 1, journal.client == client else { + throw ClientBackupError.conflict("restore journal") + } + if journal.phase == .publishing { + for index in journal.units.indices.reversed() { + try rollBack(journal, index: index) + } + } + for index in journal.units.indices { + let unit = journal.units[index] + let parent = try unit.openParent() + guard let stage = try openStage(in: parent, journal: journal, index: index) else { continue } + try parent.remove(journal.container(index), identity: BackupIO.identity(stage)) + } + try root.removeFiles([name, name + ".new"]) + } + + private static func openStage( + in parent: DirectoryHandle, journal: Journal, index: Int + ) throws -> DirectoryHandle? { + let name = journal.container(index) + guard let state = try parent.info(name) else { return nil } + guard state.st_mode & S_IFMT == S_IFDIR, + journal.phase == .staging || journal.units[index].staged == FileObjectIdentity(state) + else { throw ClientBackupError.conflict(parent.url.appendingPathComponent(name).path) } + let stage = try parent.child(name, matching: state) + try FileAccessEvidence.requirePrivate(descriptor: stage.descriptor) + return stage + } + + private static func rollBack(_ journal: Journal, index: Int) throws { + let unit = journal.units[index] + let parent = try unit.openParent() + let stage = try openStage(in: parent, journal: journal, index: index) + let current = try parent.info(unit.destination).map(FileObjectIdentity.init) + let staged = try stage?.info("payload").map(FileObjectIdentity.init) + if staged == unit.after || (stage == nil && current == unit.before) { return } + guard let stage, let after = unit.after, after == current, staged == unit.before else { + throw ClientBackupError.conflict(unit.target.path) + } + try verifyPublished(unit, in: parent) + try parent.move( + unit.destination, to: stage, named: "payload", + mode: unit.before == nil ? .exclusive : .exchange) + } + + private static func verifyPublished(_ unit: Unit, in parent: DirectoryHandle) throws { + var expected = Dictionary( + unit.leafs.map { ($0.path, $0) }, uniquingKeysWith: { first, _ in first }) + guard expected.count == unit.leafs.count else { + throw ClientBackupError.conflict(unit.target.path) + } + func verifyFile(_ directory: DirectoryHandle, name: String, path: String) throws { + guard let leaf = expected.removeValue(forKey: path), + let generation = try BackupIO.generation(directory, name) + else { throw ClientBackupError.conflict(unit.target.path) } + let actual = try BackupIO.stream(directory, name, expecting: generation) { _ in } + guard actual.digest == leaf.digest, actual.mode == leaf.mode else { + throw ClientBackupError.conflict(unit.target.path) + } + } + func walk(_ directory: DirectoryHandle, prefix: String) throws { + for name in try directory.names() { + let path = prefix + name + if let info = try directory.info(name), info.st_mode & S_IFMT == S_IFDIR, + expected.keys.contains(where: { $0.hasPrefix(path + "/") }) + { + try walk(directory.child(name), prefix: path + "/") + } else { + try verifyFile(directory, name: name, path: path) + } + } + } + if unit.isTree { + try walk(parent.child(unit.destination), prefix: "") + } else { + try verifyFile(parent, name: unit.destination, path: "") + } + guard expected.isEmpty else { throw ClientBackupError.conflict(unit.target.path) } + } + + private static func validateSpelling(_ name: String, in parent: DirectoryHandle) throws { + let folded = BackupIO.fold(name) + guard try !parent.names().contains(where: { BackupIO.fold($0) == folded && $0 != name }) else { + throw ClientBackupError.conflict(parent.url.appendingPathComponent(name).path) + } + } +} diff --git a/Sources/AgentsCore/ClientBackups/BackupScope.swift b/Sources/AgentsCore/ClientBackups/BackupScope.swift new file mode 100644 index 0000000..997a752 --- /dev/null +++ b/Sources/AgentsCore/ClientBackups/BackupScope.swift @@ -0,0 +1,652 @@ +import CPlatform +import Foundation +import TOMLSemantics + +struct BackupRoots { + let home: URL + let client: URL + let database: URL + let profile: URL + let shared: URL + let runtime: URL + let codexConfig: BackupPathFence? + let configuredCodexDatabase: Bool + let zstdPath: String? + let projects: [String: URL] + + init(_ client: BackupClient, environment: RuntimeEnvironment, projects: [String: URL]) throws { + home = try BackupIO.address(environment.homeDirectory) + zstdPath = environment.environment["PATH"] + func override(_ name: String) throws -> URL? { + guard let value = environment.environment[name], !value.isEmpty else { return nil } + guard value.hasPrefix("/") else { throw ClientBackupError.invalidLocation(name) } + return try BackupIO.address(URL(fileURLWithPath: value, isDirectory: true)) + } + switch client { + case .codex: + self.client = try override("CODEX_HOME") ?? home.appendingPathComponent(".codex") + let config = try BackupPathFence.capture(self.client.appendingPathComponent("config.toml")) + codexConfig = config + let configured = try BackupCodexConfig.sqliteHome(config.target) + configuredCodexDatabase = configured != nil + if let configured { + let path = + configured.path.hasPrefix("~/") + ? home.appendingPathComponent(String(configured.path.dropFirst(2))).path : configured.path + guard BackupIO.originalPath(path) else { + throw ClientBackupError.invalidLocation("Codex sqlite_home") + } + database = URL(fileURLWithPath: path, isDirectory: true) + } else { + database = try override("CODEX_SQLITE_HOME") ?? self.client + } + profile = home + shared = home.appendingPathComponent(".agents") + runtime = self.client + case .claudeCode: + let config = try override("CLAUDE_CONFIG_DIR") + self.client = config ?? home.appendingPathComponent(".claude") + codexConfig = nil + configuredCodexDatabase = false + database = self.client + profile = config ?? home + shared = home.appendingPathComponent(".agents") + runtime = self.client + case .geminiCLI: + let geminiHome = try override("GEMINI_CLI_HOME") ?? home + self.client = geminiHome.appendingPathComponent(".gemini") + codexConfig = nil + configuredCodexDatabase = false + database = self.client + profile = home + shared = geminiHome.appendingPathComponent(".agents") + if environment.environment["SANDBOX"] == "sandbox-exec" { + runtime = geminiHome.appendingPathComponent(".cache/.gemini") + } else { + runtime = self.client + } + } + self.projects = projects + } + + func url(_ root: String) throws -> URL { + if root.hasPrefix(BackupClaudeImports.archivePrefix) { + return try url(String(root.dropFirst(BackupClaudeImports.archivePrefix.count))) + } + return switch root { + case "client": client + case "database": database + case "profile": profile + case "shared": shared + case "runtime": runtime + default: + if let project = projects[root] { project } else { throw ClientBackupError.invalidPackage } + } + } +} + +enum BackupScope { + struct Route { + let files: Set + let trees: Set + let dynamic: Bool + + init(files: Set = [], trees: Set = [], dynamic: Bool = false) { + self.files = files + self.trees = trees + self.dynamic = dynamic + } + } + + static func routes(_ client: BackupClient, project: Bool) -> [String: Route] { + if project { + switch client { + case .codex: + return [ + "": Route( + files: ["AGENTS.md", "AGENTS.override.md", ".codex/config.toml", ".codex/hooks.json"], + trees: [ + ".agents/skills", ".codex/skills", ".codex/rules", ".codex/hooks", ".codex/agents", + ]) + ] + case .claudeCode: + return [ + "": Route( + files: [ + "CLAUDE.md", "CLAUDE.local.md", ".mcp.json", "AGENTS.md", + ".claude/CLAUDE.md", ".claude/CLAUDE.local.md", ".claude/settings.json", + ".claude/settings.local.json", + ".claude/.mcp.json", + ], + trees: [ + ".claude/rules", ".claude/skills", ".claude/commands", ".claude/agents", + ".claude/hooks", ".claude/scripts", ".claude/output-styles", + ]) + ] + case .geminiCLI: + return [ + "": Route( + files: [ + "GEMINI.md", "AGENTS.md", ".geminiignore", ".gemini/settings.json", + ".gemini/.env", ".gemini/GEMINI.md", + ], + trees: [ + ".agents/skills", ".gemini/skills", ".gemini/policies", ".gemini/commands", + ".gemini/agents", ".gemini/hooks", ".gemini/extensions", + ]) + ] + } + } + switch client { + case .codex: + return [ + "client": Route( + files: [ + "config.toml", "auth.json", "AGENTS.md", "AGENTS.override.md", "hooks.json", + "session_index.jsonl", "history.jsonl", ".codex-global-state.json", + ], + trees: [ + "sessions", "archived_sessions", "attachments", "thread-attachments", + "artifacts", "skills", "rules", "hooks", "agents", "instructions", "memories", + ]), + "database": Route(dynamic: true), + "shared": Route(trees: ["skills"]), + ] + case .claudeCode: + return [ + "shared": Route(trees: ["skills"]), + "client": Route( + files: [ + "settings.json", "settings.local.json", "CLAUDE.md", "CLAUDE.local.md", + ".credentials.json", ".mcp.json", "history.jsonl", + ], + trees: [ + "projects", "sessions", "file-history", "session-env", "tasks", "todos", + "plans", "image-cache", "paste-cache", "skills", "rules", "commands", "agents", + "hooks", "scripts", "output-styles", + ]), + "profile": Route(files: [".claude.json"]), + ] + case .geminiCLI: + return [ + "client": Route( + files: ["settings.json", ".env", "GEMINI.md", "oauth_creds.json", "keybindings.json"], + trees: ["skills", "policies", "commands", "agents", "hooks", "extensions"]), + "runtime": Route( + files: [ + "projects.json", "trustedFolders.json", "google_accounts.json", + "mcp-oauth-tokens.json", "a2a-oauth-tokens.json", + ], + dynamic: true), + "shared": Route(trees: ["skills"]), + ] + } + } + + static func skillUnit(_ client: BackupClient, root: String, project: Bool, path: String) + -> String? + { + let trees = routes(client, project: project)[project ? "" : root]?.trees ?? [] + for prefix in trees where prefix.split(separator: "/").last == "skills" { + guard path.hasPrefix(prefix + "/") else { continue } + let rest = path.dropFirst(prefix.count + 1) + if let name = rest.split(separator: "/").first { return prefix + "/" + name } + } + return nil + } + + static func isSkillManifest(_ bytes: Data) -> Bool { + guard let text = String(data: bytes, encoding: .utf8) else { return false } + let lines = text.split(whereSeparator: \.isNewline) + guard lines.first == "---" else { return false } + let header = lines.dropFirst().prefix { $0 != "---" } + return header.endIndex != lines.endIndex + && header.contains { + $0.hasPrefix("name:") && !$0.dropFirst(5).trimmingCharacters(in: .whitespaces).isEmpty + } + } + + static func isDatabase(_ name: String) -> Bool { + name.range( + of: #"^(state(_[0-9]+)?|goals_[0-9]+|thread_history_[0-9]+)\.sqlite$"#, + options: .regularExpression) != nil + } + + static func excluded(_ component: String) -> Bool { + let name = component.lowercased() + return [".git", ".build", ".ds_store", "node_modules", "__pycache__", ".cache", "deriveddata"] + .contains(name) || name.hasPrefix(".agents-backup-") || name.hasSuffix(".agentsbackup") + } + + static func allows( + _ client: BackupClient, root: String, components: [String], projects: [String] + ) -> Bool { + if client == .geminiCLI, root == "runtime", BackupGeminiCheckpoints.isPack(components) { + return !excluded(components[1]) + } + guard !components.isEmpty, components.allSatisfy({ !excluded($0) }) else { return false } + if client == .claudeCode, root.hasPrefix(BackupClaudeImports.archivePrefix) { + let owner = String(root.dropFirst(BackupClaudeImports.archivePrefix.count)) + return (owner == "client" || projects.contains(owner)) + && BackupClaudeImports.allows(components) + } + let project = projects.contains(root) + let routes = routes(client, project: project) + guard let route = routes[project ? "" : root] else { return false } + let path = components.joined(separator: "/") + if route.files.contains(path) || route.trees.contains(where: { path.hasPrefix($0 + "/") }) { + return true + } + if project, components.count > 1, let name = components.last, + components.dropLast().allSatisfy({ !$0.hasPrefix(".") }), + projectContextNames(client).contains(name) + { + return true + } + guard route.dynamic else { return false } + if client == .codex { + return components.count == 1 && isDatabase(components[0]) + } + if components.first == "history" { + return components.count == 3 && components[2] == ".project_root" + } + guard components.count >= 3, components[0] == "tmp" else { return false } + if components.count == 3, geminiCheckpoint(components[2]) { return true } + if BackupGeminiCheckpoints.isRecord(components) { return true } + switch components[2] { + case ".project_root", "logs.json": return components.count == 3 + case "chats", "attachments", "plans", "memory", "tasks", "tracker", "tool-outputs": + return components.count > 3 + default: + return components.count > 4 && ["plans", "tasks", "tracker"].contains(components[3]) + } + } + + static func geminiCheckpoint(_ name: String) -> Bool { + name.hasPrefix("checkpoint-") && name.hasSuffix(".json") + } + + static func projectContextNames(_ client: BackupClient) -> [String] { + switch client { + case .codex: ["AGENTS.md", "AGENTS.override.md"] + case .claudeCode: ["CLAUDE.md", "CLAUDE.local.md", "AGENTS.md"] + case .geminiCLI: ["GEMINI.md", "AGENTS.md"] + } + } +} + +final class BackupInventory { + private struct File { + let root: String + let path: String + let location: URL + let generation: BackupGeneration + } + + private let client: BackupClient + private let roots: BackupRoots + private let output: URL + private var observations: [URL: BackupGeneration?] = [:] + private var files: [File] = [] + + init(client: BackupClient, roots: BackupRoots, output: URL) { + self.client = client + self.roots = roots + self.output = output + } + + private func observe(_ url: URL) throws -> BackupGeneration? { + let value: BackupGeneration? + if let parent = try BackupIO.directory(url.deletingLastPathComponent()) { + value = try BackupIO.generation(parent, url.lastPathComponent) + } else { + value = nil + } + if let prior = observations[url], prior != value { + throw ClientBackupError.conflict(url.path) + } + observations.updateValue(value, forKey: url) + return value + } + + private func names(_ url: URL) throws -> [String] { + guard let value = try observe(url) else { return [] } + guard value.value.st_mode & S_IFMT == S_IFDIR, + let directory = try BackupIO.directory(url) + else { throw ClientBackupError.invalidLocation(url.path) } + return try directory.names() + } + + private func collect( + _ url: URL, root: String, path: String, recursive: Bool, depth: Int = 0, + resource: Bool = false, insideLinkedSkill: Bool = false + ) throws { + guard depth < 128 else { throw ClientBackupError.invalidLocation(url.path) } + if url.path == output.path, depth != 0 { return } + guard let state = try observe(url) else { return } + switch state.value.st_mode & S_IFMT { + case S_IFREG: + let parts = try BackupIO.components(path) + guard + BackupScope.allows( + client, root: root, components: parts, projects: Array(roots.projects.keys)) + else { throw ClientBackupError.invalidLocation(url.path) } + files.append(File(root: root, path: path, location: url, generation: state)) + case S_IFDIR where recursive: + let children = try names(url) + if insideLinkedSkill, children.contains(where: { $0.lowercased() == ".git" }) { + throw ClientBackupError.invalidLocation(url.path) + } + for name in children where !BackupScope.excluded(name) { + guard BackupIO.safeComponent(name) else { + throw ClientBackupError.invalidLocation(url.path) + } + try collect( + url.appendingPathComponent(name), root: root, path: path + "/" + name, + recursive: true, depth: depth + 1, resource: resource, + insideLinkedSkill: insideLinkedSkill) + } + case S_IFLNK where insideLinkedSkill: + throw ClientBackupError.invalidLocation(url.path) + case S_IFLNK where resource: + let target = url.resolvingSymlinksInPath() + let owningRoot = try roots.url(root) + let isProject = roots.projects[root] != nil + let route = BackupScope.routes(client, project: isProject)[isProject ? "" : root] + if BackupScope.skillUnit(client, root: root, project: isProject, path: path) == path { + guard target.path != url.path, + !([roots.home, roots.client, roots.shared] + Array(roots.projects.values)).contains( + where: { + $0.path == target.path + }), + try isOwnedSkill(target) + else { throw ClientBackupError.invalidLocation(url.path) } + try collect( + target, root: root, path: path, recursive: true, depth: depth + 1, insideLinkedSkill: true + ) + return + } + if BackupScope.skillUnit(client, root: root, project: isProject, path: path) != nil + || (route?.trees.contains(path) == true && path.split(separator: "/").last == "skills") + { + throw ClientBackupError.invalidLocation(url.path) + } + let ownedTrees = (route?.trees ?? []).map { owningRoot.appendingPathComponent($0).path } + guard target.path != url.path, ownedTrees.contains(where: { target.path.hasPrefix($0 + "/") }) + else { return } + try collect(target, root: root, path: path, recursive: recursive, depth: depth + 1) + case S_IFLNK: + return + default: + throw ClientBackupError.invalidLocation(url.path) + } + } + + private func isOwnedSkill(_ target: URL) throws -> Bool { + guard let directory = try BackupIO.directory(target), + try directory.info(".git") == nil, + let file = try directory.info("SKILL.md"), file.st_mode & S_IFMT == S_IFREG, + file.st_size <= 1024 * 1024 + else { return false } + let bytes = try directory.read("SKILL.md", matching: file, maximumBytes: 1024 * 1024) + return BackupScope.isSkillManifest(bytes) + } + + func capture(into archive: BackupArchive, in scratch: DirectoryHandle) throws { + var routes = BackupScope.routes(client, project: false) + for project in roots.projects.keys { + routes[project] = BackupScope.routes(client, project: true)[""] + } + for key in routes.keys.sorted() { + guard let route = routes[key] else { continue } + let base = try roots.url(key) + for path in route.files.sorted() { + try collect(base.appendingPathComponent(path), root: key, path: path, recursive: false) + } + for tree in route.trees.sorted() { + let resource = !["sessions", "archived_sessions", "projects", "history"].contains(tree) + try collect( + base.appendingPathComponent(tree), root: key, path: tree, recursive: true, + resource: resource) + } + if roots.projects[key] != nil { + try collectProjectContext(base, root: key, prefix: "", depth: 0) + } + if route.dynamic { + if client == .codex { + for db in try names(base).filter(BackupScope.isDatabase) { + try collect(base.appendingPathComponent(db), root: key, path: db, recursive: false) + } + } else { + try collectGemini(base, root: key) + } + } + } + if client == .claudeCode { try collectClaudeImports() } + if client == .geminiCLI { try collectGeminiPacks(in: scratch) } + for file in files { + if file.root == "database" { + let snapshot = try snapshot(file, in: scratch) + guard let generation = try BackupIO.generation(scratch, snapshot) else { + throw ClientBackupError.conflict(file.location.path) + } + try archive.add( + root: file.root, path: file.path, mode: file.generation.mode & 0o777, + parent: scratch, name: snapshot, generation: generation) + try scratch.remove(snapshot) + } else { + let parent = try DirectoryHandle(at: file.location.deletingLastPathComponent()) + try archive.add( + root: file.root, path: file.path, mode: file.generation.mode & 0o777, + parent: parent, name: file.location.lastPathComponent, generation: file.generation) + } + } + try roots.codexConfig?.validate() + for (url, previous) in observations { + guard try observe(url) == previous else { throw ClientBackupError.conflict(url.path) } + } + } + + private func collectClaudeImports() throws { + let location = BackupClaudeImports.Locations( + home: roots.home, client: roots.client, projects: roots.projects) + let native = Dictionary( + files.map { (BackupClaudeImports.File(root: $0.root, path: $0.path), $0) }, + uniquingKeysWith: { first, _ in first }) + let entries = native.keys.filter { BackupClaudeImports.isEntry($0, projects: roots.projects) } + var captured = Set() + _ = try BackupClaudeImports.closure(entries: entries, locations: location) { key in + guard let url = location.url(key) else { return nil } + let file = native[key] + let input = file?.location ?? url + guard let state = try observe(input), state.value.st_mode & S_IFMT == S_IFREG, + let parent = try BackupIO.directory(input.deletingLastPathComponent()) + else { throw ClientBackupError.invalidLocation(url.path) } + if file == nil, captured.insert(key).inserted { + files.append( + File( + root: BackupClaudeImports.archivePrefix + key.root, path: key.path, + location: input, generation: state)) + } + return try parent.read(input.lastPathComponent, matching: state.value) + } + } + + private func collectProjectContext( + _ folder: URL, root: String, prefix: String, depth: Int + ) throws { + guard depth < 128, let directory = try BackupIO.directory(folder) else { return } + for name in try directory.names() + where !name.hasPrefix(".") && !BackupScope.excluded(name) && BackupIO.safeComponent(name) { + let child = folder.appendingPathComponent(name) + if child.path == output.path { continue } + guard let info = try directory.info(name) else { continue } + if depth > 0, BackupScope.projectContextNames(client).contains(name), + info.st_mode & S_IFMT == S_IFREG + { + try collect(child, root: root, path: prefix + name, recursive: false) + } else if info.st_mode & S_IFMT == S_IFDIR { + try collectProjectContext(child, root: root, prefix: prefix + name + "/", depth: depth + 1) + } + } + } + + private func collectGemini(_ base: URL, root: String) throws { + let history = base.appendingPathComponent("history") + for key in try names(history) where BackupIO.safeComponent(key) && !BackupScope.excluded(key) { + let folder = history.appendingPathComponent(key) + if let state = try observe(folder), state.value.st_mode & S_IFMT == S_IFDIR { + try collect( + folder.appendingPathComponent(".project_root"), root: root, + path: "history/" + key + "/.project_root", recursive: false) + } + } + let tmp = base.appendingPathComponent("tmp") + for key in try names(tmp) where !BackupScope.excluded(key) { + guard BackupIO.safeComponent(key) else { throw ClientBackupError.invalidLocation(tmp.path) } + let folder = tmp.appendingPathComponent(key) + guard let state = try observe(folder), state.value.st_mode & S_IFMT == S_IFDIR else { + continue + } + for name in try names(folder) { + let path = "tmp/" + key + "/" + name + let url = folder.appendingPathComponent(name) + if [".project_root", "logs.json"].contains(name) || BackupScope.geminiCheckpoint(name) { + try collect(url, root: root, path: path, recursive: false) + } else if ["chats", "attachments", "plans", "memory", "tasks", "tracker", "tool-outputs"] + .contains(name) + { + try collect(url, root: root, path: path, recursive: true) + } else if name == "checkpoints" { + for record in try names(url) where !BackupScope.excluded(record) { + let parts = ["tmp", key, name, record] + if BackupGeminiCheckpoints.isRecord(parts) { + let file = url.appendingPathComponent(record) + guard let state = try observe(file), state.value.st_mode & S_IFMT == S_IFREG else { + throw ClientBackupError.invalidLocation(file.path) + } + try collect(file, root: root, path: parts.joined(separator: "/"), recursive: false) + } + } + } else if UUID(uuidString: name) != nil { + for child in ["plans", "tasks", "tracker"] { + try collect( + url.appendingPathComponent(child), root: root, path: path + "/" + child, + recursive: true) + } + } + } + } + } + + private func collectGeminiPacks(in scratch: DirectoryHandle) throws { + var commits: [String: [String]] = [:] + for file in files where file.root == "runtime" { + let parts = try BackupIO.components(file.path) + guard BackupGeminiCheckpoints.isRecord(parts) else { continue } + let staged = "checkpoint-" + UUID().uuidString + guard + try BackupIO.copy(file.location, to: scratch, named: staged).generation == file.generation + else { throw ClientBackupError.conflict(file.location.path) } + if let commit = try BackupGeminiCheckpoints.commit( + in: scratch.url.appendingPathComponent(staged)) + { + commits[parts[1], default: []].append(commit) + } + try scratch.remove(staged) + } + for (key, dependencies) in commits.sorted(by: { $0.key < $1.key }) { + let shadow = roots.runtime.appendingPathComponent("history/" + key) + let pack = try BackupGeminiCheckpoints.capture( + commits: dependencies, shadow: shadow, scratch: scratch, observe: observe) + for payload in pack { + try collect( + payload, root: "runtime", + path: "history/" + key + "/.git/objects/pack/" + payload.lastPathComponent, + recursive: false) + } + } + } + + private func snapshot(_ file: File, in scratch: DirectoryHandle) throws -> String { + let token = UUID().uuidString + let working = token + "-native.sqlite" + let result = token + "-snapshot.sqlite" + let main = file.location + let wal = main.deletingLastPathComponent().appendingPathComponent( + main.lastPathComponent + "-wal") + let rollback = main.deletingLastPathComponent().appendingPathComponent( + main.lastPathComponent + "-journal") + guard try observe(rollback) == nil else { throw ClientBackupError.conflict(main.path) } + let walState = try observe(wal) + guard try BackupIO.copy(main, to: scratch, named: working).generation == file.generation else { + throw ClientBackupError.conflict(main.path) + } + if let walState { + guard try BackupIO.copy(wal, to: scratch, named: working + "-wal").generation == walState + else { throw ClientBackupError.conflict(wal.path) } + } + guard try observe(main) == file.generation, try observe(wal) == walState else { + throw ClientBackupError.conflict(main.path) + } + try BackupIO.write(result, in: scratch) { _ in } + do { + let source = try BackupSQL(scratch.url.appendingPathComponent(working), writable: true) + let destination = try BackupSQL(scratch.url.appendingPathComponent(result), writable: true) + try source.snapshot(into: destination) + try destination.execute("PRAGMA journal_mode=DELETE") + try destination.verify() + } + for name in [working, working + "-wal", working + "-shm"] { try scratch.remove(name) } + return result + } +} + +enum BackupCodexConfig { + static func sqliteHome(_ url: URL) throws -> (path: String, bytes: Data, range: Range)? { + guard let directory = try BackupIO.directory(url.deletingLastPathComponent()), + try directory.info(url.lastPathComponent) != nil + else { return nil } + let bytes = try directory.read(url.lastPathComponent, maximumBytes: 4 * 1024 * 1024) + guard let text = String(data: bytes, encoding: .utf8), text.contains("sqlite_home") else { + return nil + } + let budget = SemanticBudget( + limits: .init( + storage: 16 * 1024 * 1024, work: 96 * 1024 * 1024, nodes: 100_000, depth: 96, + uninterruptedBytes: 4 * 1024 * 1024)) + guard case .object(let entries) = try SemanticDocument(source: text, budget: budget).root, + let entry = entries.first(where: { $0.key == "sqlite_home" }) + else { return nil } + guard case .scalar(.string, let path, _, let range) = entry.value else { + throw ClientBackupError.unsupportedLayout("Codex sqlite_home") + } + return (path, bytes, range) + } + + static func relocated( + _ file: URL, sourceHome: String, sourceDatabase: String, destination: URL, + preserveDestinationSetting: Bool + ) throws -> Data? { + let encoder = JSONEncoder() + encoder.outputFormatting = [.withoutEscapingSlashes] + let value = try encoder.encode(destination.path) + guard var config = try sqliteHome(file) else { + guard preserveDestinationSetting else { return nil } + var bytes = Data("sqlite_home = ".utf8) + bytes.append(value) + bytes.append(0x0a) + bytes.append(try Data(contentsOf: file)) + return bytes + } + let original = + config.path.hasPrefix("~/") + ? sourceHome + "/" + config.path.dropFirst(2) : config.path + guard original == sourceDatabase else { + throw ClientBackupError.unsupportedLayout("Codex sqlite_home") + } + if original == destination.path { return nil } + config.bytes.replaceSubrange(config.range, with: value) + return config.bytes + } +} diff --git a/Sources/AgentsCore/ClientBackups/BackupStorage.swift b/Sources/AgentsCore/ClientBackups/BackupStorage.swift new file mode 100644 index 0000000..63fa801 --- /dev/null +++ b/Sources/AgentsCore/ClientBackups/BackupStorage.swift @@ -0,0 +1,360 @@ +import CPlatform +import CSQLite +import Crypto +import Foundation + +public enum ClientBackupError: Error, LocalizedError, Sendable { + case invalidPackage + case invalidLocation(String) + case conflict(String) + case unsupportedLayout(String) + case storageFailure(String) + + public var errorDescription: String? { + switch self { + case .invalidPackage: "The file is not an intact Agents client backup." + case .invalidLocation(let path): "The backup location is unsafe or unavailable: \(path)" + case .conflict(let path): "Client data changed or conflicts at \(path)." + case .unsupportedLayout(let path): "The client data layout is unsupported at \(path)." + case .storageFailure(let action): "The backup operation failed during \(action)." + } + } +} + +struct BackupDigest: Codable, Equatable, Sendable { + let size: Int64 + let hash: String +} + +struct BackupFingerprint: Equatable, Sendable { + let generation: BackupGeneration + let digest: BackupDigest + var mode: UInt16 { generation.mode & 0o777 } +} + +struct BackupGeneration: Equatable, Sendable { + let value: stat + + var mode: UInt16 { UInt16(value.st_mode & 0o177777) } + var identity: FileObjectIdentity { FileObjectIdentity(value) } + + static func == (lhs: Self, rhs: Self) -> Bool { + DirectoryHandle.sameGeneration(lhs.value, rhs.value) + } +} + +enum BackupIO { + static let chunkSize = 1024 * 1024 + + static func safeComponent(_ value: String) -> Bool { + !value.isEmpty && value != "." && value != ".." && !value.contains("/") + && !value.contains("\\") && !value.contains("\0") + } + + static func components(_ relative: String) throws -> [String] { + let parts = relative.components(separatedBy: "/") + guard parts.count <= 128, parts.allSatisfy(safeComponent) else { + throw ClientBackupError.invalidPackage + } + return parts + } + + static func address(_ url: URL) throws -> URL { + guard url.isFileURL, url.path.hasPrefix("/"), !url.path.contains("\0") else { + throw ClientBackupError.invalidLocation(url.path) + } + return url.standardizedFileURL + } + + static func originalPath(_ path: String) -> Bool { + path.hasPrefix("/") && path != "/" && !path.contains("\0") + && URL(fileURLWithPath: path).standardizedFileURL.path == path + } + + static func fold(_ path: String) -> String { + path.precomposedStringWithCanonicalMapping.folding( + options: [.caseInsensitive], locale: Locale(identifier: "en_US_POSIX")) + } + + static func directory(_ url: URL) throws -> DirectoryHandle? { + try descend(url) { _ in } + } + + static func ancestry(_ url: URL) throws -> [FileObjectIdentity] { + var result: [FileObjectIdentity] = [] + _ = try descend(url) { result.append(try identity($0)) } + return result + } + + private static func descend( + _ url: URL, visit: (DirectoryHandle) throws -> Void + ) throws -> DirectoryHandle? { + var current = try DirectoryHandle(at: URL(fileURLWithPath: "/")) + try visit(current) + for (index, name) in url.standardizedFileURL.pathComponents.dropFirst().enumerated() { + guard let value = try current.info(name) else { return nil } + if index == 0 && platform_system_alias(name) { + current = try DirectoryHandle(at: current.url.appendingPathComponent(name)) + } else { + guard value.st_mode & S_IFMT == S_IFDIR else { + throw ClientBackupError.invalidLocation(url.path) + } + current = try current.child(name) + } + try visit(current) + } + return current + } + + static func generation(_ parent: DirectoryHandle, _ name: String) throws -> BackupGeneration? { + try parent.info(name).map(BackupGeneration.init(value:)) + } + + static func identity(_ directory: DirectoryHandle) throws -> FileObjectIdentity { + var value = stat() + guard fstat(directory.descriptor, &value) == 0 else { + throw ClientBackupError.invalidLocation(directory.url.path) + } + return FileObjectIdentity(value) + } + + static func fingerprint(_ url: URL) throws -> BackupFingerprint? { + guard let parent = try directory(url.deletingLastPathComponent()), + let before = try generation(parent, url.lastPathComponent) + else { return nil } + return try stream(parent, url.lastPathComponent, expecting: before) { _ in } + } + + static func stream( + _ parent: DirectoryHandle, _ name: String, expecting before: BackupGeneration, + consume: (Data) throws -> Void + ) throws -> BackupFingerprint { + let path = parent.url.appendingPathComponent(name).path + guard before.value.st_mode & S_IFMT == S_IFREG else { + throw ClientBackupError.invalidLocation(path) + } + let fd = openat(parent.descriptor, name, O_RDONLY | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK) + guard fd >= 0 else { throw ClientBackupError.invalidLocation(path) } + let handle = FileHandle(fileDescriptor: fd, closeOnDealloc: true) + defer { try? handle.close() } + var opened = stat() + guard fstat(fd, &opened) == 0, before == BackupGeneration(value: opened) else { + throw ClientBackupError.conflict(path) + } + var hash = SHA256() + var size: Int64 = 0 + while let bytes = try handle.read(upToCount: chunkSize), !bytes.isEmpty { + size += Int64(bytes.count) + guard size <= Int64(before.value.st_size) else { throw ClientBackupError.conflict(path) } + hash.update(data: bytes) + try consume(bytes) + } + guard size == Int64(before.value.st_size), fstat(fd, &opened) == 0, + before == BackupGeneration(value: opened), try generation(parent, name) == before + else { throw ClientBackupError.conflict(path) } + return BackupFingerprint( + generation: before, digest: BackupDigest(size: size, hash: hex(hash.finalize()))) + } + + static func hex(_ digest: SHA256.Digest) -> String { + digest.map { String(format: "%02x", $0) }.joined() + } + + static func write( + _ name: String, in parent: DirectoryHandle, mode: UInt16 = 0o600, + _ body: (FileHandle) throws -> Void + ) throws { + let fd = openat( + parent.descriptor, name, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0o600) + guard fd >= 0 else { + throw ClientBackupError.invalidLocation(parent.url.appendingPathComponent(name).path) + } + let output = FileHandle(fileDescriptor: fd, closeOnDealloc: true) + defer { try? output.close() } + if mode == 0o600 { try FileAccessEvidence.requirePrivate(descriptor: fd) } + try body(output) + guard fchmod(fd, mode_t(mode)) == 0 else { + throw ClientBackupError.storageFailure("setting file permissions") + } + try output.synchronize() + } + + @discardableResult + static func copy( + _ source: URL, to parent: DirectoryHandle, named name: String, mode: UInt16 = 0o600 + ) throws -> BackupFingerprint { + let sourceParent = try DirectoryHandle(at: source.deletingLastPathComponent()) + let sourceName = source.lastPathComponent + guard let expected = try generation(sourceParent, sourceName) else { + throw ClientBackupError.conflict(source.path) + } + var copied: BackupFingerprint? + try write(name, in: parent, mode: mode) { output in + copied = try stream(sourceParent, sourceName, expecting: expected) { + try output.write(contentsOf: $0) + } + } + guard let copied else { throw ClientBackupError.storageFailure("copying file") } + return copied + } +} + +/// Only private, engine-owned directories may hold plaintext staging files. +final class BackupScratch: @unchecked Sendable { + let url: URL + + init(in base: URL = FileManager.default.temporaryDirectory) throws { + let parent = try DirectoryHandle(at: base.resolvingSymlinksInPath()) + let name = ".agents-backup-" + UUID().uuidString + let created = try parent.createPrivateDirectory(name) + url = created.url + } + + deinit { + if let parent = try? DirectoryHandle(at: url.deletingLastPathComponent()) { + try? parent.remove(url.lastPathComponent) + } + } + + func open() throws -> DirectoryHandle { try DirectoryHandle(at: url) } + + func path(_ name: String) -> URL { url.appendingPathComponent(name) } +} + +final class BackupSQL { + private let db: OpaquePointer + private static let transient = unsafeBitCast(-1, to: sqlite3_destructor_type.self) + + enum Value { + case text(String) + case integer(Int64) + case blob(Data) + } + + init(_ url: URL, writable: Bool = false, immutable: Bool = false) throws { + var opened: OpaquePointer? + let flags = + (writable ? SQLITE_OPEN_READWRITE : SQLITE_OPEN_READONLY) | SQLITE_OPEN_NOFOLLOW + | SQLITE_OPEN_URI + let canonical = Self.absoluteFileURL(url) + let path = immutable ? canonical.absoluteString + "?immutable=1" : canonical.path + let code = sqlite3_open_v2(path, &opened, flags, nil) + guard code == SQLITE_OK, let opened else { + let extended = opened.map(sqlite3_extended_errcode) ?? code + if let opened { sqlite3_close_v2(opened) } + throw ClientBackupError.storageFailure("opening SQLite data (SQLite \(extended))") + } + db = opened + sqlite3_busy_timeout(db, 1000) + sqlite3_limit(db, SQLITE_LIMIT_ATTACHED, 1) + sqlite3_limit(db, SQLITE_LIMIT_LENGTH, 64 * 1024 * 1024) + try execute("PRAGMA trusted_schema=OFF") + } + + deinit { sqlite3_close_v2(db) } + + static func absoluteFileURL(_ url: URL) -> URL { + let path = url.standardizedFileURL.path + if let first = url.pathComponents.dropFirst().first, platform_system_alias(first) { + return URL(fileURLWithPath: "/private" + path) + } + return URL(fileURLWithPath: path) + } + + func disableTriggers() throws { + guard agents_sqlite_disable_triggers(db) == SQLITE_OK else { + throw ClientBackupError.storageFailure("disabling SQLite triggers") + } + } + + func execute(_ sql: String, _ values: [Value] = []) throws { + try rows(sql, values) { _ in } + } + + func rows( + _ sql: String, _ values: [Value] = [], _ visit: (OpaquePointer) throws -> Void + ) throws { + var prepared: OpaquePointer? + guard sqlite3_prepare_v2(db, sql, -1, &prepared, nil) == SQLITE_OK, let prepared else { + throw ClientBackupError.storageFailure("preparing SQLite data") + } + defer { sqlite3_finalize(prepared) } + guard sqlite3_bind_parameter_count(prepared) == values.count else { + throw ClientBackupError.storageFailure("binding SQLite data") + } + for (index, value) in values.enumerated() { + let column = Int32(index + 1) + let result: Int32 + switch value { + case .text(let text): + guard !text.contains("\0") else { throw ClientBackupError.invalidPackage } + result = sqlite3_bind_text(prepared, column, text, -1, Self.transient) + case .integer(let number): result = sqlite3_bind_int64(prepared, column, number) + case .blob(let bytes): + result = bytes.withUnsafeBytes { + sqlite3_bind_blob64( + prepared, column, $0.baseAddress, UInt64($0.count), Self.transient) + } + } + guard result == SQLITE_OK else { + throw ClientBackupError.storageFailure("binding SQLite data") + } + } + while true { + switch sqlite3_step(prepared) { + case SQLITE_DONE: return + case SQLITE_ROW: try visit(prepared) + default: throw ClientBackupError.storageFailure("reading or writing SQLite data") + } + } + } + + static func text(_ row: OpaquePointer, _ column: Int32) throws -> String { + guard sqlite3_column_type(row, column) == SQLITE_TEXT, + let pointer = sqlite3_column_text(row, column), + let value = String( + bytes: UnsafeBufferPointer( + start: pointer, count: Int(sqlite3_column_bytes(row, column))), encoding: .utf8), + !value.contains("\0") + else { throw ClientBackupError.invalidPackage } + return value + } + + static func integer(_ row: OpaquePointer, _ column: Int32) throws -> Int64 { + guard sqlite3_column_type(row, column) == SQLITE_INTEGER else { + throw ClientBackupError.invalidPackage + } + return sqlite3_column_int64(row, column) + } + + static func blob(_ row: OpaquePointer, _ column: Int32, limit: Int) throws -> Data { + guard sqlite3_column_type(row, column) == SQLITE_BLOB else { + throw ClientBackupError.invalidPackage + } + let count = Int(sqlite3_column_bytes(row, column)) + guard count > 0, count <= limit, let bytes = sqlite3_column_blob(row, column) else { + throw ClientBackupError.invalidPackage + } + return Data(bytes: bytes, count: count) + } + + func snapshot(into destination: BackupSQL) throws { + guard let backup = sqlite3_backup_init(destination.db, "main", db, "main") else { + throw ClientBackupError.storageFailure("starting SQLite snapshot") + } + let step = sqlite3_backup_step(backup, -1) + let finish = sqlite3_backup_finish(backup) + guard step == SQLITE_DONE, finish == SQLITE_OK else { + throw ClientBackupError.storageFailure("capturing SQLite snapshot") + } + } + + func verify() throws { + var count = 0 + try rows("PRAGMA quick_check(1)") { row in + guard try Self.text(row, 0) == "ok" else { throw ClientBackupError.invalidPackage } + count += 1 + } + guard count == 1 else { throw ClientBackupError.invalidPackage } + } +} diff --git a/Sources/AgentsCore/ClientBackups/BackupZstd.swift b/Sources/AgentsCore/ClientBackups/BackupZstd.swift new file mode 100644 index 0000000..e07b654 --- /dev/null +++ b/Sources/AgentsCore/ClientBackups/BackupZstd.swift @@ -0,0 +1,34 @@ +import Foundation + +/// Codex's compressed rollouts hold the same JSONL byte stream as plain rollouts. +/// Transcoding on relocation leaves the package's original frame bytes intact. +enum BackupZstd { + static func executable(path: String?) -> URL? { + let installed = ["/usr/bin", "/opt/homebrew/bin", "/usr/local/bin", "/opt/local/bin"] + let directories = (path ?? "").split(separator: ":").map(String.init) + installed + for value in directories where value.hasPrefix("/") { + let binary = URL(fileURLWithPath: value, isDirectory: true).appendingPathComponent("zstd") + if FileManager.default.isExecutableFile(atPath: binary.path) { return binary } + } + return nil + } + + static func transcode( + _ input: URL, into output: FileHandle, using tool: URL, decode: Bool + ) throws { + let source = try FileHandle(forReadingFrom: input) + defer { try? source.close() } + let task = Process() + task.executableURL = tool + task.arguments = decode ? ["-q", "-d", "-c"] : ["-q", "-c"] + task.environment = ["PATH": "/usr/bin:/bin"] + task.standardInput = source + task.standardOutput = output + task.standardError = FileHandle.nullDevice + try task.run() + task.waitUntilExit() + guard task.terminationStatus == 0 else { + throw ClientBackupError.unsupportedLayout("Codex compressed rollout") + } + } +} diff --git a/Sources/AgentsCore/ClientBackups/ClientBackups.swift b/Sources/AgentsCore/ClientBackups/ClientBackups.swift new file mode 100644 index 0000000..6fb0816 --- /dev/null +++ b/Sources/AgentsCore/ClientBackups/ClientBackups.swift @@ -0,0 +1,921 @@ +import CPlatform +import Foundation + +public enum BackupClient: String, CaseIterable, Hashable, Codable, Sendable { + case codex + case claudeCode + case geminiCLI + + public var displayName: String { + switch self { + case .codex: "Codex" + case .claudeCode: "Claude Code" + case .geminiCLI: "Gemini CLI" + } + } +} + +public struct ClientBackupInfo: Sendable { + public let client: BackupClient + public let projects: [String] +} + +public enum ClientBackupChangeKind: String, Hashable, Sendable { + case add + case replace + case unchanged +} + +public struct ClientBackupFileChange: Hashable, Sendable { + public let path: String + public let kind: ClientBackupChangeKind +} + +public struct ClientBackupPreview: Sendable { + public let client: BackupClient + public let files: [ClientBackupFileChange] + fileprivate let plan: BackupRestorePlan + + fileprivate init(client: BackupClient, plan: BackupRestorePlan) { + self.client = client + self.plan = plan + var seen = Set() + files = plan.items.compactMap { + let path = $0.before.link == nil ? $0.target.path : $0.before.target.path + return seen.insert(path).inserted ? ClientBackupFileChange(path: path, kind: $0.kind) : nil + } + } +} + +/// Synchronous local file operations. Consumers can perform these operations on a worker thread. +public enum ClientBackups { + public static func create( + client: BackupClient, projects: [URL], to directory: URL, + environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> URL { + let output = try BackupIO.address(directory) + var selected: [String: URL] = [:] + for project in projects { + let root = try BackupIO.address(project) + guard BackupIO.originalPath(root.path), try BackupIO.directory(root) != nil else { + throw ClientBackupError.invalidLocation(root.path) + } + selected[root.path] = root + } + try requireDistinct(Array(selected.values)) + let roots = try BackupRoots(client, environment: environment, projects: selected) + let parent = try DirectoryHandle(at: output) + let scratch = try BackupScratch(in: parent.url) + let staging = try scratch.open() + let partial = "backup.sqlite" + let header = BackupHeader( + client: client, sourceHome: roots.home.path, sourceClient: roots.client.path, + sourceDatabase: roots.database.path, projects: selected.keys.sorted()) + do { + let archive = try BackupArchive(writing: partial, in: staging, header: header) + try BackupInventory(client: client, roots: roots, output: output).capture( + into: archive, in: staging) + try archive.finish() + } + let verified = try BackupArchive(reading: scratch.path(partial)) + for entry in verified.manifest.entries { try verified.read(entry) } + try staging.syncFile(partial) + let publishedParent = try BackupIO.directory(output) + guard let publishedParent, try BackupIO.identity(publishedParent) == BackupIO.identity(parent) + else { throw ClientBackupError.conflict(output.path) } + let name = client.rawValue + "-" + UUID().uuidString.lowercased() + ".agentsbackup" + try staging.move(partial, to: parent, named: name, mode: .exclusive) + return parent.url.appendingPathComponent(name) + } + + public static func inspect(_ package: URL) throws -> ClientBackupInfo { + let archive = try BackupArchive(reading: package) + let header = archive.manifest.header + let evidence = try BackupPackageReference(url: package, archive: archive) + for entry in archive.manifest.entries { try archive.read(entry) } + try evidence.validate() + return ClientBackupInfo(client: header.client, projects: header.projects) + } + + public static func preview( + _ package: URL, projects: [String: URL], environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> ClientBackupPreview { + let archive = try BackupArchive(reading: package) + let header = archive.manifest.header + guard Set(projects.keys) == Set(header.projects) else { + throw ClientBackupError.conflict("project mappings") + } + let selected = try projects.mapValues(BackupIO.address) + try requireDistinct(Array(selected.values)) + for root in selected.values { + guard BackupIO.originalPath(root.path), try BackupIO.directory(root) != nil else { + throw ClientBackupError.invalidLocation(root.path) + } + } + let roots = try BackupRoots(header.client, environment: environment, projects: selected) + let plan = try BackupRestorePlanner(package: package, archive: archive, roots: roots).prepare() + return ClientBackupPreview(client: header.client, plan: plan) + } + + public static func restore(_ preview: ClientBackupPreview) throws { + try BackupRestoreTransaction.commit(preview.plan) + } + + private static func requireDistinct(_ roots: [URL]) throws { + let unique = Set(roots.map { BackupIO.fold($0.path) }) + guard unique.count == roots.count else { throw ClientBackupError.conflict("project roots") } + let ids = try roots.compactMap { root in + try BackupIO.directory(root).map(BackupIO.identity) + } + guard Set(ids).count == ids.count else { throw ClientBackupError.conflict("project roots") } + } +} + +struct BackupPathFence: Equatable, Sendable { + let target: URL + let ancestors: [FileObjectIdentity] + let before: BackupFingerprint? + let link: BackupGeneration? + + static func captureLink(_ target: URL) throws -> Self { + let parentURL = target.deletingLastPathComponent() + guard let parent = try BackupIO.directory(parentURL), + let link = try BackupIO.generation(parent, target.lastPathComponent), + link.identity.kind == S_IFLNK + else { throw ClientBackupError.conflict(target.path) } + return BackupPathFence( + target: target, ancestors: try BackupIO.ancestry(parentURL), before: nil, link: link) + } + + static func capture(_ target: URL) throws -> Self { + let parent = target.deletingLastPathComponent() + let ancestors = try BackupIO.ancestry(parent) + let before = try BackupIO.fingerprint(target) + if let before, before.generation.value.st_nlink != 1 { + throw ClientBackupError.conflict(target.path) + } + return BackupPathFence(target: target, ancestors: ancestors, before: before, link: nil) + } + + func validate() throws { + guard try (link == nil ? Self.capture(target) : Self.captureLink(target)) == self else { + throw ClientBackupError.conflict(target.path) + } + } +} + +struct BackupRestoreItem: Sendable { + let target: URL + let payload: URL + let mode: UInt16 + let digest: BackupDigest + let before: BackupPathFence + let isDatabase: Bool + + var kind: ClientBackupChangeKind { + if before.link != nil { return .replace } + guard let old = before.before else { return .add } + return old.digest == digest && old.mode == mode ? .unchanged : .replace + } +} + +struct BackupPackageReference: Sendable { + let target: URL + private let generation: BackupGeneration + private let ancestry: [FileObjectIdentity] + + init(url: URL, archive: BackupArchive) throws { + target = try BackupIO.address(url) + guard let captured = archive.readGeneration else { throw ClientBackupError.invalidPackage } + generation = captured + ancestry = try BackupIO.ancestry(target.deletingLastPathComponent()) + try validate() + } + + func validate() throws { + let parentURL = target.deletingLastPathComponent() + guard let parent = try BackupIO.directory(parentURL), + try BackupIO.ancestry(parentURL) == ancestry, + try BackupIO.generation(parent, target.lastPathComponent) == generation + else { throw ClientBackupError.conflict(target.path) } + } +} + +struct BackupRestorePlan: Sendable { + let scratch: BackupScratch + let package: BackupPackageReference + let home: URL + let client: BackupClient + let items: [BackupRestoreItem] + let dependencies: [BackupPathFence] +} + +final class BackupRestorePlanner { + private let archive: BackupArchive + private let package: BackupPackageReference + private let roots: BackupRoots + private let scratch: BackupScratch + private let staging: DirectoryHandle + private let mapping: BackupRelocation + private var dependencies: [URL: BackupPathFence] = [:] + private var targets: [String: String] = [:] + private var occupiedNames: [URL: [String: String]] = [:] + private var rolloutOffsets: [String: BackupRolloutOffsets] = [:] + private var geminiOriginals: [String: String] = [:] + private var geminiKeys: [String: String] = [:] + private var geminiRegistry: (target: URL, payload: URL, mode: UInt16)? + private var geminiCheckpointCommits: [Int64: String] = [:] + private var geminiShadowFiles: [URL: URL] = [:] + private var claudeOriginals: [String: String] = [:] + private var claudeKeys: [String: String] = [:] + private var claudeInstructions = Set() + + init(package: URL, archive: BackupArchive, roots: BackupRoots) throws { + self.archive = archive + self.package = try BackupPackageReference(url: package, archive: archive) + self.roots = roots + scratch = try BackupScratch() + staging = try scratch.open() + mapping = BackupRelocation(header: archive.manifest.header, roots: roots) + if let config = roots.codexConfig { dependencies[config.target] = config } + } + + func prepare() throws -> BackupRestorePlan { + let entries = archive.manifest.entries + let client = archive.manifest.header.client + var payloads: [Int64: URL] = [:] + for entry in entries { + let name = "entry-" + String(entry.number) + try archive.extract(entry, to: staging, named: name) + payloads[entry.number] = scratch.path(name) + } + if client == .geminiCLI { + try prepareGemini(payloads) + try prepareGeminiCheckpoints(payloads) + } + if client == .claudeCode { + try prepareClaude(payloads) + try prepareClaudeImports(payloads) + } + var items: [BackupRestoreItem] = [] + let manifestPaths = Dictionary( + uniqueKeysWithValues: entries.map { + ($0.root + "\0" + $0.path, $0.number) + }) + let restoreOrder = + entries.filter { $0.root != "database" } + entries.filter { $0.root == "database" } + for entry in restoreOrder { + guard let original = payloads[entry.number] else { throw ClientBackupError.invalidPackage } + if client == .geminiCLI, entry.root == "runtime", entry.path == "projects.json" { continue } + let target = try destination(entry, client: client) + let link = try installedSkillLink(for: entry, client: client, manifestPaths: manifestPaths) + try register(target, replacingLink: link?.target) + let database = entry.root == "database" + if database { try BackupNativeDatabase.requireClosed(target) } + let before = try link ?? observe(target) + let payload = try transform( + entry, client: client, incoming: original, target: target, before: before) + guard let desired = try BackupIO.fingerprint(payload) else { + throw ClientBackupError.storageFailure("staging restore preview") + } + items.append( + BackupRestoreItem( + target: target, payload: payload, mode: entry.mode, digest: desired.digest, + before: before, isDatabase: database)) + } + if let registry = geminiRegistry { + try register(registry.target) + guard let desired = try BackupIO.fingerprint(registry.payload) else { + throw ClientBackupError.storageFailure("staging Gemini project registry") + } + items.append( + BackupRestoreItem( + target: registry.target, payload: registry.payload, mode: registry.mode, + digest: desired.digest, before: try observe(registry.target), isDatabase: false)) + } + for (target, payload) in geminiShadowFiles { + try register(target) + guard let desired = try BackupIO.fingerprint(payload) else { + throw ClientBackupError.storageFailure("staging Gemini checkpoint dependency") + } + let before = try observe(target) + if let previous = before.before, previous.digest != desired.digest { + throw ClientBackupError.conflict(target.path) + } + items.append( + BackupRestoreItem( + target: target, payload: payload, mode: 0o600, digest: desired.digest, before: before, + isDatabase: false)) + } + try package.validate() + for item in dependencies.values { try item.validate() } + return BackupRestorePlan( + scratch: scratch, package: package, home: roots.home, client: client, + items: items.sorted { $0.target.path < $1.target.path }, + dependencies: Array(dependencies.values)) + } + + private var originalClaudeLocations: BackupClaudeImports.Locations { + let header = archive.manifest.header + return BackupClaudeImports.Locations( + home: URL(fileURLWithPath: header.sourceHome), + client: URL(fileURLWithPath: header.sourceClient), + projects: Dictionary( + uniqueKeysWithValues: header.projects.map { ($0, URL(fileURLWithPath: $0)) })) + } + + private func prepareClaudeImports(_ payloads: [Int64: URL]) throws { + var available: [BackupClaudeImports.File: URL] = [:] + var imported = Set() + for entry in archive.manifest.entries { + let file = BackupClaudeImports.File(root: entry.root, path: entry.path) + guard let payload = payloads[entry.number], + available.updateValue(payload, forKey: file) == nil + else { throw ClientBackupError.invalidPackage } + if entry.root.hasPrefix(BackupClaudeImports.archivePrefix) { imported.insert(file) } + } + let entries = available.keys.filter { + BackupClaudeImports.isEntry($0, projects: roots.projects) + } + // Earlier packages may contain native instruction files without the added dependency records. + // Validate the graph whenever the package claims imported resources. + if imported.isEmpty { + claudeInstructions = Set(entries) + return + } + claudeInstructions = try BackupClaudeImports.closure( + entries: entries, locations: originalClaudeLocations + ) { key in + try available[key].map { try Data(contentsOf: $0) } + } + guard imported.isSubset(of: claudeInstructions) else { throw ClientBackupError.invalidPackage } + } + + private func installedSkillLink( + for entry: BackupEntry, client: BackupClient, manifestPaths: [String: Int64] + ) throws -> BackupPathFence? { + guard + let unit = BackupScope.skillUnit( + client, root: entry.root, project: roots.projects[entry.root] != nil, path: entry.path), + entry.path.hasPrefix(unit + "/"), + let manifest = manifestPaths[entry.root + "\0" + unit + "/SKILL.md"] + else { return nil } + let target = try roots.url(entry.root).appendingPathComponent(unit) + if let existing = dependencies[target] { return existing.link == nil ? nil : existing } + guard let parent = try BackupIO.directory(target.deletingLastPathComponent()), + let info = try parent.info(target.lastPathComponent), info.st_mode & S_IFMT == S_IFLNK + else { return nil } + let bytes = try staging.read("entry-" + String(manifest), maximumBytes: 1024 * 1024) + guard BackupScope.isSkillManifest(bytes) else { throw ClientBackupError.conflict(target.path) } + let fence = try BackupPathFence.captureLink(target) + dependencies[target] = fence + return fence + } + + private func observe(_ url: URL) throws -> BackupPathFence { + if let before = dependencies[url] { return before } + let before = try BackupPathFence.capture(url) + dependencies[url] = before + return before + } + + private func existing(_ url: URL, before: BackupPathFence) throws -> URL? { + guard let prior = before.before else { return nil } + let name = "existing-" + UUID().uuidString + guard try BackupIO.copy(url, to: staging, named: name) == prior else { + throw ClientBackupError.conflict(url.path) + } + return scratch.path(name) + } + + private func write(_ bytes: Data) throws -> URL { + let name = "derived-" + UUID().uuidString + try BackupIO.write(name, in: staging) { try $0.write(contentsOf: bytes) } + return scratch.path(name) + } + + private func register(_ url: URL, replacingLink: URL? = nil) throws { + guard + BackupIO.fold(BackupSQL.absoluteFileURL(url).path) + != BackupIO.fold(BackupSQL.absoluteFileURL(package.target).path) + else { + throw ClientBackupError.conflict(url.path) + } + let parts = url.pathComponents.dropFirst() + var parent = URL(fileURLWithPath: "/", isDirectory: true) + for name in parts { + let next = parent.appendingPathComponent(name) + let key = BackupIO.fold(next.path) + if let previous = targets[key], previous != next.path { + throw ClientBackupError.conflict(url.path) + } + targets[key] = next.path + let belowLink = + replacingLink.map { parent.path == $0.path || parent.path.hasPrefix($0.path + "/") } + ?? false + if !belowLink && occupiedNames[parent] == nil { + var index: [String: String] = [:] + if let directory = try BackupIO.directory(parent) { + for existing in try directory.names() { + let folded = BackupIO.fold(existing) + if let prior = index[folded], prior != existing { + index[folded] = "" + } else { + index[folded] = existing + } + } + } + occupiedNames[parent] = index + } + if let existing = occupiedNames[parent]?[BackupIO.fold(name)], existing != name { + throw ClientBackupError.conflict(url.path) + } + parent = next + } + let physical = BackupIO.fold(BackupSQL.absoluteFileURL(url).path) + guard targets.updateValue(url.path, forKey: "file:" + physical) == nil + else { throw ClientBackupError.conflict(url.path) } + } + + private func destination(_ entry: BackupEntry, client: BackupClient) throws -> URL { + var components = try BackupIO.components(entry.path) + if client == .claudeCode, entry.root == "client", components.first == "projects", + components.count >= 3, let target = claudeKeys[components[1]] + { + components[1] = target + } + if client == .geminiCLI, entry.root == "runtime", components.count >= 3, + ["tmp", "history"].contains(components[0]), let target = geminiKeys[components[1]] + { + components[1] = target + } + return try roots.url(entry.root).appendingPathComponent(components.joined(separator: "/")) + } + + private func transform( + _ entry: BackupEntry, client: BackupClient, incoming: URL, target: URL, before: BackupPathFence + ) throws -> URL { + if client == .codex, entry.root == "client", entry.path == "config.toml", + let config = try BackupCodexConfig.relocated( + incoming, sourceHome: archive.manifest.header.sourceHome, + sourceDatabase: archive.manifest.header.sourceDatabase, destination: roots.database, + preserveDestinationSetting: roots.configuredCodexDatabase) + { + return try write(config) + } + if entry.root == "database" { + let old = try existing(target, before: before) + return try BackupNativeDatabase.adapt( + incoming, destination: old, name: entry.path, using: mapping, rolloutOffsets: rolloutOffsets + ) + } + if client == .claudeCode { + let file = BackupClaudeImports.File(root: entry.root, path: entry.path) + if claudeInstructions.contains(file), + let relocated = try BackupClaudeImports.relocated( + Data(contentsOf: incoming), file: file, source: originalClaudeLocations, + destination: .init(home: roots.home, client: roots.client, projects: roots.projects)) + { + return try write(relocated) + } + } + if client == .claudeCode, entry.root == "profile" { + return try claudeProfile(incoming, old: existing(target, before: before)) + } + if client == .claudeCode, entry.root == "client", entry.path.hasPrefix("projects/"), + entry.path.hasSuffix("/sessions-index.json") + { + return try claudeIndex(incoming, old: existing(target, before: before)) + } + if client == .geminiCLI, entry.root == "runtime" { + if entry.path.hasSuffix("/.project_root") { return try geminiMarker(incoming) } + let parts = try BackupIO.components(entry.path) + if BackupGeminiCheckpoints.isRecord(parts) { + return try geminiCheckpoint(incoming, commit: geminiCheckpointCommits[entry.number]) + } + if parts.count >= 4, parts[0] == "tmp", parts[2] == "chats", + let original = geminiOriginals[parts[1]], mapping.projectPath(original) != original + { + return try geminiChat(incoming, path: entry.path, original: original) + } + if entry.path.hasSuffix("/logs.json"), let old = try existing(target, before: before), + before.before?.digest != entry.digest + { + return try geminiLogs(incoming, old: old) + } + } + let index = client == .codex && entry.root == "client" && entry.path == "session_index.jsonl" + let history = entry.root == "client" && entry.path == "history.jsonl" + let changedProject = roots.projects.contains { $0.key != $0.value.path } + let changedHome = archive.manifest.header.sourceClient != roots.client.path + if index || history, let old = try existing(target, before: before), + before.before?.digest != entry.digest || changedProject || changedHome + { + let name = "merged-" + UUID().uuidString + try BackupIO.write(name, in: staging) { + try BackupJSONL.merge( + incoming: incoming, existing: old, to: $0, index: index, mapping: mapping) + } + return scratch.path(name) + } + let isRollout = + client == .codex && entry.root == "client" + && (entry.path.hasPrefix("sessions/") || entry.path.hasPrefix("archived_sessions/")) + if isRollout, entry.path.hasSuffix(".jsonl.zst"), changedProject { + guard let zstd = BackupZstd.executable(path: roots.zstdPath) else { + throw ClientBackupError.unsupportedLayout("zstd is required to relocate Codex rollouts") + } + let plain = "uncompressed-" + UUID().uuidString + try BackupIO.write(plain, in: staging) { + try BackupZstd.transcode(incoming, into: $0, using: zstd, decode: true) + } + let relocated = try relocateLines(scratch.path(plain), isRollout: true) + if relocated.path == scratch.path(plain).path { + try staging.remove(plain) + return incoming + } + let encoded = "compressed-" + UUID().uuidString + try BackupIO.write(encoded, in: staging) { + try BackupZstd.transcode(relocated, into: $0, using: zstd, decode: false) + } + try staging.remove(plain) + try staging.remove(relocated.lastPathComponent) + return scratch.path(encoded) + } + if entry.root == "client", entry.path.hasSuffix(".jsonl"), changedProject || changedHome { + return try relocateLines(incoming, isRollout: isRollout) + } + return incoming + } + + private func relocateLines(_ incoming: URL, isRollout: Bool) throws -> URL { + let name = "relocated-" + UUID().uuidString + var offsets = BackupRolloutOffsets() + try BackupIO.write(name, in: staging) { + offsets = try BackupJSONL.remap(incoming, to: $0) { + BackupNativeJSON.pathFields($0, using: mapping) + } + } + if offsets.edits.isEmpty { + try staging.remove(name) + return incoming + } + if isRollout, + archive.manifest.entries.contains(where: { + $0.root == "database" && $0.path.hasPrefix("thread_history_") + }) + { + guard let id = offsets.thread, rolloutOffsets.updateValue(offsets, forKey: id) == nil else { + throw ClientBackupError.unsupportedLayout("Codex rollout identity") + } + } + return scratch.path(name) + } + +} + +extension BackupRestorePlanner { + private func prepareGemini(_ payloads: [Int64: URL]) throws { + let entries = archive.manifest.entries.filter { $0.root == "runtime" } + guard !entries.isEmpty else { return } + let source = entries.first { $0.path == "projects.json" } + let sourceRegistry = try source.flatMap { payloads[$0.number] }.map(BackupNativeJSON.object) + let target = roots.runtime.appendingPathComponent("projects.json") + let before = try observe(target) + let old = try existing(target, before: before) + let currentRegistry = try old.map(BackupNativeJSON.object) + let archived = try geminiProjects(sourceRegistry) + var merged = try geminiProjects(currentRegistry) + var originals: [String: String] = [:] + for (path, key) in archived { + guard originals.updateValue(path, forKey: key) == nil else { + throw ClientBackupError.conflict("Gemini project registry") + } + } + for entry in entries where entry.path.hasSuffix("/.project_root") { + let parts = try BackupIO.components(entry.path) + guard parts.count == 3, ["tmp", "history"].contains(parts[0]), + let payload = payloads[entry.number] + else { throw ClientBackupError.invalidPackage } + let path = try markerPath(payload) + if let prior = originals[parts[1]], prior != path { + throw ClientBackupError.conflict(entry.path) + } + originals[parts[1]] = path + } + let storageKeys = Set( + try entries.compactMap { entry -> String? in + let parts = try BackupIO.components(entry.path) + return parts.count >= 3 && ["tmp", "history"].contains(parts[0]) ? parts[1] : nil + }) + for path in roots.projects.keys { + let legacy = FileHash.sha256Hex(data: Data(path.utf8)) + if storageKeys.contains(legacy) { + if let original = originals[legacy], original != path { + throw ClientBackupError.conflict("Gemini legacy project key") + } + originals[legacy] = path + } + } + for (key, original) in originals.sorted(by: { $0.key < $1.key }) { + let local = mapping.projectPath(original) + let selected = merged[local] ?? key + guard Self.geminiKey(selected), + !merged.contains(where: { $0.key != local && $0.value == selected }) + else { throw ClientBackupError.conflict("Gemini project key " + selected) } + if let marker = try existingGeminiMarker(selected), marker != local { + throw ClientBackupError.conflict("Gemini project key " + selected) + } + merged[local] = selected + geminiKeys[key] = selected + } + for unknown in storageKeys.subtracting(originals.keys) { + if try merged.values.contains(unknown) || existingGeminiMarker(unknown) != nil { + throw ClientBackupError.conflict("Gemini project key " + unknown) + } + } + geminiOriginals = originals + if let source, let original = payloads[source.number], merged == archived { + geminiRegistry = (target, original, source.mode) + } else if merged != (try geminiProjects(currentRegistry)) || source != nil { + var combined = (currentRegistry ?? [:]).merging(sourceRegistry ?? [:]) { _, new in new } + combined["projects"] = merged + geminiRegistry = (target, try write(BackupNativeJSON.encode(combined)), source?.mode ?? 0o600) + } + } + + private static func geminiKey(_ key: String) -> Bool { + !key.isEmpty + && key.utf8.allSatisfy { $0 == 45 || (48...57).contains($0) || (97...122).contains($0) } + } + + private func geminiProjects(_ registry: [String: Any]?) throws -> [String: String] { + guard let registry else { return [:] } + guard let projects = registry["projects"] as? [String: String], + projects.keys.allSatisfy(BackupIO.originalPath), projects.values.allSatisfy(Self.geminiKey), + Set(projects.values).count == projects.count + else { throw ClientBackupError.unsupportedLayout("Gemini projects.json") } + return projects + } + + private func existingGeminiMarker(_ key: String) throws -> String? { + var result: String? + for area in ["tmp", "history"] { + let marker = roots.runtime.appendingPathComponent(area + "/" + key + "/.project_root") + if let old = try existing(marker, before: observe(marker)) { + let path = try markerPath(old) + if let result, result != path { throw ClientBackupError.conflict(marker.path) } + result = path + } + } + return result + } + + private func markerPath(_ url: URL) throws -> String { + let parent = try DirectoryHandle(at: url.deletingLastPathComponent()) + let bytes = try parent.read(url.lastPathComponent, maximumBytes: 64 * 1024) + guard let value = String(data: bytes, encoding: .utf8) else { + throw ClientBackupError.unsupportedLayout("Gemini project marker") + } + let path = value.trimmingCharacters(in: .newlines) + guard BackupIO.originalPath(path) else { + throw ClientBackupError.unsupportedLayout("Gemini project marker") + } + return path + } + + private func geminiMarker(_ incoming: URL) throws -> URL { + let path = try markerPath(incoming) + let local = mapping.projectPath(path) + if path == local { return incoming } + return try write(Data(local.utf8)) + } + + private func prepareGeminiCheckpoints(_ payloads: [Int64: URL]) throws { + var records: [String: [(Int64, String)]] = [:] + var packs: [String: [String: URL]] = [:] + for entry in archive.manifest.entries where entry.root == "runtime" { + let parts = try BackupIO.components(entry.path) + guard let payload = payloads[entry.number] else { throw ClientBackupError.invalidPackage } + if BackupGeminiCheckpoints.isRecord(parts), + let commit = try BackupGeminiCheckpoints.commit(in: payload) + { + records[parts[1], default: []].append((entry.number, commit)) + } + if BackupGeminiCheckpoints.isPack(parts) { + packs[parts[1], default: [:]][parts[5]] = payload + } + } + guard Set(records.keys) == Set(packs.keys) else { + throw ClientBackupError.unsupportedLayout("Gemini checkpoint dependencies") + } + var initialized = Set() + for (key, values) in records.sorted(by: { $0.key < $1.key }) { + guard let files = packs[key] else { throw ClientBackupError.invalidPackage } + let nativeKey = geminiKeys[key] ?? key + let shadow = roots.runtime.appendingPathComponent("history/" + nativeKey + "/.git") + let head = try observe(shadow.appendingPathComponent("HEAD")) + let needsInitialization = head.before == nil && initialized.insert(nativeKey).inserted + let structure: BackupGeminiCheckpoints.Prepared + do { + structure = try BackupGeminiCheckpoints.prepare( + commits: values.map(\.1), packs: files, scratch: staging, + initialize: needsInitialization) + } catch { + throw ClientBackupError.unsupportedLayout(shadow.path) + } + for (id, commit) in values { geminiCheckpointCommits[id] = structure.commits[commit] } + for (path, payload) in structure.initialFiles { + geminiShadowFiles[shadow.appendingPathComponent(path)] = payload + } + for (path, payload) in structure.references { + geminiShadowFiles[shadow.appendingPathComponent(path)] = payload + } + } + } + + private func geminiCheckpoint(_ incoming: URL, commit: String?) throws -> URL { + let name = "gemini-checkpoint-" + UUID().uuidString + var changed = false + try BackupIO.write(name, in: staging) { output in + let json = try BackupJSONStream( + incoming, output: output, + selection: [["commitHash"], ["toolCall", "args", "file_path"]] + ) { path, value in + if path == ["commitHash"] { return commit } + return self.mapping.projectPath(value) + } + try json.process() + changed = json.changed + } + if changed { return scratch.path(name) } + try staging.remove(name) + return incoming + } + + private func geminiChat(_ incoming: URL, path: String, original: String) throws -> URL { + let records = path.hasSuffix(".jsonl") + guard records || path.hasSuffix(".json") else { return incoming } + let oldHash = FileHash.sha256Hex(data: Data(original.utf8)) + let newHash = FileHash.sha256Hex(data: Data(mapping.projectPath(original).utf8)) + let fields = ["projectHash", "directories", "cwd", "projectPath", "originalPath", "rootPath"] + let selected = Set(fields.flatMap { [[$0], ["$set", $0]] }) + let name = "gemini-chat-" + UUID().uuidString + var changed = false + try BackupIO.write(name, in: staging) { output in + let json = try BackupJSONStream(incoming, output: output, selection: selected) { + path, value in + if path.last == "projectHash" { return value == oldHash ? newHash : nil } + return self.mapping.projectPath(value) + } + try json.process(records: records) + changed = json.changed + } + if changed { return scratch.path(name) } + try staging.remove(name) + return incoming + } + + private func geminiLogs(_ incoming: URL, old: URL) throws -> URL { + guard let source = try BackupNativeJSON.value(incoming) as? [[String: Any]], + let destination = try BackupNativeJSON.value(old) as? [[String: Any]] + else { throw ClientBackupError.unsupportedLayout("Gemini logs.json") } + var seen = Set() + var rows: [[String: Any]] = [] + for record in destination + source { + if try seen.insert(BackupNativeJSON.encode(record)).inserted { rows.append(record) } + } + if rows.count == destination.count { return old } + return try write(BackupNativeJSON.encode(rows)) + } + + private func prepareClaude(_ payloads: [Int64: URL]) throws { + let source = archive.manifest.entries.first { + $0.root == "profile" && $0.path == ".claude.json" + } + guard source != nil || !roots.projects.isEmpty else { return } + let profile = try source.flatMap { payloads[$0.number] }.map(BackupNativeJSON.object) + let projectConfig = try claudeProjectConfig(profile) + for path in Array(projectConfig.keys) + Array(roots.projects.keys) { + guard BackupIO.originalPath(path) else { + throw ClientBackupError.unsupportedLayout("Claude Code project path") + } + let key = Self.claudeKey(path) + if let prior = claudeOriginals[key], prior != path { + throw ClientBackupError.conflict("Claude Code project key") + } + claudeOriginals[key] = path + } + var localKeys: [String: String] = [:] + for (key, original) in claudeOriginals { + let local = mapping.projectPath(original) + let resulting = Self.claudeKey(local) + guard localKeys.updateValue(original, forKey: resulting) == nil else { + throw ClientBackupError.conflict("Claude Code project key") + } + if original != local { + claudeKeys[key] = resulting + } + } + let target = roots.profile.appendingPathComponent(".claude.json") + if let old = try existing(target, before: observe(target)) { + for path in try claudeProjectConfig(BackupNativeJSON.object(old)).keys { + if let original = localKeys[Self.claudeKey(path)], mapping.projectPath(original) != path { + throw ClientBackupError.conflict("Claude Code project key") + } + } + } + } + + private static func claudeKey(_ path: String) -> String { + let codeUnits = path.utf16 + let name = String( + decoding: codeUnits.map { unit in + switch unit { + case 48...57, 65...90, 97...122: UInt8(unit) + default: 45 + } + }, as: UTF8.self) + if name.count <= 200 { return name } + // Claude Code hashes the original UTF-16 path with 32-bit overflow. + let hash = codeUnits.reduce(Int32(0)) { ($0 &* 31) &+ Int32($1) } + return String(name.prefix(200)) + "-" + String(Int64(hash).magnitude, radix: 36) + } + + private func claudeProjectConfig(_ profile: [String: Any]?) throws -> [String: Any] { + guard let projects = profile?["projects"] else { return [:] } + guard let values = projects as? [String: Any] else { + throw ClientBackupError.unsupportedLayout("Claude Code .claude.json projects") + } + return values + } + + private func claudeProfile(_ incoming: URL, old: URL?) throws -> URL { + var source = try BackupNativeJSON.object(incoming) + let projects = try claudeProjectConfig(source) + let relocated = projects.keys.contains { mapping.projectPath($0) != $0 } + if relocated { + source["projects"] = try BackupNativeJSON.remappedRecords(projects, using: mapping) + } + if let old { + let current = try BackupNativeJSON.object(old) + let merged = try BackupNativeJSON.mergeMaps( + source, into: current, keys: ["projects", "mcpServers"]) + let bytes = try BackupNativeJSON.encode(merged) + if bytes == (try BackupNativeJSON.encode(source)), !relocated { return incoming } + if bytes == (try BackupNativeJSON.encode(current)) { return old } + return try write(bytes) + } + return relocated ? try write(BackupNativeJSON.encode(source)) : incoming + } + + private func claudeIndex(_ incoming: URL, old: URL?) throws -> URL { + var source = try BackupNativeJSON.object(incoming) + guard let entries = source["entries"] as? [[String: Any]] else { + throw ClientBackupError.unsupportedLayout("Claude Code sessions-index.json") + } + var seen = Set() + var changed = false + var result: [[String: Any]] = [] + for entry in entries { + guard let id = entry["sessionId"] as? String, seen.insert(id).inserted else { + throw ClientBackupError.unsupportedLayout("Claude Code session index") + } + var mapped = BackupNativeJSON.pathFields(entry, using: mapping) + if let fullPath = mapped.value["fullPath"] as? String { + let prefix = roots.client.path + "/projects/" + if fullPath.hasPrefix(prefix) { + let path = fullPath.dropFirst(prefix.count) + if let separator = path.firstIndex(of: "/"), + let key = claudeKeys[String(path[.. Self { + func values(_ key: String, _ parse: (String) -> T?) throws -> [T]? { + guard let names = fields[key] else { return nil } + return try names.map { + guard let value = parse($0) else { + throw CoreError.invalidSource("invalid producer \(key) value: \($0)") + } + return value + } + } + return try Self( + agents: values("agents", AgentID.init(rawValue:)), + scopes: values("scopes", InstallScope.init(rawValue:)), + platforms: values("platforms", DeclarationPlatform.init(rawValue:))) + } + + package func matches(scope: InstallScope, platform: DeclarationPlatform) -> Bool { + (scopes?.contains(scope) ?? true) && (platforms?.contains(platform) ?? true) + } + + package func intersecting(_ other: Self) -> Self { + func intersection(_ lhs: [T]?, _ rhs: [T]?) -> [T]? { + guard let lhs else { return rhs } + guard let rhs else { return lhs } + return lhs.filter { rhs.contains($0) } + } + return Self( + agents: intersection(agents, other.agents), + scopes: intersection(scopes, other.scopes), + platforms: intersection(platforms, other.platforms)) + } + + package func recipients( + requested: [AgentID], scope: InstallScope, platform: DeclarationPlatform + ) -> Set { + guard matches(scope: scope, platform: platform) else { return [] } + return Set(requested.filter { agents?.contains($0) ?? true }) + } +} diff --git a/Sources/AgentsCore/ComponentDeclaration.swift b/Sources/AgentsCore/ComponentDeclaration.swift new file mode 100644 index 0000000..3887601 --- /dev/null +++ b/Sources/AgentsCore/ComponentDeclaration.swift @@ -0,0 +1,350 @@ +import Foundation + +/// Directories in which a source alias was declared. Linking must not reinterpret relative +/// paths using the importing document's directories. Process environment values are not captured. +public struct SourceEnvironment: Equatable, Sendable { + public var projectDirectory: URL + public var homeDirectory: URL + + public init(projectDirectory: URL, homeDirectory: URL) { + self.projectDirectory = projectDirectory.standardizedFileURL + self.homeDirectory = homeDirectory.standardizedFileURL + } + + /// URL directory hints do not change the declaring directory's identity. + public static func == (lhs: SourceEnvironment, rhs: SourceEnvironment) -> Bool { + lhs.projectDirectory.standardizedFileURL.path == rhs.projectDirectory.standardizedFileURL.path + && lhs.homeDirectory.standardizedFileURL.path == rhs.homeDirectory.standardizedFileURL.path + } + + package var runtime: RuntimeEnvironment { + RuntimeEnvironment( + projectDirectory: projectDirectory, homeDirectory: homeDirectory, environment: [:], + sourceAccess: .init()) + } +} + +public struct NamedSourceDeclaration: Equatable, Sendable { + public var name: String + public var source: SourceDeclaration + + public init(name: String, source: SourceDeclaration) { + self.name = name + self.source = source + } +} + +public enum DeclarationPlatform: String, Equatable, Sendable { + case macOS = "macos" + case linux +} + +/// Omitted dimensions impose no restriction; an explicit empty dimension matches nothing. +public struct DeclarationCondition: Equatable, Sendable { + public var agents: [AgentID]? + public var scopes: [InstallScope]? + public var platforms: [DeclarationPlatform]? + + public init( + agents: [AgentID]? = nil, scopes: [InstallScope]? = nil, platforms: [DeclarationPlatform]? = nil + ) { + self.agents = agents + self.scopes = scopes + self.platforms = platforms + } +} + +/// Values remain symbolic until binding at the consuming operation. +public enum RuntimeBinding: Equatable, Sendable { + case literal(String) + case environment(String) + case secret(String) +} + +public indirect enum NativeValue: Equatable, Sendable { + case string(String) + case integer(Int) + case decimal(String) + case boolean(Bool) + case null + case array([NativeValue]) + case object([String: NativeValue]) +} + +public typealias NativeConfiguration = [String: [String: NativeValue]] + +public struct ResourceDeclaration: Equatable, Sendable { + public var path: String + public var source: String? + + public init(path: String, source: String? = nil) { + self.path = path + self.source = source + } +} + +public enum PromptBody: Equatable, Sendable { + case literal(String) + case file(ResourceDeclaration) +} + +public struct ExecutableDeclaration: Equatable, Sendable { + public var executable: String + /// Source alias for a resource executable; nil uses the declaring source. + public var executableSource: String? + public var arguments: [String] + public var environment: [String: RuntimeBinding] + public var workingDirectory: ResourceDeclaration? + + public init( + executable: String, executableSource: String? = nil, arguments: [String] = [], + environment: [String: RuntimeBinding] = [:], + workingDirectory: ResourceDeclaration? = nil + ) { + self.executable = executable + self.executableSource = executableSource + self.arguments = arguments + self.environment = environment + self.workingDirectory = workingDirectory + } +} + +public enum MCPTransportDeclaration: Equatable, Sendable { + case stdio(ExecutableDeclaration) + case streamableHTTP(url: String, headers: [String: RuntimeBinding] = [:]) + case sse(url: String, headers: [String: RuntimeBinding] = [:]) +} + +public enum HookEventDeclaration: Equatable, Sendable { + case beforeTool + case afterTool + case sessionStart + case sessionEnd + case native(String) +} + +public struct PromptParameterDeclaration: Equatable, Sendable { + public var name: String + public var description: String + public var defaultValue: String? + + public init(name: String, description: String, defaultValue: String? = nil) { + self.name = name + self.description = description + self.defaultValue = defaultValue + } +} + +public enum PermissionOperationDeclaration: Equatable, Sendable { + case read + case write + case execute + case tool(String) +} + +public enum PermissionRuleDeclaration: Equatable, Sendable { + case allow(PermissionOperationDeclaration, String) + case ask(PermissionOperationDeclaration, String) + case deny(PermissionOperationDeclaration, String) +} + +public enum IgnorePurposeDeclaration: String, Equatable, Sendable { + case context + case indexing +} + +public enum PluginModeDeclaration: String, Equatable, Sendable { + case native + case components +} + +public enum DeclaredComponentKind: String, CaseIterable, Codable, Hashable, Sendable { + case skills, instructions, mcpServer, hook, subagent, command, lspServer, permissions, ignore, + plugin +} + +public enum ComponentReferenceDeclaration: Equatable, Sendable { + case skill(name: String) + case instruction(name: String) + case mcpServer(name: String) + case hook(name: String) + case subagent(name: String) + case command(name: String) + case lspServer(name: String) + case permissions(name: String) + case ignore(name: String) + case plugin(name: String) +} + +public enum InstructionRecipient: RawRepresentable, Codable, Hashable, Sendable { + case local(AgentID) + case chatGPTApp + case geminiApp + + public init?(rawValue: String) { + switch rawValue { + case "chatgpt-app": self = .chatGPTApp + case "gemini-app": self = .geminiApp + default: + guard let agent = AgentID(rawValue: rawValue) else { return nil } + self = .local(agent) + } + } + + public var rawValue: String { + switch self { + case .local(let agent): agent.rawValue + case .chatGPTApp: "chatgpt-app" + case .geminiApp: "gemini-app" + } + } + + public var displayName: String { + switch self { + case .local(let agent): agent.displayName + case .chatGPTApp: "ChatGPT App" + case .geminiApp: "Gemini App" + } + } + + package var localAgent: AgentID? { + if case .local(let agent) = self { return agent } + return nil + } +} + +public struct SectionDeclaration: Equatable, Sendable { + public var name: String + public var source: String? + public var condition: DeclarationCondition? + /// An exhaustive selection. Nil inherits the component's local recipients. + public var recipients: [InstructionRecipient]? + + public init( + name: String, source: String? = nil, condition: DeclarationCondition? = nil, + recipients: [InstructionRecipient]? = nil + ) { + self.name = name + self.source = source + self.condition = condition + self.recipients = recipients + } + + public init(reference: String) { + if let colon = reference.firstIndex(of: ":") { + self.init( + name: String(reference[reference.index(after: colon)...]), + source: String(reference[.. EntryKind? { + guard let value = try directory.info(name) else { return nil } + switch value.st_mode & S_IFMT { + case S_IFDIR: return .directory + case S_IFREG: return .regular + case S_IFLNK: return .symbolicLink + default: return .other + } + } + + package static func link(_ name: String, in directory: DirectoryHandle) throws -> String { + let bytes = try directory.readLinkData(name) + guard let link = String(data: bytes, encoding: .utf8) else { + throw CoreError.unsafePath("invalid prompt link") + } + return link + } + + package static func readPrompt( + _ name: String, in parent: DirectoryHandle, maximumBytes: Int + ) throws -> Data { + guard let info = try parent.info(name), info.st_mode & S_IFMT == S_IFREG, info.st_nlink == 1 + else { + throw CoreError.unsafePath("expected a regular, unshared prompt") + } + return try parent.read(name, matching: info, maximumBytes: maximumBytes) + } + + package struct FileIdentity: Sendable { + fileprivate let parent: FileObjectIdentity + fileprivate let file: FileObjectIdentity + } + + package static func readEditable( + _ name: String, in parent: DirectoryHandle, maximumBytes: Int + ) throws -> (Data, FileIdentity) { + guard let info = try parent.info(name), info.st_mode & S_IFMT == S_IFREG, + info.st_nlink == 1, info.st_mode & 0o7111 == 0 + else { throw CoreError.unsafePath("strip requires a regular, non-executable, unshared file") } + let bytes = try parent.read(name, matching: info, maximumBytes: maximumBytes) + return (bytes, try .init(parent: parent.objectIdentity, file: FileObjectIdentity(info))) + } + + /// Stage on the same volume, preserve metadata and verify the displaced preimage. + /// Keep the staging directory if concurrent changes prevent a safe rollback. + package static func applyReviewedEdit( + _ url: URL, before: Data, after: Data, identity: FileIdentity + ) throws { + let parentURL = url.deletingLastPathComponent() + let parent = try DirectoryHandle(at: parentURL) + let name = url.lastPathComponent + guard try parent.objectIdentity == identity.parent, + let original = try parent.info(name), original.st_mode & S_IFMT == S_IFREG, + original.st_nlink == 1, original.st_mode & 0o7111 == 0, + FileObjectIdentity(original) == identity.file, + try parent.read(name, matching: original, maximumBytes: before.count) == before + else { throw CoreError.invalidState("prompt changed since strip preview") } + + try FileSystem.requireAccess(R_OK | W_OK, at: url, parent: parent.descriptor) + let staging = ".agents-audit-" + UUID().uuidString + let stage = try parent.makeDirectory(staging) + let stageIdentity = try stage.objectIdentity + var disposable = true + defer { + if disposable { try? parent.remove(staging, identity: stageIdentity) } + } + let payload = "prompt" + try stage.write( + payload, data: after, preservingMetadataOf: name, originalParent: parent) + guard let staged = try stage.info(payload), + let current = try parent.info(name), DirectoryHandle.sameGeneration(original, current), + try DirectoryHandle(at: parentURL).objectIdentity == identity.parent + else { throw CoreError.invalidState("prompt changed since strip preview") } + let replacement = FileObjectIdentity(staged) + try stage.atomicRename(payload, to: parent, named: name, mode: .exchange) + .requireSuccess("apply reviewed prompt edit") + disposable = false + + do { + guard let displaced = try stage.info(payload), displaced.st_mode & S_IFMT == S_IFREG, + displaced.st_nlink == 1, FileObjectIdentity(displaced) == identity.file, + try stage.read(payload, matching: displaced, maximumBytes: before.count) == before, + try parent.info(name).map(FileObjectIdentity.init) == replacement, + try DirectoryHandle(at: parentURL).objectIdentity == identity.parent + else { throw CoreError.invalidState("prompt changed during publication") } + } catch { + guard let published = try? parent.info(name), FileObjectIdentity(published) == replacement, + (try? parent.read(name, matching: published, maximumBytes: after.count)) == after, + (try? stage.info(payload)) != nil, + (try? stage.atomicRename(payload, to: parent, named: name, mode: .exchange) + .requireSuccess("restore original prompt")) != nil + else { + throw CoreError.invalidState( + "concurrent prompt change; original retained at " + stage.url.path) + } + try syncPublication(parent: parent, stage: stage) + disposable = true + throw error + } + try syncPublication(parent: parent, stage: stage) + do { + try parent.remove(staging, identity: stageIdentity) + } catch { + throw CoreError.invalidState( + "prompt published; staging cleanup incomplete at " + stage.url.path) + } + } + + private static func syncPublication(parent: DirectoryHandle, stage: DirectoryHandle) throws { + do { + try stage.sync() + try parent.sync() + } catch { + throw CoreError.invalidState("prompt publication sync failed; inspect " + stage.url.path) + } + } +} + +extension StateStore { + /// Read the ledger under the existing scope lock, pinned to the caller's admitted root. + /// Journals can refer to other loaders, so pending recovery stops this local inspection. + package func withContentAuditLedger( + root: DirectoryHandle, _ body: (ResolvedLedger?) throws -> Result + ) throws -> Result { + guard !TransactionLockContext.isHeld else { + throw CoreError.invalidState("nested scope lock acquisition") + } + let folder = directory.lastPathComponent + func validateRoot() throws { + guard try DirectoryHandle(at: root.url).objectIdentity == root.objectIdentity else { + throw CoreError.invalidState("selected audit root changed") + } + } + while true { + guard let state = try root.directory(folder) else { + let result = try body(ResolvedLedger()) + if try root.info(folder) != nil { continue } + try validateRoot() + return result + } + let lock = ".agents.lock" + let descriptor = openat( + state.descriptor, lock, O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC) + guard descriptor >= 0 || errno == ENOENT else { + throw CoreError.unsafePath("cannot open content audit scope lock") + } + defer { if descriptor >= 0 { close(descriptor) } } + if descriptor >= 0 { + var info = stat() + guard fstat(descriptor, &info) == 0, info.st_mode & S_IFMT == S_IFREG else { + throw CoreError.unsafePath("expected a regular content audit scope lock") + } + while platform_flock(descriptor, LOCK_SH) != 0 { + if errno != EINTR { throw CoreError.invalidState("cannot acquire content audit lock") } + } + guard try state.info(lock).map(FileObjectIdentity.init) == FileObjectIdentity(info) else { + throw CoreError.invalidState("content audit scope lock changed") + } + } + guard try !TransactionJournal.isPresent(in: state), + try state.info("watch-refs.pending") == nil + else { + throw CoreError.recoveryPending("content audit scope has pending recovery") + } + var ledger: ResolvedLedger? = ResolvedLedger() + if try state.info(Self.resolvedFileName) != nil { + ledger = try? ResolvedLedgerCodec.decode( + ContentAuditFiles.readPrompt( + Self.resolvedFileName, in: state, maximumBytes: LedgerLimits.standard.encodedBytes), + limits: .standard) + } + let result = try body(ledger) + if descriptor < 0, try state.info(lock) != nil { continue } + guard try root.info(folder).map(FileObjectIdentity.init) == state.objectIdentity else { + throw CoreError.invalidState("content audit state directory changed") + } + try validateRoot() + return result + } + } + + /// Resolves only the lexical location recorded for a scope-compatible deployment. + /// The audit admits each resulting path against its own prompt profile before opening it. + package func contentAuditLocation(_ location: LedgerLocation) throws -> URL? { + guard location.kind == .registered, let key = location.root else { return nil } + let root: URL? + if key == "project", scope == .project { + root = environment.projectDirectory + } else if key == InstructionLocations.ruleRoot(in: scope) { + root = InstructionLocations.antigravityAuthority(environment, scope: scope).logicalDirectory + } else if key.hasPrefix("skills-"), let agent = AgentID(rawValue: String(key.dropFirst(7))), + agent.supportsSkills + { + root = AgentRegistry.installSkillsDirectory( + for: agent, scope: scope, environment: environment) + } else if key.hasPrefix("instructions-"), + let agent = AgentID(rawValue: String(key.dropFirst("instructions-".count))) + { + root = InstructionLocations.file(for: agent, scope: scope, environment: environment)? + .deletingLastPathComponent() + } else if let route = NativeTargetRoute.targetRoute(key), route.permits(scope), + location.path.utf8.elementsEqual(route.basename.utf8) + { + root = try route.rootAuthority(environment, validateExistingOverride: false).logicalDirectory + } else { + root = nil + } + guard let root else { return nil } + try location.validate() + return root.appendingPathComponent(location.path).standardizedFileURL + } +} diff --git a/Sources/AgentsCore/CoreError.swift b/Sources/AgentsCore/CoreError.swift index ad53c5a..fbe3c09 100644 --- a/Sources/AgentsCore/CoreError.swift +++ b/Sources/AgentsCore/CoreError.swift @@ -10,6 +10,10 @@ public enum CoreError: Error, CustomStringConvertible, Equatable { case commandFailed(String) /// Recovery completed; retry the operation against the recovered state. case transactionRecovered(String) + /// Inspection found an interrupted transaction; a command that changes the scope recovers it. + case recoveryPending(String) + /// The scope has lock or watch state but no declaration at the given path. + case missingDeclaration(String) public var description: String { switch self { @@ -27,6 +31,12 @@ public enum CoreError: Error, CustomStringConvertible, Equatable { return "Invalid state: \(message)" case .transactionRecovered(let path): return "Recovered interrupted transaction at \(path); retry the command" + case .recoveryPending(let message): + return message + case .missingDeclaration(let path): + return + "Missing declaration at \(path): the scope has lock or watch state; restore the file " + + "from version control, or remove the scope's state files to start again" case .commandFailed(let message): return "Command failed: \(message)" } diff --git a/Sources/AgentsCore/Declaration.swift b/Sources/AgentsCore/Declaration.swift index ee78408..2e6536c 100644 --- a/Sources/AgentsCore/Declaration.swift +++ b/Sources/AgentsCore/Declaration.swift @@ -6,49 +6,23 @@ public enum SourceKind: String, Codable, Sendable { case wellKnown = "well-known" } -/// A source alias's location, requirement and discovery root in agents.json. -public struct SourceDeclaration: Codable, Equatable, Sendable { +/// A source alias's location, requirement and discovery root. +public struct SourceDeclaration: Equatable, Sendable { public var kind: SourceKind public var location: String public var requirement: SourceRequirement? public var path: String? + public var environment: SourceEnvironment? public init( - kind: SourceKind, location: String, requirement: SourceRequirement? = nil, path: String? = nil + kind: SourceKind, location: String, requirement: SourceRequirement? = nil, path: String? = nil, + environment: SourceEnvironment? = nil ) { self.kind = kind self.location = location self.requirement = requirement self.path = path - } - - private enum CodingKeys: String, CodingKey { - case git, local - case wellKnown = "well-known" - case path - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - let kinds: [(CodingKeys, SourceKind)] = [ - (.git, .git), (.local, .local), (.wellKnown, .wellKnown), - ] - let present = kinds.filter { container.contains($0.0) } - guard present.count == 1, let (key, kind) = present.first else { - throw CoreError.invalidState("a source must specify exactly one of git, local or well-known") - } - self.kind = kind - location = try container.decode(String.self, forKey: key) - path = try container.decodeIfPresent(String.self, forKey: .path) - requirement = try SourceRequirement.decodeIfPresent(from: decoder) - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - let key: CodingKeys = kind == .git ? .git : (kind == .local ? .local : .wellKnown) - try container.encode(location, forKey: key) - try container.encodeIfPresent(path, forKey: .path) - try requirement?.encode(to: encoder) + self.environment = environment } public func identity(environment: RuntimeEnvironment) throws -> String { @@ -56,6 +30,16 @@ public struct SourceDeclaration: Codable, Equatable, Sendable { switch kind { case .local: return "local:" + localURL(environment: environment).path + case .wellKnown, .git: + return try transportIdentity() + } + } + + /// Normalizes a transport location without a runtime filesystem context. + package func transportIdentity() throws -> String { + guard !location.isEmpty else { throw CoreError.invalidSource("empty source location") } + switch kind { + case .local: throw CoreError.invalidSource("local identity requires a package root") case .wellKnown: guard let components = URLComponents(string: location), ["http", "https"].contains(components.scheme), components.host != nil, @@ -84,6 +68,7 @@ public struct SourceDeclaration: Codable, Equatable, Sendable { } package func localURL(environment: RuntimeEnvironment) -> URL { + let environment = self.environment.map { $0.runtime } ?? environment let expanded = location == "~" ? environment.homeDirectory.path @@ -98,33 +83,20 @@ public struct SourceDeclaration: Codable, Equatable, Sendable { } package var gitURL: String { - location.contains("://") || location.contains("@") ? location : "https://" + location + if location.contains("://") { return location } + if let colon = location.firstIndex(of: ":"), location[.. Void) + throws + { + var selections = try skills + try change(&selections) + try setSkills(selections) + } + + public var instructions: InstructionsDeclaration? { + get throws { + let values = components.compactMap { component -> InstructionsDeclaration? in + if case .instructions(let value) = component { return value } + return nil + } + guard values.count <= 1 else { + throw CoreError.invalidState("ambiguous instructions occurrence") + } + return values.first + } + } + + public mutating func setInstructions(_ value: InstructionsDeclaration?) throws { + _ = try instructions + if let index = components.firstIndex(where: { + if case .instructions = $0 { return true } + return false + }) { + if let value { + components[index] = .instructions(value) + } else { + components.remove(at: index) + } + } else if let value { + components.append(.instructions(value)) + } + } + + public mutating func updateInstructions(_ change: (inout InstructionsDeclaration?) throws -> Void) + throws + { + var value = try instructions + try change(&value) + try setInstructions(value) + } + public func validate(environment: RuntimeEnvironment) throws { - var identities = Set() - for (alias, source) in sources { - guard !alias.isEmpty, !alias.contains(":") else { - throw CoreError.invalidState("invalid source alias: \(alias)") + if let lifecycle, let issue = LifecycleDeclaration(lifecycle).issues.first { + throw CoreError.invalidState("Invalid lifecycle declaration: " + issue.message) + } + var dependencyNames = Set() + for dependency in packages { + try dependency.validate() + guard dependencyNames.insert(dependency.name).inserted else { + throw MarketplaceError.invalidPackage("duplicate dependency: " + dependency.name) } - guard try identities.insert(source.identity(environment: environment)).inserted else { - throw CoreError.invalidState("two source aliases normalize to the same source ID") + } + for root in marketplaceRoots { + try root.validate() + guard dependencyNames.insert(root.name).inserted else { + throw MarketplaceError.invalidPackage("duplicate dependency: " + root.name) + } + } + var aliases = Set() + var sourceRoots = Set<[String]>() + for entry in sourceDeclarations { + let (alias, source) = (entry.name, entry.source) + guard !alias.isEmpty, alias != ".", !alias.contains(":"), aliases.insert(alias).inserted + else { + throw CoreError.invalidState("invalid or duplicate source alias: \(alias)") + } + let identity = try source.identity(environment: environment) + let root = try PathSafety.sanitizeSubpath(source.path ?? ".") + guard sourceRoots.insert([identity, source.kind == .wellKnown ? "." : root]).inserted else { + throw CoreError.invalidState( + "two source aliases normalize to the same source and discovery root") } try source.requirement?.validate() - if let path = source.path { _ = try PathSafety.sanitizeSubpath(path) } if source.kind == .wellKnown, source.requirement != nil { throw CoreError.invalidState("well-known sources take no Git requirement") } } - for (alias, selection) in skills ?? [:] { - guard let source = sources[alias] else { - throw CoreError.invalidState("unknown source alias: \(alias)") + for component in components + groups.flatMap(\.components) { + switch component { + case .skills(let alias, let selection): + guard alias == "." || sources[alias] != nil else { + throw CoreError.invalidState("unknown source alias: \(alias)") + } + let source = sources[alias] + if let path = selection.path { + _ = try PathSafety.sanitizeSubpath(path) + guard source?.kind != .wellKnown else { + throw CoreError.invalidState("skill paths require a filesystem source") + } + } + let modes = + [selection.mode ?? .link] + selection.overrideDeclarations.compactMap { $0.override.mode } + if modes.contains(.edit), alias != ".", source?.kind != .local || source?.requirement != nil + { + throw CoreError.invalidState("edit requires a local source with no requirement") + } + if case .names(let names) = selection.select { try Self.validateNames(names) } + try Self.validateNames(selection.exclude ?? []) + try Self.validateNames(selection.overrideDeclarations.map(\.name)) + case .instructions(let instructions): + for section in instructions.sectionReferences + + instructions.prompts.flatMap({ $0.prompt.sectionReferences }) + { + guard Self.isInstructionName(section.name), + section.source == nil || section.source == "." || sources[section.source!] != nil + else { + throw CoreError.invalidState("invalid section reference: \(section.reference)") + } + } + for entry in instructions.prompts { + if let append = entry.prompt.append { _ = try PathSafety.sanitizeSubpath(append) } + } + case .mcpServer(_, let transport, _, _, _, let registry): + try registry?.validate(matching: transport) + default: break } - var modes = [selection.mode ?? .link] - modes += (selection.overrides ?? [:]).values.compactMap(\.mode) - if modes.contains(.edit), source.kind != .local || source.requirement != nil { - throw CoreError.invalidState("edit requires a local source with no requirement") + let program: ExecutableDeclaration? + switch component { + case .mcpServer(_, .stdio(let value), _, _, _, _): program = value + case .hook(_, _, let value, _, _, _, _, _), .lspServer(_, let value, _, _, _, _, _): + program = value + default: program = nil + } + if let program, let alias = program.executableSource { + guard alias == "." || sources[alias] != nil, program.executable.contains("/") else { + throw CoreError.invalidState( + "executable source requires an existing alias and resource path") + } + _ = try PathSafety.sanitizeSubpath(program.executable) } - if case .names(let names) = selection.select { try Self.validateNames(names) } - try Self.validateNames(selection.exclude ?? []) - try Self.validateNames(Array((selection.overrides ?? [:]).keys)) } guard Set(watch ?? []).count == (watch ?? []).count else { throw CoreError.invalidState("duplicate watch subscription") } - for alias in watch ?? [] where sources[alias] == nil { + for alias in watch ?? [] where !aliases.contains(alias) { throw CoreError.invalidState("unknown watch source: \(alias)") } - for reference in (instructions?.sections ?? []) - + (instructions?.chatgpt ?? [:]).values.flatMap(\.sections) - { - let parts = reference.split(separator: ":", omittingEmptySubsequences: false) - let valid = - parts.count == 1 - ? Self.isInstructionName(reference) - : parts.count == 2 && sources[String(parts[0])] != nil - && Self.isInstructionName(String(parts[1])) - guard valid else { throw CoreError.invalidState("invalid section reference: \(reference)") } - } - for prompt in (instructions?.chatgpt ?? [:]).values { - if let append = prompt.append { _ = try PathSafety.sanitizeSubpath(append) } - } } /// Whether every `/`-separated segment of an instructions name uses lowercase letters, digits @@ -284,16 +487,24 @@ public struct Declaration: Codable, Equatable, Sendable { var result = self result.agents?.sort { $0.rawValue < $1.rawValue } result.watch?.sort() - result.instructions?.agents?.sort { $0.rawValue < $1.rawValue } - for alias in (result.skills ?? [:]).keys { - result.skills?[alias]?.exclude?.sort() - result.skills?[alias]?.agents?.sort { $0.rawValue < $1.rawValue } - for name in (result.skills?[alias]?.overrides ?? [:]).keys { - result.skills?[alias]?.overrides?[name]?.agents?.sort { $0.rawValue < $1.rawValue } + result.components = components.map { component in + switch component { + case .skills(let source, var selection): + selection.exclude?.sort() + selection.agents?.sort { $0.rawValue < $1.rawValue } + for index in selection.overrideDeclarations.indices { + selection.overrideDeclarations[index].override.agents?.sort { $0.rawValue < $1.rawValue } + } + return .skills(source: source, selection) + case .instructions(var instructions): + instructions.agents?.sort { $0.rawValue < $1.rawValue } + return .instructions(instructions) + default: return component } } return result } + } extension Declaration { @@ -318,3 +529,8 @@ extension Declaration { return candidate } } + +/// Canonical order for new entries supplied through alias/name dictionaries. +private func declarationNameLess(_ lhs: String, _ rhs: String) -> Bool { + lhs.utf8.lexicographicallyPrecedes(rhs.utf8) +} diff --git a/Sources/AgentsCore/DeclarationAccess.swift b/Sources/AgentsCore/DeclarationAccess.swift new file mode 100644 index 0000000..3acaa7e --- /dev/null +++ b/Sources/AgentsCore/DeclarationAccess.swift @@ -0,0 +1,30 @@ +import Foundation + +/// Declaration source bytes that the declaration format planned and verified for one prepared +/// generation. Core publishes them without reading the format. +package struct DeclarationChange: Sendable { + package let bytes: Data + + package init(bytes: Data) { + self.bytes = bytes + } +} + +/// Reads and plans declarations through the module that owns the declaration format. +package struct DeclarationAccess: Sendable { + /// Reads the declaration, from the prepared generation when one is supplied. + package typealias Read = @Sendable (StateStore, StatePrecondition?) throws -> Declaration + /// Plans `next` against the prepared document that `previous` was read from; nil leaves the + /// declaration unchanged. + package typealias Plan = + @Sendable (StateStore, _ previous: Declaration, _ next: Declaration, StatePrecondition) + throws -> DeclarationChange? + + package let read: Read + package let plan: Plan + + package init(read: @escaping Read, plan: @escaping Plan) { + self.read = read + self.plan = plan + } +} diff --git a/Sources/AgentsCore/DeclarationIR.swift b/Sources/AgentsCore/DeclarationIR.swift new file mode 100644 index 0000000..cf80ece --- /dev/null +++ b/Sources/AgentsCore/DeclarationIR.swift @@ -0,0 +1,83 @@ +/// Syntax-independent declaration data. Arrays retain authored order; dictionaries are unordered. +/// Recipients use agent IDs, conditions remain data, and group references stay symbolic until linking. +public indirect enum DeclarationValue: Sendable, Equatable { + case string(String) + case integer(Int) + case boolean(Bool) + case null + case array([DeclarationValue]) + case dictionary([String: DeclarationValue]) + case record(DeclarationRecord) + case requirement(SourceRequirement) + + public static func == (lhs: DeclarationValue, rhs: DeclarationValue) -> Bool { + switch (lhs, rhs) { + case (.string(let a), .string(let b)): return a == b + case (.integer(let a), .integer(let b)): return a == b + case (.boolean(let a), .boolean(let b)): return a == b + case (.null, .null): return true + case (.array(let a), .array(let b)): return a == b + case (.dictionary(let a), .dictionary(let b)): return a == b + case (.record(let a), .record(let b)): return a == b + case (.requirement(let a), .requirement(let b)): return a.declarationEquivalent(to: b) + default: return false + } + } + + public var string: String? { + if case .string(let value) = self { return value } + return nil + } + + public var elements: [DeclarationValue]? { + if case .array(let value) = self { return value } + return nil + } + + public var record: DeclarationRecord? { + if case .record(let value) = self { return value } + return nil + } +} + +/// A tagged domain value. No field contains a deployment path or a syntax node. +public struct DeclarationRecord: Sendable, Equatable { + public let kind: String + public let fields: [String: DeclarationValue] + + public init(kind: String, fields: [String: DeclarationValue]) { + self.kind = kind + self.fields = fields + } + + public subscript(_ field: String) -> DeclarationValue? { fields[field] } +} + +public struct DeclarationIR: Sendable, Equatable { + public let defaultAgents: [String]? + public let exports: [String] + public let sources: [DeclarationRecord] + public let components: [DeclarationRecord] + public let groups: [DeclarationRecord] + public let uses: [DeclarationRecord] + public let watch: [String] + public let packages: [DeclarationRecord] + public let lifecycle: DeclarationValue? + + public init( + defaultAgents: [String]? = nil, exports: [String] = [], sources: [DeclarationRecord] = [], + components: [DeclarationRecord] = [], groups: [DeclarationRecord] = [], + uses: [DeclarationRecord] = [], watch: [String] = [], packages: [DeclarationRecord] = [], + lifecycle: DeclarationValue? = nil + ) { + self.defaultAgents = defaultAgents + self.exports = exports + self.sources = sources + self.components = components + self.groups = groups + self.uses = uses + self.watch = watch + self.packages = packages + self.lifecycle = lifecycle + } +} diff --git a/Sources/AgentsCore/DirectoryHandle.swift b/Sources/AgentsCore/DirectoryHandle.swift index 8e7d806..36f928b 100644 --- a/Sources/AgentsCore/DirectoryHandle.swift +++ b/Sources/AgentsCore/DirectoryHandle.swift @@ -1,45 +1,79 @@ +import CPlatform import Foundation -#if canImport(Darwin) - import Darwin -#else - import Glibc -#endif - /// Pins directory ancestry. Child operations never traverse symbolic links. -final class DirectoryHandle { +package final class DirectoryHandle { + struct SynchronizationObserver: Sendable { + let didSynchronize: @Sendable () -> Void + } + + @TaskLocal static var synchronizationObserver: SynchronizationObserver? let descriptor: Int32 - let url: URL + package let url: URL + + /// Depth counts levels above the opened directory; 0 is the directory itself. + enum AncestryStep { + case created(depth: Int) + /// The parent barrier that makes a created component durable. + case synced(depth: Int) + + var name: String { + switch self { + case .created(let depth): "created.\(depth)" + case .synced(let depth): "synced.\(depth)" + } + } + } + /// With `create`, every component's parent is synced. Checkpoints mark only components + /// this call creates, so their names and number do not depend on the host path. init( - at url: URL, create: Bool = false, checkpoint: (String) throws -> Void = { _ in } + at url: URL, create: Bool = false, reportMissing: Bool = false, + checkpoint: (AncestryStep) throws -> Void = { _ in } ) throws { self.url = url.standardizedFileURL var current = open("/", O_RDONLY | O_DIRECTORY | O_CLOEXEC) - guard current >= 0 else { throw CoreError.unsafePath("cannot open filesystem root") } + guard current >= 0 else { + if let exhaustion = OpenFileLimitError(errno, at: self.url) { throw exhaustion } + throw CoreError.unsafePath("cannot open filesystem root") + } defer { if current >= 0 { close(current) } } - for (index, component) in self.url.pathComponents.dropFirst().enumerated() { + let components = self.url.pathComponents.dropFirst() + for (index, component) in components.enumerated() { // macOS exposes these root-owned system directories through immutable aliases. // All task-controlled components, including every cache ancestor, use O_NOFOLLOW. - let systemAlias = index == 0 && ["var", "tmp", "etc"].contains(component) + let systemAlias = index == 0 && platform_system_alias(component) if create { + let depth = components.count - 1 - index var info = stat() + var created = false if fstatat(current, component, &info, AT_SYMLINK_NOFOLLOW) != 0 { guard errno == ENOENT, mkdirat(current, component, 0o700) == 0 else { - throw CoreError.unsafePath("cannot create directory: \(url.path)") + throw FileSystem.posixError( + errno, at: self.url, otherwise: .unsafePath("cannot create directory: \(url.path)")) } - try checkpoint("directory.created.\(component)") + try FileSystem.requireAccess( + R_OK | W_OK | X_OK, at: self.url, parent: current, name: component) + created = true + try checkpoint(.created(depth: depth)) } // An existing entry may have been published by an interrupted creator. try Self.synchronize(current) - try checkpoint("directory.synced.\(component)") + if created { try checkpoint(.synced(depth: depth)) } } let next = openat( current, component, O_RDONLY | O_DIRECTORY | (systemAlias ? 0 : O_NOFOLLOW) | O_CLOEXEC) - guard next >= 0 else { throw CoreError.unsafePath("unsafe directory: \(url.path)") } + guard next >= 0 else { + if reportMissing && errno == ENOENT { throw CoreError.notFound(self.url.path) } + throw FileSystem.posixError( + errno, at: self.url, otherwise: .unsafePath("unsafe directory: \(url.path)")) + } close(current) current = next } + if create { + try FileSystem.requireAccess(R_OK | W_OK | X_OK, at: self.url, parent: current, name: ".") + } descriptor = current current = -1 } @@ -47,7 +81,10 @@ final class DirectoryHandle { private init(parent: DirectoryHandle, name: String) throws { url = parent.url.appendingPathComponent(name) descriptor = openat(parent.descriptor, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC) - guard descriptor >= 0 else { throw CoreError.unsafePath("unsafe directory: \(url.path)") } + guard descriptor >= 0 else { + throw FileSystem.posixError( + errno, at: url, otherwise: .unsafePath("unsafe directory: \(url.path)")) + } } deinit { close(descriptor) } @@ -56,15 +93,41 @@ final class DirectoryHandle { try DirectoryHandle(parent: self, name: name) } + /// Opens a child directory only if it is still the generation `expected` described. + func child(_ name: String, matching expected: stat) throws -> DirectoryHandle { + let directory = try child(name) + var opened = stat() + guard fstat(directory.descriptor, &opened) == 0, Self.sameGeneration(expected, opened) else { + throw CoreError.invalidState("directory changed before reading: \(name)") + } + return directory + } + + static func sameGeneration(_ first: stat, _ second: stat) -> Bool { + var first = first + var second = second + return platform_same_generation(&first, &second) + } + func info(_ name: String) throws -> stat? { var value = stat() if fstatat(descriptor, name, &value, AT_SYMLINK_NOFOLLOW) == 0 { return value } if errno == ENOENT { return nil } - throw CoreError.unsafePath("cannot inspect \(url.appendingPathComponent(name).path)") + throw FileSystem.posixError( + errno, at: url.appendingPathComponent(name), + otherwise: .unsafePath("cannot inspect \(url.appendingPathComponent(name).path)")) } - func names() throws -> [String] { - guard let stream = fdopendir(dup(descriptor)) else { + package func names(maximumCount: Int = .max) throws -> [String] { + let copy = dup(descriptor) + guard copy >= 0 else { + if let exhaustion = OpenFileLimitError(errno, at: url) { throw exhaustion } + throw CoreError.unsafePath("cannot enumerate \(url.path)") + } + guard let stream = fdopendir(copy) else { + let code = errno + close(copy) + if let exhaustion = OpenFileLimitError(code, at: url) { throw exhaustion } throw CoreError.unsafePath("cannot enumerate \(url.path)") } defer { closedir(stream) } @@ -72,97 +135,337 @@ final class DirectoryHandle { var names: [String] = [] errno = 0 while let entry = readdir(stream) { - let name = withUnsafePointer(to: &entry.pointee.d_name) { - $0.withMemoryRebound(to: CChar.self, capacity: Int(entry.pointee.d_namlen) + 1) { - String(cString: $0) + guard let name = String(validatingCString: platform_entry_name(entry)) else { + throw CoreError.unsafePath("filesystem entry is not valid UTF-8") + } + if name != "." && name != ".." { + guard names.count < maximumCount else { + throw CoreError.invalidSource("directory entry budget at " + url.path) } + names.append(name) } - if name != "." && name != ".." { names.append(name) } } guard errno == 0 else { throw CoreError.unsafePath("cannot enumerate \(url.path)") } - return names.sorted() + return names.sorted { $0.utf8.lexicographicallyPrecedes($1.utf8) } } - /// Deletes an owned subtree, granting owner access only to directories being discarded. - func remove(_ name: String, checkpoint: (String) throws -> Void = { _ in }) throws { - if let info = try info(name) { - if info.st_mode & S_IFMT == S_IFDIR { - let directory = try child(name) - if info.st_mode & S_IRWXU != S_IRWXU { - guard fchmod(directory.descriptor, (info.st_mode & 0o7777) | S_IRWXU) == 0 else { - throw CoreError.unsafePath("cannot make discarded directory writable: \(name)") - } + enum RemovalStep: String { case unlinked, synced } + struct RemovalPoint { + /// Relative to the removed entry; empty for the entry itself. + let path: String + let step: RemovalStep + } + + /// Missing descendants are accepted only by callers with a durable disposal intent. + /// Private trees and verified user objects share the same descriptor-relative deleter. + func remove( + _ name: String, expecting expected: FileSnapshot? = nil, + identity expectedIdentity: FileObjectIdentity? = nil, + checkpoint: (RemovalPoint) throws -> Void = { _ in } + ) throws { + try removeContents( + name, expected: expected, identity: expectedIdentity, prefix: "", + checkpoint: checkpoint) + // An absent entry may be an interrupted unlink whose parent was not synced. + try sync() + try checkpoint(RemovalPoint(path: "", step: .synced)) + } + + private func removeContents( + _ name: String, expected: FileSnapshot?, identity: FileObjectIdentity?, prefix: String, + checkpoint: (RemovalPoint) throws -> Void + ) throws { + guard let info = try info(name) else { return } + let observed = FileObjectIdentity(info) + if let identity, observed != identity { + throw CoreError.invalidState("removal identity changed: \(name)") + } + if let expected, observed != expected.identity { + throw CoreError.invalidState("removal ownership changed: \(name)") + } + if info.st_mode & S_IFMT == S_IFDIR { + let directory = try child(name) + if info.st_mode & S_IRWXU != S_IRWXU { + guard fchmod(directory.descriptor, (info.st_mode & 0o7777) | S_IRWXU) == 0 else { + throw CoreError.unsafePath("cannot make removed directory writable: \(name)") } - for entry in try directory.names() { try directory.remove(entry) } - guard unlinkat(descriptor, name, AT_REMOVEDIR) == 0 else { - throw CoreError.unsafePath("cannot remove directory: \(name)") + } + let recorded = expected?.children.map { + Dictionary(uniqueKeysWithValues: $0.map { (Data($0.name.utf8), $0.snapshot) }) + } + for child in try directory.names() { + if expected != nil, recorded?[Data(child.utf8)] == nil { + throw CoreError.invalidState("unexpected descendant during removal: \(child)") } - } else if unlinkat(descriptor, name, 0) != 0 { - throw CoreError.unsafePath("cannot remove entry: \(name)") + try directory.removeContents( + child, expected: recorded?[Data(child.utf8)], identity: nil, + prefix: prefix.isEmpty ? child : prefix + "/" + child, checkpoint: checkpoint) } - try checkpoint("unlinked") + try directory.sync() + } else if let expected, try FileSnapshot.read(name, from: self) != expected { + throw CoreError.invalidState("removal content changed: \(name)") + } + guard try self.info(name).map(FileObjectIdentity.init) == observed else { + throw CoreError.invalidState("removal identity changed: \(name)") + } + guard unlinkat(descriptor, name, info.st_mode & S_IFMT == S_IFDIR ? AT_REMOVEDIR : 0) == 0 + else { + throw CoreError.invalidState("cannot remove filesystem entry: \(name): \(errno)") + } + try checkpoint(RemovalPoint(path: prefix, step: .unlinked)) + } + + /// rmdir never erases contents; an absent entry still receives the parent barrier. + func removeEmptyDirectory(_ name: String) throws { + guard unlinkat(descriptor, name, AT_REMOVEDIR) == 0 || errno == ENOENT else { + let code = errno + throw CoreError.invalidState( + "cannot remove directory: \(name): \(code) (\(String(cString: strerror(code))))") } - // An absent entry may reflect an interrupted unlink whose parent was never synced. try sync() - try checkpoint("synced") } - func rename( - _ name: String, to destination: String, swap: Bool = false, - afterRename: () throws -> Void = {} + enum RenameMode: Sendable { case exchange, exclusive } + enum RenameResult: Equatable { + case success + case exists(Int32) + case unsupported(Int32) + case failure(Int32) + + init(code: Int32) { + if code == 0 { + self = .success + } else if code == EEXIST || code == ENOTEMPTY { + self = .exists(code) + } else if [EINVAL, ENOSYS, ENOTSUP, EOPNOTSUPP].contains(code) { + self = .unsupported(code) + } else { + self = .failure(code) + } + } + + func requireSuccess(_ operation: String) throws { + switch self { + case .success: return + case .exists(let code): + throw CoreError.invalidState( + "transaction destination already exists: \(operation): \(code) (\(String(cString: strerror(code))))" + ) + case .unsupported(let code): + throw CoreError.unsupported( + "atomic rename is required: \(operation): \(code) (\(String(cString: strerror(code))))") + case .failure(let code): + throw CoreError.invalidState( + "cannot \(operation): \(code) (\(String(cString: strerror(code))))") + } + } + } + + struct AtomicRenameFailure: Sendable { + let mode: RenameMode + let code: Int32 + } + + /// A matching injected errno replaces the platform result and takes the same classifier. + @TaskLocal static var atomicRenameFailure: AtomicRenameFailure? + + var device: UInt64 { get throws { try objectIdentity.device } } + package var objectIdentity: FileObjectIdentity { + get throws { + var info = stat() + guard fstat(descriptor, &info) == 0 else { + throw CoreError.invalidState("cannot identify directory") + } + return FileObjectIdentity(info) + } + } + + enum PermissionStep: String { case changed, synced } + + /// Only the lease's recorded directory inode may receive its temporary owner-write bit. + func grant(_ lease: DirectoryWriteLease, checkpoint: (PermissionStep) throws -> Void) throws { + try setPermissions(lease.grantedMode, lease: lease, checkpoint: checkpoint) + } + + func restore(_ lease: DirectoryWriteLease, checkpoint: (PermissionStep) throws -> Void) throws { + try setPermissions(lease.originalMode, lease: lease, checkpoint: checkpoint) + } + + private func setPermissions( + _ mode: mode_t, lease: DirectoryWriteLease, checkpoint: (PermissionStep) throws -> Void ) throws { - let result: Int32 - if swap { - #if canImport(Darwin) - result = renameatx_np(descriptor, name, descriptor, destination, UInt32(RENAME_SWAP)) - #else - throw CoreError.unsupported("atomic directory exchange requires renameatx_np") - #endif - } else { - result = renameat(descriptor, name, descriptor, destination) + let current = try checkedPermissions(lease) + if current != mode { + guard fchmod(descriptor, mode) == 0 else { + let code = errno + throw CoreError.invalidState( + "cannot set directory permissions: \(code) (\(String(cString: strerror(code))))") + } + try checkpoint(.changed) + } + // A visible mode may be an interrupted chmod whose metadata barrier did not complete. + try sync() + var value = stat() + guard fstat(descriptor, &value) == 0, value.st_mode & 0o7777 == mode else { + throw CoreError.invalidState("directory permissions changed before synchronization") } - guard result == 0 else { - throw CoreError.invalidState("cannot replace \(destination): \(errno)") + try checkpoint(.synced) + } + + func checkedPermissions(_ lease: DirectoryWriteLease) throws -> mode_t { + var value = stat() + guard fstat(descriptor, &value) == 0, FileObjectIdentity(value) == lease.identity else { + throw CoreError.invalidState("recorded directory identity changed") + } + let current = value.st_mode & 0o7777 + guard lease.admits(current) else { + throw CoreError.invalidState( + "directory permissions changed beyond transaction intent: \(url.path)") + } + return current + } + + func atomicRename( + _ name: String, to parent: DirectoryHandle, named destination: String, + mode: RenameMode + ) -> RenameResult { + if let failure = Self.atomicRenameFailure, failure.mode == mode { + return RenameResult(code: failure.code) } + let result = + mode == .exchange + ? platform_exchange(descriptor, name, parent.descriptor, destination) + : platform_rename_exclusive(descriptor, name, parent.descriptor, destination) + return RenameResult(code: result == 0 ? 0 : errno) + } + + func move( + _ name: String, to parent: DirectoryHandle, named destination: String, + mode: RenameMode, afterRename: () throws -> Void = {} + ) throws { + try atomicRename(name, to: parent, named: destination, mode: mode).requireSuccess( + "rename \(destination)") try afterRename() - try sync() + try parent.sync() + if self !== parent { try sync() } + } + + enum ProbeStep: String { + case firstCreated, secondCreated, exchanged, collisionChecked, moved, verified + } + + /// The descriptor is a private container on the publication device; the caller names + /// three absent probe entries inside it. + func requireAtomicRenames( + first a: String, second b: String, moved c: String, checkpoint: (ProbeStep) throws -> Void + ) throws { + try write( + a, data: Data("a".utf8), syncParent: false, afterCreate: { try checkpoint(.firstCreated) }) + try write( + b, data: Data("b".utf8), syncParent: false, afterCreate: { try checkpoint(.secondCreated) }) + let first = try info(a).map(FileObjectIdentity.init) + let second = try info(b).map(FileObjectIdentity.init) + // Exchange must preserve both entries and exchange their physical identities. + try atomicRename(a, to: self, named: b, mode: .exchange).requireSuccess("exchange atomic probe") + try checkpoint(.exchanged) + guard try info(a).map(FileObjectIdentity.init) == second, + try info(b).map(FileObjectIdentity.init) == first + else { + throw CoreError.unsupported("atomic exchange did not preserve probe objects") + } + // An occupied destination must refuse publication and preserve both inodes. + let collision = atomicRename(a, to: self, named: b, mode: .exclusive) + switch collision { + case .exists: break + case .success: + throw CoreError.unsupported("exclusive rename replaced an occupied probe") + case .unsupported, .failure: + try collision.requireSuccess("check exclusive atomic probe collision") + } + try checkpoint(.collisionChecked) + guard try info(a).map(FileObjectIdentity.init) == second, + try info(b).map(FileObjectIdentity.init) == first + else { + throw CoreError.unsupported("exclusive rename changed occupied probe objects") + } + // The same primitive must admit an absent destination, not merely reject all calls. + try atomicRename(a, to: self, named: c, mode: .exclusive).requireSuccess( + "move exclusive atomic probe") + try checkpoint(.moved) + guard try info(a) == nil, try info(c).map(FileObjectIdentity.init) == second else { + throw CoreError.unsupported("exclusive rename did not move the probe object") + } + try checkpoint(.verified) } - func makeDirectory(_ name: String) throws { + @discardableResult + func makeDirectory( + _ name: String, syncParent: Bool = true, afterCreate: () throws -> Void = {} + ) throws -> DirectoryHandle { + if try info(name) != nil { + try FileSystem.requireAccess( + R_OK | W_OK | X_OK, at: url.appendingPathComponent(name), parent: descriptor) + } guard mkdirat(descriptor, name, 0o700) == 0 else { - throw CoreError.invalidState("cannot create directory: \(name)") + throw FileSystem.posixError( + errno, at: url.appendingPathComponent(name), + otherwise: .invalidState("cannot create directory: \(name)")) } - try sync() + try FileSystem.requireAccess( + R_OK | W_OK | X_OK, at: url.appendingPathComponent(name), parent: descriptor) + try afterCreate() + let directory = try child(name) + guard fchmod(directory.descriptor, 0o700) == 0 else { + throw CoreError.invalidState("cannot set directory permissions") + } + if syncParent { try sync() } + return directory } func sync() throws { try Self.synchronize(descriptor) } - func link(_ name: String, destination: String) throws { + func link(_ name: String, destination: String, syncParent: Bool = true) throws { guard symlinkat(destination, descriptor, name) == 0 else { - throw CoreError.invalidState("cannot create link: \(name)") + throw FileSystem.posixError( + errno, at: url.appendingPathComponent(name), + otherwise: .invalidState("cannot create link: \(name)")) } - try sync() + if syncParent { try sync() } } func write( - _ name: String, data: Data, mode: mode_t = 0o600, preservingMetadataOf original: String? = nil + _ name: String, data: Data, mode: mode_t = 0o600, preservingMetadataOf original: String? = nil, + originalParent: DirectoryHandle? = nil, syncParent: Bool = true, + afterCreate: () throws -> Void = {} ) throws { + if try info(name) != nil { + try FileSystem.requireAccess( + R_OK | W_OK, at: url.appendingPathComponent(name), parent: descriptor) + } let file = openat(descriptor, name, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, mode) - guard file >= 0 else { throw CoreError.invalidState("cannot stage \(name)") } + guard file >= 0 else { + throw FileSystem.posixError( + errno, at: url.appendingPathComponent(name), + otherwise: .invalidState("cannot stage \(name)")) + } defer { close(file) } + try afterCreate() + try FileSystem.requireAccess( + R_OK | W_OK, at: url.appendingPathComponent(name), parent: descriptor) try data.withUnsafeBytes { bytes in var offset = 0 while offset < bytes.count { - let count = Foundation.write( + let count = CPlatform.write( file, bytes.baseAddress!.advanced(by: offset), bytes.count - offset) + if count < 0 && errno == EINTR { continue } guard count > 0 else { throw CoreError.invalidState("cannot write \(name)") } offset += count } } if let original { - let source = try regularFile(original) + let source = try (originalParent ?? self).regularFile(original) defer { close(source) } var attributes = stat() guard fstat(source, &attributes) == 0 else { @@ -173,38 +476,143 @@ final class DirectoryHandle { guard fchmod(file, mode) == 0 else { throw CoreError.invalidState("cannot set permissions") } try Self.synchronize(file) } + if syncParent { try sync() } + } + + /// Replaces an index or journal whose update is serialized by its writer lock. + func replaceFile( + _ name: String, through staging: String, with data: Data, mode: mode_t = 0o600, + afterWrite: () throws -> Void, afterRename: () throws -> Void + ) throws { + if try info(staging) != nil { + _ = try read(staging) + guard unlinkat(descriptor, staging, 0) == 0 else { + throw CoreError.invalidState("cannot remove \(staging): \(errno)") + } + } + try write(staging, data: data, mode: mode, syncParent: false) + try afterWrite() + guard renameat(descriptor, staging, descriptor, name) == 0 else { + throw CoreError.invalidState("cannot replace \(name): \(errno)") + } + try afterRename() + try sync() + } + + /// Unlinks each present regular file in order, then syncs this directory once. + func removeFiles(_ names: [String], afterUnlink: (String) throws -> Void = { _ in }) throws { + for name in names { + if try info(name) != nil { + _ = try read(name) + guard unlinkat(descriptor, name, 0) == 0 else { + throw CoreError.invalidState("cannot remove \(name): \(errno)") + } + try afterUnlink(name) + } + } try sync() } - func read(_ name: String) throws -> Data { + func read(_ name: String, matching expected: stat? = nil, maximumBytes: Int? = nil) throws -> Data + { + var data = Data() + try readChunks(name, matching: expected, maximumBytes: maximumBytes) { + data.append(contentsOf: $0) + } + return data + } + + @discardableResult + func readChunks( + _ name: String, matching expected: stat?, maximumBytes: Int?, + verifyAccess: (Int32) throws -> Void = { _ in }, + _ consume: (UnsafeRawBufferPointer) throws -> Void + ) throws -> Int { let file = try regularFile(name) defer { close(file) } - var data = Data() + var before = stat() + guard fstat(file, &before) == 0 else { + throw CoreError.invalidState("cannot identify opened file: \(name)") + } + if var expected, !platform_same_generation(&expected, &before) { + throw CoreError.invalidState("file changed before reading: \(name)") + } + try verifyAccess(file) + if let maximumBytes, before.st_size > maximumBytes { + throw CoreError.invalidState("file byte budget: \(name)") + } + var total = 0 var buffer = [UInt8](repeating: 0, count: 65536) while true { - let count = Darwin.read(file, &buffer, buffer.count) - guard count >= 0 else { throw CoreError.invalidState("cannot read \(name)") } - if count == 0 { return data } - data.append(contentsOf: buffer.prefix(count)) + let count = CPlatform.read(file, &buffer, buffer.count) + if count < 0 && errno == EINTR { continue } + guard count >= 0 else { + throw FileSystem.posixError( + errno, at: url.appendingPathComponent(name), + otherwise: .invalidState("cannot read \(name)")) + } + if count == 0 { + var after = stat() + guard fstat(file, &after) == 0, platform_same_generation(&before, &after) else { + throw CoreError.invalidState("file changed while reading: \(name)") + } + try verifyAccess(file) + return total + } + if let maximumBytes, count > maximumBytes - total { + throw CoreError.invalidState("file byte budget: \(name)") + } + try buffer.withUnsafeBytes { + try consume(UnsafeRawBufferPointer(rebasing: $0[.. String { + String(decoding: try readLinkData(name), as: UTF8.self) + } + + func readLinkData(_ name: String) throws -> Data { var buffer = [CChar](repeating: 0, count: Int(PATH_MAX) + 1) let count = readlinkat(descriptor, name, &buffer, buffer.count - 1) guard count >= 0, count < buffer.count - 1 else { - throw CoreError.unsafePath("invalid symbolic link") + throw FileSystem.posixError( + count < 0 ? errno : 0, at: url.appendingPathComponent(name), + otherwise: .unsafePath("invalid symbolic link")) } - return String(decoding: buffer.prefix(count).map { UInt8(bitPattern: $0) }, as: UTF8.self) + return Data(buffer.prefix(count).map { UInt8(bitPattern: $0) }) } - func syncFile(_ name: String) throws { + func syncFile(_ name: String, includingParent: Bool = true) throws { let file = try regularFile(name) defer { close(file) } try Self.synchronize(file) + if includingParent { try sync() } + } + + /// Syncs a verified object's file contents, then each directory level after its children, + /// then this parent. + func synchronize(_ name: String, as snapshot: FileSnapshot) throws { + guard try FileSnapshot.read(name, from: self) == snapshot else { + throw CoreError.invalidState("transaction preimage changed before synchronization: \(name)") + } + try synchronizeContents(name, as: snapshot) try sync() } + private func synchronizeContents(_ name: String, as snapshot: FileSnapshot) throws { + if let children = snapshot.children { + let directory = try child(name) + for member in children { + try directory.synchronizeContents(member.name, as: member.snapshot) + } + try directory.sync() + } else if snapshot.isRegular { + try syncFile(name, includingParent: false) + } + } + var identity: String { get throws { var info = stat() @@ -218,7 +626,11 @@ final class DirectoryHandle { private func regularFile(_ name: String) throws -> Int32 { let file = openat(descriptor, name, O_RDONLY | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK) var info = stat() - guard file >= 0 else { throw CoreError.unsafePath("cannot open file: \(name)") } + guard file >= 0 else { + throw FileSystem.posixError( + errno, at: url.appendingPathComponent(name), + otherwise: .unsafePath("cannot open file: \(name)")) + } guard fstat(file, &info) == 0, info.st_mode & S_IFMT == S_IFREG else { close(file) throw CoreError.unsafePath("expected regular file: \(name)") @@ -227,65 +639,285 @@ final class DirectoryHandle { } private static func synchronize(_ file: Int32) throws { - guard fsync(file) == 0 else { throw CoreError.invalidState("cannot sync filesystem entry") } - #if canImport(Darwin) - guard fcntl(file, F_FULLFSYNC) == 0 else { - throw CoreError.invalidState("cannot flush filesystem entry to storage") - } - #endif + guard platform_sync(file) == 0 else { + throw CoreError.invalidState("cannot sync filesystem entry: \(errno)") + } + synchronizationObserver?.didSynchronize() + } + + enum CopyStep: String { case directoryCreated, fileCreated, linkCreated, entryCopied } + struct CopyPoint { + let path: String + let step: CopyStep } /// Copies through pinned descriptors, including modes, ACLs and extended attributes. func copy( _ name: String, from source: DirectoryHandle, named original: String, - checkpoint: (String) throws -> Void = { _ in } + prefix: String = "", syncParent: Bool = true, + checkpoint: (CopyPoint) throws -> Void = { _ in } ) throws { + let path = prefix.isEmpty ? name : prefix + "/" + name guard let info = try source.info(original) else { throw CoreError.notFound(original) } switch info.st_mode & S_IFMT { case S_IFDIR: + if try self.info(name) != nil { + try FileSystem.requireAccess( + R_OK | W_OK | X_OK, at: url.appendingPathComponent(name), parent: descriptor) + } guard mkdirat(descriptor, name, 0o700) == 0 else { - throw CoreError.invalidState("cannot stage directory") + throw FileSystem.posixError( + errno, at: url.appendingPathComponent(name), + otherwise: .invalidState("cannot stage directory")) } - try checkpoint("directory") + try FileSystem.requireAccess( + 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) for entry in try origin.names() { - try destination.copy(entry, from: origin, named: entry, checkpoint: checkpoint) + try destination.copy( + entry, from: origin, named: entry, prefix: path, syncParent: false, checkpoint: checkpoint + ) } try Self.copyMetadata(from: origin.descriptor, to: destination.descriptor, mode: info.st_mode) case S_IFLNK: - try link(name, destination: source.readLink(original)) - let origin = openat(source.descriptor, original, O_RDONLY | O_SYMLINK | O_CLOEXEC) - let destination = openat(descriptor, name, O_RDONLY | O_SYMLINK | O_CLOEXEC) - defer { - close(origin) - close(destination) - } - guard origin >= 0, destination >= 0 else { - throw CoreError.unsafePath("cannot copy link metadata") + try link(name, destination: source.readLink(original), syncParent: false) + try checkpoint(CopyPoint(path: path, step: .linkCreated)) + guard platform_copy_link_metadata(source.descriptor, original, descriptor, name) == 0 else { + throw CoreError.invalidState("cannot preserve link metadata: \(errno)") } - try Self.copyMetadata(from: origin, to: destination, mode: info.st_mode) case S_IFREG: + if try self.info(name) != nil { + try FileSystem.requireAccess( + R_OK | W_OK, at: url.appendingPathComponent(name), parent: descriptor) + } let origin = try source.regularFile(original) defer { close(origin) } let destination = openat( descriptor, name, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0o600) - guard destination >= 0 else { throw CoreError.unsafePath("cannot copy file") } + guard destination >= 0 else { + throw FileSystem.posixError( + errno, at: url.appendingPathComponent(name), otherwise: .unsafePath("cannot copy file")) + } defer { close(destination) } - guard fcopyfile(origin, destination, nil, copyfile_flags_t(COPYFILE_DATA)) == 0 else { + try checkpoint(CopyPoint(path: path, step: .fileCreated)) + try FileSystem.requireAccess( + R_OK | W_OK, at: url.appendingPathComponent(name), parent: descriptor) + guard platform_copy_data(origin, destination) == 0 else { throw CoreError.invalidState("cannot copy file content") } try Self.copyMetadata(from: origin, to: destination, mode: info.st_mode) default: throw CoreError.unsafePath("unsupported filesystem entry: \(original)") } - try sync() - try checkpoint("entry") + if syncParent { try sync() } + if !prefix.isEmpty { try checkpoint(CopyPoint(path: path, step: .entryCopied)) } } private static func copyMetadata(from origin: Int32, to destination: Int32, mode: mode_t) throws { - guard fcopyfile(origin, destination, nil, copyfile_flags_t(COPYFILE_METADATA)) == 0, - fchmod(destination, mode & 0o7777) == 0 - else { throw CoreError.invalidState("cannot preserve filesystem metadata") } - try synchronize(destination) + guard platform_copy_metadata(origin, destination, mode) == 0 else { + throw CoreError.invalidState("cannot preserve filesystem metadata: \(errno)") + } + synchronizationObserver?.didSynchronize() + } +} + +extension DirectoryHandle { + package static func readDirectory(at url: URL) throws -> DirectoryHandle { + try DirectoryHandle(at: url) } + + package static func readDirectoryIfPresent(at url: URL) throws -> DirectoryHandle? { + do { return try DirectoryHandle(at: url, reportMissing: true) } catch CoreError.notFound { + return nil + } + } + + /// Reads from this directory generation. Directories and links are classified without opening + /// them, and the bytes and mode must come from the same observed regular file. + package func observeRegularFile( + _ name: String, maximumBytes: Int, requireUnshared: Bool = false + ) throws -> RegularFileObservation { + guard let entry = try info(name) else { return .missing } + let identity = FileObjectIdentity(entry) + guard entry.st_mode & S_IFMT == S_IFREG, !requireUnshared || entry.st_nlink == 1 else { + return .other(identity) + } + let bytes = try read(name, matching: entry, maximumBytes: maximumBytes) + guard let current = try info(name), Self.sameGeneration(entry, current) else { + throw CoreError.invalidState("file changed while reading: " + name) + } + return .regular(identity, executable: entry.st_mode & 0o111 != 0, bytes: bytes) + } + + package func directory(_ name: String) throws -> DirectoryHandle? { + guard let generation = try info(name) else { return nil } + return try child(name, matching: generation) + } + + package func createDirectoryIfAbsent(_ name: String) throws -> DirectoryHandle { + if mkdirat(descriptor, name, 0o755) != 0, errno != EEXIST { + throw FileSystem.posixError( + errno, at: url.appendingPathComponent(name), + otherwise: .invalidState("cannot create directory: " + name)) + } + let directory = try child(name) + try sync() + return directory + } + + package func createDirectoryExclusively(_ name: String) throws -> DirectoryHandle { + try makeDirectory(name) + } + + package func readRegularFile(_ name: String, maximumBytes: Int) throws -> Data { + try read(name, maximumBytes: maximumBytes) + } + + package func readRegularFileIfPresent(_ name: String, maximumBytes: Int) throws -> Data? { + guard try info(name) != nil else { return nil } + return try readRegularFile(name, maximumBytes: maximumBytes) + } + + package func publishIndex( + _ name: String, data: Data, beforeRename: () throws -> Void + ) throws { + try replaceFile( + name, through: "." + name + ".stage", with: data, mode: 0o644, + afterWrite: beforeRename, afterRename: {}) + } + + package func regularFileSize(_ name: String) throws -> Int { + guard let info = try info(name), info.st_mode & 0o170000 == 0o100000, + let size = Int(exactly: info.st_size), size >= 0 + else { throw CoreError.unsafePath("expected regular file: " + name) } + return size + } + + package func capturePortableTree( + _ name: String, limits: LedgerLimits = .standard, recursive: Bool = true, + admitting: @escaping (String) throws -> Void + ) throws -> (entries: [LedgerEntry], objects: [String: Data]) { + try FileSnapshot.capturePortableTree( + name, from: self, limits: limits, recursive: recursive, admitting: admitting) + } + + /// Syncs a private generation before making its complete directory visible. A collision + /// leaves the existing generation intact and lets the caller verify its contents. + package func publishDirectory( + named name: String, files: [String: Data], beforeCommit: () throws -> Void = {} + ) throws -> Bool { + try publishDirectory(named: name, beforeCommit: beforeCommit) { directory in + for filename in files.keys.sorted() { + try directory.write(filename, data: files[filename]!, mode: 0o644, syncParent: false) + } + } + } + + package func publishPortableTree( + named name: String, entries: [LedgerEntry], objects: [String: Data], + beforeCommit: () throws -> Void + ) throws -> Bool { + let resource = LedgerResource( + kind: .embedded, source: "", path: ".", hash: "", entries: entries) + let tree = try LedgerResources.validatedEntries(resource) + guard tree["."]?.kind == .directory else { + throw CoreError.invalidSource("portable output must have a directory root") + } + return try publishDirectory(named: name, beforeCommit: beforeCommit) { directory in + func populate(_ parent: DirectoryHandle, prefix: String) throws { + for entry in children[prefix] ?? [] { + try Task.checkCancellation() + let name = String(entry.path.split(separator: "/").last!) + switch entry.kind { + case .directory: + let child = try parent.makeDirectory(name, syncParent: false) + try populate(child, prefix: entry.path) + guard fchmod(child.descriptor, 0o755) == 0 else { + throw CoreError.invalidState("cannot set portable directory permissions") + } + try child.sync() + case .file: + guard let object = entry.object, let data = objects[object] else { + throw CoreError.invalidSource("missing portable output file") + } + try parent.write( + name, data: data, mode: entry.executable ? 0o755 : 0o644, syncParent: false) + case .symlink: + guard let link = entry.link else { + throw CoreError.invalidSource("missing output link") + } + try parent.link(name, destination: link, syncParent: false) + } + } + } + let children = Dictionary( + grouping: entries.filter { $0.path != "." }, + by: { $0.path.split(separator: "/").dropLast().joined(separator: "/") }) + try populate(directory, prefix: "") + } + } + + package func publishRegularFile( + named name: String, bytes: Data, afterCommit: () -> Void = {}, + beforeCommit: () throws -> Void = {} + ) throws -> Bool { + let staging = ".stage-" + UUID().uuidString + let directory = try makeDirectory(staging, syncParent: false) + let identity = try directory.objectIdentity + defer { try? remove(staging, identity: identity) } + try directory.write("artifact", data: bytes, mode: 0o644) + try Task.checkCancellation() + try beforeCommit() + guard + case .regular(_, false, let stagedBytes) = try directory.observeRegularFile( + "artifact", maximumBytes: bytes.count, requireUnshared: true), + stagedBytes == bytes + else { + throw CoreError.invalidState("staged file changed before publication") + } + let result = directory.atomicRename("artifact", to: self, named: name, mode: .exclusive) + if case .exists = result { return false } + try result.requireSuccess("publish file " + name) + afterCommit() + try sync() + return true + } + + package func publishDirectory( + named name: String, beforeCommit: () throws -> Void, afterCommit: () -> Void = {}, + populate: (DirectoryHandle) throws -> Void + ) throws -> Bool { + let staging = ".stage-" + UUID().uuidString + let directory = try makeDirectory(staging, syncParent: false) + let identity = try directory.objectIdentity + var moved = false + defer { if !moved { try? remove(staging, identity: identity) } } + try populate(directory) + guard fchmod(directory.descriptor, 0o755) == 0 else { + throw CoreError.invalidState("cannot set release directory permissions") + } + try directory.sync() + try Task.checkCancellation() + try beforeCommit() + guard try info(staging).map(FileObjectIdentity.init) == identity else { + throw CoreError.invalidState("staged directory changed before publication") + } + let result = atomicRename(staging, to: self, named: name, mode: .exclusive) + if case .exists = result { + try sync() + return false + } + try result.requireSuccess("publish directory " + name) + moved = true + afterCommit() + try sync() + return true + } +} + +package enum RegularFileObservation { + case missing + case other(FileObjectIdentity) + case regular(FileObjectIdentity, executable: Bool, bytes: Data) } diff --git a/Sources/AgentsCore/FileAccess.swift b/Sources/AgentsCore/FileAccess.swift new file mode 100644 index 0000000..feca4d9 --- /dev/null +++ b/Sources/AgentsCore/FileAccess.swift @@ -0,0 +1,382 @@ +import CPlatform +import Foundation + +/// Access metadata is separate from content generations. ACL bytes contain ordered +/// numeric identities and inheritance, never resolved account names or payload bytes. +package struct FileAccessEvidence: Codable, Equatable, Sendable { + enum ACLFormat: String, Codable, Sendable { + case darwinExternal + case linuxPOSIX + } + + let identity: FileObjectIdentity + package let owner: UInt32 + package let group: UInt32 + package let mode: mode_t + let aclFormat: ACLFormat + let acl: Data + let defaultACL: Data + + func admits(_ current: Self, removal: Bool, directoryWrite: Bool = false) -> Bool { + if self == current { return true } + guard removal || directoryWrite, identity.isDirectory else { return false } + return Self( + identity: identity, owner: owner, group: group, mode: mode | (removal ? 0o700 : 0o200), + aclFormat: aclFormat, acl: acl, defaultACL: defaultACL) == current + } + + static func capture(descriptor: Int32) throws -> Self { + try read(descriptor: descriptor).evidence + } + + func validate(descriptor: Int32) throws { + guard try Self.capture(descriptor: descriptor) == self else { + throw CoreError.invalidState("filesystem access changed during preparation") + } + } + + /// Requires a live owner-readable/writable object with no effective access for + /// other identities. Root and same-UID adversaries are outside this boundary. + @discardableResult + static func requirePrivate(descriptor: Int32) throws -> Self { + let current = try read(descriptor: descriptor) + guard current.evidence.owner == geteuid(), current.evidence.mode & 0o7000 == 0, + current.assessment == 0, + current.evidence.identity.isDirectory || current.links == 1 + else { + throw CoreError.invalidState("private filesystem access cannot be established") + } + return current.evidence + } + + /// Trust metadata can be readable by other identities. Only its owner may modify it. + static func requireUserControlledFile(descriptor: Int32) throws -> Self { + let current = try read(descriptor: descriptor) + let externalControl = UInt32(PLATFORM_ACCESS_EXTERNAL_CONTROL | PLATFORM_ACCESS_EXTERNAL_WRITE) + guard current.evidence.identity.kind == S_IFREG, current.evidence.owner == geteuid(), + current.links == 1, current.assessment & externalControl == 0 + else { throw CoreError.unsafePath("file access is not controlled by its owner") } + return current.evidence + } + + /// Traversable ordinary ancestors are allowed. Sticky directories protect an + /// already-owned child, but ACL deletion/control grants are never excused by sticky. + @discardableResult + static func requireNonReplaceableDirectory( + descriptor: Int32, protectingOwner childOwner: UInt32 + ) throws -> Self { + let current = try read(descriptor: descriptor) + let evidence = current.evidence + let trustedOwner = evidence.owner == geteuid() || evidence.owner == 0 + let stickyProtection = + evidence.mode & 0o1000 != 0 && (childOwner == geteuid() || childOwner == 0) + guard evidence.identity.isDirectory, trustedOwner, + current.assessment & UInt32(PLATFORM_ACCESS_EXTERNAL_CONTROL) == 0, + current.assessment & UInt32(PLATFORM_ACCESS_EXTERNAL_WRITE) == 0 || stickyProtection, + platform_access(descriptor, ".", X_OK) == 0 + else { + throw CoreError.invalidState("filesystem ancestry permits replacement or is unprovable") + } + return evidence + } + + /// Administrative credentials never follow from the invocation's effective UID. + static func requireLifecycleWriter( + descriptor: Int32, owner: UInt32?, kind: mode_t, protectingChild: Bool = false + ) throws -> Self { + let current = try read(descriptor: descriptor) + let evidence = current.evidence + let ownership = + owner.map { evidence.owner == $0 } + ?? (evidence.owner == 0 || evidence.owner == geteuid()) + // Sticky protection applies to an already-owned child, never to discovery + // membership in an administrator directory or a writable file. + let sticky = protectingChild && evidence.mode & 0o1000 != 0 + guard ownership, evidence.identity.kind == kind, + current.assessment & UInt32(PLATFORM_ACCESS_EXTERNAL_CONTROL) == 0, + current.assessment & UInt32(PLATFORM_ACCESS_EXTERNAL_WRITE) == 0 || sticky, + kind == S_IFDIR ? platform_access(descriptor, ".", X_OK) == 0 : current.links == 1 + else { + throw CoreError.invalidState("Lifecycle source ownership or writer access cannot be proved.") + } + return evidence + } + + private static func read(descriptor: Int32) throws -> ( + evidence: Self, assessment: UInt32, links: UInt64 + ) { + var value = platform_file_access() + // Directory entry churn can advance ctime during the ACL read even if access is + // unchanged. Accept only a complete kernel observation from a stable generation. + var deadline: ContinuousClock.Instant? + while platform_read_file_access(descriptor, &value) != 0 { + let code = errno + let limit = deadline ?? (.now + .milliseconds(150)) + guard code == EAGAIN, .now < limit else { + throw CoreError.invalidState("cannot capture descriptor access evidence: \(code)") + } + deadline = limit + usleep(1000) + } + defer { platform_dispose_file_access(&value) } + #if os(macOS) + let format = ACLFormat.darwinExternal + #else + let format = ACLFormat.linuxPOSIX + #endif + let evidence = Self( + identity: FileObjectIdentity(value.info), owner: value.info.st_uid, + group: value.info.st_gid, mode: value.info.st_mode & 0o7777, aclFormat: format, + acl: value.acl.map { Data(bytes: $0, count: value.acl_size) } ?? Data(), + defaultACL: value.default_acl.map { Data(bytes: $0, count: value.default_acl_size) } ?? Data() + ) + return (evidence, value.assessment, UInt64(value.info.st_nlink)) + } +} + +extension DirectoryHandle { + func accessEvidence() throws -> FileAccessEvidence { + try FileAccessEvidence.capture(descriptor: descriptor) + } + + /// The entry and ACL are read through the same no-follow descriptor. Comparing + /// this result on every pinned ancestor detects replacement as well as access drift. + func accessEvidence(_ name: String) throws -> FileAccessEvidence? { + try requireAccessComponent(name) + guard let before = try info(name) else { return nil } + let file = openat(descriptor, name, O_RDONLY | O_NONBLOCK | O_NOFOLLOW | O_CLOEXEC) + guard file >= 0 else { + if let exhaustion = OpenFileLimitError(errno, at: url.appendingPathComponent(name)) { + throw exhaustion + } + throw CoreError.invalidState("cannot open entry for access evidence") + } + defer { close(file) } + let result = try FileAccessEvidence.capture(descriptor: file) + guard result.identity == FileObjectIdentity(before), + let after = try info(name), Self.sameGeneration(before, after) + else { throw CoreError.invalidState("entry changed while capturing access evidence") } + return result + } + + func requireUserControlledFile(_ name: String, matching expected: stat) throws { + try requireAccessComponent(name) + let file = openat(descriptor, name, O_RDONLY | O_NONBLOCK | O_NOFOLLOW | O_CLOEXEC) + guard file >= 0 else { throw CoreError.unsafePath("cannot open user-controlled file") } + defer { close(file) } + let evidence = try FileAccessEvidence.requireUserControlledFile(descriptor: file) + guard evidence.identity == FileObjectIdentity(expected), let observed = try info(name), + Self.sameGeneration(expected, observed) + else { throw CoreError.invalidState("user-controlled file changed while reading") } + } + + /// Returns an empty verified inode. No producer receives a writable payload + /// path before verification; inherited ACLs are retained and evaluated as found. + func createPrivateFile(_ name: String, executable: Bool = false) throws -> PrivateFileHandle { + try requireAccessComponent(name) + let parentEvidence = try privateCreationParent() + let file = openat( + descriptor, name, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, + executable ? 0o700 : 0o600) + guard file >= 0 else { + let code = errno + if let exhaustion = OpenFileLimitError(code, at: url.appendingPathComponent(name)) { + throw exhaustion + } + throw CoreError.invalidState("cannot create private file: \(code)") + } + var retained = false + defer { if !retained { close(file) } } + var created = stat() + guard fstat(file, &created) == 0 else { + throw CoreError.invalidState("cannot identify created private file") + } + do { + let evidence = try FileAccessEvidence.requirePrivate(descriptor: file) + try parentEvidence.validate(descriptor: descriptor) + guard try accessEvidence(name) == evidence else { + throw CoreError.invalidState("private file changed during creation") + } + let result = PrivateFileHandle( + descriptor: file, parent: self, name: name, evidence: evidence, + parentEvidence: parentEvidence) + retained = true + return result + } catch { + try? removeEmptyPrivateCreation( + name, identity: FileObjectIdentity(created), directory: false, + parentEvidence: parentEvidence) + throw error + } + } + + func createPrivateDirectory(_ name: String) throws -> DirectoryHandle { + try requireAccessComponent(name) + let parentEvidence = try privateCreationParent() + guard mkdirat(descriptor, name, 0o700) == 0 else { + throw CoreError.invalidState("cannot create private directory: \(errno)") + } + guard let created = try info(name) else { + throw CoreError.invalidState("private directory disappeared during creation") + } + do { + let directory = try child(name, matching: created) + let evidence = try FileAccessEvidence.requirePrivate(descriptor: directory.descriptor) + try parentEvidence.validate(descriptor: descriptor) + guard try accessEvidence(name) == evidence else { + throw CoreError.invalidState("private directory changed during creation") + } + try directory.sync() + try sync() + return directory + } catch { + try? removeEmptyPrivateCreation( + name, identity: FileObjectIdentity(created), directory: true, parentEvidence: parentEvidence + ) + throw error + } + } + + private func privateCreationParent() throws -> FileAccessEvidence { + let evidence = try FileAccessEvidence.requireNonReplaceableDirectory( + descriptor: descriptor, protectingOwner: geteuid()) + guard platform_access(descriptor, ".", W_OK | X_OK) == 0 else { + throw CoreError.invalidState("private creation requires writable directory access") + } + return evidence + } + + private func removeEmptyPrivateCreation( + _ name: String, identity: FileObjectIdentity, directory: Bool, + parentEvidence: FileAccessEvidence + ) throws { + // If the namespace lost its protection, retain the empty object for its owner + // rather than risking an unlink of an external replacement. + try parentEvidence.validate(descriptor: descriptor) + guard try info(name).map(FileObjectIdentity.init) == identity else { return } + // A failed creation has never received bytes. rmdir also refuses unexpected children. + guard unlinkat(descriptor, name, directory ? AT_REMOVEDIR : 0) == 0 else { return } + try sync() + } +} + +/// The parent remains pinned until the last write. Publication, full path ancestry, +/// durable journal ownership and eventual disposal remain the transaction's duties. +final class PrivateFileHandle { + let descriptor: Int32 + let evidence: FileAccessEvidence + private let parent: DirectoryHandle + private let name: String + private let parentEvidence: FileAccessEvidence + + fileprivate init( + descriptor: Int32, parent: DirectoryHandle, name: String, evidence: FileAccessEvidence, + parentEvidence: FileAccessEvidence + ) { + self.descriptor = descriptor + self.parent = parent + self.name = name + self.evidence = evidence + self.parentEvidence = parentEvidence + } + + deinit { close(descriptor) } + + func write(_ data: Data) throws { + try parentEvidence.validate(descriptor: parent.descriptor) + guard try FileAccessEvidence.requirePrivate(descriptor: descriptor) == evidence, + try parent.accessEvidence(name) == evidence + else { throw CoreError.invalidState("private file access changed before writing") } + try data.withUnsafeBytes { bytes in + var offset = 0 + while offset < bytes.count { + let count = CPlatform.write( + descriptor, bytes.baseAddress!.advanced(by: offset), bytes.count - offset) + if count < 0 && errno == EINTR { continue } + guard count > 0 else { throw CoreError.invalidState("cannot write private file") } + offset += count + } + } + guard platform_sync(descriptor) == 0 else { + throw CoreError.invalidState("cannot synchronize private file") + } + try parent.sync() + } +} + +private func requireAccessComponent(_ name: String) throws { + guard !name.isEmpty, name != ".", name != "..", !name.contains("/"), !name.contains("\0") else { + throw CoreError.invalidState("access operation requires one path component") + } +} + +/// Ordered physical ancestry, derived from a registered target rather than journal paths. +/// A prefix can describe a not-yet-created parent during preparation only. +struct DirectoryAccessEvidence: Codable, Equatable, Sendable { + let directories: [FileAccessEvidence] + + static func capture(at url: URL) throws -> Self { + var descriptor = open("/", O_RDONLY | O_DIRECTORY | O_CLOEXEC) + guard descriptor >= 0 else { + if let exhaustion = OpenFileLimitError(errno, at: url) { throw exhaustion } + throw CoreError.unsafePath("cannot open access ancestry") + } + defer { close(descriptor) } + var evidence = [try FileAccessEvidence.capture(descriptor: descriptor)] + for (index, name) in url.standardizedFileURL.pathComponents.dropFirst().enumerated() { + let alias = index == 0 && platform_system_alias(name) + let next = openat( + descriptor, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC | (alias ? 0 : O_NOFOLLOW)) + if next < 0 { + let code = errno + if let exhaustion = OpenFileLimitError(code, at: url) { throw exhaustion } + guard code == ENOENT else { throw CoreError.unsafePath("cannot open access ancestry") } + break + } + do { + let child = try FileAccessEvidence.capture(descriptor: next) + _ = try FileAccessEvidence.requireNonReplaceableDirectory( + descriptor: descriptor, protectingOwner: child.owner) + evidence.append(child) + } catch { + close(next) + throw error + } + close(descriptor) + descriptor = next + } + _ = try FileAccessEvidence.requireNonReplaceableDirectory( + descriptor: descriptor, protectingOwner: geteuid()) + return Self(directories: evidence) + } + + func validate(at url: URL, allowingCreation: Bool = false) throws { + let current = try Self.capture(at: url) + guard + allowingCreation + ? current.directories.starts(with: directories) : current == self + else { throw CoreError.invalidState("filesystem access ancestry changed during preparation") } + } +} + +extension DirectoryHandle { + @discardableResult + func requirePrivateAccess(_ name: String, matching expected: FileAccessEvidence? = nil) throws + -> FileAccessEvidence + { + try requireAccessComponent(name) + let file = openat(descriptor, name, O_RDONLY | O_NONBLOCK | O_NOFOLLOW | O_CLOEXEC) + guard file >= 0 else { + if let exhaustion = OpenFileLimitError(errno, at: url.appendingPathComponent(name)) { + throw exhaustion + } + throw CoreError.invalidState("cannot open private object") + } + defer { close(file) } + let evidence = try FileAccessEvidence.requirePrivate(descriptor: file) + guard expected == nil || expected == evidence, + try info(name).map(FileObjectIdentity.init) == evidence.identity + else { throw CoreError.invalidState("private object access changed") } + return evidence + } +} diff --git a/Sources/AgentsCore/FileHash.swift b/Sources/AgentsCore/FileHash.swift index 11a4338..67ecf8d 100644 --- a/Sources/AgentsCore/FileHash.swift +++ b/Sources/AgentsCore/FileHash.swift @@ -1,4 +1,4 @@ -import CryptoKit +import Crypto import Foundation package enum FileHash { @@ -6,8 +6,19 @@ package enum FileHash { SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() } + static func matchesGitBlob(_ bytes: Data, object: String) -> Bool { + let header = Data("blob \(bytes.count)\u{0}".utf8) + func matches(_ hasher: H) -> Bool { + var hasher = hasher + hasher.update(data: header) + hasher.update(data: bytes) + return hasher.finalize().map { String(format: "%02x", $0) }.joined() == object + } + return object.count == 40 ? matches(Insecure.SHA1()) : matches(SHA256()) + } + package static func sha256Hex(file: URL) throws -> String { - try sha256Hex(data: Data(contentsOf: file)) + try sha256Hex(data: FileSystem.read(at: file)) } /// Hashes every tree entry in path order, including hidden files and symlink destinations. @@ -38,34 +49,103 @@ package enum FileHash { } static func folderHash(_ directory: DirectoryHandle) throws -> String { - var entries: [(String, Data)] = [] + struct Entry { + let name: String + let info: stat + let descendants: Bool + + var key: String { descendants ? name + "/" : name } + } + + var hasher = SHA256() + let regularFilePrefix = Data("file\0".utf8) func collect(_ directory: DirectoryHandle, prefix: String) throws { + var entries: [Entry] = [] for name in try directory.names() { - let path = prefix + name - guard let info = try directory.info(name) else { throw CoreError.notFound(path) } - switch info.st_mode & 0o170000 { + guard let info = try directory.info(name) else { throw CoreError.notFound(prefix + name) } + entries.append(Entry(name: name, info: info, descendants: false)) + if info.st_mode & 0o170000 == 0o040000 { + entries.append(Entry(name: name, info: info, descendants: true)) + } + } + // A directory record and its descendants have different sort keys. For example, + // "rules-extra" sorts between "rules" and "rules/guide". + for entry in entries.sorted(by: { $0.key.utf8.lexicographicallyPrecedes($1.key.utf8) }) { + let path = prefix + entry.key + if entry.descendants { + try collect(directory.child(entry.name, matching: entry.info), prefix: path) + continue + } + appendField(Data(path.utf8), to: &hasher) + switch entry.info.st_mode & 0o170000 { case 0o120000: - entries.append((path, Data(("link\0" + (try directory.readLink(name))).utf8))) + let link = try directory.readLink(entry.name) + guard let current = try directory.info(entry.name), + DirectoryHandle.sameGeneration(entry.info, current) + else { throw CoreError.invalidState("link changed while reading: \(path)") } + appendField(Data(("link\0" + link).utf8), to: &hasher) case 0o040000: - entries.append((path, Data("directory".utf8))) - try collect(directory.child(name), prefix: path + "/") + appendField(Data("directory".utf8), to: &hasher) case 0o100000: - entries.append((path, Data("file\0".utf8) + (try directory.read(name)))) + guard let size = Int(exactly: entry.info.st_size), size >= 0 else { + throw CoreError.invalidState("invalid file length: \(path)") + } + appendLength(UInt64(size) + UInt64(regularFilePrefix.count), to: &hasher) + hasher.update(data: regularFilePrefix) + let read = try directory.readChunks(entry.name, matching: entry.info, maximumBytes: size) + { + hasher.update(bufferPointer: $0) + } + guard read == size else { + throw CoreError.invalidState("file changed while reading: \(path)") + } default: throw CoreError.invalidState("unsupported content entry: \(path)") } } } try collect(directory, prefix: "") + return hasher.finalize().map { String(format: "%02x", $0) }.joined() + } + + static func hashRecords(_ entries: [(String, Data)]) -> String { var hasher = SHA256() // Each field has a fixed-width byte length, so arbitrary payload bytes cannot // impersonate paths, entry types or record boundaries. - for (path, content) in entries.sorted(by: { $0.0 < $1.0 }) { - for field in [Data(path.utf8), content] { - var length = UInt64(field.count).bigEndian - withUnsafeBytes(of: &length) { hasher.update(data: Data($0)) } - hasher.update(data: field) + for (path, content) in entries.sorted(by: { $0.0.utf8.lexicographicallyPrecedes($1.0.utf8) }) { + appendField(Data(path.utf8), to: &hasher) + appendField(content, to: &hasher) + } + return hasher.finalize().map { String(format: "%02x", $0) }.joined() + } + + static func portableTreeHash(_ entries: [LedgerEntry], objects: [String: Data]) throws -> String { + var hasher = SHA256() + let regularFilePrefix = Data("file\0".utf8) + for entry in entries where entry.path != "." { + try Task.checkCancellation() + appendField(Data(entry.path.utf8), to: &hasher) + switch entry.kind { + case .directory: appendField(Data("directory".utf8), to: &hasher) + case .symlink: appendField(Data(("link\0" + entry.link!).utf8), to: &hasher) + case .file: + guard let id = entry.object, let data = objects[id] else { + throw CoreError.invalidState("file missing from captured tree") + } + appendLength(UInt64(data.count) + UInt64(regularFilePrefix.count), to: &hasher) + hasher.update(data: regularFilePrefix) + hasher.update(data: data) } } return hasher.finalize().map { String(format: "%02x", $0) }.joined() } + + private static func appendField(_ field: Data, to hasher: inout SHA256) { + appendLength(UInt64(field.count), to: &hasher) + hasher.update(data: field) + } + + private static func appendLength(_ count: UInt64, to hasher: inout SHA256) { + var length = count.bigEndian + withUnsafeBytes(of: &length) { hasher.update(bufferPointer: $0) } + } } diff --git a/Sources/AgentsCore/FileLock.swift b/Sources/AgentsCore/FileLock.swift index 207d745..835fe2a 100644 --- a/Sources/AgentsCore/FileLock.swift +++ b/Sources/AgentsCore/FileLock.swift @@ -1,30 +1,98 @@ +import CPlatform import Foundation - -#if canImport(Darwin) - import Darwin -#else - import Glibc -#endif +import Synchronization package enum FileLock { + /// Contended acquisitions are numbered within the process, so every wait has its own + /// checkpoint name. The ordinal only names checkpoints; it never changes locking. + private static let contentions = Atomic(0) + + static func ancestryCheckpoint(_ step: DirectoryHandle.AncestryStep) -> String { + "lock.ancestry." + step.name + } + + private static func contentionCheckpoint(_ ordinal: Int) -> String { + "lock.\(ordinal).contended" + } + + package static func isContentionCheckpoint(_ name: String) -> Bool { + let parts = name.split(separator: ".", omittingEmptySubsequences: false) + return parts.count >= 3 && parts[parts.count - 3] == "lock" && parts.last == "contended" + && Int(parts[parts.count - 2]) != nil + } + package static func withLock( at url: URL, checkpoint: (String) throws -> Void = { _ in }, _ body: () throws -> T ) throws -> T { try withDescriptor(at: url, checkpoint: checkpoint) { _ in try body() } } + package static func withLock( + in parent: DirectoryHandle, named name: String, _ body: () throws -> T + ) throws -> T { + try withDescriptor(in: parent, name: name) { _ in try body() } + } + + package static func withPrivateLock( + in parent: DirectoryHandle, named name: String, onContention: () -> Void, + _ body: () throws -> T + ) throws -> T { + try withDescriptor( + in: parent, name: name, + checkpoint: { point in + if isContentionCheckpoint(point) { onContention() } + }, privateFile: true, { _ in try body() }) + } + /// Children may inherit this open file description. Close, never explicitly unlock it: /// exclusion ends only when the last owner (including a surviving child) closes it. package static func withDescriptor( at url: URL, checkpoint: (String) throws -> Void = { _ in }, _ body: (Int32) throws -> T ) throws -> T { - let parent = try DirectoryHandle( - at: url.deletingLastPathComponent(), create: true, checkpoint: checkpoint) - let descriptor = openat( - parent.descriptor, url.lastPathComponent, O_CREAT | O_RDWR | O_NOFOLLOW | O_CLOEXEC, - S_IRUSR | S_IWUSR) + let parent = try DirectoryHandle(at: url.deletingLastPathComponent(), create: true) { + try checkpoint(ancestryCheckpoint($0)) + } + return try withDescriptor(in: parent, name: url.lastPathComponent, checkpoint: checkpoint, body) + } + + /// The caller pins and authorizes the existing parent; no absolute ancestry is created. + static func withDescriptor( + in parent: DirectoryHandle, name: String, checkpoint: (String) throws -> Void = { _ in }, + privateFile: Bool = false, _ body: (Int32) throws -> T + ) throws -> T { + let url = parent.url.appendingPathComponent(name) + func openLock(_ extraFlags: Int32 = 0) -> Int32 { + var file: Int32 + repeat { + file = openat( + parent.descriptor, name, O_RDWR | O_NOFOLLOW | O_CLOEXEC | extraFlags, + S_IRUSR | S_IWUSR) + } while file < 0 && errno == EINTR + return file + } + var descriptor = openLock() + if descriptor < 0, errno == ENOENT { + descriptor = openLock(O_CREAT | O_EXCL) + if descriptor < 0, errno == EEXIST { descriptor = openLock() } + } guard descriptor >= 0 else { - throw CoreError.invalidState("cannot open writer lock: \(url.path)") + let failure = errno + throw FileSystem.posixError( + failure, at: url, + otherwise: .invalidState("cannot open writer lock: \(url.path) (error \(failure))")) + } + do { + if privateFile { + let evidence = try FileAccessEvidence.requirePrivate(descriptor: descriptor) + guard evidence.identity.kind == S_IFREG else { + throw CoreError.invalidState("Private lock requires a regular file.") + } + } + // O_CREAT can return a writable fd even when the inherited ACL prevents reopening it. + try FileSystem.requireAccess(R_OK | W_OK, at: url, parent: parent.descriptor) + } catch { + close(descriptor) + throw error } return try withDescriptor(descriptor, at: url, checkpoint: checkpoint, body) } @@ -39,11 +107,84 @@ package enum FileLock { parent.descriptor, url.lastPathComponent, O_RDONLY | O_NOFOLLOW | O_CLOEXEC) if descriptor < 0, errno == ENOENT { return nil } guard descriptor >= 0 else { - throw CoreError.invalidState("cannot open existing lock: \(url.path)") + throw FileSystem.posixError( + errno, at: url, otherwise: .invalidState("cannot open existing lock: \(url.path)")) } return try withDescriptor(descriptor, at: url, checkpoint: { _ in }, body) } + /// Owns an acquired file description or an absent lock observed through this exact parent. + final class CoordinationDescriptor { + let descriptor: Int32 + private let parent: DirectoryHandle + private let name: String + private var isOpen: Bool + + fileprivate init(_ descriptor: Int32, parent: DirectoryHandle, name: String) { + self.descriptor = descriptor + self.parent = parent + self.name = name + isOpen = descriptor >= 0 + } + + deinit { release() } + + func finish() throws { + if descriptor >= 0 { + release() + } else if try parent.info(name) != nil { + throw CoordinationReadmission.required + } + } + + private func release() { + guard isOpen else { return } + isOpen = false + close(descriptor) + } + } + + static func acquireCoordinationDescriptor( + at url: URL, writable: Bool, checkpoint: (String) throws -> Void + ) throws -> CoordinationDescriptor { + let parent = try DirectoryHandle(at: url.deletingLastPathComponent()) + let name = url.lastPathComponent + let descriptor = openat( + parent.descriptor, name, (writable ? O_RDWR : O_RDONLY) | O_NOFOLLOW | O_CLOEXEC) + if descriptor < 0, !writable, errno == ENOENT { + return CoordinationDescriptor(-1, parent: parent, name: name) + } + guard descriptor >= 0 else { + if let exhaustion = OpenFileLimitError(errno, at: url) { throw exhaustion } + throw CoreError.invalidState("cannot open shared coordination lock") + } + let acquired = CoordinationDescriptor(descriptor, parent: parent, name: name) + let evidence = try FileAccessEvidence.requirePrivate(descriptor: descriptor) + guard evidence.identity.kind == S_IFREG else { + throw CoreError.invalidState("shared coordination lock is not a regular file") + } + let mode = writable ? LOCK_EX : LOCK_SH + while platform_flock(descriptor, mode | LOCK_NB) != 0 { + if errno == EINTR { continue } + guard errno == EWOULDBLOCK else { + throw CoreError.invalidState("cannot acquire shared coordination lock") + } + try checkpoint("contended") + while platform_flock(descriptor, mode) != 0 { + if errno != EINTR { + throw CoreError.invalidState("cannot acquire shared coordination lock") + } + } + break + } + guard try parent.info(name).map(FileObjectIdentity.init) == evidence.identity + else { + throw CoreError.invalidState("shared coordination lock changed") + } + try evidence.validate(descriptor: descriptor) + return acquired + } + private static func withDescriptor( _ descriptor: Int32, at url: URL, checkpoint: (String) throws -> Void, _ body: (Int32) throws -> T @@ -53,13 +194,14 @@ package enum FileLock { guard fstat(descriptor, &info) == 0, info.st_mode & 0o170000 == 0o100000 else { throw CoreError.unsafePath("writer lock must be a regular file: \(url.path)") } - while flock(descriptor, LOCK_EX | LOCK_NB) != 0 { + while platform_flock(descriptor, LOCK_EX | LOCK_NB) != 0 { if errno == EINTR { continue } guard errno == EWOULDBLOCK else { throw CoreError.invalidState("cannot acquire writer lock: \(url.path)") } - try checkpoint("lock.contended") - while flock(descriptor, LOCK_EX) != 0 { + try checkpoint( + contentionCheckpoint(contentions.wrappingAdd(1, ordering: .relaxed).oldValue)) + while platform_flock(descriptor, LOCK_EX) != 0 { if errno != EINTR { throw CoreError.invalidState("cannot acquire writer lock: \(url.path)") } diff --git a/Sources/AgentsCore/FileSystem.swift b/Sources/AgentsCore/FileSystem.swift new file mode 100644 index 0000000..e7fd317 --- /dev/null +++ b/Sources/AgentsCore/FileSystem.swift @@ -0,0 +1,101 @@ +import CPlatform +import Foundation + +struct OpenFileLimitError: LocalizedError, CustomStringConvertible { + let description: String + var errorDescription: String? { description } + + init?(_ code: Int32, at url: URL) { + switch code { + case EMFILE: description = "Too many open files for this process: \(url.path)" + case ENFILE: description = "Too many open files in the system: \(url.path)" + default: return nil + } + } +} + +/// Filesystem access diagnostics shared by descriptor and Foundation operations. +package enum FileSystem { + static func permissionDenied(at url: URL) -> CoreError { + .invalidState( + "permission denied: \(url.path); check the directory's permissions and default ACL") + } + + static func posixError(_ code: Int32, at url: URL, otherwise error: CoreError) -> any Error { + if let exhaustion = OpenFileLimitError(code, at: url) { return exhaustion } + return code == EACCES || code == EPERM ? permissionDenied(at: url) : error + } + + static func requireAccess( + _ mode: Int32, at url: URL, parent: Int32 = AT_FDCWD, name: String? = nil + ) throws { + let path = name ?? (parent == AT_FDCWD ? url.path : url.lastPathComponent) + guard platform_access(parent, path, mode) == 0 else { + throw posixError(errno, at: url, otherwise: .invalidState("cannot access \(url.path)")) + } + } + + package static func withAccessErrors(at url: URL, _ body: () throws -> T) throws -> T { + do { + return try body() + } catch let error as GitError { + throw error + } catch { + throw denial(in: error, at: url) ?? error + } + } + + /// The permission-denied error for `error`, or nil when no cause in its chain is a denial. + private static func denial(in error: Error, at url: URL) -> CoreError? { + var cause: NSError? = error as NSError + var denied = false + var failingURL: URL? + while let current = cause { + // Preserve the innermost supplied path; the operation URL may be a copy destination. + if let path = current.userInfo[NSFilePathErrorKey] as? String, !path.isEmpty { + failingURL = URL(fileURLWithPath: path) + } else if let url = current.userInfo[NSURLErrorKey] as? URL, url.isFileURL { + failingURL = url + } + if (current.domain == NSPOSIXErrorDomain + && [Int(EACCES), Int(EPERM)].contains(current.code)) + || (current.domain == NSCocoaErrorDomain + && [NSFileReadNoPermissionError, NSFileWriteNoPermissionError].contains(current.code)) + { + denied = true + } + cause = current.userInfo[NSUnderlyingErrorKey] as? NSError + } + return denied ? permissionDenied(at: failingURL ?? url) : nil + } + + package static func read(at url: URL) throws -> Data { + try withAccessErrors(at: url) { try Data(contentsOf: url) } + } + + /// Reads optional content whose absence or unreadability the caller tolerates. Only a + /// permission denial throws, so an unusable environment is not mistaken for missing content. + package static func readUnlessDenied(at url: URL) throws -> Data? { + do { + return try Data(contentsOf: url) + } catch { + if let denied = denial(in: error, at: url) { throw denied } + return nil + } + } + + package static func createDirectory(at url: URL) throws { + // Foundation callers permit existing aliases; descriptor operations still + // pin the resolved ancestry and create each missing component with 0700. + _ = try DirectoryHandle(at: url.resolvingSymlinksInPath(), create: true) + } + + package static func requireWritableFile(at url: URL) throws { + try requireAccess(R_OK | W_OK, at: url) + } + + package static func write(_ data: Data, to url: URL) throws { + let parent = try DirectoryHandle(at: url.deletingLastPathComponent().resolvingSymlinksInPath()) + try parent.write(url.lastPathComponent, data: data) + } +} diff --git a/Sources/AgentsCore/FileTransaction.swift b/Sources/AgentsCore/FileTransaction.swift index 57c063b..3b65da6 100644 --- a/Sources/AgentsCore/FileTransaction.swift +++ b/Sources/AgentsCore/FileTransaction.swift @@ -1,324 +1,693 @@ +import CPlatform import Foundation -/// A durable undo journal covers targets, scope state files and cache pruning. -/// The scope writer lock must be held through planning, commit and recovery. +/// The scope's sole durable undo journal owns private construction containers, +/// sealed publication evidence and terminal disposal. The scope writer lock spans +/// preparation, commit and recovery; external writers are identified by inode and digest. package final class FileTransaction { - private struct Entry: Codable { - var path: String - var existed: Bool - var replacement: Bool - var name: String { String(path.split(separator: "/").last!) } + package enum Source { + case data(Data) + case copy(URL) + /// A symbolic link to the URL, relative to the target parent when the URL is in the scope. + case link(URL) + /// A producer may construct arbitrary intermediate objects only inside its private container. + case prepared((URL) throws -> URL) } - private struct Journal: Codable { - var id: UUID - var scope: String - var roots: [String: String] - var phase: Phase - var entries: [Entry] - } - private enum Phase: String, Codable { case preparing, applying, committed, rolledBack } - private struct Content { - var url: URL? - var link: Bool - var data: Data? - var expectedHash: String? + /// Checks for the sealed staging; nil fields are not compared. + struct Expectation { + var hash: String? + /// Complete byte-identified subtree content and execute intent, independent of inode copies. + var objectDigest: String? var executableFlags: [String: Bool]? - var prepare: ((URL) throws -> URL)? + var kind: mode_t? + var mode: mode_t? + /// The destination a staged symbolic link must contain. + var linkDestination: String? + } + private struct Request { + let path: String + let evidence: TargetPrecondition + /// Ordinary input. Private installs produce bytes only after verified creation. + let source: Source? + let expectation: Expectation + let security: TransactionSecurity + let privateData: (() throws -> PrivateMaterializationResult)? + var privateTree: PrivateTree? = nil + var installs: Bool { source != nil || security.replacement == .privateMaterialization } } private let store: StateStore private let checkpoint: (String) throws -> Void private let outcome: TransactionOutcome - private var entries: [Entry] = [] - private var contents: [Content] = [] + private var requests: [Request] = [] + private var skillInitialization: SkillInitializationTarget? + private var skillInstallation: SkillInstallationTarget? + private var receiptStates: [String: MaterializationReceiptState] = [:] + private var receiptIndices: [Int: MaterializationReceiptState] = [:] + private var unchanged: [any PreparedEvidence] = [] + private var targetPaths: Set { Set(requests.map { $0.evidence.url.path }) } package init( store: StateStore, outcome: TransactionOutcome = TransactionOutcome(), checkpoint: @escaping (String) throws -> Void = { _ in } ) { self.store = store - self.checkpoint = checkpoint self.outcome = outcome + self.checkpoint = checkpoint } + /// `expectedHash` and `executableFlags` describe the content's tree hash and execute bits. package func replace( - _ destination: URL, content: URL?, link: Bool = false, data: Data? = nil, - expectedHash: String? = nil, executableFlags: [String: Bool]? = nil + _ destination: URL, with source: Source, expectedHash: String? = nil, + executableFlags: [String: Bool]? = nil, expecting: TargetPrecondition? = nil, + nativeArrayTransitions: [PrivateNativeArrayTransition]? = nil ) throws { - if let expectedHash { - try StateValidation.digest(expectedHash) - guard content != nil || data != nil else { - throw CoreError.invalidState("verification requires content") + if let expectedHash { try StateValidation.digest(expectedHash) } + let (path, evidence, previous) = try request(destination, expecting: expecting) + if path.hasPrefix(InstructionLocations.ruleRoot(in: store.scope) + "/") { + guard case .data = source, + InstructionLocations.isAntigravityLeaf(destination.lastPathComponent) + else { throw CoreError.unsafePath("Antigravity replacement requires a generated rule file") } + } + var security = previous + var expectation = Expectation(hash: expectedHash, executableFlags: executableFlags) + switch source { + case .copy(let url): + expectation = try Self.copyExpectation(url, hash: expectedHash, flags: executableFlags) + case .link(let url): + expectation.linkDestination = Self.linkDestination( + url, parent: destination.deletingLastPathComponent(), store: store) + case .data, .prepared: break + } + if let route = NativeTargetRoute.targetRoute(path) { + let requiredKind: mode_t = route.isContainer ? S_IFDIR : S_IFREG + if route.isContainer, case .data = source { + throw CoreError.unsafePath("registered native container requires a directory") + } + guard expectation.kind == nil || expectation.kind == requiredKind else { + throw CoreError.unsafePath("registered native target has the wrong object kind") + } + if case .link = source { + throw CoreError.unsafePath("registered native targets cannot be symbolic links") } + expectation.kind = requiredKind } - let path = try TransactionPaths(store: store).path(for: destination) - guard !entries.contains(where: { $0.path == path }) else { - throw CoreError.invalidState("duplicate transaction destination") + if skillInstallation != nil { + switch source { + case .data: + throw CoreError.unsafePath("skill installation requires a directory or live link") + case .link: + expectation.kind = S_IFLNK + case .copy, .prepared: + guard expectation.kind == nil || expectation.kind == S_IFDIR else { + throw CoreError.unsafePath("skill copy requires a directory") + } + expectation.kind = S_IFDIR + } + } + if security.preimage == .privateMaterialization { + guard case .data(let data) = source else { + throw CoreError.invalidState("sensitive replacement requires private byte construction") + } + security.replacement = .privateMaterialization + requests.append( + Request( + path: path, evidence: evidence, source: nil, expectation: expectation, + security: security, + privateData: { .init(bytes: data, nativeArrayTransitions: nativeArrayTransitions) })) + } else { + guard nativeArrayTransitions == nil else { + throw CoreError.invalidState("array tracking requires private materialization") + } + requests.append( + Request( + path: path, evidence: evidence, source: source, expectation: expectation, + security: security, privateData: nil)) } - entries.append(Entry(path: path, existed: false, replacement: content != nil || data != nil)) - contents.append( - Content( - url: content, link: link, data: data, expectedHash: expectedHash, - executableFlags: executableFlags, prepare: nil)) } - /// Builds source content inside journal-owned scratch storage before verified copying. - func prepare(_ destination: URL, content: @escaping (URL) throws -> URL) throws { - try replace(destination, content: nil) - entries[entries.count - 1].replacement = true - contents[contents.count - 1].prepare = content + /// Admits only this explicit, absent local authoring file to the ordinary journal. + package func initializeSkill(_ target: SkillInitializationTarget, bytes: Data) throws { + guard target.scope.path.utf8.elementsEqual(store.directory.path.utf8), + let context = TransactionLockContext.current(store), context.projectRootDirectory != nil + else { + throw CoreError.invalidState("skill initialization requires its observed existing parent") + } + try context.requireWriterScope() + try target.evidence.validate() + skillInitialization = target + defer { skillInitialization = nil } + try replace(target.file, with: .data(bytes), expecting: target.evidence) } - func remove(_ name: String, from parent: DirectoryHandle) throws { - try replace(parent.url.appendingPathComponent(name), content: nil) + package func replaceSkill( + _ target: SkillInstallationTarget, with source: Source, + expectedHash: String? = nil, expecting: TargetPrecondition? = nil + ) throws { + guard target.scope.path.utf8.elementsEqual(store.directory.path.utf8) else { + throw CoreError.invalidState("installation target belongs to another scope") + } + skillInstallation = target + defer { skillInstallation = nil } + try replace(target.url, with: source, expectedHash: expectedHash, expecting: expecting) } - package func commit() throws { - guard let directory = try store.openDirectoryIfPresent(), - try directory.info("transaction.json") == nil - else { - throw CoreError.invalidState("transaction recovery is required") + package func deleteSkill(_ target: SkillInstallationTarget, expecting: TargetPrecondition? = nil) + throws + { + guard target.scope.path.utf8.elementsEqual(store.directory.path.utf8) else { + throw CoreError.invalidState("installation target belongs to another scope") } - let paths = TransactionPaths(store: store) - var roots: [String: DirectoryHandle] = [:] - for entry in entries { - let key = try paths.components(entry.path).root - if roots[key] == nil { - roots[key] = try paths.root(key, create: true, checkpoint: checkpoint) + skillInstallation = target + defer { skillInstallation = nil } + try delete(target.url, expecting: expecting) + } + + package func delete(_ destination: URL, expecting: TargetPrecondition? = nil) throws { + let (path, evidence, security) = try request( + destination, expecting: expecting, allowMissingNativeArrays: true) + requests.append( + Request( + path: path, evidence: evidence, source: nil, expectation: .init(), security: security, + privateData: nil)) + } + + package func replaceArchive( + _ prepared: ArchiveDeploymentAccess, with source: Source, + skill: SkillInstallationTarget? = nil, expectedHash: String? = nil + ) throws { + if let skill { + guard skill.scope.path == store.directory.path, skill.url.path == prepared.target.url.path + else { + throw CoreError.invalidState("archive installation target belongs to another scope") } + skillInstallation = skill } - let parents = try entries.map { - try paths.parent(for: $0.path, roots: roots, create: true, checkpoint: checkpoint) - } - try Self.validateDestinations(entries, parents: parents) - if entries.contains(where: { - ["state/agents.watch", "state/agents.resolved"].contains($0.path) - }) { - try SourceCache(store: store, checkpoint: checkpoint).beginWatchReferenceUpdate() + defer { skillInstallation = nil } + try prepared.validate() + let destination = prepared.target.url + let (path, evidence, previous) = try request(destination, expecting: prepared.target) + var security = previous + security.ancestry = prepared.ancestry + security.archiveOutput = true + if let access = prepared.beforeAccess { + security.preimage = .privateMaterialization + security.preimageAccess = access + security.preimageTreeAccess = prepared.members } - for index in entries.indices { - entries[index].existed = try parents[index].info(entries[index].name) != nil - } - var journal = Journal( - id: UUID(), scope: try directory.identity, - roots: try roots.mapValues { try $0.identity }, phase: .preparing, entries: entries) - outcome.journalID = journal.id - do { - try Self.persist(journal, directory: directory, checkpoint: checkpoint) - try checkpoint("journal.preparing") - for (index, entry) in entries.enumerated() { - let parent = parents[index] - let backup = Self.temporaryName(journal, index, "old") - let staged = Self.temporaryName(journal, index, "new") - if entry.existed { try parent.copy(backup, from: parent, named: entry.name) } - try checkpoint("backup.\(index)") - var content = contents[index] - if let prepare = content.prepare { - let work = Self.temporaryName(journal, index, "work") - try parent.makeDirectory(work) - try checkpoint("prepare.\(index).directory") - let root = parent.url.appendingPathComponent(work) - let source = try prepare(root) - guard PathSafety.isContained(source.resolvingSymlinksInPath(), in: root) else { - throw CoreError.unsafePath("prepared content escapes transaction staging") - } - content.url = source - content.expectedHash = "sha256:" + (try FileHash.folderHash(source)) - content.executableFlags = try FileHash.executableFlags(source) - try checkpoint("prepare.\(index).ready") - } - if let data = content.data { - try parent.write(staged, data: data, preservingMetadataOf: entry.existed ? backup : nil) - try checkpoint("stage.\(index).written") - } else if let source = content.url { - if content.link { - try parent.link( - staged, destination: Self.linkDestination(source, parent: parent.url, store: store)) - } else { - try Self.validateCopy(source) - let origin = source.resolvingSymlinksInPath() - try parent.copy( - staged, from: DirectoryHandle(at: origin.deletingLastPathComponent()), - named: origin.lastPathComponent, - checkpoint: { try checkpoint("stage.\(index).copy.\($0)") }) - } - } - try checkpoint("stage.\(index).ready") - if let expectedHash = content.expectedHash { - let hash: String - if content.link, let source = content.url { - hash = try FileHash.folderHash(source) - } else if content.data == nil { - hash = try FileHash.folderHash(parent.child(staged)) - } else { - hash = try FileHash.sha256Hex(data: parent.read(staged)) - } - guard "sha256:" + hash == expectedHash else { - throw CoreError.invalidState("staged content digest mismatch") + let request: Request + switch source { + case .link(let url): + guard skill != nil else { + throw CoreError.unsafePath("private archive links require an admitted skill target") + } + try prepared.requirePrivateLinkTarget(url, environment: store.environment) + request = .init( + path: path, evidence: evidence, source: source, + expectation: .init( + kind: S_IFLNK, + linkDestination: Self.linkDestination( + url, parent: destination.deletingLastPathComponent(), store: store)), + security: security, privateData: nil) + case .copy(let root): + let captured = try LedgerResources.capture(root, embed: true, limits: .standard) + let entries: [PrivateTreeEntry] = try captured.entries.filter { $0.path != "." }.map { + entry in + let content: PrivateTreeEntry.Content + switch entry.kind { + case .directory: content = .directory + case .file: + guard let digest = entry.object, let bytes = captured.objects[digest] else { + throw SourceAccessError.invalidArchive } - try checkpoint("stage.\(index).verified") + content = .file(bytes, executable: entry.executable) + case .symlink: + guard let link = entry.link else { throw SourceAccessError.invalidArchive } + content = .symlink(link) } - if let flags = content.executableFlags { - let actual = - try content.link - ? FileHash.executableFlags(content.url!) - : FileHash.executableFlags(parent.child(staged)) - guard actual == flags else { - throw CoreError.invalidState("staged content executable mode mismatch") + return PrivateTreeEntry(entry.path, content: content) + } + let tree = try PrivateTree( + entries: entries, provider: NoArchiveBindings(), environment: store.environment) + security.replacement = .privateMaterialization + request = .init( + path: path, evidence: evidence, source: nil, + expectation: .init(hash: expectedHash, executableFlags: captured.flags, kind: S_IFDIR), + security: security, privateData: nil, privateTree: tree) + case .data(let data): + guard skill == nil else { throw CoreError.unsafePath("archive skill copy requires a tree") } + security.replacement = .privateMaterialization + request = .init( + path: path, evidence: evidence, source: nil, + expectation: .init(hash: expectedHash, kind: S_IFREG), + security: security, privateData: { .init(bytes: data) }) + case .prepared: + throw CoreError.unsafePath("archive publication requires a verified private producer") + } + requests.append(request) + } + + /// Values are resolved only inside commit, after private staging has been verified. + package func replacePrivate( + _ prepared: PreparedPrivateMaterialization, bindings: Set = [], + provider: any RuntimeBindingProvider, + render: @escaping (RuntimeBindingValues) throws -> Data + ) throws { + try replacePrivate( + prepared, bindings: bindings, provider: provider, + produce: { + .init(bytes: try render($0)) + }) + } + + /// Actual bytes and same-edit array transitions are resolved only in verified private staging. + package func replacePrivate( + _ prepared: PreparedPrivateMaterialization, bindings: Set = [], + provider: any RuntimeBindingProvider, + produce: @escaping (RuntimeBindingValues) throws -> PrivateMaterializationResult + ) throws { + guard NativeTargetRoute.targetRoute(prepared.target.path)?.isContainer != true, + prepared.target.scope.path == store.directory.path, prepared.owner == geteuid(), + bindings.allSatisfy({ !$0.isEmpty && !$0.contains("\0") }) + else { throw CoreError.invalidState("invalid private materialization inputs") } + guard let receiptEvidence = prepared.receiptEvidence else { + throw CoreError.invalidState( + "private publication requires an existing admitted native parent") + } + try receiptEvidence.validate() + let (path, evidence, previous) = try request( + prepared.target.url, expecting: prepared.evidence, allowMissingNativeArrays: true) + guard path == prepared.target.path else { + throw CoreError.invalidState("materialization registration changed") + } + try prepared.ancestry.validate(at: evidence.physicalURL.deletingLastPathComponent()) + var security = previous + security.replacement = .privateMaterialization + security.permissionChange = prepared.accessChange != nil + security.preimageAccess = prepared.beforeAccess + security.ancestry = prepared.ancestry + let environment = store.environment + requests.append( + Request( + path: path, evidence: evidence, source: nil, expectation: .init(), + security: security, + privateData: { + do { + var values: [String: Data] = [:] + for name in bindings.sorted() { + values[name] = try provider.value(for: name, environment: environment) + } + return try produce(RuntimeBindingValues(values)) + } catch { + throw CoreError.invalidState( + "private materialization could not resolve or render its bindings") } + })) + } + + /// Replaces one registered named container atomically. Inputs own their bytes. + package func replacePrivateTree( + _ prepared: PreparedPrivateMaterialization, entries: [PrivateTreeEntry], + provider: any RuntimeBindingProvider + ) throws { + guard NativeTargetRoute.targetRoute(prepared.target.path)?.isContainer == true, + prepared.target.scope.path.utf8.elementsEqual(store.directory.path.utf8), + prepared.owner == geteuid(), let receipt = prepared.receiptEvidence + else { throw CoreError.invalidState("private tree requires its prepared registered container") } + let tree = try PrivateTree(entries: entries, provider: provider, environment: store.environment) + try receipt.validate() + let (path, evidence, previous) = try request( + prepared.target.url, expecting: prepared.evidence, allowMissingNativeArrays: true) + guard path.utf8.elementsEqual(prepared.target.path.utf8) else { + throw CoreError.invalidState("materialization registration changed") + } + var security = previous + security.replacement = .privateMaterialization + security.permissionChange = prepared.accessChange != nil + security.preimageAccess = prepared.beforeAccess + security.preimageTreeAccess = prepared.preimageTreeAccess + security.ancestry = prepared.ancestry + requests.append( + Request( + path: path, evidence: evidence, source: nil, + expectation: .init(kind: S_IFDIR), security: security, privateData: nil, privateTree: tree)) + } + + private func queueReceipt() throws { + var byReceipt: [String: [(key: String, security: TransactionSecurity)]] = [:] + for request in requests { + let location = try store.materializationReceiptLocation(for: request.path) + byReceipt[location.path, default: []].append((location.key, request.security)) + } + for state in receiptStates.values.sorted(by: { $0.path < $1.path }) { + let shared = NativeTargetRoute.metadataRoute(state.path) != nil + let affected = (byReceipt[state.path] ?? []).filter { + ($0.security.isPrivate && $0.security.archiveOutput != true) + || state.records.targets[$0.key] != nil + } + guard !affected.isEmpty else { continue } + var sensitiveTargets = Set(state.records.targets.keys) + for request in affected { + if request.security.replacement == .privateMaterialization, + request.security.archiveOutput != true + { + sensitiveTargets.insert(request.key) + } else { + sensitiveTargets.remove(request.key) } - try checkpoint("stage.\(index)") - } - journal.phase = .applying - outcome.disposition = .recoveryRequired - try Self.persist(journal, directory: directory, checkpoint: checkpoint) - try checkpoint("journal.applying") - for (index, entry) in entries.enumerated() { - let parent = parents[index] - if entry.replacement { - try parent.rename( - Self.temporaryName(journal, index, "new"), to: entry.name, swap: entry.existed - ) { - try checkpoint("replace.\(index).renamed") - } - } else if entry.existed { - try parent.rename(entry.name, to: Self.temporaryName(journal, index, "removed")) { - try checkpoint("replace.\(index).renamed") - } + } + var security = TransactionSecurity() + security.preimage = state.access == nil ? .ordinary : .privateMaterialization + let deletesShared = shared && sensitiveTargets.isEmpty + security.replacement = deletesShared ? .ordinary : .privateMaterialization + security.preimageAccess = state.access + security.ancestry = try DirectoryAccessEvidence.capture( + at: state.url.deletingLastPathComponent()) + if !deletesShared { receiptIndices[requests.count] = state } + requests.append( + Request( + path: state.path, evidence: state.evidence, source: nil, + expectation: .init(), security: security, privateData: nil)) + } + } + + /// Prepared inputs that this journal does not replace must still match at commit entry, + /// after staging and after publication; the journal verifies its own targets itself. + package func requireUnchanged(since evidence: any PreparedEvidence...) { + unchanged += evidence + } + + private func validateUnchanged() throws { + for evidence in unchanged { try evidence.validate(excludingTargets: targetPaths) } + } + + private func request( + _ destination: URL, expecting: TargetPrecondition?, allowMissingNativeArrays: Bool = false + ) throws -> ( + path: String, evidence: TargetPrecondition, security: TransactionSecurity + ) { + let path = try TransactionPaths(store: store).path( + for: destination, skillInitialization: skillInitialization, installation: skillInstallation) + guard path != "state/" + MaterializationReceipts.fileName else { + throw CoreError.unsafePath("materialization receipts are transaction-owned") + } + if try TransactionPaths(store: store).coordinationRoute(for: path) != nil { + guard TransactionLockContext.current(store)?.writable == true else { + throw CoreError.invalidState("shared writes require the held writer footprint") + } + } + let receipt = try store.materializationReceipts(for: path) + if receiptStates[receipt.path] == nil { receiptStates[receipt.path] = receipt } + let receiptState = receiptStates[receipt.path]! + guard !requests.contains(where: { $0.path == path }) else { + throw CoreError.invalidState("duplicate transaction destination") + } + let evidence = try expecting ?? TargetPrecondition(destination) + if let route = NativeTargetRoute.targetRoute(path), let snapshot = evidence.snapshot { + let requiredKind: mode_t = route.isContainer ? S_IFDIR : S_IFREG + guard snapshot.identity.kind == requiredKind else { + throw CoreError.unsafePath("registered native preimage has the wrong object kind") + } + } + guard evidence.url.path == destination.standardizedFileURL.path else { + throw CoreError.invalidState("precondition belongs to another target") + } + if let snapshot = evidence.snapshot, snapshot.identity.isDirectory { + func holdsCoordination(_ value: FileSnapshot) -> Bool { + (value.children ?? []).contains { member in + let metadata = + member.name.utf8.elementsEqual(SharedResource.metadataName.utf8) + && member.snapshot.identity.isDirectory + && (member.snapshot.children ?? []).contains { domain in + domain.name.utf8.count == 64 + && domain.name.utf8.allSatisfy { (48...57).contains($0) || (97...102).contains($0) } + && domain.snapshot.identity.isDirectory + && domain.snapshot.child(named: "lock")?.isRegular == true + } + return metadata || holdsCoordination(member.snapshot) } - try checkpoint("replace.\(index)") } - journal.phase = .committed - try Self.persist(journal, directory: directory, checkpoint: checkpoint) - outcome.disposition = .committed - try checkpoint("journal.committed") - try Self.cleanup(journal, directory: directory, parents: parents, checkpoint: checkpoint) - } catch { - do { - _ = try Self.recover(store: store, outcome: outcome) - } catch { - outcome.disposition = .recoveryRequired + guard !holdsCoordination(snapshot) else { + throw CoreError.unsafePath("container contains independently coordinated native targets") } - throw error } + var security = TransactionSecurity() + if let record = receiptState.records.targets[try store.materializationReceiptKey(for: path)] { + guard try store.materializationRootIdentity(path) == record.rootIdentity else { + throw CoreError.invalidState("materialization receipt root changed") + } + // A known absence has no sensitive preimage; its receipt is reconciled in this journal. + guard evidence.snapshot != nil else { + guard record.nativeArrays == nil || allowMissingNativeArrays else { + throw CoreError.invalidState("tracked native file is missing its receipted preimage") + } + return (path, evidence, security) + } + guard evidence.snapshot?.digest == record.digest, + evidence.snapshot?.identity == record.access.identity + else { throw CoreError.invalidState("materialized preimage differs from its receipt") } + let parent = try DirectoryHandle(at: evidence.physicalURL.deletingLastPathComponent()) + _ = try parent.requirePrivateAccess(destination.lastPathComponent, matching: record.access) + security.preimage = .privateMaterialization + security.preimageAccess = record.access + security.preimageTreeAccess = record.treeAccess + try TreeMemberAccess.verify( + record.treeAccess, snapshot: evidence.snapshot!, named: destination.lastPathComponent, + in: parent, requirePrivate: true) + security.ancestry = try DirectoryAccessEvidence.capture(at: parent.url) + } + return (path, evidence, security) } - /// Recovers only after validating and pinning every parent in the journal. - package static func recover( - store: StateStore, outcome: TransactionOutcome? = nil, - checkpoint: (String) throws -> Void = { _ in } - ) - throws -> Bool - { - guard let directory = try store.openDirectoryIfPresent() else { return false } - guard try directory.info("transaction.json") != nil else { - guard try directory.info("transaction.new") != nil else { return false } - _ = try directory.read("transaction.new") - try directory.remove("transaction.new") - return true + static func copyExpectation( + _ source: URL, hash: String?, flags: [String: Bool]? + ) throws -> Expectation { + let physical = source.resolvingSymlinksInPath() + let parent = try DirectoryHandle(at: physical.deletingLastPathComponent()) + let capture = try FileSnapshot.capture(physical.lastPathComponent, from: parent) + guard let snapshot = capture.snapshot else { throw CoreError.notFound(source.path) } + return Expectation( + hash: hash ?? "sha256:" + capture.contentHash, objectDigest: snapshot.digest, + executableFlags: flags ?? capture.executableFlags, + kind: snapshot.identity.kind, mode: snapshot.mode) + } + + package func commit() throws { + guard !requests.isEmpty else { return } + let shared = try requests.filter { + try TransactionPaths(store: store).coordinationRoute(for: $0.path) != nil } - var journal = try StateStore.decode(directory.read("transaction.json"), as: Journal.self) - guard journal.scope == (try directory.identity) else { - throw CoreError.invalidState("transaction journal belongs to another scope location") + if !shared.isEmpty { + guard let context = TransactionLockContext.current(store), context.writable else { + throw CoreError.invalidState("shared commit requires its held writer footprint") + } + try context.requireWriterScope() + for request in shared { + let resource = try context.resource( + for: TransactionPaths(store: store).coordinationRoute(for: request.path)!) + let parent = try DirectoryHandle( + at: request.evidence.physicalURL.deletingLastPathComponent()) + guard try parent.objectIdentity == resource.identity.parent else { + throw CoreError.invalidState("shared commit physical registration changed") + } + } } - let paths = TransactionPaths(store: store) - var roots: [String: DirectoryHandle] = [:] - let keys = try Set(journal.entries.map { try paths.components($0.path).root }) - guard keys == Set(journal.roots.keys) else { - throw CoreError.invalidState("invalid transaction roots") - } - for key in keys { - let root = try paths.root(key) - guard try root.identity == journal.roots[key] else { - throw CoreError.invalidState("transaction root identity changed") - } - roots[key] = root - } - let parents = try journal.entries.map { try paths.parent(for: $0.path, roots: roots) } - try validateDestinations(journal.entries, parents: parents) - for (index, entry) in journal.entries.enumerated() { - if journal.phase == .applying, entry.existed, - try parents[index].info(temporaryName(journal, index, "old")) == nil + guard let directory = try store.openDirectoryIfPresent(), + try !TransactionJournal.isPresent(in: directory) + else { + throw CoreError.invalidState("transaction recovery is required") + } + try queueReceipt() + let paths = Set(requests.map(\.path)) + let originalLedger = "state/" + StateStore.originalLedgerFileName + let importingConfiguration = paths.contains(originalLedger) + if importingConfiguration { + guard + paths == [ + originalLedger, "state/" + StateStore.declarationFileName, + "state/" + StateStore.resolvedFileName, + ], requests.count == 3, requests.allSatisfy(\.installs), + requests.first(where: { $0.path == originalLedger })?.evidence.exists == false, + requests.first(where: { $0.path == "state/" + StateStore.declarationFileName })? + .evidence.exists == false, + requests.first(where: { $0.path == "state/" + StateStore.resolvedFileName })? + .evidence.exists == true + else { + throw CoreError.invalidState( + "configuration import requires the declaration, resolved ledger, and original ledger copy" + ) + } + } + for state in receiptStates.values { try state.evidence.validate() } + try validateUnchanged() + for request in requests { try request.evidence.validate() } + try validateOverlap() + let session = try makeSession(directory) + outcome.journalID = session.journal.id + do { + try session.persist(.created) + try session.emit(.phase(.preparing)) + try session.createReservations(owner: store.directory.path) + try session.createContainers() + try session.checkCapabilities() + // Capability probing may only touch missing ancestry, journal and private containers. + if !importingConfiguration, + session.journal.entries.contains(where: { + ["state/agents.watch", "state/agents.resolved"].contains($0.path) + }) { - throw CoreError.invalidState("missing transaction backup") - } - } - // Validate the journal's scratch file before any recovery mutation as well. - if try directory.info("transaction.new") != nil { _ = try directory.read("transaction.new") } - if journal.phase == .applying { - for (index, entry) in journal.entries.enumerated().reversed() { - let parent = parents[index] - if entry.existed { - let restore = temporaryName(journal, index, "restore") - try parent.remove(restore) - try parent.copy(restore, from: parent, named: temporaryName(journal, index, "old")) - try parent.rename(restore, to: entry.name, swap: try parent.info(entry.name) != nil) { - try checkpoint("restore.\(index).renamed") + try SourceCache(store: store, checkpoint: checkpoint).beginWatchReferenceUpdate() + } + for (index, request) in requests.enumerated() { + if let state = receiptIndices[index] { + try session.stage(index, source: request.source, expectation: request.expectation) { + let bytes = try StateStore.encode( + session.materializationReceipts( + previous: state.records, + targetRoot: NativeTargetRoute.metadataRoute(state.path)?.root)) + try LedgerAdmission.check(bytes, limits: .standard) + return .init(bytes: bytes) } - try parent.remove(restore) } else { - try parent.remove(entry.name) { try checkpoint("restore.\(index).remove.\($0)") } + let location = try store.materializationReceiptLocation(for: request.path) + let previous = receiptStates[location.path]?.records.targets[location.key] + try session.stage( + index, source: request.source, expectation: request.expectation, + privateData: request.privateData, privateTree: request.privateTree, + previousReceipt: previous) } - try checkpoint("restore.\(index)") } + try session.emit(.preconditions) + try validateUnchanged() + try session.validatePreimages() + outcome.requireRecovery() + for index in session.journal.entries.indices { try session.publish(index) } + try validateUnchanged() + try session.sealDisposal() + try session.emit(.commitValidated) + try session.finish(.committed) + outcome.recordTerminal(.committed) + try session.emit(.phase(.committed)) + try session.dispose() + outcome.recoveryPending = false + } catch { + // Recovery names its checkpoints under `recovery.`, apart from the failed commit's. + do { + _ = try Self.recover(store: store, outcome: outcome) { + try self.checkpoint("recovery." + $0) + } + } catch { + outcome.requireRecovery() + } + throw error } - if journal.phase == .applying || journal.phase == .preparing { - journal.phase = .rolledBack - try persist(journal, directory: directory, checkpoint: checkpoint) - } - try cleanup(journal, directory: directory, parents: parents, checkpoint: checkpoint) - if outcome?.journalID == journal.id { - outcome?.disposition = journal.phase == .committed ? .committed : .unchanged - } - return true } - private static func validateDestinations(_ entries: [Entry], parents: [DirectoryHandle]) throws { - var paths: [URL] = [] - for (index, entry) in entries.enumerated() { - let path = parents[index].url.appendingPathComponent(entry.name) + private func validateOverlap() throws { + var targets: [URL] = [] + var treeMembers = 0 + var treeBytes = 0 + for request in requests { + if let tree = request.privateTree { + guard tree.entries.count <= LedgerLimits.standard.entries - treeMembers, + tree.inputBytes <= LedgerLimits.standard.resourceBytes - treeBytes + else { throw CoreError.invalidState("private trees exceed candidate limits") } + treeMembers += tree.entries.count + treeBytes += tree.inputBytes + } + let target = request.evidence.physicalURL guard - !paths.contains(where: { - PathSafety.isContained(path, in: $0) || PathSafety.isContained($0, in: path) + !targets.contains(where: { + PathSafety.isContained(target, in: $0) || PathSafety.isContained($0, in: target) }) else { throw CoreError.invalidState("overlapping transaction destinations") } - paths.append(path) + targets.append(target) } } - private static func cleanup( - _ journal: Journal, directory: DirectoryHandle, parents: [DirectoryHandle], - checkpoint: (String) throws -> Void - ) throws { - // A visible terminal phase may have been renamed but not synced by a killed - // writer. Make that observed generation durable before deleting any backup. - try directory.syncFile("transaction.json") - try checkpoint("journal.terminalSynced") - for (index, _) in journal.entries.enumerated() { - for suffix in ["old", "new", "removed", "restore", "work"] { - try parents[index].remove(temporaryName(journal, index, suffix)) - } - try checkpoint("cleanup.\(index)") - } - try directory.remove("transaction.new") - try directory.remove("transaction.json") - try checkpoint("journal.removed") - } - - private static func temporaryName(_ journal: Journal, _ index: Int, _ suffix: String) -> String { - ".agents-\(journal.id.uuidString)-\(index).\(suffix)" - } - - private static func persist( - _ journal: Journal, directory: DirectoryHandle, - checkpoint: (String) throws -> Void - ) throws { - try directory.remove("transaction.new") - try directory.write("transaction.new", data: StateStore.encode(journal)) - try directory.rename("transaction.new", to: "transaction.json") { - try checkpoint("journal.\(journal.phase.rawValue).renamed") + private func makeSession(_ directory: DirectoryHandle) throws -> TransactionSession { + let paths = TransactionPaths(store: store) + var roots: [String: DirectoryHandle] = [:] + for request in requests { + let key = try paths.components(request.path).root + if roots[key] == nil { + roots[key] = try paths.root(key, create: true) { step in + try checkpoint(TransactionCheckpoint.rootAncestry(key, step).name) + } + } } + let parents = try requests.enumerated().map { index, request in + try paths.parent(for: request.path, roots: roots, create: true) { step in + try checkpoint(TransactionCheckpoint.parentAncestry(entry: index, step).name) + } + } + for (index, request) in requests.enumerated() { + try request.evidence.validateIdentity() + if NativeTargetRoute.targetRoute(request.path) != nil, + parents[index].url.standardizedFileURL.path + != request.evidence.physicalURL.deletingLastPathComponent().standardizedFileURL.path + { + throw CoreError.invalidState("registered native parent changed after preparation") + } + } + let id = UUID() + var containers: [TransactionJournal.Container] = [] + var identities: [String: Int] = [:] + var entries: [TransactionJournal.Entry] = [] + for (index, request) in requests.enumerated() { + let identity = try parents[index].identity + let container: Int + if let existing = identities[identity] { + container = existing + } else { + container = containers.count + identities[identity] = container + containers.append( + .init(entry: index, name: TransactionJournal.containerName(id: id, index: container))) + } + var security = request.security + if let ancestry = security.ancestry { + try ancestry.validate(at: parents[index].url, allowingCreation: true) + security.ancestry = try DirectoryAccessEvidence.capture(at: parents[index].url) + } + entries.append( + .init( + path: request.path, action: request.installs ? .install : .delete, + preimage: request.evidence.snapshot, parentIdentity: identity, container: container, + security: security)) + } + let entryRoutes = try entries.map { try paths.coordinationRoute(for: $0.path) } + let sharedRoutes = Set(entryRoutes.compactMap { $0 }) + let admittedResources = try sharedRoutes.map { route in + guard let context = TransactionLockContext.current(store) else { + throw CoreError.invalidState("shared transaction requires its held footprint") + } + return try context.resource(for: route) + }.sorted { $0.identity < $1.identity } + var resources: [SharedResource] = [] + var resourceIndices: [SharedResourceIdentity: Int] = [:] + for resource in admittedResources where resourceIndices[resource.identity] == nil { + resourceIndices[resource.identity] = resources.count + resources.append(resource) + } + for index in entries.indices { + if let route = entryRoutes[index] { + let resource = try TransactionLockContext.current(store)!.resource(for: route) + entries[index].coordination = resourceIndices[resource.identity] + entries[index].coordinationRoot = resource.route.root + } + } + let journal = TransactionJournal( + id: id, scope: try directory.identity, + roots: try roots.mapValues { try $0.identity }, entries: entries, containers: containers, + footprint: resources.map(\.identity)) + let session = TransactionSession( + journal: journal, directory: directory, parents: parents, + checkpoint: checkpoint, resources: resources, + nativeRoots: try paths.nativeRootAuthorities(Set(journal.roots.keys)), outcome: outcome) + try session.validateRecords(store: store) + return session } package static func linkDestination(_ source: URL, parent: URL, store: StateStore) -> String { @@ -334,22 +703,4 @@ package final class FileTransaction { } return source.path } - - /// A copied subtree keeps relative links that stay inside it, dangling ones included. - private static func validateCopy(_ source: URL) throws { - guard let root = PathSafety.realPath(source.path), - let entries = FileManager.default.enumerator( - at: URL(fileURLWithPath: root), includingPropertiesForKeys: [.isSymbolicLinkKey]) - else { return } - for case let entry as URL in entries { - if try entry.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink == true { - entries.skipDescendants() - let destination = try FileManager.default.destinationOfSymbolicLink(atPath: entry.path) - guard !destination.hasPrefix("/"), try PathSafety.linkStaysInside(entry, root: root) - else { - throw CoreError.unsafePath("copy symlink escapes installed subtree: \(entry.path)") - } - } - } - } } diff --git a/Sources/AgentsCore/GitError.swift b/Sources/AgentsCore/GitError.swift index b703a52..683b0cd 100644 --- a/Sources/AgentsCore/GitError.swift +++ b/Sources/AgentsCore/GitError.swift @@ -53,6 +53,8 @@ public struct GitError: Error, CustomStringConvertible, Equatable, Sendable { public let command: [String] /// Git's exit status, for debugging only. Classify with `operation`. public let exitCode: Int32 + /// Declaration and reference locations attached without changing the sanitized Git diagnostic. + public var context: [SourceSpan] = [] init( operation: Operation, source: String, stderr: String, command: [String], exitCode: Int32, @@ -80,7 +82,9 @@ public struct GitError: Error, CustomStringConvertible, Equatable, Sendable { public var description: String { let summary = "Git could not \(operation.description) \(source)." - return stderr.isEmpty ? summary : summary + "\n" + stderr + let diagnostic = stderr.isEmpty ? summary : summary + "\n" + stderr + return diagnostic + + context.map { " at \($0.document.rawValue):\($0.line):\($0.column)" }.joined() } private static func isProgress(_ line: String) -> Bool { diff --git a/Sources/AgentsCore/HostedMarketplace.swift b/Sources/AgentsCore/HostedMarketplace.swift new file mode 100644 index 0000000..1e8c789 --- /dev/null +++ b/Sources/AgentsCore/HostedMarketplace.swift @@ -0,0 +1,151 @@ +import Foundation + +/// Retrieval evidence for an immutable hosted release. The archive is stored in the lock's +/// content objects under the release digest. +public struct HostedMarketplaceEvidence: Codable, Equatable, Sendable { + public let indexDigest: String + public let archiveByteCount: Int + public let indexRequests: [URL] + public let archiveRequests: [URL] + + package init( + indexDigest: String, archiveByteCount: Int, indexRequests: [URL], archiveRequests: [URL] + ) { + self.indexDigest = indexDigest + self.archiveByteCount = archiveByteCount + self.indexRequests = indexRequests + self.archiveRequests = archiveRequests + } + + package func validate(index: String) throws { + try StateValidation.digest(indexDigest) + guard (1...LedgerLimits.standard.objectBytes).contains(archiveByteCount), + indexRequests.first?.absoluteString == index, let first = archiveRequests.first + else { throw MarketplaceError.invalidOrigin("invalid hosted release evidence") } + let anchor = try HostedMarketplaceLocation(index) + try anchor.validate(requests: indexRequests, archive: false) + guard try anchor.contains(HostedMarketplaceLocation(first.absoluteString)) else { + throw MarketplaceError.invalidOrigin("archive request is outside its catalog") + } + try anchor.validate(requests: archiveRequests, archive: true) + } + + package var requests: [URL] { indexRequests + archiveRequests } +} + +/// An HTTPS origin and an unambiguous absolute path. Reject encoded separators and dot +/// segments before Foundation can reinterpret them during URL resolution. +package struct HostedMarketplaceLocation: Equatable, Sendable { + package static let maximumRedirects = 5 + package static let indexFilename = "marketplace.json" + + package let url: URL + package let origin: SourceOrigin + package let path: String + + package init(_ location: String) throws { + guard location.utf8.count <= 4096, !location.contains("%"), + !location.utf8.contains(where: { $0 <= 32 || $0 >= 127 || $0 == 92 }), + let parts = URLComponents(string: location), parts.scheme?.lowercased() == "https", + parts.user == nil, parts.password == nil, parts.query == nil, parts.fragment == nil, + let host = parts.host, !host.isEmpty, !host.hasSuffix("."), + host.utf8.allSatisfy({ Self.alphanumeric($0) || [45, 46, 58, 91, 93].contains($0) }) + else { throw Self.invalidLocation } + let path = parts.percentEncodedPath + guard path.hasPrefix("/"), Self.validRelativePath(path.dropFirst()) else { + throw Self.invalidLocation + } + let origin = try SourceOrigin.http(location) + guard let canonical = URL(string: origin.identity! + path) else { + throw Self.invalidLocation + } + self.url = canonical + self.origin = origin + self.path = path + } + + package func archive(_ path: String) throws -> Self { + try Self.validateArchivePath(path) + return try Self(origin.identity! + prefix + path) + } + + package func redirect(to location: String) throws -> Self { + guard location.utf8.count <= 4096, !location.isEmpty, + !location.hasPrefix("//"), !location.contains("%") + else { throw Self.invalidLocation } + if location.hasPrefix("/") { + return try Self(origin.identity! + location) + } + if location.contains("://") { return try Self(location) } + return try archive(location) + } + + package func contains(_ destination: Self) -> Bool { + origin == destination.origin && destination.path.hasPrefix(prefix) + } + + package var policyPath: String { String(path.dropFirst()) } + + private var prefix: String { String(path.prefix(through: path.lastIndex(of: "/")!)) } + + fileprivate func validate(requests: [URL], archive: Bool) throws { + guard (1...Self.maximumRedirects + 1).contains(requests.count), + Set(requests).count == requests.count + else { throw Self.invalidLocation } + var prefixes = [origin: self] + for request in requests { + let destination = try Self(request.absoluteString) + guard request.absoluteString == destination.url.absoluteString else { + throw Self.invalidLocation + } + try admit(destination, prefixes: &prefixes, archive: archive) + } + } + + package func admit( + _ destination: Self, prefixes: inout [SourceOrigin: Self], archive: Bool + ) throws { + if let prefix = prefixes[destination.origin] { + guard prefix.contains(destination) else { throw Self.invalidLocation } + } else { + guard archive else { throw Self.invalidLocation } + prefixes[destination.origin] = destination + } + } + + package static func validateArchivePath(_ path: String) throws { + guard path.utf8.count <= 4096, validRelativePath(path[...]) else { throw invalidLocation } + } + + private static func validRelativePath(_ path: Substring) -> Bool { + !path.isEmpty + && path.split(separator: "/", omittingEmptySubsequences: false).allSatisfy { + !$0.isEmpty && $0 != "." && $0 != ".." + && $0.utf8.allSatisfy { alphanumeric($0) || [43, 45, 46, 95, 126].contains($0) } + } + } + + private static func alphanumeric(_ byte: UInt8) -> Bool { + (48...57).contains(byte) || (65...90).contains(byte) || (97...122).contains(byte) + } + + private static var invalidLocation: MarketplaceError { + .invalidOrigin("expected an unambiguous HTTPS marketplace URL or relative path") + } +} + +extension MarketplaceOrigin { + /// The URL persisted in authored roots and stable across registration name changes. + public var hostedIndex: URL? { + kind == .hosted ? URL(string: location) : nil + } + + public init(hostedIndex: URL) throws { + try self.init(kind: .hosted, location: hostedIndex.absoluteString) + } + + package var policyPath: String? { + if kind == .hosted { return (try? HostedMarketplaceLocation(location))?.policyPath } + return subpath + } +} diff --git a/Sources/AgentsCore/InstructionLocations.swift b/Sources/AgentsCore/InstructionLocations.swift index 4efb755..a821029 100644 --- a/Sources/AgentsCore/InstructionLocations.swift +++ b/Sources/AgentsCore/InstructionLocations.swift @@ -1,7 +1,47 @@ import Foundation -/// Fixed agent instruction destinations shared by lifecycle planning and journal validation. +/// Registered agent instruction destinations shared by lifecycle planning and journal validation. package enum InstructionLocations { + package static let antigravityRoot = "instructions-antigravity" + package static let antigravityFormat = "agents/antigravity-rule@1" + + package static let antigravityProjectRoot = "instructions-antigravity-project" + + package static func ruleRoot(in scope: InstallScope) -> String { + scope == .project ? antigravityProjectRoot : antigravityRoot + } + + static func antigravityAuthority( + _ environment: RuntimeEnvironment, scope: InstallScope + ) -> NativeRootAuthority { + switch scope { + case .project: .init(loader: environment.projectDirectory, descendants: [".agents", "rules"]) + case .user: + .init(loader: environment.homeDirectory, descendants: [".gemini", "config", "rules"]) + } + } + + package static func isAntigravityLeaf(_ name: String, legacy: Bool = false) -> Bool { + let pattern = + legacy + ? #"^memex-[a-z0-9][a-z0-9_-]{0,159}\.md\z"# : #"^agents-[a-z0-9_-]{1,60}-[a-f0-9]{64}\.md\z"# + return name.range(of: pattern, options: .regularExpression) != nil + } + + package static func antigravityLeaf(_ name: String, store: StateStore, legacy: Bool = false) + throws -> URL + { + guard !legacy || store.scope == .user, isAntigravityLeaf(name, legacy: legacy) else { + throw CoreError.unsafePath("unregistered Antigravity rule: \(name)") + } + return try antigravityAuthority(store.environment, scope: store.scope).physicalDirectory() + .appendingPathComponent(name) + } + + package static func isInstructionFormat(_ format: String) -> Bool { + ["agents/instructions@1", "agents/claude-import@1", antigravityFormat].contains(format) + } + package static let projectPaths = [ "AGENTS.md", "GEMINI.md", "CLAUDE.md", ".claude/CLAUDE.md", "CLAUDE.local.md", ] @@ -23,11 +63,11 @@ package enum InstructionLocations { package static func file( for agent: AgentID, scope: InstallScope, environment: RuntimeEnvironment ) -> URL? { + guard agent != .antigravity, agent.supportsInstructions(in: scope) else { return nil } if scope == .project { return environment.projectDirectory.appendingPathComponent( agent == .geminiCLI ? "GEMINI.md" : "AGENTS.md") } - guard agent != .cursor else { return nil } let directory = AgentRegistry.userSkillsDirectory(for: agent, environment: environment) .deletingLastPathComponent() let name = agent == .claudeCode ? "CLAUDE.md" : agent == .geminiCLI ? "GEMINI.md" : "AGENTS.md" @@ -51,6 +91,15 @@ package enum InstructionLocations { } package static func file(for key: String, store: StateStore) throws -> URL { + let ruleRoot = antigravityAuthority(store.environment, scope: store.scope) + let name = (key as NSString).lastPathComponent + if isAntigravityLeaf(name), + key + == self.key( + for: try ruleRoot.plannedPhysicalDirectory.appendingPathComponent(name), store: store) + { + return try antigravityLeaf(name, store: store) + } let file: URL if key.hasPrefix("/") { guard store.scope == .user else { throw CoreError.unsafePath("absolute project target") } @@ -82,3 +131,25 @@ package enum InstructionLocations { return file.standardizedFileURL } } + +extension InstructionLocations { + package static func clientFiles( + for agent: AgentID, scope: InstallScope, environment: RuntimeEnvironment + ) -> [(String, URL)] { + if agent == .antigravity { + return [ + ("instructions.rules", antigravityAuthority(environment, scope: scope).logicalDirectory) + ] + } + var result = + file(for: agent, scope: scope, environment: environment).map { + [("instructions.fixed", $0)] + } ?? [] + if agent == .claudeCode && scope == .project { + result += projectPaths.filter { $0.contains("CLAUDE") }.map { + ("instructions." + $0, environment.projectDirectory.appendingPathComponent($0)) + } + } + return result + } +} diff --git a/Sources/AgentsCore/LedgerAdmission.swift b/Sources/AgentsCore/LedgerAdmission.swift new file mode 100644 index 0000000..f44c26e --- /dev/null +++ b/Sources/AgentsCore/LedgerAdmission.swift @@ -0,0 +1,252 @@ +import Foundation + +/// All counts are aggregate per ledger. The caller may reduce limits for a constrained operation. +package struct LedgerLimits: Sendable { + package var encodedBytes: Int + package var depth: Int + package var nodes: Int + package var objectBytes: Int + package var entries: Int + package var keyBytes: Int + package var resourceBytes: Int + package init( + encodedBytes: Int, depth: Int, nodes: Int, objectBytes: Int, entries: Int, keyBytes: Int, + resourceBytes: Int? = nil + ) { + self.encodedBytes = encodedBytes + self.depth = depth + self.nodes = nodes + self.objectBytes = objectBytes + self.entries = entries + self.keyBytes = keyBytes + self.resourceBytes = resourceBytes ?? objectBytes + } +} + +/// Grammar and aggregate bounds are checked before Foundation constructs a decoded object graph. +package enum LedgerAdmission { + package static func check(_ data: Data, limits: LedgerLimits) throws { + guard data.count <= limits.encodedBytes, limits.depth > 0, limits.nodes > 0, + limits.objectBytes >= 0, limits.entries >= 0, limits.keyBytes > 0, + String(data: data, encoding: .utf8) != nil, !data.starts(with: [239, 187, 191]) + else { + throw CoreError.invalidState("ledger encoding or byte budget") + } + var scanner = Scanner(data: data, limits: limits) + try scanner.value(depth: 0) + scanner.space() + guard scanner.index == data.count else { throw CoreError.invalidState("trailing ledger JSON") } + } + + private struct Scanner { + let data: Data + let limits: LedgerLimits + var index = 0 + var nodes = 0 + var objectBytes = 0 + var entries = 0 + + var byte: UInt8? { index < data.count ? data[index] : nil } + mutating func space() { while let byte, [9, 10, 13, 32].contains(byte) { index += 1 } } + mutating func take(_ expected: UInt8) throws { + guard byte == expected else { throw CoreError.invalidState("invalid ledger JSON") } + index += 1 + } + + mutating func value( + depth: Int, contentObjects: Bool = false, object: Bool = false, treeEntries: Bool = false, + pendingDeployment: Bool = false, pendingLedger: Bool = false + ) throws { + nodes += 1 + guard depth <= limits.depth, nodes <= limits.nodes else { + throw CoreError.invalidState("ledger structure budget") + } + space() + guard let current = byte else { throw CoreError.invalidState("truncated ledger JSON") } + switch current { + case 123: + index += 1 + space() + var keys = Set() + if byte == 125 { + index += 1 + return + } + while true { + let range = try string() + guard range.count <= limits.keyBytes else { + throw CoreError.invalidState("ledger key budget") + } + let contents = data[(range.lowerBound + 1)..<(range.upperBound - 1)] + // The whole input is valid UTF-8 and string() has checked the token's grammar. + let key = + if contents.contains(92) { + try JSONDecoder().decode(String.self, from: data.subdata(in: range)) + } else { + String(decoding: contents, as: UTF8.self) + } + guard keys.insert(key).inserted else { + throw CoreError.invalidState("duplicate ledger key") + } + space() + try take(58) + try value( + depth: depth + 1, + contentObjects: (depth == 0 || pendingLedger) && key == "contentObjects", + object: contentObjects, treeEntries: key == "entries" || key == "support", + pendingDeployment: depth == 0 && key == "pendingMarketplaceDeployment", + pendingLedger: pendingDeployment && key == "ledger") + space() + if byte == 125 { + index += 1 + break + } + try take(44) + space() + } + case 91: + index += 1 + space() + if byte == 93 { + index += 1 + return + } + while true { + if treeEntries { + entries += 1 + guard entries <= limits.entries else { + throw CoreError.invalidState("ledger entry budget") + } + } + try value(depth: depth + 1) + space() + if byte == 93 { + index += 1 + break + } + try take(44) + } + case 34: + let range = try string() + if object { + let count = try base64Bytes(in: range) + guard count <= limits.objectBytes - objectBytes else { + throw CoreError.invalidState("ledger content byte budget") + } + objectBytes += count + } + case 116: try literal("true") + case 102: try literal("false") + case 110: try literal("null") + case 45, 48...57: try number() + default: throw CoreError.invalidState("invalid ledger JSON value") + } + } + + /// Counts the decoded Base64 spelling without allocating either the unescaped string or bytes. + func base64Bytes(in range: Range) throws -> Int { + var cursor = range.lowerBound + 1 + let end = range.upperBound - 1 + var length = 0 + var padding = 0 + while cursor < end { + var scalar = Int(data[cursor]) + cursor += 1 + if scalar == 92 { + let escaped = data[cursor] + cursor += 1 + if escaped == 117 { + scalar = 0 + for _ in 0..<4 { + let hex = Int(data[cursor]) + scalar = scalar * 16 + (hex <= 57 ? hex - 48 : hex <= 70 ? hex - 55 : hex - 87) + cursor += 1 + } + } else if escaped == 47 { + scalar = 47 + } else { + throw CoreError.invalidState("invalid content encoding") + } + } + length += 1 + if scalar == 61 { + padding += 1 + guard padding <= 2 else { throw CoreError.invalidState("invalid content padding") } + } else { + guard padding == 0, + (65...90).contains(scalar) || (97...122).contains(scalar) + || (48...57).contains(scalar) || scalar == 43 || scalar == 47 + else { + throw CoreError.invalidState("invalid content encoding") + } + } + } + guard length % 4 == 0 else { throw CoreError.invalidState("invalid content encoding") } + return length / 4 * 3 - padding + } + + mutating func literal(_ text: String) throws { + for value in text.utf8 { try take(value) } + } + + mutating func string() throws -> Range { + let start = index + try take(34) + while let value = byte { + index += 1 + if value == 34 { return start..= 32 else { throw CoreError.invalidState("control byte in ledger string") } + if value == 92 { + guard let escaped = byte else { throw CoreError.invalidState("truncated ledger escape") } + index += 1 + if escaped == 117 { + for _ in 0..<4 { + guard let hex = byte, + (48...57).contains(hex) || (65...70).contains(hex) + || (97...102).contains(hex) + else { + throw CoreError.invalidState("invalid ledger Unicode escape") + } + index += 1 + } + } else if ![34, 92, 47, 98, 102, 110, 114, 116].contains(escaped) { + throw CoreError.invalidState("invalid ledger escape") + } + } + } + throw CoreError.invalidState("unterminated ledger string") + } + + mutating func number() throws { + if byte == 45 { index += 1 } + if byte == 48 { + index += 1 + } else { + guard let byte, (49...57).contains(byte) else { + throw CoreError.invalidState("invalid ledger number") + } + digits() + } + if byte == 46 { + index += 1 + let start = index + digits() + guard index > start else { throw CoreError.invalidState("invalid ledger fraction") } + } + if byte == 101 || byte == 69 { + index += 1 + if byte == 43 || byte == 45 { index += 1 } + let start = index + digits() + guard index > start else { throw CoreError.invalidState("invalid ledger exponent") } + } + } + mutating func digits() { while let byte, (48...57).contains(byte) { index += 1 } } + } +} + +extension LedgerLimits { + package static let standard = LedgerLimits( + encodedBytes: 256 * 1024 * 1024, depth: 128, nodes: 2_000_000, + objectBytes: 128 * 1024 * 1024, entries: 100_000, keyBytes: 256 * 1024 * 1024) +} diff --git a/Sources/AgentsCore/LedgerDisplayEvidence.swift b/Sources/AgentsCore/LedgerDisplayEvidence.swift new file mode 100644 index 0000000..1a137f6 --- /dev/null +++ b/Sources/AgentsCore/LedgerDisplayEvidence.swift @@ -0,0 +1,84 @@ +import Foundation + +extension TargetPrecondition { + package func capturingPublicationAccess() throws -> Self { try capturingAccess() } + + /// A verified adoption or migration binds to the exact file generation shown in its preview. + package func generationEvidence() throws -> String { + struct Generation: Encodable { + let path: String + let snapshot: FileSnapshot? + } + return try ResolvedLedgerCodec.digest(Generation(path: physicalURL.path, snapshot: snapshot)) + } + /// Stable access semantics omit inode generations, timestamps and private payload digests. + package func displayEvidence(includeContent: Bool) throws -> String { + struct Access: Encodable { + let owner: UInt32 + let group: UInt32 + let mode: UInt32 + let acl: Data + let defaults: Data + init(_ evidence: FileAccessEvidence) { + owner = evidence.owner + group = evidence.group + mode = UInt32(evidence.mode) + acl = evidence.acl + defaults = evidence.defaultACL + } + } + struct Display: Encodable { + let path: String + let exists: Bool + let content: String? + let target: Access? + let ancestry: [Access] + let linkOwner: UInt32? + let linkGroup: UInt32? + } + let access = try TargetAccessPrecondition.capture(at: physicalURL) + var ancestry = access.ancestry.directories + for (root, before) in TransactionLockContext.currentForDisplay?.createdAncestry ?? [] { + let parent = physicalURL.deletingLastPathComponent() + // Creating a nested lock directory can also create the parent of a sibling output. + // A separate branch that appeared after preview must still change its fingerprint. + let existingDepth = access.ancestry.directories.count + let sharedDepth = zip(root.pathComponents, parent.pathComponents) + .prefix { $0.0.utf8.elementsEqual($0.1.utf8) }.count + let sharesCreatedParent = + existingDepth > before.directories.count && existingDepth <= sharedDepth + if parent.path == root.path || parent.path.hasPrefix(root.path + "/") || sharesCreatedParent { + guard access.ancestry.directories.starts(with: before.directories) else { + throw CoreError.invalidState("existing publication ancestry access changed") + } + if before.directories.count < ancestry.count { ancestry = before.directories } + } + } + return try ResolvedLedgerCodec.digest( + Display( + path: physicalURL.path, exists: snapshot != nil, + content: includeContent ? snapshot?.digest : nil, + target: access.target.map(Access.init), + ancestry: ancestry.map(Access.init), linkOwner: access.linkOwner, + linkGroup: access.linkGroup)) + } +} + +extension TargetPrecondition { + /// Publication may create previously absent ancestry. Existing access and the leaf generation + /// stay fixed; the transaction separately owns every created container. + package func validateDuringPublication() throws { + try validateIdentity() + if let access { + let current = try TargetAccessPrecondition.capture(at: physicalURL) + guard current.target == access.target, current.linkOwner == access.linkOwner, + current.linkGroup == access.linkGroup, + current.ancestry.directories.starts(with: access.ancestry.directories) + else { + throw CoreError.invalidState( + "target or existing ancestry access changed during publication") + } + } + try validateSnapshot() + } +} diff --git a/Sources/AgentsCore/LedgerNativeAuthority.swift b/Sources/AgentsCore/LedgerNativeAuthority.swift new file mode 100644 index 0000000..6db7361 --- /dev/null +++ b/Sources/AgentsCore/LedgerNativeAuthority.swift @@ -0,0 +1,171 @@ +import Foundation + +/// Evidence for one admitted native document. Physical admission and continuity belong to D/E/F. +package struct LedgerNativeAuthority: Codable, Equatable, Sendable { + package var version: Int = 1 + package var target: LedgerLocation + package var targetRoute: String + /// Closed dialects: json, jsonc, jsonc-trailing-commas, toml. JSONC alone forbids trailing commas. + package var documentFormat: String + package var regions: [LedgerNativeOwnedRegion] + package var createdContainers: [LedgerNativeCreatedContainer] + + package init( + target: LedgerLocation, targetRoute: String, documentFormat: String, + regions: [LedgerNativeOwnedRegion], createdContainers: [LedgerNativeCreatedContainer] = [] + ) { + self.target = target + self.targetRoute = targetRoute + self.documentFormat = documentFormat + self.regions = regions + self.createdContainers = createdContainers + } + + package static func == (a: Self, b: Self) -> Bool { + a.version == b.version && a.target.kind == b.target.kind + && a.target.root.map { Data($0.utf8) } == b.target.root.map { Data($0.utf8) } + && Data(a.target.path.utf8) == Data(b.target.path.utf8) + && Data(a.targetRoute.utf8) == Data(b.targetRoute.utf8) + && Data(a.documentFormat.utf8) == Data(b.documentFormat.utf8) + && a.regions == b.regions && a.createdContainers == b.createdContainers + } +} + +package struct LedgerNativeOwnedRegion: Codable, Equatable, Sendable { + package var deployments: [String] + package var path: [LedgerNativePathStep] + package init(deployments: [String], path: [LedgerNativePathStep]) { + self.deployments = deployments + self.path = path + } + package static func == (a: Self, b: Self) -> Bool { + a.deployments.map { Data($0.utf8) } == b.deployments.map { Data($0.utf8) } + && a.path == b.path + } +} + +package struct LedgerNativeCreatedContainer: Codable, Equatable, Sendable { + package var deployments: [String] + package var path: [LedgerNativePathStep] + package var kind: String + package init(deployments: [String], path: [LedgerNativePathStep], kind: String) { + self.deployments = deployments + self.path = path + self.kind = kind + } + package static func == (a: Self, b: Self) -> Bool { + a.deployments.map { Data($0.utf8) } == b.deployments.map { Data($0.utf8) } + && a.path == b.path && Data(a.kind.utf8) == Data(b.kind.utf8) + } +} + +/// Decoded native strings retain UTF-8 identity; these are not filesystem paths. +package enum LedgerNativePathStep: Codable, Equatable, Sendable { + case key(String) + case stableID(key: String, value: String) + case position(index: Int, evidence: LedgerNativeArrayEvidence) + + private enum CodingKeys: String, CodingKey { case kind, key, value, index, evidence } + private enum Kind: String, Codable { case key, stableID, position } + + package init(from decoder: any Decoder) throws { + let fields = try decoder.container(keyedBy: CodingKeys.self) + let kind = try fields.decode(Kind.self, forKey: .kind) + let allowed: Set + switch kind { + case .key: + allowed = [.kind, .key] + self = .key(try fields.decode(String.self, forKey: .key)) + case .stableID: + allowed = [.kind, .key, .value] + self = .stableID( + key: try fields.decode(String.self, forKey: .key), + value: try fields.decode(String.self, forKey: .value)) + case .position: + allowed = [.kind, .index, .evidence] + self = .position( + index: try fields.decode(Int.self, forKey: .index), + evidence: try fields.decode(LedgerNativeArrayEvidence.self, forKey: .evidence)) + } + guard Set(fields.allKeys).isSubset(of: allowed) else { + throw CoreError.invalidState("invalid native path fields") + } + } + + package func encode(to encoder: any Encoder) throws { + var fields = encoder.container(keyedBy: CodingKeys.self) + switch self { + case .key(let key): + try fields.encode(Kind.key, forKey: .kind) + try fields.encode(key, forKey: .key) + case .stableID(let key, let value): + try fields.encode(Kind.stableID, forKey: .kind) + try fields.encode(key, forKey: .key) + try fields.encode(value, forKey: .value) + case .position(let index, let evidence): + try fields.encode(Kind.position, forKey: .kind) + try fields.encode(index, forKey: .index) + try fields.encode(evidence, forKey: .evidence) + } + } + + package static func == (a: Self, b: Self) -> Bool { + switch (a, b) { + case (.key(let x), .key(let y)): x.utf8.elementsEqual(y.utf8) + case (.stableID(let x, let y), .stableID(let u, let v)): + x.utf8.elementsEqual(u.utf8) && y.utf8.elementsEqual(v.utf8) + case (.position(let x, let y), .position(let u, let v)): x == u && y == v + default: false + } + } +} + +/// Semantic digests are non-secret. Private tokens contain no array values or secret digests. +package enum LedgerNativeArrayEvidence: Codable, Equatable, Sendable { + case semantic(format: String, digest: String) + case privateArray(token: UUID) + + private enum CodingKeys: String, CodingKey { case kind, format, digest, token } + private enum Kind: String, Codable { case semantic, privateArray } + + package init(from decoder: any Decoder) throws { + let fields = try decoder.container(keyedBy: CodingKeys.self) + let kind = try fields.decode(Kind.self, forKey: .kind) + let allowed: Set + switch kind { + case .semantic: + allowed = [.kind, .format, .digest] + self = .semantic( + format: try fields.decode(String.self, forKey: .format), + digest: try fields.decode(String.self, forKey: .digest)) + case .privateArray: + allowed = [.kind, .token] + self = .privateArray(token: try fields.decode(UUID.self, forKey: .token)) + } + guard Set(fields.allKeys).isSubset(of: allowed) else { + throw CoreError.invalidState("invalid native array evidence fields") + } + } + + package func encode(to encoder: any Encoder) throws { + var fields = encoder.container(keyedBy: CodingKeys.self) + switch self { + case .semantic(let format, let digest): + try fields.encode(Kind.semantic, forKey: .kind) + try fields.encode(format, forKey: .format) + try fields.encode(digest, forKey: .digest) + case .privateArray(let token): + try fields.encode(Kind.privateArray, forKey: .kind) + try fields.encode(token, forKey: .token) + } + } + + package static func == (a: Self, b: Self) -> Bool { + switch (a, b) { + case (.semantic(let x, let y), .semantic(let u, let v)): + x.utf8.elementsEqual(u.utf8) && y.utf8.elementsEqual(v.utf8) + case (.privateArray(let x), .privateArray(let y)): x == y + default: false + } + } +} diff --git a/Sources/AgentsCore/LedgerProjection.swift b/Sources/AgentsCore/LedgerProjection.swift new file mode 100644 index 0000000..c171e02 --- /dev/null +++ b/Sources/AgentsCore/LedgerProjection.swift @@ -0,0 +1,125 @@ +import Foundation + +extension ResolvedLedger { + /// Bundled producers use the package revision recorded with their content. + package func bundledSourceIdentities(in store: StateStore, roots: [String: URL]) throws -> Set< + String + > { + try Set( + sources.compactMap { key, source in + guard source.bundleSources != nil, let location = source.location, + BundleSourceLocation.container(of: try location.resolve(roots: roots), in: store) != nil + else { return nil } + return try sourceIdentity(key, roots: roots) + }) + } + + /// Domain inventory views are derived from the ledger; they are never persisted as state. + package func domainProjection(roots: [String: URL]) throws -> ResolvedState { + var result = ResolvedState() + let contentSources = Set( + components.values.filter { ["skills", "instructions"].contains($0.kind) }.map(\.source)) + for (id, source) in sources where contentSources.contains(id) { + let identity = try sourceIdentity(id, roots: roots) + result.sources[identity] = LockedSource( + kind: source.kind, url: source.kind == .git ? source.transport : nil, + requirement: sourceUses.first(where: { $0.source == id })?.requirement, + path: sourceUses.first(where: { $0.source == id }).flatMap { + $0.root == "." ? nil : $0.root + }) + } + var seen = Set() + for occurrence in occurrences { + guard let component = components[occurrence.component] else { continue } + let id = occurrence.component + let source = try sourceIdentity(component.source, roots: roots) + let resource = component.resources.first.flatMap { resources[$0] } + if component.kind == DeclaredComponentKind.skills.rawValue, let resource { + let mode = component.payload.object?["mode"]?.text.flatMap(InstallMode.init) ?? .copy + let name = PathSafety.sanitizeName(component.name) + var skill = + result.skills[name] + ?? LockedSkill( + source: source, revision: component.revision, version: component.version, + artifact: resource.artifact, + path: resource.artifact != nil && resource.path == "." ? nil : resource.path, + hash: mode == .edit ? nil : resource.hash, installs: [:]) + for agent in component.recipients { skill.installs[agent.rawValue] = mode } + result.skills[name] = skill + } else if component.kind == DeclaredComponentKind.instructions.rawValue, let resource { + let own = + resource.path.hasPrefix(".agent/instructions/") + && sources[component.source]?.revision == "live" + && sources[component.source]?.location?.root == "project" + let section = LockedSection( + name: component.name, source: own ? "." : source, + revision: component.revision, version: component.version, + artifact: resource.artifact, path: resource.path, + hash: component.payload.object?["sourceHash"]?.text ?? resource.hash) + if component.chatGPT, let prompt = component.payload.object?["prompt"]?.text { + result.instructions.chatgpt[prompt, default: LockedPrompt(sections: [])].sections.append( + section) + if let value = component.payload.object?["localAppend"] { + result.instructions.chatgpt[prompt]?.append = try LedgerLocation(ledgerValue: value) + .path + } else if let append = component.resources.dropFirst().first.flatMap({ resources[$0] }) { + result.instructions.chatgpt[prompt]?.append = append.path + } + } else if !component.recipients.isEmpty { + result.instructions.sections.append(section) + } + } + seen.insert(id) + } + for deployment in deployments + where InstructionLocations.isInstructionFormat(deployment.route) { + let key = try instructionTargetKey(deployment.target, roots: roots) + result.instructions.targets[key] = LockedTarget( + agents: deployment.recipients, headingOffset: deployment.headingOffset, + import: deployment.importReference, blockHash: deployment.expectedHash, + created: deployment.created) + } + return result + } + + package func instructionTargetKey(_ target: LedgerLocation, roots: [String: URL]) throws -> String + { + let file = try target.resolve(roots: roots) + if target.root == "project" || target.root == InstructionLocations.antigravityProjectRoot, + let project = roots["project"] + { + return PathSafety.relativePath(file.path, to: project.path) + } + if let home = roots["home"], PathSafety.isContained(file, in: home) { + return "~/" + PathSafety.relativePath(file.path, to: home.path) + } + return file.path + } + + package func rootSource(_ id: String) throws -> LedgerSource { + guard var source = sources[id] else { throw CoreError.invalidState("missing source authority") } + var visited = Set() + while let parent = source.container { + guard visited.insert(parent).inserted, let container = sources[parent] else { + throw CoreError.invalidState("invalid source container") + } + source = container + } + return source + } + + package func sourceIdentity(_ id: String, roots: [String: URL]) throws -> String { + guard let source = sources[id] else { throw CoreError.invalidState("missing ledger source") } + if let parent = source.container { + return try sourceIdentity(parent, roots: roots) + (source.namespace ?? "") + } + if let location = source.location { + return "local:" + (try location.resolve(roots: roots).path) + } + if let transport = source.transport { + return try SourceDeclaration(kind: source.kind, location: transport).identity( + environment: RuntimeEnvironment(environment: [:])) + } + throw CoreError.invalidState("missing source identity coordinates") + } +} diff --git a/Sources/AgentsCore/LedgerResourceLinks.swift b/Sources/AgentsCore/LedgerResourceLinks.swift new file mode 100644 index 0000000..55cbd16 --- /dev/null +++ b/Sources/AgentsCore/LedgerResourceLinks.swift @@ -0,0 +1,103 @@ +import Foundation + +extension LedgerResources { + /// Validates the graph in the coordinates used by materialization, before any writes. + /// Supporting entries extend ownership to the source root; otherwise the selected tree is root. + 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 { + throw CoreError.invalidState("conflicting resource support") + } + entries[original.path] = original + } + if !resource.support.isEmpty { + let parents = resource.path.split(separator: "/").dropLast() + for count in 0...parents.count { + let path = count == 0 ? "." : parents.prefix(count).joined(separator: "/") + if entries[path] == nil { + entries[path] = .init(path: path, kind: .directory, executable: false) + } + } + } + for path in entries.keys where path != "." { + let parts = path.split(separator: "/") + guard entries["."]?.kind == .directory else { + throw CoreError.invalidState("resource ancestor is not a directory") + } + for count in 1.. = [entry.path] + var pending: [Step] = [.finish(entry.path)] + func parts(_ link: String?) throws -> [Step] { + guard let link, !link.isEmpty, !link.hasPrefix("/"), !link.contains("\0"), + !link.contains("\\") + else { throw CoreError.invalidState("invalid resource link") } + return link.split(separator: "/").reversed().map { .part(String($0)) } + } + pending += try parts(entry.link) + while let step = pending.popLast() { + switch step { + case .finish(let link): + resolved[link] = path + active.remove(link) + case .part(let part): + let current = path.isEmpty ? "." : path.joined(separator: "/") + guard entries[current]?.kind == .directory else { + throw CoreError.invalidState("resource link traverses non-directory") + } + if part == "." { continue } + if part == ".." { + guard !path.isEmpty else { throw CoreError.invalidState("resource link escapes tree") } + path.removeLast() + continue + } + let next = (path + [part]).joined(separator: "/") + guard let target = entries[next] else { + throw CoreError.invalidState("resource link has missing support") + } + if target.kind == .symlink { + if let cached = resolved[next] { + path = cached + } else { + guard active.insert(next).inserted else { + throw CoreError.invalidState("resource link cycle") + } + pending.append(.finish(next)) + pending += try parts(target.link) + } + } else { + path.append(part) + } + } + } + } + return entries + } +} diff --git a/Sources/AgentsCore/LedgerResources.swift b/Sources/AgentsCore/LedgerResources.swift new file mode 100644 index 0000000..6e9eb2f --- /dev/null +++ b/Sources/AgentsCore/LedgerResources.swift @@ -0,0 +1,292 @@ +import Foundation + +/// Resource trees retain empty directories, symlink spellings and executable files separately. +package enum LedgerResources { + /// The snapshot must have been extracted from the pinned commit when it includes support + /// outside the resource's hashed tree. The saved hash is compared to the captured bytes. + package static func captureLockedGit( + _ resource: LedgerResource, snapshotRoot: URL + ) throws -> (entries: [LedgerEntry], support: [LedgerEntry], objects: [String: Data]) { + let root = try DirectoryHandle.readDirectory(at: snapshotRoot) + var limits = LedgerLimits.standard + var objects: [String: Data] = [:] + func capture( + _ path: String, matching expected: [LedgerEntry], recursive: Bool + ) throws -> [LedgerEntry] { + try ledgerPath(path) + var parent = root + let name: String + if path == "." { + parent = try DirectoryHandle.readDirectory(at: snapshotRoot.deletingLastPathComponent()) + name = snapshotRoot.lastPathComponent + } else { + let parts = path.split(separator: "/").map(String.init) + for part in parts.dropLast() { + guard let child = try parent.directory(part) else { throw CoreError.notFound(path) } + parent = child + } + name = parts.last! + } + let expected = Dictionary(uniqueKeysWithValues: expected.map { ($0.path, $0) }) + let result = try parent.capturePortableTree(name, limits: limits, recursive: recursive) { + relative in + guard expected[relative.isEmpty ? "." : relative] != nil else { + throw CoreError.invalidState("unexpected entry in locked resource: " + path) + } + } + guard expected.count == result.entries.count, + result.entries.allSatisfy({ entry in + var recorded = entry + recorded.object = nil + return expected[entry.path] == recorded + }) + else { throw CoreError.invalidState("locked resource shape changed: " + path) } + for (digest, data) in result.objects where objects[digest] == nil { + guard data.count <= limits.objectBytes else { + throw CoreError.invalidState("locked object budget") + } + limits.objectBytes -= data.count + objects[digest] = data + } + limits.entries -= result.entries.count + limits.resourceBytes -= result.entries.reduce(0) { $0 + ($1.byteCount ?? 0) } + return result.entries + } + let entries = try capture(resource.path, matching: resource.entries, recursive: true) + let digest: String + if entries.first?.kind == .file { + digest = entries[0].object! + } else { + digest = try "sha256:" + FileHash.portableTreeHash(entries, objects: objects) + } + guard digest == resource.hash else { + throw CoreError.invalidState("locked resource digest changed: " + resource.path) + } + var support: [LedgerEntry] = [] + for record in resource.support { + var expected = record + expected.path = "." + var entry = try capture(record.path, matching: [expected], recursive: false)[0] + entry.path = record.path + support.append(entry) + } + return (entries, support, objects) + } + + /// A live resource keeps its authored alias for link matching and uses its checked directory + /// for reads and new links. + package static func liveEditSource( + _ resource: LedgerResource, ledger: ResolvedLedger, roots: [String: URL] + ) throws -> (authored: URL, directory: URL) { + guard resource.kind == .liveEdit, let location = resource.location, + 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) + else { throw CoreError.notFound("live edit skill source: \(authored.path)") } + guard + sourcePath == "/" || directoryPath.utf8.elementsEqual(sourcePath.utf8) + || directoryPath.utf8.starts(with: (sourcePath + "/").utf8) + 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.") + } + var directory: ObjCBool = false + guard FileManager.default.fileExists(atPath: directoryPath, isDirectory: &directory), + directory.boolValue + else { throw CoreError.notFound("live edit skill source: \(authored.path)") } + return (authored, URL(fileURLWithPath: directoryPath, isDirectory: true)) + } + + package static func capture(_ url: URL, embed: Bool, limits: LedgerLimits, sourceRoot: URL? = nil) + throws -> ( + entries: [LedgerEntry], support: [LedgerEntry], objects: [String: Data], hash: String, + flags: [String: Bool] + ) + { + var entries: [LedgerEntry] = [] + var objects: [String: Data] = [:] + var support: [String: LedgerEntry] = [:] + var visiting = Set() + var bytes = 0 + var expandedBytes = 0 + var isDirectory: ObjCBool = false + guard FileManager.default.fileExists(atPath: url.path, isDirectory: &isDirectory) else { + throw CoreError.notFound("locked resource") + } + func collect(_ file: URL, path: String, supporting: Bool = false) throws { + if supporting { + if !visiting.insert(path).inserted { return } + let parts = path.split(separator: "/") + for count in 1.. = [file.path] + guard !link.hasPrefix("/") else { throw CoreError.unsafePath("absolute resource link") } + while let step = pending.popLast() { + guard case .part(let part) = step else { + if case .finish(let path) = step { followed.remove(path) } + continue + } + if part == "." { continue } + if part == ".." { + resolved.deleteLastPathComponent() + } else { + resolved.appendPathComponent(part) + } + guard PathSafety.isContained(resolved, in: sourceRoot) else { + throw CoreError.unsafePath("resource link escapes source snapshot") + } + let info = try FileManager.default.attributesOfItem(atPath: resolved.path) + if info[.type] as? FileAttributeType == .typeSymbolicLink { + guard followed.insert(resolved.path).inserted else { + throw CoreError.unsafePath("resource link cycle") + } + if !PathSafety.isContained(resolved, in: url) { + try collect( + resolved, path: PathSafety.relativePath(resolved.path, to: sourceRoot.path), + supporting: true) + } + let next = try FileManager.default.destinationOfSymbolicLink(atPath: resolved.path) + guard !next.hasPrefix("/") else { + throw CoreError.unsafePath("absolute resource link") + } + pending.append(.finish(resolved.path)) + resolved.deleteLastPathComponent() + pending += next.split(separator: "/").reversed().map { .part(String($0)) } + } + } + if !PathSafety.isContained(resolved, in: url) { + let relative = PathSafety.relativePath(resolved.path, to: sourceRoot.path) + let parts = relative.split(separator: "/") + for count in 1..= 0, size <= limits.resourceBytes - expandedBytes else { + throw CoreError.invalidState("expanded resource byte budget") + } + expandedBytes += size + let object: String? + if embed { + guard size <= limits.objectBytes else { + throw CoreError.invalidState("resource byte budget") + } + let data = try FileSystem.read(at: file) + guard data.count == size else { + throw CoreError.invalidState("resource changed during freeze") + } + let digest = "sha256:" + FileHash.sha256Hex(data: data) + if objects[digest] == nil { + guard size <= limits.objectBytes - bytes else { + throw CoreError.invalidState("resource aggregate byte budget") + } + bytes += size + objects[digest] = data + } + object = digest + } else { + object = nil + } + append( + .init( + path: path, kind: .file, object: object, + executable: ((info[.posixPermissions] as? NSNumber)?.intValue ?? 0) & 0o111 != 0, + byteCount: size)) + } else { + throw CoreError.invalidState("unsupported locked resource entry") + } + } + try collect(url, path: ".") + let hash = + try "sha256:" + + (isDirectory.boolValue + ? FileHash.folderHash(url) : FileHash.sha256Hex(file: url)) + let flags = + try isDirectory.boolValue + ? FileHash.executableFlags(url) + : [ + ".": + ((FileManager.default.attributesOfItem(atPath: url.path)[.posixPermissions] as? NSNumber)? + .intValue ?? 0) & 0o111 != 0 + ] + return (entries, support.keys.sorted().map { support[$0]! }, objects, hash, flags) + } + + /// Writes only beneath a caller-owned disposable directory. This is not publication. + package static func materialize( + _ resource: LedgerResource, objects: [String: Data], at destination: URL + ) throws { + guard resource.kind == .embedded else { + throw CoreError.invalidState("resource is not embedded") + } + let unique = try validatedEntries(resource) + for entry in unique.values.sorted(by: { $0.path < $1.path }) { + try Task.checkCancellation() + let file = + entry.path == "." + ? destination + : try PathSafety.resolvedChild(base: destination, subpath: entry.path) + switch entry.kind { + case .directory: try FileSystem.createDirectory(at: file) + case .file: + guard let id = entry.object, let bytes = objects[id], + "sha256:" + FileHash.sha256Hex(data: bytes) == id + else { + throw CoreError.invalidState("missing or corrupt content object") + } + try FileSystem.createDirectory(at: file.deletingLastPathComponent()) + try FileSystem.write(bytes, to: file) + try FileManager.default.setAttributes( + [.posixPermissions: entry.executable ? 0o755 : 0o644], ofItemAtPath: file.path) + case .symlink: + try FileSystem.createDirectory(at: file.deletingLastPathComponent()) + guard let link = entry.link else { throw CoreError.invalidState("missing link") } + try FileManager.default.createSymbolicLink(atPath: file.path, withDestinationPath: link) + } + } + } +} diff --git a/Sources/AgentsCore/LedgerSourcePolicy.swift b/Sources/AgentsCore/LedgerSourcePolicy.swift new file mode 100644 index 0000000..bc22f3f --- /dev/null +++ b/Sources/AgentsCore/LedgerSourcePolicy.swift @@ -0,0 +1,137 @@ +import Foundation + +extension EffectiveSourcePolicy { + /// The admitted lock records source containers and resource dependencies even when replay + /// uses embedded content. The consumer manifest itself is structural provenance. + package func violations( + in ledger: ResolvedLedger, store: StateStore, roots: [String: URL] + ) throws -> [SourcePolicyViolation] { + guard isConfigured else { return [] } + let rootKey = store.scope == .project ? "project" : "state" + let manifestRoot = LedgerLocation(kind: .registered, root: rootKey, path: ".") + let declared = Set(ledger.sourceUses.map(\.source)) + let implicit = Set( + ledger.sources.compactMap { id, source in + source.kind == .local && source.revision == "live" && source.container == nil + && source.location == manifestRoot && !declared.contains(id) ? id : nil + }) + let packageSources = Set( + (ledger.marketplacePackages ?? []).flatMap { pin in + pin.componentRecords.compactMap { ledger.components[$0]?.declaringSource } + }) + var failures: [SourcePolicyViolation] = [] + for (id, source) in ledger.sources.sorted(by: { $0.key < $1.key }) { + try Task.checkCancellation() + guard source.container == nil, !implicit.contains(id) else { continue } + if source.kind == .local, let location = source.location, + BundleSourceLocation.container(of: try location.resolve(roots: roots), in: store) != nil + { + failures += bundleViolations(source.bundleSources ?? [], reference: id) + continue + } + let origin: SourceOrigin + switch source.kind { + case .git: origin = source.transport.flatMap { try? .git($0) } ?? .missing + case .wellKnown: origin = source.transport.flatMap { try? .http($0) } ?? .missing + case .local: + origin = + packageSources.contains(id) + ? .missing + : try source.location.map { .local(at: try $0.resolve(roots: roots)) } ?? .missing + } + failures += violations(for: origin, reference: id) + if let archive = source.archive { + let destination = try SourceOrigin.http(archive.effectiveURL.absoluteString) + failures += violations(for: destination, reference: id) + } + } + let ownRoot = store.scope == .project ? store.environment.projectDirectory : store.directory + for (id, resource) in ledger.resources.sorted(by: { $0.key < $1.key }) { + try Task.checkCancellation() + if implicit.contains(resource.source) { + failures += violations(for: .local(at: ownRoot), reference: id) + } + if let artifact = resource.artifact { + let origins = EffectiveSourcePolicy.artifactOrigins(artifact) + var seen = Set() + for origin in origins where seen.insert(origin).inserted { + failures += violations(for: origin, reference: id) + } + } + } + for (id, component) in ledger.components.sorted(by: { $0.key < $1.key }) { + try Task.checkCancellation() + if let registry = component.mcpRegistry { + for origin in registry.origins { + failures += violations(for: origin, reference: id) + } + } else if implicit.contains(component.source), + component.kind != DeclaredComponentKind.instructions.rawValue, + component.kind != DeclaredComponentKind.skills.rawValue + { + failures += violations(for: .inline, reference: id) + } + } + for pin in ledger.marketplacePackages ?? [] { + failures += violations( + for: try pin.policyOrigin(environment: store.environment), reference: pin.dependency.name) + } + for node in ledger.marketplaceGraph?.nodes ?? [] { + let origins = + try node.hostedEvidence.map { evidence in + try Set(evidence.requests.map { try SourceOrigin.http($0.absoluteString) }) + } ?? [node.id.catalog.origin] + for origin in origins.sorted(by: { $0.description < $1.description }) { + failures += violations(for: origin, reference: node.id.description) + } + } + return failures + } + + private func bundleViolations(_ sources: [PortableSourceEvidence], reference: String) + -> [SourcePolicyViolation] + { + let origins = sources.isEmpty ? [.missing] : sources.map(\.policyOrigin) + var seen = Set() + return origins.filter { seen.insert($0).inserted }.flatMap { + violations(for: $0, reference: reference) + } + } + + package func requireBundleSources(_ sources: [PortableSourceEvidence], reference: String) throws { + guard isConfigured else { return } + let failures = bundleViolations(sources, reference: reference) + guard failures.isEmpty else { throw SourcePolicyFailure(violations: failures) } + } + + package func require(_ ledger: ResolvedLedger, store: StateStore, roots: [String: URL]) throws { + let failures = try violations(in: ledger, store: store, roots: roots) + guard failures.isEmpty else { throw SourcePolicyFailure(violations: failures) } + let environment = store.environment + let access = try environment.resolvedSourceAccess() + for source in ledger.sources.values where source.container == nil { + if source.kind == .git, let transport = source.transport { + let route = try SourceRoute( + SourceDeclaration(kind: .git, location: transport), environment: environment, policy: self + ) + _ = try route.requireRecordedArchive(source.archive) + } else if source.kind == .wellKnown, let transport = source.transport, + let url = URL(string: transport) + { + try access.requireDirectHTTP(url, policy: self) + } + } + guard access.egress == .proxyOnly else { return } + try environment.requireMCPRegistryRoutes(in: ledger) + if ledger.resources.values.contains(where: { $0.artifact != nil }) + || (ledger.marketplacePackages ?? []).contains(where: { + $0.dependency.catalog.kind != .directory + }) + || (ledger.marketplaceGraph?.nodes ?? []).contains(where: { + $0.id.catalog.kind != .directory + }) + { + throw SourceAccessError.egressDenied + } + } +} diff --git a/Sources/AgentsCore/LedgerStateStore.swift b/Sources/AgentsCore/LedgerStateStore.swift new file mode 100644 index 0000000..1cc14d8 --- /dev/null +++ b/Sources/AgentsCore/LedgerStateStore.swift @@ -0,0 +1,121 @@ +import Foundation + +extension StateStore { + /// Reads the complete committed v2 ledger without resolution, recovery or persistent writes. + public func loadLedger() throws -> ResolvedLedger { + try loadLedger(limits: .standard) + } + + /// Reads the single resolved ledger without recovery or persistent writes. + package func loadLedger(limits: LedgerLimits) throws -> ResolvedLedger { + try withReadLock { + _ = try declarationBytes() + return try readLedger(limits: limits) + } + } + + package func readLedger( + prepared: StatePrecondition? = nil, limits: LedgerLimits = .standard + ) throws -> ResolvedLedger { + let bytes = + try prepared.map { try $0.bytes(for: resolvedURL) } + ?? ledgerBytes(limits: limits) + guard let bytes else { return ResolvedLedger() } + do { return try ResolvedLedgerCodec.decode(bytes, limits: limits) } catch let error + as DecodingError + { throw CoreError.invalidState("invalid resolved ledger: " + String(describing: error)) } + } + + package var ledgerRoots: [String: URL] { + ledgerRoots(recordedIn: try? readLedger()) + } + + /// Resolves roots using the committed ledger already read for this operation. + /// These URLs locate content; transaction admission independently checks filesystem identity. + package func ledgerRoots(recordedIn committed: ResolvedLedger?) -> [String: URL] { + var roots = [ + "project": environment.projectDirectory, "home": environment.homeDirectory, + "state": directory, + ] + roots[NativeTargetRoute.projectRoot] = environment.projectDirectory.resolvingSymlinksInPath() + roots[NativeTargetRoute.globalRoot] = + environment.environment["CLAUDE_CONFIG_DIR"].flatMap { + $0.isEmpty ? nil : URL(fileURLWithPath: $0) + } ?? environment.homeDirectory + roots[NativeTargetRoute.globalRoot] = roots[NativeTargetRoute.globalRoot]? + .resolvingSymlinksInPath() + for agent in AgentRegistry.skillAgents { + roots["skills-" + agent.rawValue] = AgentRegistry.installSkillsDirectory( + for: agent, scope: scope, environment: environment) + if let file = InstructionLocations.file(for: agent, scope: scope, environment: environment) { + roots["instructions-" + agent.rawValue] = file.deletingLastPathComponent() + } + } + roots[InstructionLocations.ruleRoot(in: scope)] = + InstructionLocations.antigravityAuthority( + environment, scope: scope + ).logicalDirectory + for route in NativeTargetRoute.allCases { + roots[route.root] = try? route.logicalDirectory(environment).resolvingSymlinksInPath() + } + for route in TransactionLockContext.current(self)?.requestedRoutes ?? [] + where route.isNamed && route.permits(scope) { + roots[route.root] = try? route.physicalDirectory(environment) + } + if let committed { + for deployment in committed.deployments { + guard deployment.target.kind == .registered, let key = deployment.target.root, + let route = NativeTargetRoute.targetRoute(key), route.isNamed, + route.permits(scope), deployment.target.path.utf8.elementsEqual(route.basename.utf8), + Set(deployment.recipients).isSubset(of: route.knownReaders) + else { continue } + roots[key] = try? route.physicalDirectory(environment) + } + } + return roots + } + + package func stageLedger( + _ ledger: ResolvedLedger, limits: LedgerLimits, transaction: FileTransaction, + prepared: StatePrecondition + ) throws { + if let bytes = try ResolvedLedgerCodec.replacement( + ledger, existing: prepared.bytes(for: resolvedURL), limits: limits) + { + try transaction.replace( + resolvedURL, with: .data(bytes), expecting: prepared.evidence(for: resolvedURL)) + } + } + + package func stageLedger( + producing ledger: @escaping () throws -> ResolvedLedger, limits: LedgerLimits, + transaction: FileTransaction, prepared: StatePrecondition + ) throws { + let original = try prepared.bytes(for: resolvedURL) + try transaction.replace( + resolvedURL, + with: .prepared { directory in + let bytes = + try ResolvedLedgerCodec.replacement(ledger(), existing: original, limits: limits) + ?? original + guard let bytes else { throw CoreError.invalidState("missing deferred ledger") } + let file = directory.appendingPathComponent("ledger") + try bytes.write(to: file) + return file + }, expecting: prepared.evidence(for: resolvedURL)) + } + + private func ledgerBytes(limits: LedgerLimits) throws -> Data? { + guard let directory = try openDirectoryIfPresent(), + try directory.info(Self.resolvedFileName) != nil + else { return nil } + return try directory.read(Self.resolvedFileName, maximumBytes: limits.encodedBytes) + } + + /// Ref cleanup consumes the committed closure after physical journal recovery. + func retentionReferences() throws -> RetentionReferences { + guard let bytes = try ledgerBytes(limits: .standard) else { return RetentionReferences() } + let committed = try ResolvedLedgerCodec.decode(bytes, limits: .standard) + return try RetentionReferences(ledger: committed, roots: ledgerRoots(recordedIn: committed)) + } +} diff --git a/Sources/AgentsCore/LedgerValidation.swift b/Sources/AgentsCore/LedgerValidation.swift new file mode 100644 index 0000000..69b96c1 --- /dev/null +++ b/Sources/AgentsCore/LedgerValidation.swift @@ -0,0 +1,556 @@ +import Foundation + +extension ResolvedLedger { + package func validate() throws { + guard version == 2 else { throw CoreError.invalidState("unsupported ledger version") } + try pendingDeployment?.validate(in: self) + var packageNames = Set() + var packageAliases = Set() + for pin in marketplacePackages ?? [] { + try pin.validate() + guard packageNames.insert(pin.dependency.name).inserted, + pin.sourceAliases.allSatisfy({ packageAliases.insert($0).inserted }), + pin.componentRecords.allSatisfy({ components[$0] != nil }) + else { throw MarketplaceError.contributionMismatch(pin.dependency.name) } + } + if let marketplaceGraph { + guard marketplaceGraph.roots.allSatisfy({ packageNames.insert($0.intent.name).inserted }) + else { + throw MarketplaceError.invalidPackage("duplicate package root") + } + try marketplaceGraph.validate( + components: components, resources: resources, objects: contentObjects, + aliases: &packageAliases) + } + for (id, source) in sources { + guard !id.isEmpty, !source.revision.isEmpty else { + throw CoreError.invalidState("invalid ledger source") + } + if let container = source.container { + guard sources[container] != nil, container != id else { + throw CoreError.invalidState("dangling source container") + } + } + try source.location?.validate() + if let name = source.bundlePackageName { + guard source.bundleSources != nil, !name.isEmpty, name.utf8.count <= 128, + name.utf8.allSatisfy({ + (48...57).contains($0) || (65...90).contains($0) + || (97...122).contains($0) || [43, 45, 46, 95].contains($0) + }) + else { throw CoreError.invalidState("invalid frozen bundle package identity") } + } + if let producers = source.bundleSources { + guard source.kind == .local, source.container == nil, source.location != nil, + !producers.isEmpty, Set(producers).count == producers.count, + try ResolvedLedgerCodec.digest(source) == id + else { throw CoreError.invalidState("invalid frozen bundle source evidence") } + for producer in producers { try producer.validate() } + } + if let archive = source.archive { + guard source.kind == .git, source.location == nil, source.container == nil, + let transport = source.transport, source.revision == archive.treeDigest, + try ResolvedLedgerCodec.digest(source) == id + else { throw SourceAccessError.invalidArchive } + _ = try SourceRepository(transport) + try archive.validate() + if let version = source.version { + guard case .tag(let tag) = archive.ref, SemanticVersion(tag)?.description == version + else { + throw SourceAccessError.invalidArchive + } + } + } else if source.kind == .git { + guard let transport = source.transport, !transport.isEmpty, + SourceCache.isObjectID(source.revision) + else { + throw CoreError.invalidState("Git ledger source needs exact transport and commit") + } + } + var visited: Set = [id] + var current = source.container + while let next = current { + guard visited.insert(next).inserted else { throw CoreError.invalidState("source cycle") } + current = sources[next]?.container + } + } + for use in sourceUses { + try requireSource(use.source) + try ledgerPath(use.root) + try use.requirement?.validate() + let source = try rootSource(use.source) + if let archive = source.archive, + !archive.admits(use.requirement, version: source.version), + use.organizationRequirements == nil + { + throw SourceAccessError.archiveChanged + } + if let overrides = use.organizationRequirements { + guard let source = sources[use.source], source.kind != .wellKnown, + SourceCache.isObjectID(source.revision) || source.archive != nil, + let version = source.version, !overrides.isEmpty, + overrides.count <= LedgerLimits.standard.entries + else { throw CoreError.invalidState("invalid source organization version override") } + for constraint in overrides { + try constraint.validateMarketplaceVersion() + guard constraint.admitsMarketplaceVersion(version) else { + throw CoreError.invalidState("source version differs from its organization override") + } + } + } + } + for (digest, bytes) in contentObjects { + try StateValidation.digest(digest) + guard "sha256:" + FileHash.sha256Hex(data: bytes) == digest else { + throw CoreError.invalidState("content object digest mismatch") + } + } + for (id, resource) in resources { + guard !id.isEmpty else { throw CoreError.invalidState("empty resource ID") } + try requireSource(resource.source) + try ledgerPath(resource.path) + try StateValidation.digest(resource.hash) + try resource.location?.validate() + if resource.kind == .liveEdit { + guard resource.location != nil, resource.artifact == nil, resource.entries.isEmpty, + resource.support.isEmpty + else { + throw CoreError.invalidState("invalid live edit resource") + } + } else { + guard resource.location == nil || resource.kind == .artifact, !resource.entries.isEmpty + else { + throw CoreError.invalidState("incomplete locked resource") + } + } + let authority = try rootSource(resource.source) + if resource.kind == .git { + guard authority.kind != .wellKnown, authority.archive == nil, + SourceCache.isObjectID(authority.revision) + else { + throw CoreError.invalidState("resource requires exact Git commit") + } + } else if authority.archive != nil || resource.kind == .archive { + guard authority.archive != nil, resource.kind == .archive, resource.location == nil, + (resource.entries + resource.support).allSatisfy({ $0.object == nil }) + else { throw SourceAccessError.invalidArchive } + } + if resource.kind == .artifact { + guard let artifact = resource.artifact else { + throw CoreError.invalidState("artifact resource needs immutable coordinates") + } + try artifact.validate() + if let location = resource.location { + guard try location == SourceCache.artifactContentLocation(digest: artifact.digest), + resource.path == ".", resource.support.isEmpty, + resource.entries.contains(where: { $0.path == "." && $0.kind == .directory }) + else { throw CoreError.invalidState("invalid retained artifact content location") } + } + } else if resource.artifact != nil { + throw CoreError.invalidState("unexpected resource artifact") + } + guard Set(resource.entries.map(\.path)).count == resource.entries.count, + Set(resource.support.map(\.path)).count == resource.support.count + else { + throw CoreError.invalidState("duplicate resource path") + } + var entries: [String: LedgerEntry] = [:] + var treeEntries = resource.support + treeEntries += resource.entries.map { original in + var entry = original + entry.path = + original.path == "." + ? resource.path + : resource.path == "." ? original.path : resource.path + "/" + original.path + return entry + } + for entry in treeEntries { + try ledgerPath(entry.path) + guard entries[entry.path] == nil || entries[entry.path] == entry else { + throw CoreError.invalidState("conflicting resource path") + } + entries[entry.path] = entry + switch entry.kind { + case .file: + guard let byteCount = entry.byteCount, byteCount >= 0 else { + throw CoreError.invalidState("file requires byte count") + } + guard entry.link == nil else { throw CoreError.invalidState("file has link target") } + if let object = entry.object { + guard contentObjects[object]?.count == byteCount else { + throw CoreError.invalidState("dangling content object") + } + } else if resource.kind == .embedded || resource.kind == .artifact { + throw CoreError.invalidState("embedded file lacks content") + } + case .directory: + guard entry.object == nil, entry.link == nil, entry.byteCount == nil, !entry.executable + else { + throw CoreError.invalidState("invalid directory entry") + } + case .symlink: + guard let link = entry.link, entry.object == nil, entry.byteCount == nil, + !entry.executable, + !link.hasPrefix("/"), !link.contains("\0"), !link.contains("\\") + else { + throw CoreError.invalidState("invalid resource link") + } + } + } + if resource.kind != .liveEdit, !resource.entries.contains(where: { $0.path == "." }) { + throw CoreError.invalidState("missing resource root entry") + } + _ = try LedgerResources.validatedEntries(resource) + if let root = resource.entries.first(where: { $0.path == "." }), root.kind != .directory, + resource.entries.count != 1 + { + throw CoreError.invalidState("file resource has descendants") + } + } + for component in components.values { + try requireSource(component.declaringSource) + try requireSource(component.source) + try ledgerPath(component.root) + try component.containerRoot.map(ledgerPath) + guard DeclaredComponentKind(rawValue: component.kind) != nil, !component.name.isEmpty else { + throw CoreError.invalidState("invalid component identity") + } + try component.payload.validate() + if let registry = component.mcpRegistry { + guard component.kind == "mcpServer", component.version == registry.version + else { throw CoreError.invalidState("invalid frozen MCP registry evidence") } + try registry.validate(matching: MCPTransportDeclaration(ledgerPayload: component.payload)) + } + if let append = component.payload.object?["localAppend"] { + let location = try LedgerLocation(ledgerValue: append) + guard component.kind == "instructions", + component.payload.object?["prompt"]?.kind == .string, + location.kind == .registered, ["project", "home"].contains(location.root) + else { throw CoreError.invalidState("invalid local prompt append") } + } + try requireResources(component.resources) + for condition in component.conditions { try validate(condition) } + } + let groupIDs = Set(groups.map(\.id)) + let occurrenceIDs = Set(occurrences.map(\.id)) + guard groupIDs.count == groups.count, occurrenceIDs.count == occurrences.count, + groupIDs.isDisjoint(with: occurrenceIDs) + else { + throw CoreError.invalidState("duplicate ledger occurrence") + } + var children: [Int: [Int]] = [:] + for group in groups { + if let parent = group.parent { children[parent, default: []].append(group.id) } + } + for occurrence in occurrences { + if let parent = occurrence.reference { children[parent, default: []].append(occurrence.id) } + } + for group in groups { + try requireSource(group.source) + try ledgerPath(group.root) + try group.requirement?.validate() + try StateValidation.digest(group.manifestHash) + guard group.id >= 0, group.parent.map({ groupIDs.contains($0) && $0 < group.id }) ?? true, + Set(group.children).count == group.children.count, + group.children.allSatisfy({ groupIDs.contains($0) || occurrenceIDs.contains($0) }) + else { + throw CoreError.invalidState("invalid group closure") + } + guard group.children == (children[group.id] ?? []).sorted() else { + throw CoreError.invalidState("incomplete group child closure") + } + } + for occurrence in occurrences { + try requireSource(occurrence.declaringSource) + try ledgerPath(occurrence.manifestPath) + guard occurrence.id >= 0, components[occurrence.component] != nil, + occurrence.reference.map({ groupIDs.contains($0) && $0 < occurrence.id }) ?? true + else { + throw CoreError.invalidState("dangling component occurrence") + } + for dependency in occurrence.dependencies { try requireSource(dependency) } + try validate(occurrence.condition) + } + try validatePluginRelations() + let deploymentIDs = Set(deployments.map(\.id)) + guard deploymentIDs.count == deployments.count else { + throw CoreError.invalidState("duplicate deployment") + } + var ruleLeaves = Set() + for deployment in deployments { + let producers = lowerings.filter { $0.deployments.contains(deployment.id) } + guard !producers.isEmpty, + producers.allSatisfy({ + Set(deployment.owners).isSubset(of: Set($0.inputs)) && $0.format == deployment.route + }) + else { throw CoreError.invalidState("deployment has incomplete lowering ownership") } + try deployment.target.validate() + let ruleRoot = [ + InstructionLocations.antigravityRoot, InstructionLocations.antigravityProjectRoot, + ] + .contains { $0 == deployment.target.root } + if deployment.route == InstructionLocations.antigravityFormat { + guard deployment.target.kind == .registered, ruleRoot, + InstructionLocations.isAntigravityLeaf(deployment.target.path), + ruleLeaves.insert(deployment.target.path).inserted, + deployment.recipients == [.antigravity], deployment.ownership == .generated, + deployment.owners.count == 1, let owner = components[deployment.owners[0]], + owner.kind == "instructions", owner.recipients.contains(.antigravity), + producers.count == 1, producers[0].deployments == [deployment.id], + producers[0].inputs == deployment.owners, producers[0].resources == owner.resources, + let unit = owner.resources.first.flatMap({ resources[$0] }), unit.source == owner.source, + owner.resources.allSatisfy({ + resources[$0]?.entries.first?.kind == .file && resources[$0]?.support.isEmpty == true + }) + else { throw CoreError.invalidState("invalid Antigravity rule deployment") } + } else if ruleRoot + || (deployment.recipients.contains(.antigravity) + && InstructionLocations.isInstructionFormat(deployment.route)) + { + throw CoreError.invalidState("Antigravity rule requires its registered format") + } + guard deployment.target.kind != .authoringRelative else { + throw CoreError.invalidState("authoring coordinates cannot be deployment targets") + } + try StateValidation.digest(deployment.expectedHash) + guard !deployment.id.isEmpty, !deployment.route.isEmpty, !deployment.owners.isEmpty, + deployment.owners.allSatisfy({ components[$0] != nil }), + deployment.ownership != .importBlock || deployment.importReference != nil + else { + throw CoreError.invalidState("invalid deployment ownership") + } + } + try validateNativeAuthorities() + guard Set(lowerings.map(\.id)).count == lowerings.count else { + throw CoreError.invalidState("duplicate lowering") + } + for lowering in lowerings { + guard !lowering.id.isEmpty, !lowering.format.isEmpty, + DeclarationPlatform(rawValue: lowering.platform) != nil, + lowering.inputs.allSatisfy({ components[$0] != nil }), + lowering.deployments.allSatisfy({ deploymentIDs.contains($0) }), + Set(lowering.artifacts.map(\.name)).count == lowering.artifacts.count + else { + throw CoreError.invalidState("invalid locked lowering references") + } + try lowering.layout.validate() + try requireResources(lowering.resources) + if lowering.format == LockedLowering.instructionCopyFormat { + guard let recipient = lowering.instructionCopyRecipient, + lowering.deployments.isEmpty, !lowering.inputs.isEmpty, + lowering.layout.object?["name"]?.text == lowering.id, + lowering.layout.object?["sectionCount"]?.integer == lowering.inputs.count, + lowering.inputs.count == lowering.resources.count, + zip(lowering.inputs, lowering.resources).allSatisfy({ id, resource in + guard let input = components[id] else { return false } + return input.kind == "instructions" && input.resources.first == resource + && input.payload.object?["copyRecipients"]?.array?.contains(.init(recipient.rawValue)) + == true + }) + else { throw CoreError.invalidState("invalid instruction copy product") } + } + for artifact in lowering.artifacts { try StateValidation.digest(artifact.hash) } + } + } + + private func validatePluginRelations() throws { + let index = Dictionary(uniqueKeysWithValues: occurrences.map { ($0.id, $0) }) + var children: [Int: [Int]] = [:] + var selectors: [Int: Set] = [:] + var memberOccurrences: [String: [LedgerOccurrence]] = [:] + func exact(_ a: String, _ b: String) -> Bool { a.utf8.elementsEqual(b.utf8) } + func input(_ value: LedgerInputProvenance) throws { + guard !value.format.isEmpty, !value.adapterVersion.isEmpty, + !value.format.contains("\0"), !value.adapterVersion.contains("\0") + else { + throw CoreError.invalidState("invalid native input provenance") + } + } + func narrower(_ child: [T]?, _ parent: [T]?) -> Bool { + guard let parent else { return true } + guard let child else { return false } + return Set(child).isSubset(of: Set(parent)) + } + for occurrence in occurrences { + if let provenance = occurrence.input { try input(provenance) } + guard let member = occurrence.pluginMember else { + guard components[occurrence.component]?.containerRoot == nil else { + throw CoreError.invalidState("container occurrence lacks plugin member relation") + } + continue + } + guard !member.name.isEmpty, !member.name.contains("\0"), + member.parent >= 0, member.parent < occurrence.id, + let parent = index[member.parent], let expansion = parent.pluginExpansion, + let component = components[occurrence.component], + let container = component.containerRoot, + exact(component.kind, member.kind), exact(component.name, member.name), + exact(component.root, expansion.root), exact(container, expansion.containerRoot), + component.declaringSource == expansion.source, + occurrence.declaringSource == component.declaringSource, + occurrence.dependencies.contains(expansion.source), + occurrence.dependencies.contains(component.source), + expansion.containerRoot == "." + || occurrence.manifestPath.utf8.starts(with: (expansion.containerRoot + "/").utf8), + component.resources.allSatisfy({ resource in + resources[resource].map { occurrence.dependencies.contains($0.source) } ?? false + }), + !occurrence.consumerEditable, occurrence.input != nil, + Set(occurrence.recipients).isSubset(of: Set(parent.recipients)), + narrower(occurrence.condition.agents, parent.condition.agents), + narrower(occurrence.condition.scopes, parent.condition.scopes), + narrower(occurrence.condition.platforms, parent.condition.platforms) + else { throw CoreError.invalidState("invalid plugin member relation") } + let selector = Data((member.kind + "\0" + member.name).utf8) + guard selectors[member.parent, default: []].insert(selector).inserted else { + throw CoreError.invalidState("duplicate plugin member selector") + } + children[member.parent, default: []].append(occurrence.id) + memberOccurrences[occurrence.component, default: []].append(occurrence) + } + for occurrence in occurrences { + guard let expansion = occurrence.pluginExpansion else { continue } + guard let component = components[occurrence.component], component.kind == "plugin", + component.payload.object?["mode"]?.text == "components", + exact(expansion.source, component.source), + occurrence.dependencies.contains(expansion.source), + expansion.children == (children[occurrence.id] ?? []).sorted() + else { throw CoreError.invalidState("invalid plugin expansion closure") } + try requireSource(expansion.source) + try ledgerPath(expansion.root) + try ledgerPath(expansion.containerRoot) + try ledgerPath(expansion.document) + guard + expansion.containerRoot == "." + || expansion.document.utf8.starts(with: (expansion.containerRoot + "/").utf8) + else { + throw CoreError.invalidState("plugin document outside container") + } + try input(expansion.input) + } + let related = Set(occurrences.filter { $0.pluginMember != nil }.map(\.component)) + for (id, component) in components where component.containerRoot != nil { + guard related.contains(id), let contributions = memberOccurrences[id], + Set(contributions.flatMap(\.recipients)) == Set(component.recipients), + try Set(component.conditions.map { try ResolvedLedgerCodec.bytes($0) }) + == Set(contributions.map { try ResolvedLedgerCodec.bytes($0.condition) }) + else { + throw CoreError.invalidState("container component lacks plugin occurrence") + } + } + } + + private func validateNativeAuthorities() throws { + let deployments = Dictionary(uniqueKeysWithValues: deployments.map { (Data($0.id.utf8), $0) }) + var targets = Set() + for authority in nativeAuthorities ?? [] { + try authority.target.validate() + guard authority.version == 1, NativeTargetRoute(rawValue: authority.targetRoute) != nil, + ["json", "jsonc", "jsonc-trailing-commas", "toml"].contains(authority.documentFormat), + authority.target.kind != .authoringRelative, !authority.regions.isEmpty, + try targets.insert(ResolvedLedgerCodec.bytes(authority.target)).inserted + else { throw CoreError.invalidState("invalid native authority target") } + + func owners(_ ids: [String]) throws -> Set { + let exact = ids.map { Data($0.utf8) } + guard !ids.isEmpty, Set(exact).count == ids.count, + exact.allSatisfy({ id in + guard let deployment = deployments[id] else { return false } + return deployment.ownership == .ownedValues + && deployment.target.kind == authority.target.kind + && deployment.target.root.map { Data($0.utf8) } + == authority.target.root.map { Data($0.utf8) } + && Data(deployment.target.path.utf8) == Data(authority.target.path.utf8) + }) + else { throw CoreError.invalidState("invalid native authority ownership") } + return Set(exact) + } + + var arrays: [[NativeAddressStep]: LedgerNativeArrayEvidence] = [:] + var kinds: [[NativeAddressStep]: String] = [:] + func address(_ path: [LedgerNativePathStep]) throws -> [NativeAddressStep] { + var prefix: [NativeAddressStep] = [] + for step in path { + let kind: String + let next: NativeAddressStep + switch step { + case .key(let key): + kind = "object" + next = .key(Data(key.utf8)) + case .stableID(let key, let value): + kind = "array" + next = .stableID(Data(key.utf8), Data(value.utf8)) + case .position(let index, let evidence): + guard index >= 0 else { throw CoreError.invalidState("negative native ordinal") } + switch evidence { + case .semantic(let format, let digest): + guard format == "native-array@1" else { + throw CoreError.invalidState("unsupported native array evidence") + } + try StateValidation.digest(digest) + case .privateArray: break + } + guard arrays[prefix] == nil || arrays[prefix] == evidence else { + throw CoreError.invalidState("conflicting native array evidence") + } + arrays[prefix] = evidence + kind = "array" + next = .position(index) + } + guard kinds[prefix] == nil || kinds[prefix] == kind else { + throw CoreError.invalidState("conflicting native container kind") + } + kinds[prefix] = kind + prefix.append(next) + } + return prefix + } + + var regions = Set<[NativeAddressStep]>() + var descendants: [[NativeAddressStep]: Set] = [:] + for region in authority.regions { + let owners = try owners(region.deployments) + let path = try address(region.path) + guard regions.insert(path).inserted else { + throw CoreError.invalidState("duplicate native region") + } + for count in 0..() + for container in authority.createdContainers { + let owners = try owners(container.deployments) + let path = try address(container.path) + guard !path.isEmpty, ["object", "array"].contains(container.kind), + kinds[path] == container.kind, containers.insert(path).inserted, + owners.isSubset(of: descendants[path] ?? []) + else { throw CoreError.invalidState("orphan or invalid native created container") } + } + } + } + + private func requireSource(_ id: String) throws { + guard sources[id] != nil else { throw CoreError.invalidState("dangling ledger source") } + } + + private func requireResources(_ ids: [String]) throws { + guard ids.allSatisfy({ resources[$0] != nil }) else { + throw CoreError.invalidState("dangling ledger resource") + } + } + + private func validate(_ condition: LedgerCondition) throws { + guard condition.platforms?.allSatisfy({ DeclarationPlatform(rawValue: $0) != nil }) ?? true + else { + throw CoreError.invalidState("unknown ledger platform") + } + } +} + +/// Array evidence is checked separately so contradictory descriptions cannot create distinct slots. +private enum NativeAddressStep: Hashable { + case key(Data) + case stableID(Data, Data) + case position(Int) +} diff --git a/Sources/AgentsCore/LifecycleDeclaration.swift b/Sources/AgentsCore/LifecycleDeclaration.swift new file mode 100644 index 0000000..16cc420 --- /dev/null +++ b/Sources/AgentsCore/LifecycleDeclaration.swift @@ -0,0 +1,273 @@ +import Foundation + +public enum LifecycleEvent: String, CaseIterable, Codable, Sendable { + case preInstall = "pre-install" + case postInstall = "post-install" + case preUpdate = "pre-update" + case postUpdate = "post-update" + case preUninstall = "pre-uninstall" + case postUninstall = "post-uninstall" + case preCompile = "pre-compile" +} + +package struct LifecycleDeclarationIssue: Equatable, Sendable { + package let event: String? + package let index: Int? + package let field: String + package let message: String +} + +package struct DeclaredLifecycleAction: Sendable { + package enum CommandField: String, CaseIterable, Sendable { + case bash, command, run + } + + package enum Body: Sendable { + case command(CommandField, String, environment: [String: String]) + case http(URL, headers: [String: String], allowedVariables: Set) + } + + package let event: LifecycleEvent + package let index: Int + package let body: Body + package let timeout: Int + package let authored: DeclarationValue +} + +package struct LifecycleDeclaration: Sendable { + package let actions: [DeclaredLifecycleAction] + package let issues: [LifecycleDeclarationIssue] + + package init(_ value: DeclarationValue) { + guard case .dictionary(let events) = value else { + actions = [] + issues = [.init(event: nil, index: nil, field: "", message: "Expected an event mapping.")] + return + } + var actions: [DeclaredLifecycleAction] = [] + var issues: [LifecycleDeclarationIssue] = [] + for name in events.keys.sorted() where LifecycleEvent(rawValue: name) == nil { + issues.append(.init(event: name, index: nil, field: "", message: "Unknown lifecycle event.")) + } + for event in LifecycleEvent.allCases { + guard let value = events[event.rawValue] else { continue } + guard let entries = value.elements, entries.count <= 128 else { + issues.append( + .init( + event: event.rawValue, index: nil, field: "", + message: "Expected a sequence of up to 128 actions.")) + continue + } + for (index, entry) in entries.enumerated() { + var validation = ActionValidation(event: event, index: index) + if let action = validation.action(entry) { actions.append(action) } + issues += validation.issues + } + } + self.actions = issues.isEmpty ? actions : [] + self.issues = issues + } + + package static func isVariable(_ text: String) -> Bool { + let bytes = text.utf8 + guard let first = bytes.first, isLetter(first) || first == 95 else { return false } + return bytes.allSatisfy { isLetter($0) || $0 == 95 || (48...57).contains($0) } + } + + private static func isLetter(_ byte: UInt8) -> Bool { + (65...90).contains(byte) || (97...122).contains(byte) + } +} + +private struct ActionValidation { + let event: LifecycleEvent + let index: Int + var issues: [LifecycleDeclarationIssue] = [] + + mutating func action(_ entry: DeclarationValue) -> DeclaredLifecycleAction? { + guard case .dictionary(let fields) = entry else { + issue("", "Expected an action mapping.") + return nil + } + let commandFields = DeclaredLifecycleAction.CommandField.allCases + let presentCommands = commandFields.filter { fields[$0.rawValue] != nil } + let type = fields["type"]?.string + let httpFields: Set = ["url", "headers", "allowedEnvVars"] + let commandNames = Set(commandFields.map(\.rawValue) + ["env"]) + let common: Set = ["type", "timeout"] + let permitted: Set + let body: DeclaredLifecycleAction.Body? + switch type { + case "command": + permitted = common.union(commandNames) + if presentCommands.count != 1 { + issue("", "A command action requires exactly one of bash, command, or run.") + } + var command: (DeclaredLifecycleAction.CommandField, String)? + for field in presentCommands { + if let value = string(fields[field.rawValue], field: field.rawValue, nonempty: true) { + command = (field, value) + } + } + let environment = mapping( + fields["env"], field: "env", keyIsValid: LifecycleDeclaration.isVariable) + body = command.map { .command($0.0, $0.1, environment: environment) } + case "http": + permitted = common.union(httpFields) + let urlText = string(fields["url"], field: "url", nonempty: true) + let url = urlText.flatMap { httpURL($0) } + let headers = mapping(fields["headers"], field: "headers", keyIsValid: validHeaderName) + var fieldNames: Set = [] + for (name, value) in headers.sorted(by: { $0.key < $1.key }) { + if !fieldNames.insert(name.lowercased()).inserted { + issue("headers." + name, "Duplicate HTTP field name.") + } + if !Self.validHeaderValue(value) { + issue("headers." + name, "Header values must be printable and contain no line breaks.") + } + } + let variables = allowedVariables(fields["allowedEnvVars"]) + body = url.map { .http($0, headers: headers, allowedVariables: variables) } + default: + permitted = common.union(httpFields).union(commandNames) + issue("type", "Expected command or http.") + body = nil + } + for name in fields.keys.sorted() where !permitted.contains(name) { + issue(name, "Field is not permitted for this action.") + } + var timeout = 30 + if let value = fields["timeout"] { + if case .integer(let seconds) = value, (1...300).contains(seconds) { + timeout = seconds + } else { + issue("timeout", "Expected an integer from 1 through 300 seconds.") + } + } + guard issues.isEmpty, let body else { return nil } + return .init(event: event, index: index, body: body, timeout: timeout, authored: entry) + } + + mutating func issue(_ field: String, _ message: String) { + issues.append(.init(event: event.rawValue, index: index, field: field, message: message)) + } + + mutating func string(_ input: DeclarationValue?, field: String, nonempty: Bool = false) -> String? + { + guard let value = input?.string, !value.utf8.contains(0), !nonempty || !value.isEmpty else { + issue(field, nonempty ? "Expected a nonempty string." : "Expected a string without NUL.") + return nil + } + return value + } + + mutating func mapping( + _ input: DeclarationValue?, field: String, keyIsValid: (String) -> Bool + ) -> [String: String] { + guard let input else { return [:] } + guard case .dictionary(let fields) = input, fields.count <= 128 else { + issue(field, "Expected a mapping of up to 128 strings.") + return [:] + } + var result: [String: String] = [:] + for (key, value) in fields.sorted(by: { $0.key < $1.key }) { + let path = field + "." + key + if !keyIsValid(key) { issue(path, "Invalid name.") } + if let value = string(value, field: path) { result[key] = value } + } + return result + } + + mutating func httpURL(_ value: String) -> URL? { + guard let parts = URLComponents(string: value), parts.scheme?.lowercased() == "https", + let host = parts.host, !host.isEmpty, parts.user == nil, parts.password == nil, + parts.fragment == nil, let url = parts.url, + !value.unicodeScalars.contains(where: { $0.value <= 32 || $0.value == 127 }) + else { + issue("url", "Expected an HTTPS URL without embedded credentials, spaces, or a fragment.") + return nil + } + return url + } + + func validHeaderName(_ name: String) -> Bool { + let punctuation = Set("!#$%&'*+-.^_`|~".utf8) + let transportHeaders: Set = [ + "connection", "content-length", "content-type", "host", "proxy-authorization", "te", + "trailer", + "transfer-encoding", "upgrade", + ] + return !name.isEmpty && !transportHeaders.contains(name.lowercased()) + && name.utf8.allSatisfy { + (48...57).contains($0) || (65...90).contains($0) || (97...122).contains($0) + || punctuation.contains($0) + } + } + + static func validHeaderValue(_ value: String) -> Bool { + value.unicodeScalars.allSatisfy { $0.value == 9 || ($0.value >= 32 && $0.value != 127) } + } + + mutating func allowedVariables(_ input: DeclarationValue?) -> Set { + guard let input else { return [] } + guard let values = input.elements, values.count <= 128 else { + issue("allowedEnvVars", "Expected a sequence of up to 128 environment variable names.") + return [] + } + var valid: Set = [] + for (index, value) in values.enumerated() { + guard let name = value.string, LifecycleDeclaration.isVariable(name) else { + issue("allowedEnvVars.\(index)", "Invalid environment variable name.") + continue + } + valid.insert(name) + } + return valid + } +} + +extension LifecycleDeclaration { + package static func equivalent(_ lhs: DeclarationValue?, _ rhs: DeclarationValue?) -> Bool { + switch (lhs, rhs) { + case (nil, nil): return true + case (let lhs?, let rhs?): + guard let left = try? digest(lhs), let right = try? digest(rhs) else { return false } + return left == right + default: return false + } + } + + /// Versioned, type-tagged UTF-8 encoding. Lengths and counts delimit values independently + /// of YAML spelling, Unicode normalization, escape choices and dictionary enumeration. + package static func digest(_ value: DeclarationValue) throws -> String { + var bytes = Data("agents.lifecycle.v1\0".utf8) + func append(_ text: String) { bytes.append(contentsOf: text.utf8) } + func string(_ text: String) { + append("s\(text.utf8.count):") + append(text) + } + func encode(_ value: DeclarationValue) throws { + switch value { + case .string(let text): string(text) + case .integer(let integer): append("i\(integer):") + case .boolean(let flag): append(flag ? "t" : "f") + case .null: append("n") + case .array(let entries): + append("a\(entries.count):") + for entry in entries { try encode(entry) } + case .dictionary(let entries): + append("m\(entries.count):") + for (key, value) in entries.sorted(by: { + $0.key.utf8.lexicographicallyPrecedes($1.key.utf8) + }) { + string(key) + try encode(value) + } + case .record, .requirement: + throw CoreError.invalidState("Unsupported lifecycle scalar.") + } + } + try encode(value) + return "sha256:" + FileHash.sha256Hex(data: bytes) + } +} diff --git a/Sources/AgentsCore/LifecycleFileAccess.swift b/Sources/AgentsCore/LifecycleFileAccess.swift new file mode 100644 index 0000000..8838461 --- /dev/null +++ b/Sources/AgentsCore/LifecycleFileAccess.swift @@ -0,0 +1,140 @@ +import CPlatform +import Foundation + +package enum LifecycleFileAuthority: Sendable { + case administrator, user, project, privateState +} + +extension DirectoryHandle { + /// Walks physical ancestry from the filesystem root before privileged bytes may be read. + /// A missing component is optional only when reached through admitted ancestry. + package static func lifecycleDirectory( + at path: URL, authority: LifecycleFileAuthority + ) throws -> DirectoryHandle? { + var components = Array(path.standardizedFileURL.pathComponents.dropFirst()) + var directory = try DirectoryHandle(at: URL(fileURLWithPath: "/", isDirectory: true)) + if let name = components.first, platform_system_alias(name), + let info = try directory.info(name), info.st_mode & S_IFMT == S_IFLNK + { + guard info.st_uid == 0, try directory.readLink(name) == "private/" + name else { + throw CoreError.unsafePath("Untrusted system alias.") + } + components.insert("private", at: 0) + } + for name in components { + let admin = authority == .administrator + _ = try FileAccessEvidence.requireLifecycleWriter( + descriptor: directory.descriptor, owner: admin ? 0 : nil, kind: S_IFDIR, + protectingChild: !admin) + guard let info = try directory.info(name) else { return nil } + guard info.st_mode & S_IFMT == S_IFDIR, + admin ? info.st_uid == 0 : (info.st_uid == 0 || info.st_uid == geteuid()) + else { throw CoreError.unsafePath("Untrusted lifecycle directory: \(name)") } + directory = try directory.lifecycleOpenChild(name, matching: info) + } + _ = try FileAccessEvidence.requireLifecycleWriter( + descriptor: directory.descriptor, owner: authority == .administrator ? 0 : geteuid(), + kind: S_IFDIR) + return directory + } + + package func lifecycleChild(_ name: String, authority: LifecycleFileAuthority) throws + -> DirectoryHandle? + { + guard let info = try info(name) else { return nil } + let result = try lifecycleOpenChild(name, matching: info) + switch authority { + case .administrator, .user: + _ = try FileAccessEvidence.requireLifecycleWriter( + descriptor: result.descriptor, owner: authority == .administrator ? 0 : geteuid(), + kind: S_IFDIR) + case .privateState: try FileAccessEvidence.requirePrivate(descriptor: result.descriptor) + case .project: break + } + return result + } + + private func lifecycleOpenChild(_ name: String, matching info: stat) throws -> DirectoryHandle { + let opened = try child(name) + guard try opened.objectIdentity == FileObjectIdentity(info) else { + throw CoreError.unsafePath("Lifecycle directory changed during admission.") + } + return opened + } + + package func createPrivateLifecycleChild( + _ name: String, existingAuthority: LifecycleFileAuthority = .privateState + ) throws -> DirectoryHandle { + if let existing = try lifecycleChild(name, authority: existingAuthority) { return existing } + do { + return try createPrivateDirectory(name) + } catch { + if let concurrent = try lifecycleChild(name, authority: existingAuthority) { + return concurrent + } + throw error + } + } + + package func readLifecycleFile( + _ name: String, authority: LifecycleFileAuthority, maximumBytes: Int + ) throws -> (bytes: Data, provenance: String)? { + guard let before = try info(name) else { return nil } + guard before.st_nlink == 1, before.st_mode & S_IFMT == S_IFREG else { + throw CoreError.unsafePath("Lifecycle source requires a regular, single-link file.") + } + var evidence: FileAccessEvidence? + var bytes = Data() + try readChunks( + name, matching: before, maximumBytes: maximumBytes, + verifyAccess: { descriptor in + let current: FileAccessEvidence + switch authority { + case .administrator, .user: + current = try FileAccessEvidence.requireLifecycleWriter( + descriptor: descriptor, owner: authority == .administrator ? 0 : geteuid(), + kind: S_IFREG) + case .privateState: current = try FileAccessEvidence.requirePrivate(descriptor: descriptor) + case .project: current = try FileAccessEvidence.capture(descriptor: descriptor) + } + guard evidence == nil || evidence == current else { + throw CoreError.invalidState("Lifecycle source permissions changed while reading.") + } + evidence = current + }, { bytes.append(contentsOf: $0) }) + guard let after = try info(name), Self.sameGeneration(before, after), let evidence else { + throw CoreError.invalidState("Lifecycle source changed while reading.") + } + return (bytes, try ResolvedLedgerCodec.digest(evidence)) + } + + package func replacePrivateLifecycleFile(_ name: String, bytes: Data) throws { + try FileAccessEvidence.requirePrivate(descriptor: descriptor) + let stage = ".\(name).new" + try replaceFile( + name, through: stage, with: bytes, + afterWrite: { + _ = try requirePrivateAccess(stage) + }, afterRename: {}) + } + + package var lifecycleDirectoryURL: URL { url } + package var lifecycleIdentity: String { + get throws { + var seconds: Int64 = 0 + var nanoseconds: Int64 = 0 + guard platform_directory_birthtime(descriptor, &seconds, &nanoseconds) == 0 else { + throw CoreError.invalidState("The project directory identity could not be established.") + } + return try ResolvedLedgerCodec.digest( + LifecycleDirectoryIdentity( + object: objectIdentity, birthSeconds: seconds, birthNanoseconds: nanoseconds)) + } + } +} + +private struct LifecycleDirectoryIdentity: Encodable { + let object: FileObjectIdentity + let birthSeconds: Int64 + let birthNanoseconds: Int64 +} diff --git a/Sources/AgentsCore/MCPRegistryEvidence.swift b/Sources/AgentsCore/MCPRegistryEvidence.swift new file mode 100644 index 0000000..5680aad --- /dev/null +++ b/Sources/AgentsCore/MCPRegistryEvidence.swift @@ -0,0 +1,260 @@ +import Foundation + +/// Registry metadata associated with a selected, symbolic MCP definition. +public struct MCPRegistryEvidence: Codable, Equatable, Hashable, Sendable { + public let registry: String + public let server: String + public let version: String + /// Canonical HTTP origin of the endpoint or artifact registry. + public let origin: String + /// Exact package or image coordinate for a stdio selection. + public let package: String? + /// Digest of the exact selected transport, arguments and symbolic configuration. + public let invocationDigest: String? + /// Digests of portable, non-secret literals captured by Registry selection. + package let portableBindings: [String: String]? + + package init( + registry: String, server: String, version: String, origin: String, package: String?, + invocationDigest: String? = nil, portableBindings: [String: String]? = nil + ) { + self.registry = registry + self.server = server + self.version = version + self.origin = origin + self.package = package + self.invocationDigest = invocationDigest + self.portableBindings = portableBindings + } + + package func validate() throws { + guard let base = URLComponents(string: registry), base.query == nil, + try SourceOrigin.http(origin).identity == origin, + version != "latest", + [server, version, package].compactMap({ $0 }).allSatisfy({ + !$0.isEmpty && $0.utf8.count <= 1024 && !$0.utf8.contains(where: { $0 < 32 || $0 == 127 }) + }), + invocationDigest.map(Self.isDigest) ?? (portableBindings == nil), + portableBindings?.values.allSatisfy(Self.isDigest) ?? true + else { throw CoreError.invalidSource("invalid MCP registry evidence") } + _ = try SourceOrigin.http(registry) + } + + /// Captures the actual declaration after the caller configures its inputs. + package func bound(to transport: MCPTransportDeclaration) throws -> Self { + let literals = try Self.bindings(in: transport).compactMapValues { binding in + if case .literal(let value) = binding { return try ResolvedLedgerCodec.digest(value) } + return nil + } + let portable = literals.isEmpty ? nil : literals + let result = Self( + registry: registry, server: server, version: version, origin: origin, package: package, + invocationDigest: try digest(of: transport, portable: portable), portableBindings: portable) + try result.validate(matching: transport) + return result + } + + package func validate(matching transport: MCPTransportDeclaration) throws { + try validate() + let selectedOrigin: String? + switch transport { + case .stdio(let run): + selectedOrigin = package.flatMap { Self.launcherOrigin(run, coordinate: $0) } + case .streamableHTTP(let url, _), .sse(let url, _): + selectedOrigin = package == nil ? url : nil + } + guard let selectedOrigin, (try? SourceOrigin.http(selectedOrigin).identity) == origin, + try invocationDigest.map({ try $0 == digest(of: transport, portable: portableBindings) }) + ?? true + else { + throw CoreError.invalidSource( + "MCP registry evidence does not match the configured invocation. " + + Self.reselectionMessage) + } + } + + /// Returns only literal names whose current values match captured Registry selections. + /// Archive admission still applies its own secret and portability checks. + package func portableLiteralBindings(in transport: MCPTransportDeclaration) throws -> Set + { + try validate(matching: transport) + let bindings = Self.bindings(in: transport) + if invocationDigest == nil, + bindings.values.contains(where: { + if case .literal = $0 { return true } + return false + }) + { + throw CoreError.invalidSource(Self.reselectionMessage) + } + return try Set( + (portableBindings ?? [:]).compactMap { name, digest in + guard case .literal(let value) = bindings[name], + try ResolvedLedgerCodec.digest(value) == digest + else { return nil } + return name + }) + } + + package static let reselectionMessage = + "Reselect the exact MCP registry version and replace the managed declaration, " + + "or regenerate it from a refreshed bundle." + + private struct Invocation: Encodable { + let format = 1 + let coordinate: [String] + let command: [String] + let bindings: [String: [String]] + let portableLiterals: [String: String]? + } + + private func digest(of transport: MCPTransportDeclaration, portable: [String: String]?) throws + -> String + { + let invocation: [String] + switch transport { + case .stdio(let run): invocation = ["stdio", run.executable] + run.arguments + case .streamableHTTP(let url, _): invocation = ["streamableHTTP", url] + case .sse(let url, _): invocation = ["sse", url] + } + let inputs = Self.bindings(in: transport).mapValues { binding in + switch binding { + case .literal(let value): ["literal", value] + case .environment(let name): ["environment", name] + case .secret(let name): ["secret", name] + } + } + return try ResolvedLedgerCodec.digest( + Invocation( + coordinate: [registry, server, version, origin] + (package.map { [$0] } ?? []), + command: invocation, bindings: inputs, portableLiterals: portable)) + } + + private static func bindings(in transport: MCPTransportDeclaration) -> [String: RuntimeBinding] { + switch transport { + case .stdio(let run): run.environment + case .streamableHTTP(_, let headers), .sse(_, let headers): headers + } + } + + private static func launcherOrigin(_ run: ExecutableDeclaration, coordinate: String) -> String? { + guard run.executableSource == nil, run.workingDirectory == nil else { return nil } + let arguments = run.arguments + let index: String + switch run.executable { + case "npx": + let flag = "--registry=" + guard arguments.count >= 4, arguments[0] == "--yes", arguments[1].hasPrefix(flag), + arguments[2] == "--", arguments[3].utf8.elementsEqual(coordinate.utf8), + matches( + coordinate, + #"^(?:@[a-z0-9][a-z0-9._-]*/)?[a-z0-9][a-z0-9._-]*@v?[0-9]+\.[0-9]+\.[0-9]+(?:-[A-Za-z0-9.-]+)?(?:\+[A-Za-z0-9.-]+)?$"# + ) + else { return nil } + index = String(arguments[1].dropFirst(flag.count)) + case "uvx": + guard arguments.count >= 6, arguments[0] == "--default-index", arguments[2] == "--from", + arguments[3].utf8.elementsEqual(coordinate.utf8), arguments[4] == "--", + matches(coordinate, #"^[A-Za-z0-9][A-Za-z0-9._-]*==[0-9][A-Za-z0-9._+!-]*$"#), + matches(arguments[5], #"^[A-Za-z0-9][A-Za-z0-9._-]*$"#) + else { return nil } + index = arguments[1] + case "docker": + let prefix = ["run", "--rm", "-i"] + run.environment.keys.sorted().flatMap { ["-e", $0] } + guard arguments.starts(with: prefix), + arguments.dropFirst(prefix.count).first?.utf8.elementsEqual(coordinate.utf8) == true + else { return nil } + return imageOrigin(coordinate) + default: + return nil + } + guard let parts = URLComponents(string: index), parts.scheme?.lowercased() == "https", + parts.query == nil + else { return nil } + return index + } + + private static func imageOrigin(_ coordinate: String) -> String? { + let path = coordinate.split(separator: "/", omittingEmptySubsequences: false) + guard let image = path.last, + matches( + String(image), + #"^[a-z0-9][a-z0-9._-]*(?::[A-Za-z0-9_][A-Za-z0-9_.-]{0,127})?(?:@sha256:[a-f0-9]{64})?$"#), + image.contains(":"), + !image.lowercased().hasSuffix(":latest") + else { return nil } + let first = path[0] + let qualified = + path.count > 1 && (first.contains(".") || first.contains(":") || first == "localhost") + let namespace = qualified ? path.dropFirst().dropLast() : path.dropLast() + guard namespace.allSatisfy({ matches(String($0), #"^[a-z0-9][a-z0-9._-]*$"#) }) else { + return nil + } + if !qualified { return "https://docker.io" } + let origin = "https://" + first + guard let url = URL(string: origin), let parts = try? SourceURL.https(url), + parts.path.isEmpty, parts.query == nil + else { return nil } + return origin + } + + private static func isDigest(_ value: String) -> Bool { + matches(value, #"^sha256:[0-9a-f]{64}$"#) + } + + private static func matches(_ value: String, _ pattern: String) -> Bool { + value.range(of: pattern, options: .regularExpression) == value.startIndex.. (SourceAuthority, [String]) { + let parts = try SourceURL.https(url) + guard parts.query == nil else { throw SourceAccessError.invalidConfiguration } + return ( + try SourceAuthority(parts), + try SourceURL.segments(parts.percentEncodedPath, allowingRoot: true) + ) + } + guard let configured = URL(string: setting), + let (configuredAuthority, configuredPath) = try? location(configured) + else { throw SourceAccessError.invalidConfiguration } + let (authority, path) = try location(endpoint) + guard authority == configuredAuthority, + path.elementsEqual(configuredPath, by: { $0.utf8.elementsEqual($1.utf8) }) + else { throw SourceAccessError.egressDenied } + } +} + +extension ComponentDeclaration { + package var mcpRegistry: MCPRegistryEvidence? { + if case .mcpServer(_, _, _, _, _, let evidence) = self { return evidence } + return nil + } +} diff --git a/Sources/AgentsCore/MCPTransportPayload.swift b/Sources/AgentsCore/MCPTransportPayload.swift new file mode 100644 index 0000000..0117dcc --- /dev/null +++ b/Sources/AgentsCore/MCPTransportPayload.swift @@ -0,0 +1,59 @@ +extension MCPTransportDeclaration { + /// Reads the portable transport shared by frozen state and managed MCP operations. + package init(ledgerPayload payload: LedgerValue) throws { + func invalid() -> CoreError { .invalidState("invalid frozen MCP transport") } + func string(_ value: LedgerValue?) throws -> String { + guard value?.kind == .string, let text = value?.text else { throw invalid() } + return text + } + func bindings(_ value: LedgerValue?) throws -> [String: RuntimeBinding] { + guard value?.kind == .object, let values = value?.object else { throw invalid() } + return try values.mapValues { item in + guard let text = item.text else { throw invalid() } + switch item.kind { + case .literal: return .literal(text) + case .environment: return .environment(text) + case .secret: return .secret(text) + default: throw invalid() + } + } + } + guard let fields = payload.object?["transport"]?.object else { throw invalid() } + switch try string(fields["kind"]) { + case "stdio": + guard Set(fields.keys) == ["kind", "run"], let run = fields["run"]?.object, + Set(run.keys).subtracting(["workingDirectory", "executableSource"]) == [ + "executable", "arguments", "environment", + ], + run["arguments"]?.kind == .array, let arguments = run["arguments"]?.array + else { throw invalid() } + let executable = try string(run["executable"]) + let executableSource = try run["executableSource"].map { try string($0) } + if executableSource != nil && !executable.contains("/") { throw invalid() } + let cwd: ResourceDeclaration? + if let directory = run["workingDirectory"] { + guard let object = directory.object, Set(object.keys).isSubset(of: ["path", "source"]) + else { + throw invalid() + } + cwd = try .init( + path: string(object["path"]), source: object["source"].map { try string($0) }) + } else { + cwd = nil + } + self = try .stdio( + .init( + executable: executable, executableSource: executableSource, + arguments: arguments.map { try string($0) }, + environment: bindings(run["environment"]), workingDirectory: cwd)) + case "streamableHTTP", "sse": + guard Set(fields.keys) == ["kind", "url", "headers"] else { throw invalid() } + let url = try string(fields["url"]) + let headers = try bindings(fields["headers"]) + self = + fields["kind"]?.text == "sse" + ? .sse(url: url, headers: headers) : .streamableHTTP(url: url, headers: headers) + default: throw invalid() + } + } +} diff --git a/Sources/AgentsCore/ManagedSourceGit.swift b/Sources/AgentsCore/ManagedSourceGit.swift new file mode 100644 index 0000000..d83fc81 --- /dev/null +++ b/Sources/AgentsCore/ManagedSourceGit.swift @@ -0,0 +1,122 @@ +import Foundation + +/// Network Git uses an isolated home and, for fetches, a Core-owned bare configuration. +package struct ManagedSourceGit { + let repository: SourceRepository + let binding: SourceCredentialBinding + let access: SourceAccessConfiguration + + static func select(_ route: SourceRoute, environment: RuntimeEnvironment) throws -> Self? { + guard case .git(let repository?) = route, + let binding = try route.credential(environment.sourceAccess) + else { return nil } + return Self(repository: repository, binding: binding, access: environment.sourceAccess) + } + + func command( + _ arguments: [String], lock: Int32? = nil, in mirror: URL? = nil + ) throws -> ProcessOutput { + let temporary = FileManager.default.temporaryDirectory.resolvingSymlinksInPath() + let parent = try DirectoryHandle(at: temporary) + let name = "agents-source-git-" + UUID().uuidString + let workspace = try parent.createPrivateDirectory(name) + defer { try? FileManager.default.removeItem(at: workspace.url) } + var environment = ProcessRunner.isolatedGitEnvironment(in: workspace.url, network: true) + environment["GIT_CEILING_DIRECTORIES"] = temporary.path + + let context: [String] + let ancestry: DirectoryAccessEvidence? + if let mirror { + ancestry = try DirectoryAccessEvidence.capture(at: mirror) + let directory = try DirectoryHandle(at: mirror) + let config = try directory.read("config", maximumBytes: 4096) + guard + config == controlledConfiguration(sha256: false) + || config == controlledConfiguration(sha256: true) + else { throw SourceAccessError.routeChanged } + context = ["--git-dir=" + mirror.path] + } else { + ancestry = nil + context = [] + } + + var options = + ProcessRunner.isolatedGitOptions + [ + "-c", "credential.useHttpPath=true", "-c", "credential.interactive=false", + "-c", "fetch.recurseSubmodules=false", "-c", "submodule.recurse=false", + ] + if let certificate = GitAcquisition.fixtureCertificateAuthority { + options += ["-c", "http.sslCAInfo=" + certificate.path] + } + let effective = try ProcessRunner.execute( + "/usr/bin/git", + arguments: options + context + ["ls-remote", "--get-url", "--", repository.url], + workingDirectory: workspace.url, environment: environment, lock: lock) + guard effective.exitCode == 0, + effective.stdout.trimmingCharacters(in: .newlines).utf8.elementsEqual(repository.url.utf8) + else { throw SourceAccessError.routeChanged } + + let fifo = workspace.url.appendingPathComponent("credential.pipe").path + guard mkfifo(fifo, 0o600) == 0 else { throw SourceAccessError.requestFailed } + let descriptor = open(fifo, O_RDWR | O_NONBLOCK | O_CLOEXEC | O_NOFOLLOW) + guard descriptor >= 0 else { throw SourceAccessError.requestFailed } + defer { close(descriptor) } + try access.requireCurrentSettings() + let secret = Data((try binding.value() + "\n").utf8) + guard secret.withUnsafeBytes({ write(descriptor, $0.baseAddress, $0.count) }) == secret.count + else { throw SourceAccessError.credentialUnavailable } + + let url = URLComponents(string: repository.url)! + environment["AGENTS_SOURCE_GIT_HOST"] = url.host! + (url.port.map { ":\($0)" } ?? "") + environment["AGENTS_SOURCE_GIT_PATH"] = String(repository.gitPath.dropFirst()) + environment["AGENTS_SOURCE_GIT_PIPE"] = fifo + environment["AGENTS_SOURCE_GIT_USER"] = binding.gitUsername + var network = options + network += ["-c", "credential.helper=" + Self.helper] + if let mirror { try ancestry?.validate(at: mirror) } + let output = try ProcessRunner.execute( + "/usr/bin/git", arguments: network + context + arguments, + workingDirectory: workspace.url, environment: environment, lock: lock) + guard output.exitCode == 0 else { throw SourceAccessError.requestFailed } + return ProcessOutput(stdout: output.stdout, stderr: "", exitCode: 0) + } + + func sealClonedConfiguration(_ mirror: URL) throws { + let directory = try DirectoryHandle(at: mirror) + let generated = try directory.read("config", maximumBytes: 4096) + let sha256 = String(decoding: generated, as: UTF8.self).contains("objectformat = sha256") + try directory.replaceFile( + "config", through: "agents-config", with: controlledConfiguration(sha256: sha256), + afterWrite: {}, afterRename: {}) + } + + private func controlledConfiguration(sha256: Bool) -> Data { + var value = "[core]\n\trepositoryformatversion = \(sha256 ? 1 : 0)\n\tbare = true\n" + if sha256 { value += "[extensions]\n\tobjectformat = sha256\n" } + let quoted = repository.url.replacingOccurrences(of: "\\", with: "\\\\") + .replacingOccurrences(of: "\"", with: "\\\"") + value += "[remote \"origin\"]\n\turl = \"\(quoted)\"\n" + return Data(value.utf8) + } + + // Git appends the action as an argument. Git and other subprocesses never inherit the + // credential descriptor. The helper opens it only after matching the complete context. + private static let helper = #""" + !f() { + [ "$1" = get ] || exit 0 + protocol= host= path= + while IFS= read -r line && [ -n "$line" ]; do + case "$line" in + protocol=*) protocol=${line#protocol=} ;; + host=*) host=${line#host=} ;; + path=*) path=${line#path=} ;; + esac + done + [ "$protocol" = https ] && + [ "$host" = "$AGENTS_SOURCE_GIT_HOST" ] && + [ "$path" = "$AGENTS_SOURCE_GIT_PATH" ] || exit 0 + IFS= read -r password < "$AGENTS_SOURCE_GIT_PIPE" || exit 1 + printf 'username=%s\npassword=%s\n' "$AGENTS_SOURCE_GIT_USER" "$password" + }; f + """# +} diff --git a/Sources/AgentsCore/MarketplaceGraph.swift b/Sources/AgentsCore/MarketplaceGraph.swift new file mode 100644 index 0000000..1fd9509 --- /dev/null +++ b/Sources/AgentsCore/MarketplaceGraph.swift @@ -0,0 +1,487 @@ +import Foundation + +/// A dependency authored in a portable bundle. An omitted catalog means the publishing catalog. +public struct MarketplacePackageRequirement: Codable, Equatable, Sendable { + public let package: String + public let requirement: SourceRequirement + public let catalog: MarketplaceOrigin? + + public init(package: String, requirement: SourceRequirement, catalog: MarketplaceOrigin? = nil) + throws + { + self.package = package + self.requirement = try requirement.canonicalized() + self.catalog = catalog + try validate() + } + + package func validate() throws { + guard MarketplaceCoordinate.isName(package) else { + throw MarketplaceError.invalidPackage(package) + } + try requirement.validateMarketplaceVersion() + try catalog?.validatePortable() + } + + package static func validate(_ dependencies: [Self]) throws { + guard dependencies.count <= MarketplaceGraph.maximumEdgesPerNode else { + throw MarketplaceError.resolutionLimit("dependencies per release") + } + for dependency in dependencies { try dependency.validate() } + } +} + +/// A package-local member identity that can survive content and provenance changes. +public struct MarketplaceMemberKey: Codable, Equatable, Hashable, Sendable { + public let kind: DeclaredComponentKind + public let name: String + + public init(kind: DeclaredComponentKind, name: String) { + self.kind = kind + self.name = name + } + + package func validate() throws { + guard [.skills, .instructions, .mcpServer].contains(kind), !name.isEmpty, + name.utf8.count <= 1024, !name.utf8.contains(0) + else { throw MarketplaceError.invalidPackage("invalid member: " + name) } + } +} + +/// One root's recipients for one logical member of a reachable package. An omitted catalog +/// selects a package in the root's catalog. An explicit catalog uses its portable catalog identity. +public struct MarketplaceMemberSelection: Codable, Equatable, Sendable { + public let package: String + public let catalog: MarketplaceOrigin? + public let member: MarketplaceMemberKey + public let targets: [AgentID] + + public init( + package: String, catalog: MarketplaceOrigin? = nil, member: MarketplaceMemberKey, + targets: [AgentID] + ) throws { + self.package = package + self.catalog = catalog + self.member = member + self.targets = targets.sorted { $0.rawValue < $1.rawValue } + try validate() + } + + package func validate() throws { + guard MarketplaceCoordinate.isName(package), !targets.isEmpty, + targets.count == Set(targets).count + else { throw MarketplaceError.selectionMismatch(package + " / " + member.name) } + try member.validate() + try catalog?.validatePortable() + } +} + +/// Authored root intent. The catalog locator is supplied by the caller after registration lookup. +public struct MarketplaceRoot: Codable, Equatable, Sendable { + public let name: String + public let catalog: MarketplaceOrigin + public let package: String + public let requirement: SourceRequirement + public let selections: [MarketplaceMemberSelection] + + public init( + name: String, catalog: MarketplaceOrigin, package: String, requirement: SourceRequirement, + selections: [MarketplaceMemberSelection] = [] + ) throws { + self.name = name + self.catalog = catalog + self.package = package + self.requirement = try requirement.canonicalized() + self.selections = selections + try validate() + } + + package func validate() throws { + guard MarketplaceCoordinate.isName(name), MarketplaceCoordinate.isName(package), + selections.count <= MarketplaceGraph.maximumSelectionsPerRoot + else { throw MarketplaceError.invalidPackage(name) } + try catalog.validate() + try requirement.validateMarketplaceVersion() + for selection in selections { try selection.validate() } + } +} + +/// Canonical catalog identity, independent of discovery ref and Git transport spelling. +public struct MarketplaceCatalogID: Codable, Equatable, Hashable, Sendable { + public let kind: MarketplaceOrigin.Kind + public let origin: SourceOrigin + public let subpath: String? + public let hostedIndex: URL? + + package var policyPath: String? { + hostedIndex.map { String($0.path.dropFirst()) } ?? subpath + } + + package init(_ catalog: MarketplaceOrigin, origin: SourceOrigin) { + kind = catalog.kind + self.origin = origin + subpath = catalog.subpath + hostedIndex = catalog.hostedIndex + } + + package var sortKey: [String] { + [kind.rawValue, origin.description, policyPath ?? ""] + } +} + +/// One version can be selected for each catalog and package pair in a consumer scope. +public struct MarketplaceNodeID: Codable, Equatable, Hashable, Sendable, CustomStringConvertible { + public let catalog: MarketplaceCatalogID + public let package: String + + public var description: String { + catalog.origin.description + (catalog.policyPath.map { " / " + $0 } ?? "") + " / " + package + } + + package init(catalog: MarketplaceCatalogID, package: String) { + self.catalog = catalog + self.package = package + } + + package static func ordered(_ lhs: Self, _ rhs: Self) -> Bool { + (lhs.catalog.sortKey + [lhs.package]).lexicographicallyPrecedes( + rhs.catalog.sortKey + [rhs.package]) + } +} + +public struct MarketplaceResolvedEdge: Codable, Equatable, Sendable { + public let requirement: MarketplacePackageRequirement + public let target: MarketplaceNodeID + + package init(requirement: MarketplacePackageRequirement, target: MarketplaceNodeID) { + self.requirement = requirement + self.target = target + } +} + +public struct MarketplaceResolvedRoot: Codable, Equatable, Sendable { + public let intent: MarketplaceRoot + public let node: MarketplaceNodeID + + package init(intent: MarketplaceRoot, node: MarketplaceNodeID) { + self.intent = intent + self.node = node + } +} + +public struct MarketplaceResolvedMember: Codable, Equatable, Sendable { + public let key: MarketplaceMemberKey + public let componentID: String + public let sourceAlias: String + /// Embedded seal and producer tree for catalog-free recovery and subsequent reconciliation. + public package(set) var producerResource: String? + /// Effective recipients, unioned over all requesting roots. + public let targets: [AgentID] + + package init( + key: MarketplaceMemberKey, componentID: String, sourceAlias: String, targets: [AgentID], + producerResource: String? = nil + ) { + self.key = key + self.componentID = componentID + self.sourceAlias = sourceAlias + self.producerResource = producerResource + self.targets = targets + } +} + +/// A verified immutable release plus its selected component contributions. +public struct MarketplaceResolvedNode: Codable, Equatable, Sendable { + public let id: MarketplaceNodeID + public let catalog: MarketplaceOrigin + public let coordinate: MarketplaceCoordinate + public let archiveDigest: String + public let catalogCommit: String? + public package(set) var hostedEvidence: HostedMarketplaceEvidence? + public let dependencies: [MarketplaceResolvedEdge] + /// A recorded version override still needs matching trusted policy before restore or publication. + package var organizationRequirements: [SourceRequirement]? + public package(set) var members: [MarketplaceResolvedMember] + public package(set) var componentRecords: [String] + package var contributionDigest: String + + package init( + id: MarketplaceNodeID, catalog: MarketplaceOrigin, coordinate: MarketplaceCoordinate, + archiveDigest: String, catalogCommit: String?, dependencies: [MarketplaceResolvedEdge], + members: [MarketplaceResolvedMember] = [], componentRecords: [String] = [], + contributionDigest: String = "", organizationRequirements: [SourceRequirement]? = nil, + hostedEvidence: HostedMarketplaceEvidence? = nil + ) { + self.id = id + self.catalog = catalog + self.coordinate = coordinate + self.archiveDigest = archiveDigest + self.catalogCommit = catalogCommit + self.hostedEvidence = hostedEvidence + self.dependencies = dependencies + self.organizationRequirements = organizationRequirements + self.members = members + self.componentRecords = componentRecords + self.contributionDigest = contributionDigest + } + + package var sourceAliases: [String] { members.map(\.sourceAlias) } + + package static let sourceAliasPrefix = "marketplace-" +} + +/// One admitted graph. Edges preserve each incoming constraint, and roots own recipient intent. +public struct MarketplaceGraph: Codable, Equatable, Sendable { + public let roots: [MarketplaceResolvedRoot] + public package(set) var nodes: [MarketplaceResolvedNode] + + package static let maximumNodes = 256 + package static let maximumDepth = 64 + package static let maximumEdgesPerNode = 64 + package static let maximumSelectionsPerRoot = 1024 + private static let maximumSelections = 4096 + package static let maximumEdges = 2048 + + package init(roots: [MarketplaceResolvedRoot], nodes: [MarketplaceResolvedNode]) { + self.roots = roots + self.nodes = nodes + } + + /// All roots that require a node, irrespective of which roots enable its components. + public func rootsRequiring(_ node: MarketplaceNodeID) -> [String] { + let edges = Dictionary( + nodes.map { ($0.id, $0.dependencies.map(\.target)) }, + uniquingKeysWith: { first, _ in first }) + return roots.filter { Self.reachable(from: $0.node, edges: edges).contains(node) } + .map(\.intent.name) + } + + /// Immediate parents and their constraints. Together with roots and outgoing edges, this + /// describes every reason for a node without expanding exponentially many paths. + public func incoming(to node: MarketplaceNodeID) -> [MarketplaceIncomingRequirement] { + nodes.flatMap { parent in + parent.dependencies.filter { $0.target == node }.map { + MarketplaceIncomingRequirement(parent: parent.id, requirement: $0.requirement) + } + } + } + + /// Recipients attributed to each root for one member in an admitted graph. + public func recipientsByRoot( + for member: MarketplaceMemberKey, in node: MarketplaceNodeID + ) -> [String: [AgentID]] { + var result: [String: [AgentID]] = [:] + for root in roots { + for selection in root.intent.selections + where selection.member == member && (try? Self.node(for: selection, from: root)) == node { + result[root.intent.name] = selection.targets + } + } + return result + } + + /// Longest known path to each node. Equal-length paths retain authored root/edge order. + /// The solver also calls this on partial DAGs before observing any next node. + package func policyPaths() -> [MarketplaceNodeID: [MarketplaceNodeID]] { + let edges = Dictionary( + uniqueKeysWithValues: nodes.map { ($0.id, $0.dependencies.map(\.target)) }) + var paths: [MarketplaceNodeID: [MarketplaceNodeID]] = [:] + var pending = roots.reversed().map { [$0.node] } + while let path = pending.popLast() { + guard let last = path.last, path.count > (paths[last]?.count ?? 0), + path.count <= Self.maximumNodes + else { continue } + paths[last] = path + for child in (edges[last] ?? []).reversed() where !path.contains(child) { + pending.append(path + [child]) + } + } + return paths + } + + package func reachable(from node: MarketplaceNodeID) -> Set { + Self.reachable( + from: node, + edges: Dictionary( + uniqueKeysWithValues: + nodes.map { ($0.id, $0.dependencies.map(\.target)) })) + } + + private static func reachable( + from node: MarketplaceNodeID, edges: [MarketplaceNodeID: [MarketplaceNodeID]] + ) -> Set { + var seen = Set() + var pending = [node] + while let current = pending.popLast() { + if seen.insert(current).inserted { pending += edges[current] ?? [] } + } + return seen + } + + package func selectedTargets() throws -> [MarketplaceNodeID: [MarketplaceMemberKey: Set]] + { + guard roots.count <= Self.maximumNodes, + roots.reduce(0, { $0 + $1.intent.selections.count }) <= Self.maximumSelections + else { throw MarketplaceError.resolutionLimit("root selections") } + let edges = Dictionary( + uniqueKeysWithValues: nodes.map { ($0.id, $0.dependencies.map(\.target)) }) + var targets: [MarketplaceNodeID: [MarketplaceMemberKey: Set]] = [:] + for root in roots { + let reachable = Self.reachable(from: root.node, edges: edges) + var selected: [MarketplaceNodeID: Set] = [:] + for selection in root.intent.selections { + let id = try Self.node(for: selection, from: root) + guard reachable.contains(id), selected[id, default: []].insert(selection.member).inserted + else { + throw MarketplaceError.selectionMismatch(root.intent.name + " / " + selection.member.name) + } + targets[id, default: [:]][selection.member, default: []].formUnion(selection.targets) + } + } + return targets + } + + private static func node( + for selection: MarketplaceMemberSelection, from root: MarketplaceResolvedRoot + ) throws -> MarketplaceNodeID { + let catalog: MarketplaceCatalogID + if let explicit = selection.catalog { + catalog = try MarketplaceCatalogID(explicit, origin: explicit.remotePolicyOrigin()) + } else { + catalog = root.node.catalog + } + return MarketplaceNodeID(catalog: catalog, package: selection.package) + } + + package func validate( + components: [String: LedgerComponent], resources: [String: LedgerResource], + objects: [String: Data], aliases: inout Set + ) throws { + guard !roots.isEmpty, roots.count <= Self.maximumNodes, nodes.count <= Self.maximumNodes, + nodes.reduce(0, { $0 + $1.dependencies.count }) <= Self.maximumEdges, + Set(roots.map(\.intent.name)).count == roots.count, + Set(nodes.map(\.id)).count == nodes.count + else { throw MarketplaceError.invalidPackage("invalid frozen graph") } + let byID = Dictionary(uniqueKeysWithValues: nodes.map { ($0.id, $0) }) + let targets = try selectedTargets() + var refs: [MarketplaceCatalogID: MarketplaceOrigin] = [:] + for node in nodes { + try node.catalog.validate() + try node.coordinate.validate() + try StateValidation.digest(node.archiveDigest) + try StateValidation.digest(node.contributionDigest) + try validate(node.id, catalog: node.catalog) + guard node.coordinate.package == node.id.package, + (node.catalog.kind == .git) == (node.catalogCommit != nil), + node.catalogCommit.map(SourceCache.isObjectID) ?? true, + node.componentRecords == Array(Set(node.componentRecords)).sorted(), + node.componentRecords.allSatisfy({ components[$0] != nil }), + node.members.isEmpty == node.componentRecords.isEmpty, + Set(node.members.map(\.key)).count == node.members.count, + node.members.count == (targets[node.id]?.count ?? 0) + else { throw MarketplaceError.contributionMismatch(node.id.description) } + if let hosted = node.hostedEvidence { + guard node.catalog.kind == .hosted, + objects[node.archiveDigest]?.count == hosted.archiveByteCount + else { throw MarketplaceError.integrityMismatch(node.coordinate.label) } + try hosted.validate(index: node.catalog.location) + } else if node.catalog.kind == .hosted { + throw MarketplaceError.integrityMismatch(node.coordinate.label) + } + if let other = refs[node.id.catalog], other.ref != node.catalog.ref { + throw MarketplaceError.originConflict(node.id.description) + } + refs[node.id.catalog] = node.catalog + let sources = Set(node.componentRecords.compactMap { components[$0]?.declaringSource }) + for member in node.members { + try member.key.validate() + try StateValidation.digest(member.componentID) + guard let selected = targets[node.id]?[member.key], + member.targets == selected.sorted(by: { $0.rawValue < $1.rawValue }), + let id = member.producerResource, let resource = resources[id], + resource.kind == .embedded, resource.path == ".", + try ResolvedLedgerCodec.digest(resource) == id, + sources.contains(resource.source), + member.sourceAlias.hasPrefix(MarketplaceResolvedNode.sourceAliasPrefix), + aliases.insert(member.sourceAlias).inserted + else { throw MarketplaceError.contributionMismatch(node.id.description) } + try StateValidation.digest( + "sha256:" + member.sourceAlias.dropFirst(MarketplaceResolvedNode.sourceAliasPrefix.count)) + } + if let overrides = node.organizationRequirements { + guard !overrides.isEmpty, overrides.count <= LedgerLimits.standard.entries else { + throw MarketplaceError.invalidPackage("invalid organization version override") + } + for requirement in overrides { + try requirement.validateMarketplaceVersion() + guard requirement.admitsMarketplaceVersion(node.coordinate.version) else { + throw MarketplaceError.contributionMismatch(node.id.description) + } + } + } + try MarketplacePackageRequirement.validate(node.dependencies.map(\.requirement)) + for edge in node.dependencies { + var catalog = node.id.catalog + if let portable = edge.requirement.catalog { + catalog = try MarketplaceCatalogID(portable, origin: portable.remotePolicyOrigin()) + guard byID[edge.target]?.catalog.ref == portable.ref else { + throw MarketplaceError.originConflict(edge.target.description) + } + } + guard edge.target == MarketplaceNodeID(catalog: catalog, package: edge.requirement.package), + let target = byID[edge.target], + target.organizationRequirements != nil + || edge.requirement.requirement.admitsMarketplaceVersion(target.coordinate.version) + else { throw MarketplaceError.contributionMismatch(node.id.description) } + } + } + var heights: [MarketplaceNodeID: Int] = [:] + var visiting = Set() + func visit(_ id: MarketplaceNodeID, depth: Int) throws -> Int { + if let height = heights[id] { return height } + guard depth < Self.maximumDepth else { throw MarketplaceError.resolutionLimit("graph depth") } + guard visiting.insert(id).inserted else { + throw MarketplaceError.dependencyCycle(id.description) + } + guard let node = byID[id] else { throw MarketplaceError.missingPin(id.description) } + let height = + try 1 + (node.dependencies.map { try visit($0.target, depth: depth + 1) }.max() ?? 0) + visiting.remove(id) + heights[id] = height + return height + } + for root in roots { + try root.intent.validate() + try validate(root.node, catalog: root.intent.catalog) + guard let node = byID[root.node], node.catalog.ref == root.intent.catalog.ref, + root.node.package == root.intent.package, + node.organizationRequirements != nil + || root.intent.requirement.admitsMarketplaceVersion(node.coordinate.version), + try visit(root.node, depth: 0) <= Self.maximumDepth + else { throw MarketplaceError.selectionMismatch(root.intent.name) } + } + guard heights.count == nodes.count else { + throw MarketplaceError.invalidPackage("unreachable frozen package") + } + } + + private func validate(_ node: MarketplaceNodeID, catalog: MarketplaceOrigin) throws { + guard catalog.kind == node.catalog.kind, catalog.subpath == node.catalog.subpath, + catalog.hostedIndex == node.catalog.hostedIndex + else { + throw MarketplaceError.originConflict(node.description) + } + if catalog.isLocal { + guard node.catalog.origin.kind == .local, node.catalog.origin.identity != nil else { + throw MarketplaceError.originConflict(node.description) + } + } else if try node.catalog.origin != catalog.remotePolicyOrigin() { + throw MarketplaceError.originConflict(node.description) + } + } +} + +public struct MarketplaceIncomingRequirement: Equatable, Sendable { + public let parent: MarketplaceNodeID + public let requirement: MarketplacePackageRequirement +} diff --git a/Sources/AgentsCore/MarketplacePackage.swift b/Sources/AgentsCore/MarketplacePackage.swift new file mode 100644 index 0000000..c2c665c --- /dev/null +++ b/Sources/AgentsCore/MarketplacePackage.swift @@ -0,0 +1,288 @@ +import Foundation + +public enum MarketplaceError: Error, Equatable, Sendable, CustomStringConvertible { + case invalidOrigin(String) + case invalidPackage(String) + case releaseNotFound(String) + case publicationConflict(String) + case integrityMismatch(String) + case originConflict(String) + case missingPin(String) + case selectionMismatch(String) + case contributionMismatch(String) + case unsatisfiable(String) + case dependencyCycle(String) + case resolutionLimit(String) + case dependenciesRequireResolution(String) + case pendingDeployment + case changedPendingDeclaration + + public var description: String { + switch self { + case .invalidOrigin(let detail): "Invalid marketplace origin: " + detail + case .invalidPackage(let coordinate): "Invalid marketplace package: " + coordinate + case .releaseNotFound(let coordinate): "Marketplace release not found: " + coordinate + case .publicationConflict(let coordinate): "Marketplace release already exists: " + coordinate + case .integrityMismatch(let coordinate): "Marketplace release integrity mismatch: " + coordinate + case .originConflict(let name): "Marketplace dependency origin changed: " + name + case .missingPin(let name): "Missing marketplace pin: " + name + case .selectionMismatch(let name): + "Marketplace selection differs from committed intent: " + name + case .contributionMismatch(let name): "Marketplace package contribution differs: " + name + case .unsatisfiable(let detail): "Marketplace requirements cannot be resolved: " + detail + case .dependencyCycle(let detail): "Marketplace dependency cycle: " + detail + case .resolutionLimit(let detail): "Marketplace resolution exceeded the budget for " + detail + case .dependenciesRequireResolution(let detail): + "Marketplace dependencies require catalog resolution: " + detail + case .pendingDeployment: "A marketplace resolution is awaiting explicit deployment." + case .changedPendingDeclaration: + "The declaration changed after the marketplace resolution was locked." + } + } +} + +/// A team catalog locator. Relative filesystem locations are interpreted from the consumer's +/// project directory. The Git ref controls discovery; a selected release records its full commit. +public struct MarketplaceOrigin: Codable, Equatable, Hashable, Sendable { + public enum Kind: String, Codable, Sendable { case directory, git, hosted } + + public let kind: Kind + public let location: String + public let ref: String? + public let subpath: String? + + public init(kind: Kind, location: String, ref: String? = nil, subpath: String? = nil) throws { + guard !location.isEmpty, location.utf8.count <= 4096, + !location.contains("\\"), !location.utf8.contains(where: { $0 < 32 || $0 == 127 }) + else { throw MarketplaceError.invalidOrigin("invalid catalog location") } + self.kind = kind + switch kind { + case .directory: + guard ref == nil, subpath == nil, !location.contains("://"), !location.hasPrefix("~") else { + throw MarketplaceError.invalidOrigin("invalid directory catalog") + } + self.location = Self.normalizedPath(location) + self.ref = nil + self.subpath = nil + case .hosted: + guard ref == nil, subpath == nil else { + throw MarketplaceError.invalidOrigin("hosted catalog uses one HTTPS index URL") + } + self.location = try HostedMarketplaceLocation(location).url.absoluteString + self.ref = nil + self.subpath = nil + case .git: + if let ref { + try SourceRequirement.revision(ref).validate() + guard ref.utf8.count <= 1024, + !ref.utf8.contains(where: { $0 <= 32 || $0 == 127 }) + else { throw MarketplaceError.invalidOrigin("invalid Git catalog ref") } + } + if location.hasPrefix("/") || location.hasPrefix("./") || location.hasPrefix("../") + || location == "." || location == ".." + { + let path = Self.normalizedPath(location) + self.location = + path.hasPrefix("/") || path.hasPrefix("../") || path == ".." || path == "." + ? path : "./" + path + } else { + let source = SourceDeclaration(kind: .git, location: location) + guard var url = URLComponents(string: source.gitURL), + let scheme = url.scheme?.lowercased(), ["https", "http", "ssh", "file"].contains(scheme), + url.query == nil, url.fragment == nil, url.password == nil, + scheme == "ssh" || url.user == nil + else { throw MarketplaceError.invalidOrigin("invalid Git catalog URL") } + if scheme == "file" { + guard url.host == nil || url.host == "" || url.host == "localhost", url.port == nil, + url.path.hasPrefix("/"), !url.path.utf8.contains(where: { $0 < 32 || $0 == 127 }) + else { throw MarketplaceError.invalidOrigin("invalid local Git catalog URL") } + self.location = Self.normalizedPath(url.path) + } else { + guard let host = url.host, !host.isEmpty, url.path.count > 1 else { + throw MarketplaceError.invalidOrigin("Git catalog needs a host and repository path") + } + url.scheme = scheme + url.host = host.lowercased() + self.location = url.string! + } + } + self.ref = ref == "HEAD" ? nil : ref + let path = try PathSafety.sanitizeSubpath(subpath ?? ".") + self.subpath = path == "." ? nil : path + } + } + + package func validate() throws { + guard try Self(kind: kind, location: location, ref: ref, subpath: subpath) == self else { + throw MarketplaceError.invalidOrigin("catalog origin is not canonical") + } + } + + package var isLocal: Bool { + kind == .directory || location.hasPrefix("/") || location.hasPrefix("./") + || location.hasPrefix("../") || location == "." || location == ".." + } + + package func validatePortable() throws { + try validate() + guard !isLocal else { + throw MarketplaceError.invalidOrigin("portable dependencies require a remote catalog") + } + _ = try policyOrigin(environment: RuntimeEnvironment(environment: [:])) + } + + package func fileURL(environment: RuntimeEnvironment) -> URL? { + guard isLocal else { return nil } + return URL( + fileURLWithPath: location, isDirectory: true, + relativeTo: URL(fileURLWithPath: environment.projectDirectory.path, isDirectory: true) + ).standardizedFileURL + } + + package func policyOrigin(environment: RuntimeEnvironment) throws -> SourceOrigin { + if let file = fileURL(environment: environment) { return .local(at: file) } + return try remotePolicyOrigin() + } + + package func remotePolicyOrigin() throws -> SourceOrigin { + try kind == .hosted ? .http(location) : .git(location) + } + + package func gitSource(commit: String? = nil) -> SourceDeclaration { + SourceDeclaration( + kind: isLocal ? .local : .git, location: location, + requirement: (commit ?? ref).map(SourceRequirement.revision)) + } + + private static func normalizedPath(_ path: String) -> String { + let absolute = path.hasPrefix("/") + var parts: [Substring] = [] + for part in path.split(separator: "/") where part != "." { + if part == "..", let previous = parts.last, previous != ".." { + parts.removeLast() + } else if part != ".." || !absolute { + parts.append(part) + } + } + let relative = parts.joined(separator: "/") + return absolute ? "/" + relative : relative.isEmpty ? "." : relative + } +} + +/// Package IDs are lowercase portable directory names. Versions use canonical SemVer spelling. +public struct MarketplaceCoordinate: Codable, Equatable, Hashable, Sendable { + public let package: String + public let version: String + + public init(package: String, version: String) throws { + guard Self.isName(package), version.utf8.count <= 128, + version.utf8.first.map({ (48...57).contains($0) }) == true, + SemanticVersion(version)?.description == version + else { throw MarketplaceError.invalidPackage("\(package)@\(version)") } + self.package = package + self.version = version + } + + package var label: String { "\(package)@\(version)" } + + public var releasePath: String { "releases/\(package)/\(version)" } + + package func validate() throws { _ = try Self(package: package, version: version) } + + package static func isName(_ name: String) -> Bool { + func alphanumeric(_ byte: UInt8) -> Bool { + (97...122).contains(byte) || (48...57).contains(byte) + } + return name.utf8.count <= 128 && name.utf8.first.map(alphanumeric) == true + && name.utf8.allSatisfy { alphanumeric($0) || [45, 46, 95].contains($0) } + && !name.hasSuffix(".") + } + + /// SemVer precedence with a deterministic tie-break for different build metadata. + package static func newer(_ lhs: Self, than rhs: Self) -> Bool { + guard let a = SemanticVersion(lhs.version), let b = SemanticVersion(rhs.version) else { + return false + } + return a == b ? lhs.version > rhs.version : a > b + } + + package func hasHigherPrecedence(than other: Self) -> Bool { + guard let version = SemanticVersion(version), let previous = SemanticVersion(other.version) + else { return false } + return version > previous + } +} + +/// The committed selection addressed by a dependency name in one consumer scope. +public struct MarketplaceDependency: Codable, Equatable, Sendable { + public let name: String + public let catalog: MarketplaceOrigin + public let coordinate: MarketplaceCoordinate + + public init(name: String, catalog: MarketplaceOrigin, coordinate: MarketplaceCoordinate) throws { + self.name = name + self.catalog = catalog + self.coordinate = coordinate + try validate() + } + + package func validate() throws { + guard MarketplaceCoordinate.isName(name) else { throw MarketplaceError.invalidPackage(name) } + try catalog.validate() + try coordinate.validate() + } +} + +/// Verified acquisition and the exact imported contributions frozen in one scope ledger. +public struct MarketplacePin: Codable, Equatable, Sendable { + public let dependency: MarketplaceDependency + public let archiveDigest: String + public let catalogCommit: String? + /// The physical catalog origin observed at acquisition. + public let catalogOrigin: SourceOrigin? + public let sourceAliases: [String] + public let componentRecords: [String] + package let contributionDigest: String + + package init( + dependency: MarketplaceDependency, archiveDigest: String, catalogCommit: String?, + sourceAliases: [String], componentRecords: [String], contributionDigest: String, + catalogOrigin: SourceOrigin? = nil + ) { + self.dependency = dependency + self.archiveDigest = archiveDigest + self.catalogCommit = catalogCommit + self.catalogOrigin = catalogOrigin + self.sourceAliases = sourceAliases + self.componentRecords = componentRecords + self.contributionDigest = contributionDigest + } + + package func policyOrigin(environment: RuntimeEnvironment) throws -> SourceOrigin { + if let catalogOrigin { return catalogOrigin } + if dependency.catalog.fileURL(environment: environment) != nil { return .missing } + return try dependency.catalog.policyOrigin(environment: environment) + } + + package func validate() throws { + try dependency.validate() + try StateValidation.digest(archiveDigest) + try StateValidation.digest(contributionDigest) + if let catalogOrigin { + if dependency.catalog.fileURL(environment: RuntimeEnvironment(environment: [:])) != nil { + guard catalogOrigin.kind == .local, catalogOrigin.identity != nil else { + throw MarketplaceError.originConflict(dependency.name) + } + } else if try catalogOrigin != dependency.catalog.remotePolicyOrigin() { + throw MarketplaceError.originConflict(dependency.name) + } + } + guard dependency.catalog.kind != .hosted, + (dependency.catalog.kind == .git) == (catalogCommit != nil), + catalogCommit.map(SourceCache.isObjectID) ?? true, + !sourceAliases.isEmpty, sourceAliases.count == Set(sourceAliases).count, + sourceAliases.allSatisfy({ !$0.isEmpty && $0 != "." && !$0.contains(":") }), + componentRecords == Array(Set(componentRecords)).sorted(), !componentRecords.isEmpty + else { throw MarketplaceError.contributionMismatch(dependency.name) } + } +} diff --git a/Sources/AgentsCore/NativeTargetCoordination.swift b/Sources/AgentsCore/NativeTargetCoordination.swift new file mode 100644 index 0000000..c195ee0 --- /dev/null +++ b/Sources/AgentsCore/NativeTargetCoordination.swift @@ -0,0 +1,1493 @@ +import CPlatform +import Foundation + +/// Closed physical routes; regional ownership and rendering belong to the native adapter. +enum FixedNativeTargetRoute: String, Codable, Sendable, CaseIterable { + case claudeMCPProject = "claude.mcp.project" + case claudeMCPLocal = "claude.mcp.local" + case claudeMCPUser = "claude.mcp.user" + case codexMCPProject = "codex.mcp.project" + case codexMCPUser = "codex.mcp.user" + case antigravityMCPProject = "antigravity.mcp.project" + case antigravityMCPUser = "antigravity.mcp.user" + case geminiMCPProject = "gemini.mcp.project" + case geminiMCPUser = "gemini.mcp.user" + case cursorMCPProject = "cursor.mcp.project" + case cursorMCPUser = "cursor.mcp.user" + case openCodeMCPProjectJSON = "opencode.mcp.project.json" + case openCodeMCPProjectJSONC = "opencode.mcp.project.jsonc" + case openCodeMCPUserJSON = "opencode.mcp.user.json" + case openCodeMCPUserJSONC = "opencode.mcp.user.jsonc" + + case claudeSettingsProject = "claude.settings.project" + case claudeSettingsUser = "claude.settings.user" + case codexHooksProject = "codex.hooks.project" + case codexHooksUser = "codex.hooks.user" + case antigravityHooksProject = "antigravity.hooks.project" + case antigravityHooksUser = "antigravity.hooks.user" + case cursorHooksProject = "cursor.hooks.project" + case cursorHooksUser = "cursor.hooks.user" + case geminiIgnoreProject = "gemini.ignore.project" + case cursorIgnoreProject = "cursor.ignore.project" + + var shared: Bool { + switch self { + case .claudeMCPLocal, .claudeMCPUser, .codexMCPUser, .geminiMCPUser, .cursorMCPUser, + .openCodeMCPUserJSON, .openCodeMCPUserJSONC, .claudeSettingsUser, .codexHooksUser, + .cursorHooksUser, .antigravityMCPUser, .antigravityHooksUser: + true + default: false + } + } + static let projectRoot = "native-claude-project" + static let globalRoot = "native-claude-global" + static let metadataRoot = "native-claude-metadata" + + var root: String { + switch self { + case .claudeMCPProject: Self.projectRoot + case .claudeMCPLocal, .claudeMCPUser: Self.globalRoot + default: + "native-" + + rawValue.replacingOccurrences(of: ".mcp.", with: "-") + .replacingOccurrences(of: ".", with: "-") + } + } + var metadata: String { root == Self.globalRoot ? Self.metadataRoot : root + "-metadata" } + var basename: String { + switch self { + case .claudeSettingsProject, .claudeSettingsUser: "settings.json" + case .codexHooksProject, .codexHooksUser, .cursorHooksProject, .cursorHooksUser: "hooks.json" + case .antigravityHooksProject, .antigravityHooksUser: "hooks.json" + case .antigravityMCPProject, .antigravityMCPUser: "mcp_config.json" + case .geminiIgnoreProject: ".geminiignore" + case .cursorIgnoreProject: ".cursorignore" + case .claudeMCPProject: ".mcp.json" + case .claudeMCPLocal, .claudeMCPUser: ".claude.json" + case .codexMCPProject, .codexMCPUser: "config.toml" + case .geminiMCPProject, .geminiMCPUser: "settings.json" + case .cursorMCPProject, .cursorMCPUser: "mcp.json" + case .openCodeMCPProjectJSON, .openCodeMCPUserJSON: "opencode.json" + case .openCodeMCPProjectJSONC, .openCodeMCPUserJSONC: "opencode.jsonc" + } + } + static var sharedRoutes: [Self] { + [ + .claudeMCPLocal, .codexMCPUser, .geminiMCPUser, .cursorMCPUser, + .openCodeMCPUserJSON, .openCodeMCPUserJSONC, .claudeSettingsUser, .codexHooksUser, + .cursorHooksUser, .antigravityMCPUser, .antigravityHooksUser, + ] + } + static func targetRoute(_ path: String) -> Self? { + let key = path.split(separator: "/").first.map(String.init) + return allCases.first { $0.root == key } + } + static func sharedRoute(_ path: String) -> Self? { + targetRoute(path).flatMap { $0.shared ? $0 : nil } + } + static func metadataRoute(_ path: String) -> Self? { + let key = path.split(separator: "/").first.map(String.init) + return sharedRoutes.first { $0.metadata == key } + } + + func logicalDirectory(_ environment: RuntimeEnvironment, validateExistingOverride: Bool = true) + throws -> URL + { + func home() throws -> URL { try Self.absoluteDirectory(environment.homeDirectory) } + func override(_ key: String) throws -> URL? { + guard let value = environment.environment[key], !value.isEmpty else { return nil } + guard value.hasPrefix("/"), !value.contains("\0") else { + throw CoreError.unsafePath("registered " + key + " must be an absolute directory") + } + return URL(fileURLWithPath: value).standardizedFileURL + } + switch self { + case .claudeSettingsProject: + return try Self.absoluteDirectory(environment.projectDirectory).appendingPathComponent( + ".claude") + case .claudeSettingsUser: + return try override("CLAUDE_CONFIG_DIR") ?? home().appendingPathComponent(".claude") + case .codexHooksProject: return try Self.codexMCPProject.logicalDirectory(environment) + case .codexHooksUser: + return try Self.codexMCPUser.logicalDirectory( + environment, validateExistingOverride: validateExistingOverride) + case .cursorHooksProject: return try Self.cursorMCPProject.logicalDirectory(environment) + case .cursorHooksUser: return try Self.cursorMCPUser.logicalDirectory(environment) + case .geminiIgnoreProject, .cursorIgnoreProject: + return try Self.absoluteDirectory(environment.projectDirectory) + case .claudeMCPProject: + return try Self.absoluteDirectory(environment.projectDirectory) + case .claudeMCPLocal, .claudeMCPUser: + return try override("CLAUDE_CONFIG_DIR") ?? home() + case .codexMCPProject: + return try Self.absoluteDirectory(environment.projectDirectory).appendingPathComponent( + ".codex") + case .codexMCPUser: + if let root = try override("CODEX_HOME") { + if validateExistingOverride { _ = try DirectoryHandle(at: root.resolvingSymlinksInPath()) } + return root + } + return try home().appendingPathComponent(".codex") + case .antigravityMCPProject, .antigravityHooksProject: + return try Self.absoluteDirectory(environment.projectDirectory).appendingPathComponent( + ".agents") + case .antigravityMCPUser, .antigravityHooksUser: + return try home().appendingPathComponent(".gemini/config") + case .geminiMCPProject: + return try Self.absoluteDirectory(environment.projectDirectory).appendingPathComponent( + ".gemini") + case .geminiMCPUser: + return try (override("GEMINI_CLI_HOME") ?? home()).appendingPathComponent(".gemini") + case .cursorMCPProject: + return try Self.absoluteDirectory(environment.projectDirectory).appendingPathComponent( + ".cursor") + case .cursorMCPUser: + return try home().appendingPathComponent(".cursor") + case .openCodeMCPProjectJSON, .openCodeMCPProjectJSONC: + return try Self.absoluteDirectory(environment.projectDirectory) + case .openCodeMCPUserJSON, .openCodeMCPUserJSONC: + if environment.environment["OPENCODE_CONFIG_DIR"] == "" { + throw CoreError.unsafePath( + "empty OPENCODE_CONFIG_DIR does not establish a registered absolute root") + } + return try override("OPENCODE_CONFIG_DIR") + ?? (override("XDG_CONFIG_HOME") ?? home().appendingPathComponent(".config")) + .appendingPathComponent("opencode") + } + } + static func absoluteDirectory(_ url: URL) throws -> URL { + guard url.isFileURL, url.path.hasPrefix("/"), !url.path.contains("\0") else { + throw CoreError.unsafePath("registered native root must be an absolute filesystem directory") + } + return url.standardizedFileURL + } + static func globalLogicalDirectory(_ environment: RuntimeEnvironment) throws -> URL { + try Self.claudeMCPLocal.logicalDirectory(environment) + } + static func globalDirectory(_ environment: RuntimeEnvironment) throws -> URL { + try globalLogicalDirectory(environment).resolvingSymlinksInPath() + } +} + +/// A closed loader recipe. Named routes carry only validated native member names; +/// runtime directories remain owned by the recipe and explicit environment. +package struct NativeTargetRoute: RawRepresentable, Hashable, Codable, Sendable { + package enum Member: String, Codable, Sendable, CaseIterable { + case claudeCommand, claudeAgent, claudeSkillPlugin + case codexAgent, geminiCommand, geminiAgent, geminiExtension + case cursorCommand, cursorAgent, cursorLocalPlugin + } + package let rawValue: String + private let fixed: FixedNativeTargetRoute? + private let member: Member? + private let memberScope: InstallScope? + private let name: String? + + private init(_ fixed: FixedNativeTargetRoute) { + self.fixed = fixed + member = nil + memberScope = nil + name = nil + rawValue = fixed.rawValue + } + package init?(rawValue: String) { + if let fixed = FixedNativeTargetRoute(rawValue: rawValue) { + self.init(fixed) + return + } + let parts = rawValue.split(separator: ":", maxSplits: 2, omittingEmptySubsequences: false) + guard parts.count == 3, let member = Member(rawValue: String(parts[0])), + let scope = InstallScope(rawValue: String(parts[1])), + let value = try? Self.named(member, scope: scope, name: String(parts[2])) + else { return nil } + self = value + } + /// `name` is the adapter's exact extension-free name, including command subdirectories. + package static func named(_ member: Member, scope: InstallScope, name: String) throws -> Self { + let parts = name.split(separator: "/", omittingEmptySubsequences: false) + guard (member.rawValue + ":" + scope.rawValue + ":" + name).utf8.count <= 4096, + !parts.isEmpty, + parts.allSatisfy({ + !$0.isEmpty && $0 != "." && $0 != ".." + && !$0.contains("\\") && !$0.contains("\0") && !$0.contains(":") + && !$0.hasPrefix(".agents-") + }), + member == .claudeCommand || member == .geminiCommand || parts.count == 1, + !(member == .cursorCommand && scope != .project), + !([Member.cursorLocalPlugin, .geminiExtension].contains(member) && scope != .user) + else { throw CoreError.unsafePath("unregistered native member or scope") } + return Self(member: member, scope: scope, name: name) + } + /// Accepts the adapter-owned relative file path, never an absolute destination. + package static func file(_ member: Member, scope: InstallScope, relativePath: String) throws + -> Self + { + let suffix: String + switch member { + case .claudeCommand, .claudeAgent, .cursorCommand, .cursorAgent, .geminiAgent: suffix = ".md" + case .codexAgent, .geminiCommand: suffix = ".toml" + default: throw CoreError.unsafePath("native container requires its registered bundle name") + } + guard relativePath.hasSuffix(suffix) else { + throw CoreError.unsafePath("native member has the wrong filename extension") + } + return try named(member, scope: scope, name: String(relativePath.dropLast(suffix.count))) + } + private init(member: Member, scope: InstallScope, name: String) { + fixed = nil + self.member = member + memberScope = scope + self.name = name + rawValue = member.rawValue + ":" + scope.rawValue + ":" + name + } + package init(from decoder: any Decoder) throws { + let container = try decoder.singleValueContainer() + guard let route = Self(rawValue: try container.decode(String.self)) else { + throw CoreError.invalidState("unregistered native route") + } + self = route + } + package func encode(to encoder: any Encoder) throws { + var container = encoder.singleValueContainer() + try container.encode(rawValue) + } + package static let claudeMCPProject = Self(.claudeMCPProject) + package static let claudeMCPLocal = Self(.claudeMCPLocal) + package static let claudeMCPUser = Self(.claudeMCPUser) + package static let codexMCPProject = Self(.codexMCPProject) + package static let codexMCPUser = Self(.codexMCPUser) + package static let antigravityMCPProject = Self(.antigravityMCPProject) + package static let antigravityMCPUser = Self(.antigravityMCPUser) + package static let antigravityHooksProject = Self(.antigravityHooksProject) + package static let antigravityHooksUser = Self(.antigravityHooksUser) + package static let geminiMCPProject = Self(.geminiMCPProject) + package static let geminiMCPUser = Self(.geminiMCPUser) + package static let cursorMCPProject = Self(.cursorMCPProject) + package static let cursorMCPUser = Self(.cursorMCPUser) + package static let openCodeMCPProjectJSON = Self(.openCodeMCPProjectJSON) + package static let openCodeMCPProjectJSONC = Self(.openCodeMCPProjectJSONC) + package static let openCodeMCPUserJSON = Self(.openCodeMCPUserJSON) + package static let openCodeMCPUserJSONC = Self(.openCodeMCPUserJSONC) + package static let claudeSettingsProject = Self(.claudeSettingsProject) + package static let claudeSettingsUser = Self(.claudeSettingsUser) + package static let codexHooksProject = Self(.codexHooksProject) + package static let codexHooksUser = Self(.codexHooksUser) + package static let cursorHooksProject = Self(.cursorHooksProject) + package static let cursorHooksUser = Self(.cursorHooksUser) + package static let geminiIgnoreProject = Self(.geminiIgnoreProject) + package static let cursorIgnoreProject = Self(.cursorIgnoreProject) + package static var allCases: [Self] { FixedNativeTargetRoute.allCases.map(Self.init) } + static var mcpRoutes: [Self] { allCases.filter { $0.rawValue.contains(".mcp.") } } + static var sharedRoutes: [Self] { + FixedNativeTargetRoute.sharedRoutes.filter { $0.rawValue.contains(".mcp.") }.map(Self.init) + } + static let projectRoot = FixedNativeTargetRoute.projectRoot + static let globalRoot = FixedNativeTargetRoute.globalRoot + static let metadataRoot = FixedNativeTargetRoute.metadataRoot + package static func == (lhs: Self, rhs: Self) -> Bool { + lhs.rawValue.utf8.elementsEqual(rhs.rawValue.utf8) + } + package func hash(into hasher: inout Hasher) { + for byte in rawValue.utf8 { hasher.combine(byte) } + } + package var shared: Bool { fixed?.shared ?? (memberScope == .user) } + var isNamed: Bool { member != nil } + package var isContainer: Bool { + member.map { [.claudeSkillPlugin, .cursorLocalPlugin, .geminiExtension].contains($0) } ?? false + } + func permits(_ scope: InstallScope) -> Bool { + if let memberScope { return memberScope == scope } + if fixed == .antigravityMCPUser { return scope == .user } + if rawValue.contains(".mcp.") { return shared || scope == .project } + return shared ? scope == .user : scope == .project + } + /// Known readers are a lower bound; plugin/custom-root exclusivity needs reader evidence. + package var knownReaders: Set { + Self.knownReaders(rawValue: rawValue, fixed: fixed, member: member) + } + private static func knownReaders( + rawValue: String, fixed: FixedNativeTargetRoute?, member: Member? + ) -> Set { + if fixed == .claudeSettingsProject || fixed == .claudeSettingsUser || member == .claudeAgent { + return [.claudeCode, .cursor] + } + let prefix = rawValue.lowercased() + if prefix.hasPrefix("antigravity") { return [.antigravity] } + if prefix.hasPrefix("claude") { return [.claudeCode] } + if prefix.hasPrefix("codex") { return [.codex] } + if prefix.hasPrefix("gemini") { return [.geminiCLI] } + if prefix.hasPrefix("cursor") { return [.cursor] } + return [.opencode] + } + package var root: String { + fixed?.root ?? "native-member-" + rawValue.utf8.map { String(format: "%02x", $0) }.joined() + } + var metadata: String { fixed?.metadata ?? root + "-metadata" } + package var basename: String { + if let fixed { return fixed.basename } + let suffix: String + switch member! { + case .claudeCommand, .claudeAgent, .cursorCommand, .cursorAgent, .geminiAgent: suffix = ".md" + case .codexAgent, .geminiCommand: suffix = ".toml" + default: suffix = "" + } + return String(name!.split(separator: "/").last!) + suffix + } + private static func routeRoot(_ key: String) -> Self? { + if let fixed = FixedNativeTargetRoute.allCases.first(where: { $0.root == key }) { + return Self(fixed) + } + guard key.hasPrefix("native-member-") else { return nil } + let hex = Array(key.dropFirst("native-member-".count).utf8) + guard hex.count.isMultiple(of: 2), hex.count <= 8192 else { return nil } + var bytes: [UInt8] = [] + for index in stride(from: 0, to: hex.count, by: 2) { + guard let byte = UInt8(String(decoding: hex[index...index + 1], as: UTF8.self), radix: 16) + else { return nil } + bytes.append(byte) + } + guard let raw = String(bytes: bytes, encoding: .utf8), let route = Self(rawValue: raw), + route.root == key + else { return nil } + return route + } + package static func targetRoute(_ path: String) -> Self? { + routeRoot(String(path.split(separator: "/").first ?? "")) + } + static func sharedRoute(_ path: String) -> Self? { + targetRoute(path).flatMap { $0.shared ? $0 : nil } + } + static func metadataRoute(_ path: String) -> Self? { + let key = String(path.split(separator: "/").first ?? "") + if key == metadataRoot { return .claudeMCPLocal } + guard key.hasSuffix("-metadata"), + let route = routeRoot(String(key.dropLast("-metadata".count))), route.shared + else { return nil } + return route + } + func rootAuthority(_ environment: RuntimeEnvironment, validateExistingOverride: Bool = true) + throws -> NativeRootAuthority + { + switch fixed { + case .antigravityMCPProject, .antigravityHooksProject: + return .init(loader: environment.projectDirectory, descendants: [".agents"]) + case .antigravityMCPUser, .antigravityHooksUser: + return .init(loader: environment.homeDirectory, descendants: [".gemini", "config"]) + default: break + } + if let fixed { + return NativeRootAuthority( + loader: try fixed.logicalDirectory( + environment, validateExistingOverride: validateExistingOverride), descendants: []) + } + let recipe = Self.memberRecipe(member!, scope: memberScope!) + return NativeRootAuthority( + loader: try recipe.base.logicalDirectory( + environment, validateExistingOverride: validateExistingOverride), + descendants: recipe.container + name!.split(separator: "/").dropLast().map(String.init)) + } + + private static func memberRecipe(_ member: Member, scope: InstallScope) + -> (base: FixedNativeTargetRoute, container: [String]) + { + let base: FixedNativeTargetRoute + switch member { + case .claudeCommand, .claudeAgent, .claudeSkillPlugin: + base = scope == .project ? .claudeSettingsProject : .claudeSettingsUser + case .codexAgent: base = scope == .project ? .codexMCPProject : .codexMCPUser + case .geminiCommand, .geminiAgent, .geminiExtension: + base = scope == .project ? .geminiMCPProject : .geminiMCPUser + case .cursorCommand, .cursorAgent, .cursorLocalPlugin: + base = scope == .project ? .cursorMCPProject : .cursorMCPUser + } + let container: [String] + switch member { + case .claudeCommand, .geminiCommand, .cursorCommand: container = ["commands"] + case .claudeAgent, .codexAgent, .geminiAgent, .cursorAgent: container = ["agents"] + case .claudeSkillPlugin: container = ["skills"] + case .cursorLocalPlugin: container = ["plugins", "local"] + case .geminiExtension: container = ["extensions"] + } + return (base, container) + } + + package struct ClientLocation { + package let identity: String + package let agents: Set + package let evidenceScope: String + package let container: Bool + package let location: Result + } + + package static func clientLocations(scope: InstallScope, environment: RuntimeEnvironment) + -> [ClientLocation] + { + let fixed = FixedNativeTargetRoute.allCases.filter { + scope == .user ? $0.shared : !$0.shared || $0 == .claudeMCPLocal + }.map { route in + return ClientLocation( + identity: route.rawValue, agents: Self(route).knownReaders, + evidenceScope: route == .claudeMCPLocal ? "local" : scope.rawValue, container: false, + location: Result { + try route.logicalDirectory(environment, validateExistingOverride: false) + .appendingPathComponent(route.basename) + }) + } + let members = Member.allCases.filter { + !($0 == .cursorCommand && scope != .project) + && !([Member.cursorLocalPlugin, .geminiExtension].contains($0) && scope != .user) + }.map { member in + let recipe = memberRecipe(member, scope: scope) + return ClientLocation( + identity: member.rawValue + "." + scope.rawValue, + agents: knownReaders(rawValue: member.rawValue, fixed: nil, member: member), + evidenceScope: scope.rawValue, container: true, + location: Result { + try recipe.container.reduce( + recipe.base.logicalDirectory(environment, validateExistingOverride: false) + ) { $0.appendingPathComponent($1) } + }) + } + return fixed + members + } + package func logicalDirectory(_ environment: RuntimeEnvironment) throws -> URL { + try rootAuthority(environment).logicalDirectory + } + func physicalDirectory(_ environment: RuntimeEnvironment) throws -> URL { + try rootAuthority(environment).physicalDirectory() + } + + /// Detect closed user slots without creating a root or granting publication authority. + static func userRoute(at destination: URL, environment: RuntimeEnvironment) throws -> Self? { + var lookup = UserRouteLookup(environment: environment) + return try lookup.route(at: destination) + } + + /// Reused within one observation pass. Lock admission starts a fresh lookup in each phase. + struct UserRouteLookup { + let environment: RuntimeEnvironment + private var identities: [Data: FileObjectIdentity?] = [:] + private var memberContainers: [Member: URL] = [:] + + init(environment: RuntimeEnvironment) { self.environment = environment } + + private mutating func identity(at url: URL) throws -> FileObjectIdentity? { + let key = Data(url.path.utf8) + if let known = identities[key] { return known } + let identity = try (try? DirectoryHandle(at: url))?.objectIdentity + identities[key] = .some(identity) + return identity + } + + private mutating func matches(_ route: NativeTargetRoute, target: URL, parent: URL) throws + -> Bool + { + guard route.basename.utf8.elementsEqual(target.lastPathComponent.utf8) else { return false } + let authority = try route.rootAuthority(environment, validateExistingOverride: false) + let planned = try authority.plannedPhysicalDirectory + if planned.path.utf8.elementsEqual(parent.path.utf8) { + _ = try authority.physicalDirectory() + return true + } + if planned.resolvingSymlinksInPath().path.utf8.elementsEqual(parent.path.utf8) { + _ = try authority.physicalDirectory() + return true + } + // Unselected, disjoint roots do not impose access requirements on this target. + // Confirm any descriptor-equivalent match against the live alias. + guard let candidate = try? DirectoryHandle(at: planned), + let actual = try? DirectoryHandle(at: parent), + try candidate.objectIdentity == actual.objectIdentity + else { return false } + _ = try authority.physicalDirectory() + return true + } + mutating func route(at destination: URL) throws -> NativeTargetRoute? { + let parent = destination.deletingLastPathComponent().resolvingSymlinksInPath() + let leaf = destination.lastPathComponent + let target = parent.appendingPathComponent(leaf) + for route in NativeTargetRoute.allCases + where route.shared && route.basename.utf8.elementsEqual(leaf.utf8) { + if try matches(route, target: target, parent: parent) { return route } + } + for member in Member.allCases { + guard let probe = try? NativeTargetRoute.named(member, scope: .user, name: "probe") + else { continue } + let suffix = String(probe.basename.dropFirst("probe".count)) + guard leaf.hasSuffix(suffix) else { continue } + let container: URL + if let known = memberContainers[member] { + container = known + } else { + let authority = try probe.rootAuthority(environment, validateExistingOverride: false) + container = try authority.plannedPhysicalDirectory + memberContainers[member] = container + } + var ancestor = parent + var relativeParts = [leaf] + let containerIdentity = try? identity(at: container) + while ancestor.path != "/" { + if let containerIdentity, try identity(at: ancestor) == containerIdentity { break } + relativeParts.insert(ancestor.lastPathComponent, at: 0) + ancestor.deleteLastPathComponent() + } + let relative: String + if ancestor.path != "/" { + // Descriptor-equivalent container aliases retain the entire validated nested name. + relative = relativeParts.joined(separator: "/") + } else { + let prefix = container.path + "/" + let bytes = Array(target.path.utf8) + guard bytes.starts(with: prefix.utf8) else { continue } + relative = String(decoding: bytes.dropFirst(prefix.utf8.count), as: UTF8.self) + } + let candidate = + probe.isContainer + ? try? NativeTargetRoute.named(member, scope: .user, name: relative) + : try? NativeTargetRoute.file(member, scope: .user, relativePath: relative) + if let candidate, try matches(candidate, target: target, parent: parent) { + return candidate + } + } + return nil + } + } + static func globalLogicalDirectory(_ environment: RuntimeEnvironment) throws -> URL { + try claudeMCPLocal.logicalDirectory(environment) + } + static func globalDirectory(_ environment: RuntimeEnvironment) throws -> URL { + try globalLogicalDirectory(environment).resolvingSymlinksInPath() + } +} + +/// The configured loader boundary may be an admitted alias. Every descendant is no-follow. +struct NativeRootAuthority: Sendable { + let loader: URL + let descendants: [String] + var logicalDirectory: URL { descendants.reduce(loader) { $0.appendingPathComponent($1) } } + var plannedPhysicalDirectory: URL { + get throws { + try descendants.reduce(PathSafety.resolvedDirectoryBoundary(loader)) { + $0.appendingPathComponent($1) + } + } + } + func physicalDirectory() throws -> URL { + var result = try PathSafety.resolvedDirectoryBoundary(loader) + let ancestry = try DirectoryAccessEvidence.capture(at: result) + var opened = + ancestry.directories.count == result.pathComponents.count + ? try DirectoryHandle(at: result) : nil + for part in descendants { + result.appendPathComponent(part) + if let parent = opened, try parent.info(part) != nil { + opened = try parent.child(part) + } else { + opened = nil + } + } + return result + } +} + +/// Pathname authorization is checked separately. Neither route nor caller participates here. +struct SharedResourceIdentity: Codable, Hashable, Comparable { + let parent: FileObjectIdentity + let basename: String + + var orderingKey: String { + "\(parent.device):\(parent.inode):\(parent.kind):\(basename.utf8.count):\(basename)" + } + var directoryName: String { FileHash.sha256Hex(data: Data(orderingKey.utf8)) } + static func == (lhs: Self, rhs: Self) -> Bool { + lhs.parent == rhs.parent && lhs.basename.utf8.elementsEqual(rhs.basename.utf8) + } + func hash(into hasher: inout Hasher) { + hasher.combine(parent) + hasher.combine(Data(basename.utf8)) + } + static func < (lhs: Self, rhs: Self) -> Bool { + lhs.orderingKey.utf8.lexicographicallyPrecedes(rhs.orderingKey.utf8) + } + + func validate() throws { + guard parent.isDirectory, + !basename.isEmpty, basename != ".", basename != "..", + !basename.contains("/"), !basename.contains("\\"), !basename.contains("\0") + else { + throw CoreError.invalidState("unregistered shared transaction resource") + } + } +} + +struct SharedReservation: Codable, Equatable { + let version: Int + let resource: SharedResourceIdentity + let scope: String + let owner: String + let journal: UUID +} + +/// An opened, verified physical coordination domain. Its lock inode is never removed. +final class SharedResource { + private struct ParentValidationKey: Hashable { + let loader: Data + let descendants: [Data] + let parent: Data + let identity: FileObjectIdentity + } + + static let metadataName = ".agents-native" + let identity: SharedResourceIdentity + let route: NativeTargetRoute + let parent: DirectoryHandle + let metadata: DirectoryHandle? + let ancestry: DirectoryAccessEvidence + let metadataAccess: FileAccessEvidence? + let metadataAncestry: DirectoryAccessEvidence? + let authority: NativeRootAuthority + private let parentValidationKey: ParentValidationKey + private var lockDescriptor: Int32? + private var lockAccess: FileAccessEvidence? + + var receiptPath: String { route.metadata + "/receipt" } + + init( + store: StateStore, route: NativeTargetRoute = .claudeMCPLocal, create: Bool, + existingRoot: ExistingProjectRoot? = nil, projectRoot: DirectoryHandle? = nil, + onReadLocation: ((URL) -> Void)? = nil + ) throws { + guard route.shared else { throw CoreError.invalidState("project route has no shared resource") } + self.route = NativeTargetRoute.targetRoute(route.root)! + authority = try route.rootAuthority(store.environment) + let url = try authority.physicalDirectory() + if let existingRoot, let projectRoot, + let anchored = try existingRoot.descendant(at: url, from: projectRoot, create: create) + { + parent = anchored + } else { + parent = try DirectoryHandle(at: url, create: create) + } + ancestry = try DirectoryAccessEvidence.capture(at: url) + identity = SharedResourceIdentity(parent: try parent.objectIdentity, basename: route.basename) + parentValidationKey = ParentValidationKey( + loader: Data(authority.loader.path.utf8), + descendants: authority.descendants.map { Data($0.utf8) }, + parent: Data(parent.url.path.utf8), identity: identity.parent) + // Record the intended private domain before opening it: missing entries or invalid access + // can stop admission before a SharedResource exists. + let baseURL = parent.url.appendingPathComponent(Self.metadataName) + let metadataURL = baseURL.appendingPathComponent(identity.directoryName) + onReadLocation?(baseURL) + onReadLocation?(metadataURL) + onReadLocation?(metadataURL.appendingPathComponent("lock")) + func child(_ parent: DirectoryHandle, _ name: String) throws -> DirectoryHandle? { + if try parent.info(name) == nil { + guard create else { return nil } + return try parent.createPrivateDirectory(name) + } + let result = try parent.child(name) + _ = try FileAccessEvidence.requirePrivate(descriptor: result.descriptor) + return result + } + if let base = try child(parent, Self.metadataName) { + metadata = try child(base, identity.directoryName) + } else { + metadata = nil + } + metadataAccess = try metadata?.accessEvidence() + metadataAncestry = try metadata.map { try DirectoryAccessEvidence.capture(at: $0.url) } + } + + func bindLock(_ descriptor: Int32) throws { + guard descriptor >= 0 else { return } + lockDescriptor = descriptor + lockAccess = try FileAccessEvidence.requirePrivate(descriptor: descriptor) + try validate() + } + + func validate() throws { + try validateLock() + try validateParent() + try validateMetadata() + } + + /// Each pass revalidates the root and every domain's lock and metadata. + static func validateAll(_ resources: [SharedResource]) throws { + var parents: [ParentValidationKey: DirectoryAccessEvidence] = [:] + for resource in resources { + try resource.validateLock() + if let ancestry = parents[resource.parentValidationKey] { + guard ancestry == resource.ancestry else { + throw CoreError.invalidState("filesystem access ancestry changed during preparation") + } + } else { + try resource.validateParent() + parents[resource.parentValidationKey] = resource.ancestry + } + try resource.validateMetadataWithValidatedParent() + } + } + + private func validateLock() throws { + if let descriptor = lockDescriptor, let access = lockAccess { + guard let metadata, + try metadata.info("lock").map(FileObjectIdentity.init) == access.identity + else { + throw CoreError.invalidState("held shared coordination lock identity changed") + } + try access.validate(descriptor: descriptor) + } + } + + private func validateParent() throws { + try ancestry.validate(at: parent.url) + guard + try DirectoryHandle(at: authority.physicalDirectory()).objectIdentity + == identity.parent, + try DirectoryHandle(at: parent.url).objectIdentity == identity.parent + else { + throw CoreError.invalidState("shared target parent identity changed") + } + } + + private func validateMetadata() throws { + if let metadata { + try metadataAncestry?.validate(at: metadata.url) + let current = try DirectoryHandle(at: metadata.url) + guard try current.objectIdentity == metadata.objectIdentity else { + throw CoreError.invalidState("shared coordination directory changed") + } + _ = try FileAccessEvidence.requirePrivate(descriptor: current.descriptor) + try metadataAccess?.validate(descriptor: current.descriptor) + } + } + + private func validateMetadataWithValidatedParent() throws { + guard let metadata else { return } + let name = metadata.url.lastPathComponent + guard let metadataAccess, let directories = metadataAncestry?.directories, + ancestry.directories.count == parent.url.pathComponents.count, + directories.count == ancestry.directories.count + 2, + directories.dropLast(2).elementsEqual(ancestry.directories), + let parentAccess = ancestry.directories.last, parentAccess.identity == identity.parent, + let base = try? parent.child(Self.metadataName), + let current = try? base.child(name) + else { + try validateMetadata() + return + } + + // The pass has checked the physical prefix. Reopen both private entries + // for each resource and check the namespace edges using each child's owner. + let leafAccess = try current.accessEvidence() + let baseAccess = try FileAccessEvidence.requireNonReplaceableDirectory( + descriptor: base.descriptor, protectingOwner: leafAccess.owner) + let currentParentAccess = try FileAccessEvidence.requireNonReplaceableDirectory( + descriptor: parent.descriptor, protectingOwner: baseAccess.owner) + let currentLeafAccess = try FileAccessEvidence.requireNonReplaceableDirectory( + descriptor: current.descriptor, protectingOwner: geteuid()) + guard currentParentAccess == parentAccess, + baseAccess == directories[directories.count - 2], + leafAccess == directories.last, currentLeafAccess == leafAccess, + try parent.info(Self.metadataName).map(FileObjectIdentity.init) == baseAccess.identity, + try base.info(name).map(FileObjectIdentity.init) == leafAccess.identity + else { + throw CoreError.invalidState("filesystem access ancestry changed during preparation") + } + guard try FileAccessEvidence.requirePrivate(descriptor: current.descriptor) == metadataAccess + else { + throw CoreError.invalidState("filesystem access changed during preparation") + } + } + + func reservation() throws -> SharedReservation? { + try validate() + guard let metadata, try metadata.info("reservation") != nil else { return nil } + let access = try metadata.requirePrivateAccess("reservation") + let value: SharedReservation + do { + value = try StateStore.decode( + metadata.read("reservation", maximumBytes: 16_384), as: SharedReservation.self) + } catch let exhaustion as OpenFileLimitError { + throw exhaustion + } catch { throw CoreError.invalidState("invalid shared reservation; owner action required") } + guard value.version == 1, value.resource == identity, !value.scope.isEmpty, + !value.owner.isEmpty + else { throw CoreError.invalidState("invalid shared reservation ownership") } + _ = try metadata.requirePrivateAccess("reservation", matching: access) + return value + } + + static func temporaryName(_ journal: UUID) -> String { "reservation-\(journal.uuidString).new" } + + func inspect(journal: TransactionJournal?, scope: String) throws { + try validate() + guard let metadata else { return } + let own = journal.map { Self.temporaryName($0.id) } + for name in try metadata.names() where name.hasPrefix("reservation-") { + guard name == own, journal?.footprint.contains(identity) == true else { + throw CoreError.invalidState( + "pending shared reservation construction; owner action required") + } + // A durable intent owns the exact slot even when its bytes are incomplete. + _ = try metadata.requirePrivateAccess(name) + } + if let reservation = try reservation() { + guard reservation.scope == scope, reservation.journal == journal?.id, + journal?.footprint.contains(identity) == true + else { + throw CoreError.recoveryPending( + "Shared target requires recovery by \(reservation.owner), journal \(reservation.journal.uuidString)" + ) + } + } else if journal?.reservationsReady == true, journal?.finalized == false, + journal?.footprint.contains(identity) == true + { + throw CoreError.invalidState("ready shared transaction is missing its reservation") + } + } + + func reserve(_ journal: TransactionJournal, owner: String, checkpoint: (String) throws -> Void) + throws + { + guard let metadata, journal.footprint.contains(identity), !journal.reservationsReady else { + throw CoreError.invalidState("missing durable shared reservation intent") + } + try inspect(journal: journal, scope: journal.scope) + guard try reservation() == nil else { return } + let name = Self.temporaryName(journal.id) + guard try metadata.info(name) == nil else { + throw CoreError.invalidState("unfinished shared reservation needs recovery") + } + let file = try metadata.createPrivateFile(name) + try checkpoint("reservation.created") + let record = SharedReservation( + version: 1, resource: identity, scope: journal.scope, owner: owner, journal: journal.id) + let bytes = try StateStore.encode(record) + let middle = bytes.count / 2 + try file.write(bytes.prefix(middle)) + try checkpoint("reservation.halfWritten") + try file.write(bytes.suffix(from: middle)) + try checkpoint("reservation.written") + try metadata.move(name, to: metadata, named: "reservation", mode: .exclusive) { + try checkpoint("reservation.published") + } + try checkpoint("reservation.synced") + } + + func validateFinalized(_ journal: TransactionJournal) throws { + try validate() + guard let metadata else { throw CoreError.invalidState("shared metadata is missing") } + let name = Self.temporaryName(journal.id) + if try metadata.info(name) != nil { _ = try metadata.requirePrivateAccess(name) } + if let record = try reservation(), record.journal == journal.id, + record.scope != journal.scope + { + throw CoreError.invalidState("finalized reservation owner changed") + } + } + + /// Finalized journals may encounter a newer owner's final reservation. Never remove it. + func release(_ journal: TransactionJournal, checkpoint: (String) throws -> Void) throws { + try validate() + guard let metadata else { throw CoreError.invalidState("shared metadata is missing") } + let name = Self.temporaryName(journal.id) + if try metadata.info(name) != nil { + let access = try metadata.requirePrivateAccess(name) + try metadata.remove(name, identity: access.identity) + } + if let record = try reservation(), record.journal == journal.id { + guard record.scope == journal.scope, record.resource == identity else { + throw CoreError.invalidState("shared reservation owner changed") + } + let access = try metadata.requirePrivateAccess("reservation") + try metadata.remove("reservation", identity: access.identity) + try checkpoint("reservation.removed") + } else if !journal.finalized, journal.reservationsReady { + throw CoreError.invalidState("ready shared transaction lost its reservation") + } + try metadata.sync() + } +} + +/// Absence has no physical resource key. Only read admission may carry this evidence; +/// a writer must create and open the real parent before deriving its coordination domain. +struct AbsentSharedRoot { + let route: NativeTargetRoute + let authority: NativeRootAuthority + let physical: URL + let ancestry: DirectoryAccessEvidence + + init?(store: StateStore, route: NativeTargetRoute) throws { + authority = try route.rootAuthority(store.environment) + physical = try authority.physicalDirectory() + ancestry = try DirectoryAccessEvidence.capture(at: physical) + guard ancestry.directories.count < physical.pathComponents.count else { return nil } + self.route = route + } + + func remainsAbsent() throws -> Bool { + guard try authority.physicalDirectory().path.utf8.elementsEqual(physical.path.utf8) else { + throw CoreError.invalidState("registered native root changed during inspection") + } + let current = try DirectoryAccessEvidence.capture(at: physical) + guard current.directories.starts(with: ancestry.directories) else { + throw CoreError.invalidState("registered native ancestry changed during inspection") + } + return current.directories.count < physical.pathComponents.count + } +} + +/// Synchronous, thread-confined admission. There is no lock acquisition inside a transaction. +final class TransactionLockContext { + private static let threadKey = "agents.core.transaction-lock-context" + let scopeURL: URL + let resources: [SharedResource] + var createdAncestry: [(URL, DirectoryAccessEvidence)] = [] + let admissions: [SharedResource] + private let resourcesByIdentity: [SharedResourceIdentity: SharedResource] + private let admissionsByRoot: [String: SharedResource] + let requestedRoutes: Set + let writable: Bool + let requestedShared: Bool + let absentRoots: [AbsentSharedRoot] + let installations: [SkillInstallationTarget] + private let installationAuthorities: [SkillInstallationTarget] + var existingProjectRoot: ExistingProjectRoot? + var projectRootDirectory: DirectoryHandle? + private var scopeDirectory: DirectoryHandle? + private var scopeDescriptor: Int32? + private var scopeLockIdentity: FileObjectIdentity? + + init( + store: StateStore, resources: [SharedResource], writable: Bool, requestedShared: Bool, + absentRoots: [AbsentSharedRoot] = [], admissions: [SharedResource] = [], + requestedRoutes: Set = [], installations: [SkillInstallationTarget] = [] + ) { + scopeURL = store.directory.standardizedFileURL + self.resources = resources + self.admissions = admissions.isEmpty ? resources : admissions + resourcesByIdentity = Dictionary( + resources.map { ($0.identity, $0) }, uniquingKeysWith: { first, _ in first }) + admissionsByRoot = Dictionary( + self.admissions.map { ($0.route.root, $0) }, uniquingKeysWith: { first, _ in first }) + self.requestedRoutes = requestedRoutes + self.writable = writable + self.requestedShared = requestedShared + self.absentRoots = absentRoots + self.installations = installations + installationAuthorities = SkillInstallationTarget.distinctAuthorities(installations) + } + + static var currentForDisplay: TransactionLockContext? { + Thread.current.threadDictionary[threadKey] as? TransactionLockContext + } + + static var isHeld: Bool { Thread.current.threadDictionary[threadKey] != nil } + + static func current(_ store: StateStore) -> TransactionLockContext? { + let context = Thread.current.threadDictionary[threadKey] as? TransactionLockContext + return context?.scopeURL.path == store.directory.standardizedFileURL.path ? context : nil + } + + func run(_ body: () throws -> T) throws -> T { + guard Thread.current.threadDictionary[Self.threadKey] == nil else { + throw CoreError.invalidState("nested scope operations cannot acquire transaction locks") + } + Thread.current.threadDictionary[Self.threadKey] = self + defer { Thread.current.threadDictionary.removeObject(forKey: Self.threadKey) } + return try body() + } + + static func validateHeldScope(_ identity: String) throws { + guard let context = Thread.current.threadDictionary[threadKey] as? TransactionLockContext else { + return + } + try context.validateScope() + if let directory = context.scopeDirectory, try directory.identity != identity { + throw CoreError.invalidState("transaction belongs to another held scope") + } + } + + func bindScope(_ directory: DirectoryHandle, descriptor: Int32) throws { + var info = stat() + guard fstat(descriptor, &info) == 0, + try directory.info(".agents.lock").map(FileObjectIdentity.init) == FileObjectIdentity(info) + else { throw CoreError.invalidState("scope lock changed during admission") } + scopeDirectory = directory + scopeDescriptor = descriptor + scopeLockIdentity = FileObjectIdentity(info) + try validateScope() + } + + func validateScope() throws { + try existingProjectRoot?.validate() + for target in installationAuthorities { try target.validateAuthority() } + guard let directory = scopeDirectory else { return } + var info = stat() + guard let descriptor = scopeDescriptor, let identity = scopeLockIdentity, + fstat(descriptor, &info) == 0, FileObjectIdentity(info) == identity, + try DirectoryHandle(at: directory.url).identity == directory.identity, + try directory.info(".agents.lock").map(FileObjectIdentity.init) == identity + else { throw CoreError.invalidState("held transaction scope or lock identity changed") } + } + + func requireWriterScope() throws { + guard writable, scopeDirectory != nil else { + throw CoreError.invalidState("shared commit requires a held scope writer descriptor") + } + try validateScope() + } + + func requireHeldScope() throws { + guard scopeDirectory != nil else { + throw CoreError.invalidState("publication requires a held scope lock") + } + try validateScope() + } + + func resource(_ identity: SharedResourceIdentity? = nil) throws -> SharedResource { + try validateScope() + let resource = + if let identity { + resourcesByIdentity[identity] + } else { + resources.count == 1 ? resources.first : nil + } + guard let resource else { + throw CoreError.invalidState("shared target is outside the held request footprint") + } + try resource.validate() + return resource + } + + func resource(for route: NativeTargetRoute) throws -> SharedResource { + guard let resource = admissionsByRoot[route.root] else { + throw CoreError.invalidState("shared target is outside the held request footprint") + } + if resource !== resourcesByIdentity[resource.identity] { try resource.validate() } + return try self.resource(resource.identity) + } + + func absentRoot(for route: NativeTargetRoute) throws -> AbsentSharedRoot? { + guard !writable, let absent = absentRoots.first(where: { $0.route.root == route.root }) else { + return nil + } + guard try absent.remainsAbsent() else { throw CoordinationReadmission.required } + return absent + } + + func targetDirectory(for route: NativeTargetRoute) throws -> URL { + if let absent = try absentRoot(for: route) { return absent.physical } + return try resource(for: route).parent.url + } + + func validate(_ journal: TransactionJournal, scope: DirectoryHandle) throws { + try journal.validateCoordination() + try validateScope() + guard try scope.identity == journal.scope else { + throw CoreError.invalidState("transaction scope identity changed") + } + for identity in journal.footprint { + let resource = try resource(identity) + if !journal.finalized { try resource.inspect(journal: journal, scope: journal.scope) } + } + } +} + +private enum SharedCoordinationFrame { + case lock(FileLock.CoordinationDescriptor) + case missingMetadata(SharedResource) +} + +extension StateStore { + func requireProjectNativeAuthority(at destination: URL) throws { + if scope == .project, + try NativeTargetRoute.userRoute(at: destination, environment: environment) != nil + { + throw CoreError.unsafePath("project target coincides with a registered shared user target") + } + } + + package func nativeTarget(for route: NativeTargetRoute) throws -> MaterializationTarget { + guard route.permits(scope) else { + throw CoreError.unsafePath("project native targets require their project scope") + } + if !route.shared, route.isNamed { + let target = try route.physicalDirectory(environment).appendingPathComponent(route.basename) + _ = try coordinationRoute(for: route) + if route.isContainer { + for shared in NativeTargetRoute.allCases where shared.shared { + let parent = try shared.rootAuthority(environment, validateExistingOverride: false) + .plannedPhysicalDirectory + if parent.path.utf8.elementsEqual(target.path.utf8) + || parent.path.utf8.starts(with: (target.path + "/").utf8) + { + throw CoreError.unsafePath("registered container encloses a shared native loader") + } + } + } + } + var canonical = route + let parent: URL + let coordinated = try coordinationRoute(for: route) + if let coordinated, let context = TransactionLockContext.current(self) { + let held = try context.targetDirectory(for: coordinated) + parent = route.shared ? held : try route.physicalDirectory(environment) + if route.shared, try context.absentRoot(for: coordinated) == nil { + canonical = try context.resource(for: coordinated).route + } + } else { + parent = try route.physicalDirectory(environment) + } + if !route.shared, let context = TransactionLockContext.current(self) { + for candidate in context.requestedRoutes.filter({ !$0.shared && $0.permits(scope) }).sorted( + by: { + $0.rawValue.utf8.lexicographicallyPrecedes($1.rawValue.utf8) + }) where candidate.basename.utf8.elementsEqual(route.basename.utf8) + { + if try candidate.physicalDirectory(environment).path.utf8.elementsEqual(parent.path.utf8) { + canonical = candidate + break + } + } + } + return MaterializationTarget( + url: parent.appendingPathComponent(route.basename), + path: canonical.root + "/" + canonical.basename, scope: directory) + } + + /// Acquire the union before the scope lock, rechecking optimistic reads on unwind. + func withCoordination( + routes: Set, installations: [SkillInstallationTarget] = [], writable: Bool, + checkpoint: (String) throws -> Void = { _ in }, + existingRoot: ExistingProjectRoot? = nil, projectRoot: DirectoryHandle? = nil, + onReadLocation: ((URL) -> Void)? = nil, admitRecovery: Bool = true, + _ body: () throws -> T + ) throws -> T { + func recordAncestry(_ url: URL) { + guard let onReadLocation else { return } + var ancestor = url.standardizedFileURL + while true { + onReadLocation(ancestor) + guard ancestor.path != "/" else { return } + ancestor.deleteLastPathComponent() + } + } + try existingRoot?.validate() + if TransactionLockContext.isHeld { + throw CoreError.invalidState("nested scope lock acquisition") + } + guard routes.allSatisfy({ $0.permits(scope) }) else { + throw CoreError.unsafePath("registered native request belongs to another scope") + } + for target in SkillInstallationTarget.distinctAuthorities(installations) { + try target.validateAuthority() + } + var installationResolver = SkillInstallationTargetResolver(store: self) + for target in installations { + let current = try installationResolver.target(for: target.agent, named: target.name) + guard current.scope.path.utf8.elementsEqual(target.scope.path.utf8), + current.url.path.utf8.elementsEqual(target.url.path.utf8), + current.footprint == target.footprint + else { throw CoreError.invalidState("installation authority changed before admission") } + } + let installationRoutes = installations.reduce(into: Set()) { + $0.formUnion($1.footprint) + } + for route in routes where !route.shared && route.isNamed { _ = try nativeTarget(for: route) } + while true { + let before = try admitRecovery ? pendingCoordinationJournal(diagnosing: !writable) : nil + var resources: [SharedResource] = [] + var createdAncestry: [(URL, DirectoryAccessEvidence)] = [] + if writable { + let evidence = try DirectoryAccessEvidence.capture(at: directory) + if evidence.directories.count < directory.pathComponents.count { + createdAncestry.append((directory, evidence)) + } + } + var absentRoots: [AbsentSharedRoot] = [] + let pending = before?.footprint ?? [] + var admissions: [SharedResource] = [] + let recoveryRoutes = Set( + (before?.entries ?? []).compactMap { entry in + entry.coordinationRoot.flatMap { NativeTargetRoute.sharedRoute($0) } + ?? NativeTargetRoute.sharedRoute(entry.path) + ?? NativeTargetRoute.metadataRoute(entry.path) + }) + var requested = Set(try routes.compactMap { try coordinationRoute(for: $0) }) + requested.formUnion(installationRoutes) + let requestedShared = !requested.isEmpty + requested.formUnion(recoveryRoutes) + let ordered = requested.sorted { left, right in + let leftPending = recoveryRoutes.contains(left) + let rightPending = recoveryRoutes.contains(right) + return leftPending == rightPending ? left.rawValue < right.rawValue : leftPending + } + let physicalTargets = try ordered.map { route in + if onReadLocation != nil { + let authority = try route.rootAuthority(environment, validateExistingOverride: false) + recordAncestry(authority.loader) + recordAncestry(authority.logicalDirectory) + recordAncestry(try authority.plannedPhysicalDirectory) + } + return try route.physicalDirectory(environment).appendingPathComponent(route.basename) + } + var checkedAncestors = Set() + var routeLookup = NativeTargetRoute.UserRouteLookup(environment: environment) + for parent in physicalTargets.map({ $0.deletingLastPathComponent() }) { + var ancestor = parent + while ancestor.path != "/", checkedAncestors.insert(Data(ancestor.path.utf8)).inserted { + if let enclosing = try routeLookup.route(at: ancestor), enclosing.isContainer { + throw CoreError.unsafePath("native coordination would be inside a registered container") + } + ancestor.deleteLastPathComponent() + } + } + for (index, target) in physicalTargets.enumerated() { + for (other, nested) in physicalTargets.enumerated() where index != other { + let parent = nested.deletingLastPathComponent() + if parent.path.utf8.elementsEqual(target.path.utf8) + || parent.path.hasPrefix(target.path + "/") + { + throw CoreError.unsafePath("nested native coordination domains conflict") + } + } + } + for route in ordered { + let recovering = recoveryRoutes.contains(route) + if writable, !recovering, let absent = try AbsentSharedRoot(store: self, route: route) { + createdAncestry.append((absent.physical, absent.ancestry)) + } + if !writable, !recovering, let absent = try AbsentSharedRoot(store: self, route: route) { + absentRoots.append(absent) + continue + } + let resource: SharedResource + do { + resource = try SharedResource( + store: self, route: route, create: writable && !recovering, + existingRoot: existingRoot, projectRoot: projectRoot, + onReadLocation: onReadLocation) + } catch let exhaustion as OpenFileLimitError { + throw exhaustion + } catch { + if recovering { + throw CoreError.invalidState( + "shared recovery requires the original registered runtime context and verifiable coordination metadata" + ) + } + throw error + } + if recovering { + guard pending.contains(resource.identity), let metadata = resource.metadata, + try metadata.info("lock") != nil + else { + throw CoreError.invalidState( + "shared recovery requires the original runtime context and coordination lock") + } + } + admissions.append(resource) + if !resources.contains(where: { $0.identity == resource.identity }) { + resources.append(resource) + } + } + guard pending.allSatisfy({ identity in resources.contains { $0.identity == identity } }) + else { + throw CoreError.invalidState("shared recovery footprint has no registered runtime resource") + } + let context = TransactionLockContext( + store: self, resources: resources.sorted { $0.identity < $1.identity }, writable: writable, + requestedShared: requestedShared, absentRoots: absentRoots, + admissions: admissions, requestedRoutes: routes, installations: installations) + context.createdAncestry = createdAncestry + context.existingProjectRoot = existingRoot + context.projectRootDirectory = projectRoot + var frames: [SharedCoordinationFrame] = [] + frames.reserveCapacity(context.resources.count) + var outcome = Result { + for (index, resource) in context.resources.enumerated() { + guard let metadata = resource.metadata else { + frames.append(.missingMetadata(resource)) + continue + } + let url = metadata.url.appendingPathComponent("lock") + if writable { + if try metadata.info("lock") == nil { + _ = try metadata.createPrivateFile("lock") + } + _ = try metadata.requirePrivateAccess("lock") + } + let lock = try FileLock.acquireCoordinationDescriptor( + at: url, writable: writable, + checkpoint: { try checkpoint("shared.\(index).lock." + $0) }) + frames.append(.lock(lock)) + try resource.bindLock(lock.descriptor) + try resource.validate() + } + let result = Result { try context.run { try body() } } + for absent in absentRoots where try !absent.remainsAbsent() { + throw CoordinationReadmission.required + } + return try result.get() + } + + // An outer observation can override a success, failure or requested readmission. + while let frame = frames.popLast() { + do { + switch frame { + case .lock(let lock): + try lock.finish() + case .missingMetadata(let resource): + let current = try SharedResource( + store: self, route: resource.route, create: false, onReadLocation: onReadLocation) + if current.metadata != nil { throw CoordinationReadmission.required } + } + } catch { + outcome = .failure(error) + } + } + // The scope-lock body checks that the preflight footprint still covers the journal. + do { + return try outcome.get() + } catch CoordinationReadmission.required { continue } + } + } + + func pendingCoordinationJournal(diagnosing: Bool = false) throws -> TransactionJournal? { + guard let directory = try openDirectoryIfPresent() else { return nil } + let primary = try directory.info(TransactionJournal.fileName) != nil + let name = primary ? TransactionJournal.fileName : TransactionJournal.incompleteFileName + guard try directory.info(name) != nil else { return nil } + do { + guard let info = try directory.info(name), let limit = Int(exactly: info.st_size), limit >= 0 + else { + throw CoreError.invalidState("cannot bound pending journal generation") + } + let bytes = try directory.read(name, matching: info, maximumBytes: limit) + if !primary, (try? JSONSerialization.jsonObject(with: bytes)) == nil { return nil } + let journal = try FileTransaction.readJournal(bytes) + try journal.validateCoordination() + return journal + } catch let exhaustion as OpenFileLimitError { + throw exhaustion + } catch { + // A corrupt journal admits no data callback. The read boundary still takes the + // scope lock and routes to its pending-recovery diagnostic without writes. + if diagnosing { return nil } + throw error + } + } + + func verifyCoordinationAdmission() throws { + guard let context = TransactionLockContext.current(self) else { + throw CoreError.invalidState("missing held scope coordination context") + } + let journal = try pendingCoordinationJournal(diagnosing: !context.writable) + let held = context.resources.map(\.identity) + if let journal, !journal.footprint.allSatisfy(held.contains) { + throw CoordinationReadmission.required + } + if !context.requestedShared, journal?.footprint.isEmpty != false, !held.isEmpty { + throw CoordinationReadmission.required + } + let directory = try openDirectoryIfPresent() + if let journal, context.writable { + guard let directory else { throw CoreError.invalidState("missing transaction scope") } + try context.validate(journal, scope: directory) + } + var installationResolver = SkillInstallationTargetResolver(store: self) + for target in context.installations { + let current = try installationResolver.target(for: target.agent, named: target.name) + guard current.url.path.utf8.elementsEqual(target.url.path.utf8), + current.footprint == target.footprint + else { throw CoreError.invalidState("installation authority changed during admission") } + } + try SharedResource.validateAll(context.admissions) + for resource in context.resources { + if journal?.finalized != true && (context.writable || journal == nil) { + try resource.inspect(journal: journal, scope: directory?.identity ?? "") + } + } + } + +} + +enum CoordinationReadmission: Error { case required } + +extension Optional where Wrapped == TransactionLockContext { + func requiredResource(_ identity: SharedResourceIdentity? = nil) throws -> SharedResource { + guard let context = self else { + throw CoreError.invalidState("shared target requires a held request footprint") + } + return try context.resource(identity) + } +} + +/// Descriptor-derived physical file key. Absence deliberately has no fabricated key. +package struct NativeTargetIdentity: Hashable, Sendable { + package let device: UInt64 + package let inode: UInt64 + package let kind: UInt32 + package let basename: String + package static func == (lhs: Self, rhs: Self) -> Bool { + lhs.device == rhs.device && lhs.inode == rhs.inode && lhs.kind == rhs.kind + && lhs.basename.utf8.elementsEqual(rhs.basename.utf8) + } + package func hash(into hasher: inout Hasher) { + hasher.combine(device) + hasher.combine(inode) + hasher.combine(kind) + for byte in basename.utf8 { hasher.combine(byte) } + } +} + +extension StateStore { + package func nativeTargetIdentity(for route: NativeTargetRoute) throws -> NativeTargetIdentity? { + let target = try nativeTarget(for: route) + let parent = target.url.deletingLastPathComponent() + let evidence = try DirectoryAccessEvidence.capture(at: parent) + guard evidence.directories.count == parent.pathComponents.count else { return nil } + let descriptor = try DirectoryHandle(at: parent) + let identity = try descriptor.objectIdentity + try evidence.validate(at: parent) + return NativeTargetIdentity( + device: identity.device, inode: identity.inode, + kind: UInt32(identity.kind), basename: target.url.lastPathComponent) + } +} + +extension StateStore { + func coordinationRoute(for route: NativeTargetRoute) throws -> NativeTargetRoute? { + if route.shared { return route } + let target = try route.physicalDirectory(environment).appendingPathComponent(route.basename) + guard let shared = try NativeTargetRoute.userRoute(at: target, environment: environment) + else { return nil } + guard route.knownReaders == shared.knownReaders, route.isContainer == shared.isContainer else { + throw CoreError.unsafePath("native alias has incompatible reader or object authority") + } + return shared + } + + func materializationReceiptKey(for path: String) throws -> String { + try materializationReceiptLocation(for: path).key + } + + func materializationReceiptLocation(for path: String) throws -> (path: String, key: String) { + if let route = try TransactionPaths(store: self).coordinationRoute(for: path) { + let resource = try TransactionLockContext.current(self).requiredResourceForRoute(route) + return (resource.receiptPath, resource.route.root + "/" + resource.identity.basename) + } + return ("state/" + MaterializationReceipts.fileName, path) + } +} + +extension Optional where Wrapped == TransactionLockContext { + func requiredResourceForRoute(_ route: NativeTargetRoute) throws -> SharedResource { + guard let context = self else { + throw CoreError.invalidState("shared target requires its held footprint") + } + return try context.resource(for: route) + } +} diff --git a/Sources/AgentsCore/OrganizationPolicy.swift b/Sources/AgentsCore/OrganizationPolicy.swift new file mode 100644 index 0000000..df4232e --- /dev/null +++ b/Sources/AgentsCore/OrganizationPolicy.swift @@ -0,0 +1,207 @@ +import Foundation + +/// Organization policy is selected by the host application. A project manifest never selects it. +public enum OrganizationPolicySource: Equatable, Sendable, Encodable { + case local(URL) + case https(URL) + /// Discover from a GitHub remote already identified by the trusted caller. + case organization(gitRemote: String) + case invalidLocation +} + +public struct OrganizationPolicySelection: Equatable, Sendable, Encodable { + public let source: OrganizationPolicySource + public let required: Bool + + init(location: String) { + if location.hasPrefix("/") { + self.init(.local(URL(fileURLWithPath: location))) + } else if location.hasPrefix("github:") { + self.init(.organization(gitRemote: "https://github.com/" + location.dropFirst(7))) + } else if let url = URL(string: location), url.scheme?.lowercased() == "https" { + self.init(.https(url)) + } else { + self.init(.invalidLocation) + } + } + + public init(_ source: OrganizationPolicySource, required: Bool = true) { + self.source = source + self.required = required + } +} + +public enum OrganizationPolicyMode: String, Codable, Sendable, Comparable { + case off, warn, block + + public static func < (lhs: Self, rhs: Self) -> Bool { + let rank: [Self] = [.off, .warn, .block] + return rank.firstIndex(of: lhs)! < rank.firstIndex(of: rhs)! + } +} + +public struct OrganizationPolicyDocumentEvidence: Codable, Equatable, Sendable { + public let url: URL + public let digest: String + public let name: String? + public let version: String? + public let ageSeconds: Int? + public let stale: Bool + + package init( + url: URL, digest: String, name: String?, version: String?, ageSeconds: Int?, stale: Bool + ) { + self.url = url + self.digest = digest + self.name = name + self.version = version + self.ageSeconds = ageSeconds + self.stale = stale + } +} + +public struct OrganizationPolicyFinding: Codable, Hashable, Sendable { + public enum Subject: String, Codable, Sendable { + case policy, source, package, mcp, executable, manifest, workspace + } + + public let subject: Subject + public let identity: String + public let rule: String + public let matchedPattern: String? + public let dependencyPath: [String] + public let authority: InstallScope + public let document: URL? + public let documentDigest: String? + public let outcome: OrganizationPolicyMode + public let message: String + + package init( + subject: Subject, identity: String, rule: String, matchedPattern: String? = nil, + dependencyPath: [String] = [], authority: InstallScope, document: URL?, + documentDigest: String?, outcome: OrganizationPolicyMode, message: String + ) { + self.subject = subject + self.identity = identity + self.rule = rule + self.matchedPattern = matchedPattern + self.dependencyPath = dependencyPath + self.authority = authority + self.document = document + self.documentDigest = documentDigest + self.outcome = outcome + self.message = message + } +} + +public struct OrganizationPolicyStatus: Codable, Equatable, Sendable { + public enum Outcome: String, Codable, Sendable { case loaded, absent, unavailable } + + public let authority: InstallScope + public let outcome: Outcome + public let mode: OrganizationPolicyMode? + /// Parent first. The leaf is the last document. + public let documents: [OrganizationPolicyDocumentEvidence] + + package init( + authority: InstallScope, outcome: Outcome, mode: OrganizationPolicyMode? = nil, + documents: [OrganizationPolicyDocumentEvidence] = [] + ) { + self.authority = authority + self.outcome = outcome + self.mode = mode + self.documents = documents + } +} + +public struct OrganizationPolicyReport: Codable, Equatable, Sendable { + public let policies: [OrganizationPolicyStatus] + public let findings: [OrganizationPolicyFinding] + public var isBlocked: Bool { findings.contains { $0.outcome == .block } } + + package init(policies: [OrganizationPolicyStatus], findings: [OrganizationPolicyFinding]) { + self.policies = policies + self.findings = findings + } + + package func requireAdmission() throws { + if isBlocked { throw OrganizationPolicyFailure(report: self) } + } +} + +public struct OrganizationPolicyFailure: Error, Sendable, CustomStringConvertible { + public let report: OrganizationPolicyReport + + package init(report: OrganizationPolicyReport) { self.report = report } + + public var description: String { + report.findings.filter { $0.outcome == .block }.map { + let origin = $0.document.map { " [\($0.absoluteString)]" } ?? "" + return "\($0.authority.rawValue) organization policy \($0.rule): \($0.identity) " + + "— \($0.message)\(origin)" + }.joined(separator: "\n") + } +} + +package struct OrganizationRules: Sendable { + package enum Resolution: String, CaseIterable, Sendable { + case projectWins = "project-wins" + case policyWins = "policy-wins" + case block + } + + package enum Action: String, CaseIterable, Sendable { + case ignore, warn, deny + } + + package enum SelfDefined: String, CaseIterable, Sendable { + case allow, warn, deny + } + + package struct RequiredPackage: Sendable { + package let identity: String + package let version: SourceRequirement? + + package init(identity: String, version: SourceRequirement?) { + self.identity = identity + self.version = version + } + } + + package var name: String? + package var version: String? + package var parent: String? + package var enforcement: OrganizationPolicyMode = .warn + package var fetchFailure: OrganizationPolicyMode = .warn + package var ttl = 3600 + package var sourceAllow: [String]? + package var sourceDeny: [String] = [] + package var dependencyAllow: [String]? + package var dependencyDeny: [String] = [] + package var dependencyRequire: [RequiredPackage] = [] + package var resolution: Resolution? + package var maximumDepth: Int? + package var pinnedConstraint = false + package var marketplaceAllow: [String]? + package var mcpAllow: [String]? + package var mcpDeny: [String] = [] + package var mcpRequire: [String] = [] + package var mcpTransportAllow: [String]? + package var mcpSelfDefined: SelfDefined? + package var mcpTrustTransitive: Bool? + package var executableDenyAll = false + package var executableDeny: [String] = [] + package var executableRequire: [String] = [] + package var requiredFields: [String] = [] + package var explicitIncludes = false + package var contentTypes: [String]? + package var scriptsDenied = false + package var requireHashes = false + package var failOnDrift = false + package var unmanagedAction: Action = .ignore + package var unmanagedDirectories: [String] = [] + package var unmanagedExclude: [String] = [] + package var warnings: [String] = [] + + package init() {} +} diff --git a/Sources/AgentsCore/OrganizationPolicyEvaluation.swift b/Sources/AgentsCore/OrganizationPolicyEvaluation.swift new file mode 100644 index 0000000..69e1fa9 --- /dev/null +++ b/Sources/AgentsCore/OrganizationPolicyEvaluation.swift @@ -0,0 +1,521 @@ +import Foundation + +#if canImport(Darwin) + import Darwin +#else + import Glibc +#endif + +package struct OrganizationPolicyLayer: Sendable { + package let rules: OrganizationRules + package let evidence: OrganizationPolicyDocumentEvidence + + package init(rules: OrganizationRules, evidence: OrganizationPolicyDocumentEvidence) { + self.rules = rules + self.evidence = evidence + } +} + +package struct OrganizationPolicyChain: Sendable { + package let scope: InstallScope + package let layers: [OrganizationPolicyLayer] + package var mode: OrganizationPolicyMode { layers.map(\.rules.enforcement).max() ?? .off } + + package init(scope: InstallScope, layers: [OrganizationPolicyLayer]) { + self.scope = scope + self.layers = layers + } + + var resolution: OrganizationRules.Resolution { + let order: [OrganizationRules.Resolution] = [.block, .policyWins, .projectWins] + return order.first { value in layers.contains { $0.rules.resolution == value } } ?? .projectWins + } +} + +package struct OrganizationPolicyIdentity: Equatable, Sendable { + package let origin: SourceOrigin + package let suffix: String? + package let root: String? + let spelling: String + + package init(_ origin: SourceOrigin, suffix: String? = nil, root: String? = nil) { + self.origin = origin + self.suffix = suffix + self.root = root + let location: String + switch origin.kind { + case .git: + location = (origin.identity ?? "missing").components(separatedBy: "://").last! + case .http: + location = (origin.identity ?? "missing").components(separatedBy: "://").last! + case .local: + location = origin.identity.map { "local:" + $0 } ?? "local" + case .inline: location = "inline" + case .missing: location = "missing" + } + let subpath = root.flatMap { $0 == "." ? nil : $0 }.map { "/" + $0 } ?? "" + let member = suffix.map { origin.kind == .inline ? "/" + $0 : "#" + $0 } ?? "" + spelling = location + subpath + member + } + + package init(_ node: MarketplaceNodeID) { + self.init(node.catalog.origin, suffix: node.package, root: node.catalog.policyPath) + } + + private init(spelling: String) { + origin = .local + suffix = nil + root = nil + self.spelling = spelling + } + + package static func localBundle(_ name: String) -> Self { .init(spelling: "_local/" + name) } + package var description: String { spelling } + package var hasKnownOrigin: Bool { origin != .missing } + + package func matches(_ raw: String, exact: Bool = false, deny: Bool = false) -> Bool { + if origin.kind == .local && raw == "local" { return !exact } + var value = spelling + var pattern = raw + if origin.kind == .git || origin.kind == .http { + pattern = raw.components(separatedBy: "://").last! + let first = pattern.prefix(while: { $0 != "/" && $0 != "#" }) + let qualified = first.contains(".") || first.contains(":") + let authority = value.prefix(while: { $0 != "/" && $0 != "#" }) + let host = + authority.first == "[" + ? authority.split(separator: "]")[0] + "]" + : Substring(authority.split(separator: ":").first ?? authority) + if deny { + if host != authority { value = String(host) + value.dropFirst(authority.count) } + if qualified, let colon = first.lastIndex(of: ":"), + first[first.index(after: colon)...].allSatisfy(\.isNumber) + { + pattern = String(first[.. [OrganizationPolicyFinding] + ) -> [OrganizationPolicyFinding] { + chains.flatMap { chain -> [OrganizationPolicyFinding] in + guard chain.mode != .off else { return [] } + return chain.layers.flatMap { layer in + build(layer.rules, Rules(chain: chain, layer: layer)) + } + } + } + + package struct Rules { + package let chain: OrganizationPolicyChain + let layer: OrganizationPolicyLayer + + package func finding( + _ subject: OrganizationPolicyFinding.Subject, _ identity: String, _ rule: String, + _ message: String, pattern: String? = nil, path: [String] = [], advisory: Bool = false + ) -> OrganizationPolicyFinding { + .init( + subject: subject, identity: identity, rule: rule, matchedPattern: pattern, + dependencyPath: path, authority: chain.scope, document: layer.evidence.url, + documentDigest: layer.evidence.digest, outcome: advisory ? .warn : chain.mode, + message: message) + } + + func admission( + _ identity: OrganizationPolicyIdentity, subject: OrganizationPolicyFinding.Subject, + allow: [String]?, deny: [String], path: [String] + ) -> [OrganizationPolicyFinding] { + if let pattern = deny.first(where: { identity.matches($0, deny: true) }) { + return [ + finding( + subject, identity.description, "\(subject.rawValue)-deny", + "Matches a denied identity.", pattern: pattern, path: path) + ] + } + if !identity.hasKnownOrigin && (allow != nil || !deny.isEmpty) { + return [ + finding( + subject, identity.description, "\(subject.rawValue)-unknown", + "Origin is unavailable to verify the admission rule.", path: path) + ] + } + if let allow, !allow.contains(where: { identity.matches($0) }) { + return [ + finding( + subject, identity.description, "\(subject.rawValue)-allow", + "Does not match the document’s allow list.", path: path) + ] + } + return [] + } + } + + package func artifactOriginCheck( + _ admit: @escaping @Sendable ([OrganizationPolicyFinding]) throws -> Void + ) -> (@Sendable (SourceOrigin) throws -> Void)? { + guard blocksUnknownHTTPOrigins else { return nil } + return { origin in try admit(source(origin)) } + } + + package func directSource( + _ origin: SourceOrigin, root: String?, requirement: SourceRequirement?, reference: String + ) -> [OrganizationPolicyFinding] { + let identity = OrganizationPolicyIdentity(origin, root: root) + let path = [reference] + var result = source(origin, root: root, path: path) + packageIdentity(identity, path: path) + if origin.kind == .git { + let name = identity.description.split(separator: "/").last.map(String.init) ?? reference + result += pinned(requirement, identity: identity, name: name, path: path) + } + return result + } + + package func source( + _ origin: SourceOrigin, root: String? = nil, path: [String] = [] + ) -> [OrganizationPolicyFinding] { + let identity = OrganizationPolicyIdentity(origin, root: root) + return findings { rules, context in + context.admission( + identity, subject: .source, allow: rules.sourceAllow, deny: rules.sourceDeny, path: path) + } + } + + package func packageIdentity( + _ identity: OrganizationPolicyIdentity, catalog: OrganizationPolicyIdentity? = nil, + path: [String] = [], requireAllow: Bool = true + ) -> [OrganizationPolicyFinding] { + let packageFindings = findings { rules, context in + context.admission( + identity, subject: .package, allow: requireAllow ? rules.dependencyAllow : nil, + deny: rules.dependencyDeny, path: path) + } + return packageFindings + (catalog.map { catalogAdmission($0, for: identity, path: path) } ?? []) + } + + package func catalogAdmission( + _ catalog: OrganizationPolicyIdentity, for package: OrganizationPolicyIdentity? = nil, + path: [String] = [] + ) -> [OrganizationPolicyFinding] { + findings { rules, context in + var results: [OrganizationPolicyFinding] = [] + if let allow = rules.marketplaceAllow, !allow.contains(where: { catalog.matches($0) }) { + results.append( + context.finding( + package == nil ? .source : .package, (package ?? catalog).description, + "marketplace-allow", + "Catalog does not match the document’s allow list.", path: path)) + } + return results + + context.admission( + catalog, subject: .source, allow: rules.sourceAllow, deny: rules.sourceDeny, path: path) + } + } + + package func marketplace( + _ id: MarketplaceNodeID, path: [String] = [] + ) -> [OrganizationPolicyFinding] { + packageIdentity( + .init(id), catalog: .init(id.catalog.origin, root: id.catalog.policyPath), path: path) + } + + package func recordedBundlePackage( + _ source: PortableSourceEvidence, path: [String] + ) -> [OrganizationPolicyFinding] { + guard let name = source.packageName else { return [] } + let origin = source.policyOrigin + let identity = + origin == .local + ? OrganizationPolicyIdentity.localBundle(name) + : .init(origin, suffix: name, root: source.root) + var findings = packageIdentity( + identity, catalog: .init(origin, root: source.root), path: path) + if origin.kind == .local, origin.identity != nil { + findings += packageIdentity(.localBundle(name), path: path, requireAllow: false) + } + return findings + } + + package func depth(_ depth: Int, path: [String]) -> [OrganizationPolicyFinding] { + findings { rules, context in + guard let limit = rules.maximumDepth, depth > limit else { return [] } + return [ + context.finding( + .package, path.last ?? "dependency graph", "dependency-depth", + "Dependency depth \(depth) exceeds \(limit).", path: path) + ] + } + } + + package func pinned( + _ requirement: SourceRequirement?, identity: OrganizationPolicyIdentity, name: String, + path: [String] = [] + ) -> [OrganizationPolicyFinding] { + if let requirement, requirement.isPolicyBounded(packageName: name) { return [] } + return findings { rules, context in + guard rules.pinnedConstraint else { return [] } + return [ + context.finding( + .package, identity.description, "dependency-pinned-constraint", + "The authored constraint does not bound the selected version.", path: path) + ] + } + } + + package func mcp( + _ identity: OrganizationPolicyIdentity, transport: String?, selfDefined: Bool, + transitive: Bool, path: [String] = [], legacyRegistry: Bool = false + ) -> [OrganizationPolicyFinding] { + findings { rules, context in + var results = context.admission( + identity, subject: .mcp, allow: rules.mcpAllow, deny: rules.mcpDeny, path: path) + if transitive, rules.mcpTrustTransitive == false, + !(rules.mcpAllow?.contains(where: { identity.matches($0) }) ?? false) + { + results.append( + context.finding( + .mcp, identity.description, "mcp-transitive", + "Transitive server needs an explicit allow rule.", path: path)) + } + if let allowed = rules.mcpTransportAllow, !(transport.map(allowed.contains) ?? false) { + results.append( + context.finding( + .mcp, identity.description, "mcp-transport", + transport.map { "Transport \($0) is outside the allow list." } + ?? "Effective transport is unavailable.", path: path)) + } + if legacyRegistry, + rules.mcpAllow?.contains(where: { identity.matches($0) }) == true + || rules.mcpRequire.contains(where: { identity.matches($0, exact: true) }) + || rules.mcpSelfDefined == .deny + { + results.append( + context.finding( + .mcp, identity.description, "mcp-registry-evidence", + MCPRegistryEvidence.reselectionMessage, path: path)) + } else if selfDefined || legacyRegistry, let action = rules.mcpSelfDefined, action != .allow { + results.append( + context.finding( + .mcp, identity.description, "mcp-self-defined", + legacyRegistry ? MCPRegistryEvidence.reselectionMessage : "The server is self-defined.", + path: path, advisory: action == .warn)) + } + return results + } + } + + package func unverifiedMCP( + in identity: OrganizationPolicyIdentity, component: String + ) -> [OrganizationPolicyFinding] { + findings { rules, context in + guard + rules.mcpAllow != nil || !rules.mcpDeny.isEmpty || rules.mcpTransportAllow != nil + || rules.mcpTrustTransitive == false || rules.mcpSelfDefined == .deny + else { return [] } + return [ + context.finding( + .mcp, identity.description, "mcp-opaque", + "The lock cannot verify servers within native plugin \(component).") + ] + } + } + + package func executable( + _ identity: OrganizationPolicyIdentity, name: String, unknown: Bool = false, + legacyRegistry: Bool = false + ) -> [OrganizationPolicyFinding] { + findings { rules, context in + let match = rules.executableDeny.first { identity.matches($0, deny: true) } + let unknownOrigin = !identity.hasKnownOrigin && !rules.executableDeny.isEmpty + guard rules.executableDenyAll || match != nil || unknownOrigin else { return [] } + return [ + context.finding( + .executable, identity.description, "executables-deny", + legacyRegistry + ? MCPRegistryEvidence.reselectionMessage + : unknown || unknownOrigin + ? "Executable contents or origin of \(name) cannot be verified." + : "Executable deployment of \(name) exceeds the organization ceiling.", + pattern: match) + ] + } + } + + /// A policy override narrows catalog candidates. A preview and locked audit retain the + /// authored constraint and use the same comparison to detect a conflict. + package func version( + _ version: String?, identity: OrganizationPolicyIdentity, authored: [SourceRequirement], + available: Bool = true, path: [String] = [] + ) -> [OrganizationPolicyFinding] { + findings { rules, context in + guard context.chain.resolution != .projectWins || authored.isEmpty else { return [] } + return rules.dependencyRequire.compactMap { requirement in + guard identity.matches(requirement.identity, exact: true), + let constraint = requirement.version, + !available || !(version.map(constraint.admitsMarketplaceVersion) ?? false) + else { return nil } + return context.finding( + .package, identity.description, "dependency-required-version", + available + ? "Selected version must satisfy \(constraint.marketplaceDescription)." + : "No eligible version satisfies \(constraint.marketplaceDescription).", + pattern: requirement.identity, path: path) + } + } + } + + package func marketplaceRequirements( + for id: MarketplaceNodeID + ) -> (constraints: [SourceRequirement], overrides: Bool) { + requirements(for: .init(id)) + } + + package func requirements( + for identity: OrganizationPolicyIdentity + ) -> (constraints: [SourceRequirement], overrides: Bool) { + var constraints: [SourceRequirement] = [] + var overrides = false + var forbidsOverride = false + for chain in chains where chain.mode == .block && chain.resolution != .projectWins { + let matches = chain.layers.flatMap(\.rules.dependencyRequire).compactMap { + identity.matches($0.identity, exact: true) ? $0.version : nil + } + if !matches.isEmpty { + constraints += matches.filter { !constraints.contains($0) } + overrides = overrides || chain.resolution == .policyWins + forbidsOverride = forbidsOverride || chain.resolution == .block + } + } + return (constraints, overrides && !forbidsOverride) + } + + package static func glob(_ pattern: String, matches value: String) -> Bool { + let rule = pattern.split(separator: "/", omittingEmptySubsequences: false) + let path = value.split(separator: "/", omittingEmptySubsequences: false) + var ends: Set = [0] + for segment in rule { + if segment == "**" { + guard let first = ends.min() else { return false } + ends = Set(first...path.count) + } else { + ends = Set( + ends.compactMap { index in + guard index < path.count, fnmatch(String(segment), String(path[index]), 0) == 0 + else { return nil } + return index + 1 + }) + } + if ends.isEmpty { return false } + } + return ends.contains(path.count) + } +} + +extension SourceRequirement { + fileprivate func isPolicyBounded(packageName: String) -> Bool { + switch self { + case .branch: return false + case .revision(let raw): + if SourceCache.isObjectID(raw) || SemanticVersion(raw) != nil { return true } + let tag = raw.hasPrefix("refs/tags/") ? String(raw.dropFirst(10)) : raw + if SemanticVersion(tag) != nil { return true } + for prefix in [packageName + "-v", packageName + "--v"] where tag.hasPrefix(prefix) { + if SemanticVersion(String(tag.dropFirst(prefix.count))) != nil { return true } + } + guard let separator = tag.lastIndex(of: "@"), separator != tag.startIndex else { + return false + } + let name = tag[.. 1 + && !segments[1].isEmpty) + && !name.dropFirst().contains("@") + && SemanticVersion(String(tag[tag.index(after: separator)...])) != nil + default: + return (try? validate()) != nil + } + } +} + +extension MCPTransportDeclaration { + package var organizationPolicyName: String { + switch self { + case .stdio: "stdio" + case .streamableHTTP: "streamable-http" + case .sse: "sse" + } + } +} + +extension MCPRegistryEvidence { + package var organizationPolicyIdentity: OrganizationPolicyIdentity { + let location = URLComponents(string: registry)?.path + let root = location.map { $0.trimmingCharacters(in: CharacterSet(charactersIn: "/")) } + return .init( + (try? .http(registry)) ?? .missing, suffix: server, root: root?.isEmpty == false ? root : nil) + } +} diff --git a/Sources/AgentsCore/OwnedDuplexProcess.swift b/Sources/AgentsCore/OwnedDuplexProcess.swift new file mode 100644 index 0000000..9156ebd --- /dev/null +++ b/Sources/AgentsCore/OwnedDuplexProcess.swift @@ -0,0 +1,255 @@ +import CPlatform +import Foundation + +package struct DuplexProcessConfiguration: Sendable { + package var executable: String + package var arguments: [String] + package var directory: URL + package var environment: [String: String] + + package init( + executable: String, arguments: [String], directory: URL, environment: [String: String] + ) { + self.executable = executable + self.arguments = arguments + self.directory = directory + self.environment = environment + } +} + +package enum DuplexProcessError: Error, Sendable { + case invalidInput + case launchFailed + case ioFailed +} + +package enum DuplexRead: Sendable { + case bytes(Data) + case wouldBlock + case end +} + +/// Owns the child's wait status exclusively until group cleanup and reap finish. +/// The unreaped leader reserves its PID/PGID; no group signal is sent after reap +/// or ECHILD. Every descriptor access is locked and every I/O syscall nonblocking. +package final class OwnedDuplexProcess: @unchecked Sendable { + private let lock = NSLock() + private var descriptors: [Int32] + private var owned = true + private var reaped = false + private var waitStatus: Int32? + package let identifier: Int32 + package let resolvedExecutable: String + + package init( + _ configuration: DuplexProcessConfiguration, workingDirectory: DirectoryHandle? = nil + ) throws { + func valid(_ value: String) -> Bool { !value.utf8.contains(0) } + guard valid(configuration.executable), !configuration.executable.isEmpty, + valid(configuration.directory.path), configuration.arguments.allSatisfy(valid), + configuration.environment.allSatisfy({ + !$0.key.isEmpty && !$0.key.contains("=") && valid($0.key) && valid($0.value) + }) + else { throw DuplexProcessError.invalidInput } + var isDirectory: ObjCBool = false + guard configuration.directory.isFileURL, + workingDirectory != nil + || (FileManager.default.fileExists( + atPath: configuration.directory.path, isDirectory: &isDirectory) + && isDirectory.boolValue) + else { throw DuplexProcessError.invalidInput } + let executable: String + if configuration.executable.contains("/") { + executable = + configuration.executable.hasPrefix("/") + ? configuration.executable + : configuration.directory.appendingPathComponent(configuration.executable).path + } else { + guard let path = configuration.environment["PATH"] else { + throw DuplexProcessError.invalidInput + } + guard configuration.executable.utf8.count <= Int(NAME_MAX) else { + throw DuplexProcessError.invalidInput + } + let candidates = path.split(separator: ":", omittingEmptySubsequences: false).lazy.map { + entry in + let path = String(entry) + let base = + path.hasPrefix("/") + ? URL(fileURLWithPath: path, isDirectory: true) + : configuration.directory.appendingPathComponent(path, isDirectory: true) + return base.appendingPathComponent(configuration.executable).standardizedFileURL.path + } + guard + let found = candidates.first(where: { + var directory: ObjCBool = false + return FileManager.default.fileExists(atPath: $0, isDirectory: &directory) + && !directory.boolValue && access($0, X_OK) == 0 + }) + else { + throw DuplexProcessError.launchFailed + } + executable = found + } + guard executable.utf8.count <= Int(PATH_MAX) else { throw DuplexProcessError.invalidInput } + resolvedExecutable = executable + let arguments = ([executable] + configuration.arguments).map { strdup($0) } + [nil] + let environment = + configuration.environment.sorted(by: { $0.key < $1.key }).map { + strdup($0.key + "=" + $0.value) + } + [nil] + defer { for pointer in arguments + environment { free(pointer) } } + var pid: pid_t = 0 + var fds: [Int32] = [-1, -1, -1] + let result = withExtendedLifetime(workingDirectory) { + platform_duplex_spawn( + &pid, executable, arguments, environment, configuration.directory.path, + workingDirectory?.descriptor ?? -1, &fds) + } + guard result == 0 else { throw DuplexProcessError.launchFailed } + identifier = pid + descriptors = fds + } + + package func readStandardOutput() throws -> DuplexRead { try read(1) } + package func readStandardError() throws -> DuplexRead { try read(2) } + + private func read(_ index: Int) throws -> DuplexRead { + try lock.withLock { + let fd = descriptors[index] + guard fd >= 0 else { return .end } + var bytes = [UInt8](repeating: 0, count: 4096) + let count = bytes.withUnsafeMutableBytes { buffer in + CPlatform.read(fd, buffer.baseAddress, buffer.count) + } + if count > 0 { return .bytes(Data(bytes.prefix(count))) } + if count == 0 { + close(fd) + descriptors[index] = -1 + return .end + } + if errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR { return .wouldBlock } + throw DuplexProcessError.ioFailed + } + } + + package func write(_ bytes: Data, offset: Int) throws -> Int { + try lock.withLock { + guard offset >= 0 && offset <= bytes.count else { throw DuplexProcessError.invalidInput } + if offset == bytes.count { return 0 } + guard descriptors[0] >= 0 else { throw DuplexProcessError.ioFailed } + let count = bytes.withUnsafeBytes { buffer in + platform_duplex_write( + descriptors[0], buffer.baseAddress!.advanced(by: offset), bytes.count - offset) + } + if count >= 0 { return count } + if errno == EAGAIN || errno == EWOULDBLOCK { return 0 } + throw DuplexProcessError.ioFailed + } + } + + package func closeInput() { + lock.withLock { + if descriptors[0] >= 0 { + close(descriptors[0]) + descriptors[0] = -1 + } + } + } + + package func closeOutput() { + lock.withLock { + for index in 1...2 where descriptors[index] >= 0 { + close(descriptors[index]) + descriptors[index] = -1 + } + } + } + + private func signalGroup(_ signal: Int32) -> Bool { + lock.withLock { + guard owned && !reaped else { return false } + var exited = false + guard platform_duplex_observe(identifier, &exited) == 0 else { + owned = false + return false + } + return platform_duplex_signal(identifier, signal) == 0 + } + } + + private func reapIfExited(requireQuiescence: Bool = true) -> Bool { + lock.withLock { + if reaped { return true } + guard owned else { return false } + var exited = false + guard platform_duplex_observe(identifier, &exited) == 0 else { + owned = false + return false + } + guard exited else { return false } + if requireQuiescence { + var quiescent = false + guard platform_duplex_group_quiescent(identifier, &quiescent) == 0, quiescent else { + return false + } + } + var status: Int32 = 0 + let result = waitpid(identifier, &status, WNOHANG) + if result == identifier { + reaped = true + waitStatus = status + owned = false + return true + } + if result < 0 && errno != EINTR { owned = false } + return false + } + } + + package enum Exit: Sendable { + case status(Int32) + case signal(Int32) + } + + /// Natural completion is reported only after the owned process group is quiescent. + package func exitIfFinished() -> Exit? { + guard reapIfExited(), let status = lock.withLock({ waitStatus }) else { return nil } + let signal = status & 0x7f + return signal == 0 ? .status((status >> 8) & 0xff) : .signal(signal) + } + + /// Cleanup has its own finite grace/TERM/KILL budgets in addition to the + /// protocol deadline. Keep the leader's identity reserved until no live group + /// members remain or the cleanup deadline fails. False means the + /// kernel did not confirm cleanup; callers must not report complete success. + package func finish(grace: Duration, terminate: Duration, killWait: Duration) async -> Bool { + closeInput() + try? await Task.sleep(for: grace) + let term = signalGroup(SIGTERM) + try? await Task.sleep(for: terminate) + let killed = signalGroup(SIGKILL) + closeOutput() + let deadline = ContinuousClock.now + killWait + repeat { + if reapIfExited() { return ContinuousClock.now <= deadline && term && killed } + try? await Task.sleep(for: .milliseconds(2)) + } while ContinuousClock.now < deadline + // No further group signals follow release of the reserved identity. + _ = reapIfExited(requireQuiescence: false) + return false + } + + deinit { + // Exceptional abandoned ownership must never turn into an unbounded wait. + for fd in descriptors where fd >= 0 { close(fd) } + if owned && !reaped { + var exited = false + if platform_duplex_observe(identifier, &exited) == 0 { + _ = platform_duplex_signal(identifier, SIGKILL) + var status: Int32 = 0 + _ = waitpid(identifier, &status, WNOHANG) + } + } + } +} diff --git a/Sources/AgentsCore/PackageSourceHTTP.swift b/Sources/AgentsCore/PackageSourceHTTP.swift new file mode 100644 index 0000000..f37ec30 --- /dev/null +++ b/Sources/AgentsCore/PackageSourceHTTP.swift @@ -0,0 +1,133 @@ +import Foundation +import Synchronization + +#if canImport(FoundationNetworking) + import FoundationNetworking +#endif + +/// Bounded HTTPS transfer with one effective request and no credential storage. +package enum PackageSourceHTTP { + package struct Response: Sendable { + let status: Int + let body: Data + + package init(status: Int, body: Data) { + self.status = status + self.body = body + } + } + + // Tests supply a local transport without modifying URLSession or OS trust. + @TaskLocal package static var fixture: (@Sendable (URLRequest, Int?) throws -> Response)? + + static func read(_ request: URLRequest, maximumBytes: Int?) throws -> Response { + guard let url = request.url else { throw SourceAccessError.requestFailed } + _ = try SourceURL.https(url) + if let fixture { + let response = try fixture(request, maximumBytes) + if let maximumBytes, response.body.count > maximumBytes { + throw SourceAccessError.requestFailed + } + return response + } + + let configuration = URLSessionConfiguration.ephemeral + configuration.urlCredentialStorage = nil + configuration.httpCookieStorage = nil + configuration.httpShouldSetCookies = false + configuration.urlCache = nil + configuration.requestCachePolicy = .reloadIgnoringLocalCacheData + configuration.timeoutIntervalForRequest = 30 + configuration.timeoutIntervalForResource = 90 + + var request = request + request.httpShouldHandleCookies = false + request.setValue("identity", forHTTPHeaderField: "Accept-Encoding") + let delegate = Transfer(maximumBytes: maximumBytes) + let session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: nil) + defer { session.invalidateAndCancel() } + session.dataTask(with: request).resume() + guard delegate.finished.wait(timeout: .now() + 95) == .success else { + throw SourceAccessError.requestFailed + } + return try delegate.response() + } + + private final class Transfer: NSObject, URLSessionDataDelegate, Sendable { + struct State { + var status: Int? + var body = Data() + var failed = false + } + + let finished = DispatchSemaphore(value: 0) + let maximumBytes: Int? + let state = Mutex(State()) + + init(maximumBytes: Int?) { self.maximumBytes = maximumBytes } + + func urlSession( + _ session: URLSession, task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest, completionHandler: @escaping @Sendable (URLRequest?) -> Void + ) { + completionHandler(nil) + } + + func urlSession( + _ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, + completionHandler: + @escaping @Sendable (URLSession.AuthChallengeDisposition, URLCredential?) + -> Void + ) { + // Foundation still performs its standard TLS certificate checks. + let serverTrust = + challenge.protectionSpace.authenticationMethod == "NSURLAuthenticationMethodServerTrust" + completionHandler(serverTrust ? .performDefaultHandling : .rejectProtectionSpace, nil) + } + + func urlSession( + _ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, + completionHandler: @escaping @Sendable (URLSession.ResponseDisposition) -> Void + ) { + let status = (response as? HTTPURLResponse)?.statusCode + let readBody = status == 200 && maximumBytes != nil + state.withLock { + $0.status = status + if let maximumBytes, readBody, response.expectedContentLength > maximumBytes { + $0.failed = true + } + } + completionHandler(readBody && !state.withLock({ $0.failed }) ? .allow : .cancel) + } + + func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + let accepted = state.withLock { + guard !$0.failed, let maximumBytes, data.count <= maximumBytes - $0.body.count else { + $0.failed = true + return false + } + $0.body.append(data) + return true + } + if !accepted { dataTask.cancel() } + } + + func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) + { + state.withLock { + if $0.status == nil || ($0.status == 200 && maximumBytes != nil && error != nil) { + $0.failed = true + } + } + finished.signal() + } + + func response() throws -> Response { + try state.withLock { + guard !$0.failed, let status = $0.status else { throw SourceAccessError.requestFailed } + return Response(status: status, body: $0.body) + } + } + } +} diff --git a/Sources/AgentsCore/PathSafety.swift b/Sources/AgentsCore/PathSafety.swift index 2ac30e7..cd9a4ab 100644 --- a/Sources/AgentsCore/PathSafety.swift +++ b/Sources/AgentsCore/PathSafety.swift @@ -38,6 +38,26 @@ public enum PathSafety { return target } + /// A managed link may name the authored location or the physical location emitted at + /// installation. Relative destinations are interpreted from the link's physical parent. + package static func matchesSymbolicLink(at link: URL, destination: URL) -> Bool { + guard let spelling = try? FileManager.default.destinationOfSymbolicLink(atPath: link.path) + else { return false } + let parent = link.deletingLastPathComponent().resolvingSymlinksInPath() + let observed = URL(fileURLWithPath: spelling, relativeTo: parent).standardizedFileURL.path + let authored = destination.standardizedFileURL.path + let physical = destination.resolvingSymlinksInPath().path + guard + observed.utf8.elementsEqual(authored.utf8) + || observed.utf8.elementsEqual(physical.utf8) + else { return false } + // Normalizing ".." in the spelling alone can hide an intermediate directory link. + if let expected = realPath(destination.path) { + return realPath(link.path).map { $0.utf8.elementsEqual(expected.utf8) } ?? false + } + return realPath(link.path) == nil + } + /// Whether the symbolic link at `link` stays inside the real directory `root` wherever that /// tree is placed. Its destination is resolved from the link's directory as the kernel does, /// byte by byte and following links inside `root`. An absolute destination, a step above `root` @@ -122,3 +142,24 @@ public enum PathSafety { return components.isEmpty ? "." : components.joined(separator: "/") } } + +extension PathSafety { + /// Resolve the configured loader boundary's existing prefix; missing suffixes carry no identity. + static func resolvedDirectoryBoundary(_ directory: URL) throws -> URL { + var prefix = directory.standardizedFileURL + var suffix: [String] = [] + while true { + if let physical = realPath(prefix.path) { + return suffix.reduce(URL(fileURLWithPath: physical).resolvingSymlinksInPath()) { + $0.appendingPathComponent($1) + } + } + var info = stat() + guard lstat(prefix.path, &info) != 0, errno == ENOENT, prefix.path != "/" else { + throw CoreError.unsafePath("cannot resolve registered loader boundary") + } + suffix.insert(prefix.lastPathComponent, at: 0) + prefix.deleteLastPathComponent() + } + } +} diff --git a/Sources/AgentsCore/PortableSourceEvidence.swift b/Sources/AgentsCore/PortableSourceEvidence.swift new file mode 100644 index 0000000..f7e1846 --- /dev/null +++ b/Sources/AgentsCore/PortableSourceEvidence.swift @@ -0,0 +1,112 @@ +import Foundation + +/// Producer claims sealed by the archive. Local producer paths are omitted. A catalog +/// acquisition may provide the policy identity of a real local catalog directory. +public struct PortableSourceEvidence: Codable, Equatable, Hashable, Sendable { + public let kind: SourceKind + public let identity: String? + public let revision: String + public let version: String? + + /// Captures a catalog or artifact origin, or the transport of a source with a + /// policy identity that cannot be recovered from its scheme-neutral identity. + public let origin: SourceOrigin? + /// Present for an exact marketplace release contributing to the portable closure. + public let packageName: String? + public let root: String? + + package init( + kind: SourceKind, identity: String?, revision: String, version: String?, + origin: SourceOrigin? = nil, packageName: String? = nil, root: String? = nil + ) { + self.kind = kind + self.identity = identity + self.revision = revision + self.version = version + self.origin = origin + self.packageName = packageName + self.root = root + } + + package init( + origin: SourceOrigin, revision: String, version: String? = nil, + packageName: String? = nil, root: String? = nil + ) throws { + let kind: SourceKind + switch origin.kind { + case .git: kind = .git + case .http: kind = .wellKnown + case .local, .missing, .inline: kind = .local + } + let identity: String? + if packageName != nil, origin.kind == .http, let root, let authority = origin.identity { + identity = try HostedMarketplaceLocation(authority + "/" + root).url.absoluteString + } else { + identity = try origin.policyLocator.flatMap { + kind == .local ? nil : try SourceDeclaration(kind: kind, location: $0).transportIdentity() + } + } + self.init( + kind: kind, identity: identity, revision: revision, version: version, origin: origin, + packageName: packageName, root: root) + } + + package var policyOrigin: SourceOrigin { + if let origin { return origin } + guard let identity else { return .missing } + switch kind { + case .git: return .missing + case .wellKnown: return (try? .http(identity)) ?? .missing + case .local: return .missing + } + } + + package func validate() throws { + guard !revision.isEmpty, revision.utf8.count <= 256, !revision.utf8.contains(0), + !revision.utf8.contains(47), !revision.utf8.contains(92), + version.map({ !$0.isEmpty && $0.utf8.count <= 256 && !$0.utf8.contains(0) }) ?? true + else { throw CoreError.invalidSource("invalid bundle source revision") } + if let root { + guard root != ".", try PathSafety.sanitizeSubpath(root) == root else { + throw CoreError.invalidSource("invalid portable source root") + } + } + if let packageName, let version { + _ = try MarketplaceCoordinate(package: packageName, version: version) + try StateValidation.digest(revision) + switch origin?.kind { + case .git, .local: break + case .http: + guard let identity, let root else { + throw CoreError.invalidSource("missing portable hosted catalog path") + } + let hosted = try HostedMarketplaceLocation(identity) + guard hosted.url.absoluteString == identity, hosted.origin == origin, + hosted.policyPath == root + else { throw CoreError.invalidSource("invalid portable hosted catalog identity") } + default: throw CoreError.invalidSource("invalid portable package origin") + } + } else if packageName != nil { + throw CoreError.invalidSource("incomplete portable package coordinates") + } + switch kind { + case .local: + guard identity == nil, + origin.map({ [.missing, .local, .inline].contains($0.kind) }) ?? true + else { + throw CoreError.invalidSource("nonportable local source identity") + } + case .git: + guard origin.map({ $0.kind == .git }) ?? true, + let identity, !identity.contains("@"), !identity.contains("://"), + !identity.contains("?"), !identity.contains("#"), + try SourceDeclaration(kind: .git, location: identity).transportIdentity() == identity + else { throw CoreError.invalidSource("invalid portable Git identity") } + case .wellKnown: + guard origin.map({ $0.kind == .http }) ?? true, + let identity, let url = URLComponents(string: identity), url.query == nil, + try SourceDeclaration(kind: .wellKnown, location: identity).transportIdentity() == identity + else { throw CoreError.invalidSource("invalid portable index identity") } + } + } +} diff --git a/Sources/AgentsCore/PrivateMaterialization.swift b/Sources/AgentsCore/PrivateMaterialization.swift new file mode 100644 index 0000000..6e88b6f --- /dev/null +++ b/Sources/AgentsCore/PrivateMaterialization.swift @@ -0,0 +1,445 @@ +import CPlatform +import Foundation + +/// Runtime data supplied by the application. Source declarations never supply commands. +/// Implementations must return bounded, noninteractive data synchronously. They must not +/// hide network requests, login flows or unbounded work inside value resolution. +public protocol RuntimeBindingProvider: Sendable { + func value(for binding: String, environment: RuntimeEnvironment) throws -> Data +} + +/// Ephemeral values have no encoding or diagnostic representation. +package struct RuntimeBindingValues: CustomStringConvertible, CustomDebugStringConvertible, + CustomReflectable +{ + package var description: String { "" } + package var debugDescription: String { description } + package var customMirror: Mirror { Mirror(self, children: [Mirror.Child]()) } + private let values: [String: Data] + + package init(_ values: [String: Data]) { self.values = values } + + package func value(for binding: String) throws -> Data { + guard let value = values[binding] else { + throw CoreError.invalidState("required runtime binding is unavailable") + } + return value + } +} + +/// A file or complete named container admitted by Core's scope-owned path registrations. +package struct MaterializationTarget { + package let url: URL + package let path: String + let scope: URL +} + +/// The before-access and intended owner-only replacement are available for a prepared report. +package struct PrivateAccessChange { + package let before: FileAccessEvidence + package let owner: UInt32 + package let mode: UInt32 +} + +package struct PrivateTreeAccessChange { + package let path: String + package let before: FileAccessEvidence + package let owner: UInt32 + package let mode: UInt32 +} + +/// Package-only physical evidence. Array semantic digests remain private to the materializer. +package struct MaterializationReceipt { + package let generation: UUID + package let access: FileAccessEvidence + package let treeAccess: [TreeMemberAccess]? + package let nativeArrays: [PrivateNativeArrayRecord]? +} + +package struct PreparedPrivateMaterialization { + package let owner: UInt32 + package let receiptGeneration: UUID? + package let accessChange: PrivateAccessChange? + package let target: MaterializationTarget + let evidence: TargetPrecondition + let receiptEvidence: TargetPrecondition? + package let memberAccessChanges: [PrivateTreeAccessChange] + let preimageTreeAccess: [TreeMemberAccess]? + var ancestry: DirectoryAccessEvidence { evidence.access!.ancestry } + var beforeAccess: FileAccessEvidence? { evidence.access?.target } + + /// A non-secret access segment for the enclosing candidate's displayed fingerprint. + package func accessFingerprint() throws -> String { + let input = PrivateAccessFingerprint( + target: target.path, owner: owner, + publicationAccess: try evidence.displayEvidence(includeContent: false), + permissionChange: accessChange != nil, + members: preimageTreeAccess) + return "sha256:" + FileHash.sha256Hex(data: try StateStore.encode(input)) + } +} + +private struct PrivateAccessFingerprint: Encodable { + let version = 1 + let target: String + let owner: UInt32 + let publicationAccess: String + let permissionChange: Bool + let members: [TreeMemberAccess]? +} + +extension StateStore { + /// Native routes must extend the owning static registration after route verification. + /// This seam cannot authorize arbitrary external roots or source-authoring files. + package func materializationTarget(at url: URL) throws -> MaterializationTarget { + let paths = TransactionPaths(store: self) + let path = try paths.path(for: url) + let root = try paths.components(path).root + guard root.hasPrefix("instructions-"), root != "instructions-authoring" else { + throw CoreError.unsafePath("private materialization requires a registered file target") + } + return MaterializationTarget(url: url.standardizedFileURL, path: path, scope: directory) + } + + /// Inspects the last local generation under the caller's scope lock, without exposing bytes. + package func materializationReceipt(for target: MaterializationTarget) throws + -> MaterializationReceipt? + { + guard target.scope.path == directory.path, + try TransactionPaths(store: self).path(for: target.url) == target.path + else { throw CoreError.invalidState("materialization target belongs to another scope") } + if let route = try TransactionPaths(store: self).coordinationRoute(for: target.path), + try TransactionLockContext.current(self)?.absentRoot(for: route) != nil + { + return nil + } + guard + let record = try materializationReceipts(for: target.path).records.targets[ + materializationReceiptKey(for: target.path)] + else { + return nil + } + _ = try preparePrivateMaterialization(target, expecting: record.generation) + return MaterializationReceipt( + generation: record.generation, access: record.access, treeAccess: record.treeAccess, + nativeArrays: record.nativeArrays) + } + + /// Under the caller's scope lock, preparation never calls a provider or renderer. + package func preparePrivateMaterialization( + _ target: MaterializationTarget, changingAccess: Bool = false, + requiringReceiptForExistingTarget: Bool = false, expecting generation: UUID? = nil + ) throws -> PreparedPrivateMaterialization { + guard target.scope.path == directory.path, + try TransactionPaths(store: self).path(for: target.url) == target.path + else { throw CoreError.invalidState("materialization target belongs to another scope") } + if let route = try TransactionPaths(store: self).coordinationRoute(for: target.path), + try TransactionLockContext.current(self)?.absentRoot(for: route) != nil + { + guard generation == nil else { + throw CoreError.invalidState("materialization receipt generation changed or is missing") + } + let evidence = try TargetPrecondition(target.url).capturingAccess() + return PreparedPrivateMaterialization( + owner: UInt32(geteuid()), receiptGeneration: nil, accessChange: nil, target: target, + evidence: evidence, receiptEvidence: nil, memberAccessChanges: [], preimageTreeAccess: nil) + } + let receipt = try materializationReceipts(for: target.path) + let record = receipt.records.targets[try materializationReceiptKey(for: target.path)] + if let generation, record?.generation != generation { + throw CoreError.invalidState("materialization receipt generation changed or is missing") + } + let evidence = try TargetPrecondition(target.url).capturingAccess() + guard !requiringReceiptForExistingTarget || evidence.snapshot == nil || record != nil else { + throw CoreError.invalidState("known materialized target is missing its private receipt") + } + guard + evidence.snapshot == nil || evidence.snapshot?.isRegular == true + || evidence.snapshot?.identity.isDirectory == true + else { + throw CoreError.unsafePath( + "private materialization requires a regular file or registered container") + } + let parentURL = evidence.physicalURL.deletingLastPathComponent() + let ancestry = try DirectoryAccessEvidence.capture(at: parentURL) + var beforeAccess: FileAccessEvidence? + var change: PrivateAccessChange? + var tree: [TreeMemberAccess]? + var memberChanges: [PrivateTreeAccessChange] = [] + let privateMode: mode_t = evidence.snapshot?.identity.isDirectory == true ? 0o700 : 0o600 + if evidence.snapshot != nil { + let parent = try DirectoryHandle(at: parentURL) + beforeAccess = try parent.accessEvidence(target.url.lastPathComponent) + if let snapshot = evidence.snapshot { + tree = try TreeMemberAccess.capture( + target.url.lastPathComponent, in: parent, snapshot: snapshot) + } + for member in tree ?? [] { + let parts = member.path.split(separator: "/").map(String.init) + var directory = try parent.child(target.url.lastPathComponent) + for name in parts.dropLast() { directory = try directory.child(name) } + let mode: UInt32 = + member.access.identity.isDirectory || member.access.mode & 0o100 != 0 ? 0o700 : 0o600 + var changes = UInt32(member.access.mode) != mode + do { _ = try directory.requirePrivateAccess(parts.last!, matching: member.access) } catch { + changes = true + } + if changes { + memberChanges.append( + .init(path: member.path, before: member.access, owner: UInt32(geteuid()), mode: mode)) + } + } + var changesAccess = beforeAccess?.mode != privateMode || !memberChanges.isEmpty + if let snapshot = evidence.snapshot { + do { + try TreeMemberAccess.verify( + tree, snapshot: snapshot, named: target.url.lastPathComponent, + in: parent, requirePrivate: true) + } catch { changesAccess = true } + } + do { _ = try parent.requirePrivateAccess(target.url.lastPathComponent) } catch { + changesAccess = true + } + if changesAccess { + guard changingAccess, let beforeAccess else { + throw CoreError.invalidState("private materialization requires an explicit access change") + } + change = PrivateAccessChange( + before: beforeAccess, owner: UInt32(geteuid()), mode: UInt32(privateMode)) + } + } + if let record = receipt.records.targets[try materializationReceiptKey(for: target.path)] { + guard try materializationRootIdentity(target.path) == record.rootIdentity else { + throw CoreError.invalidState("materialization receipt root changed") + } + if evidence.snapshot != nil { + guard evidence.snapshot?.digest == record.digest, beforeAccess == record.access, + tree == record.treeAccess + else { + throw CoreError.invalidState("materialized preimage differs from its receipt") + } + _ = try DirectoryHandle(at: parentURL).requirePrivateAccess( + target.url.lastPathComponent, matching: record.access) + try TreeMemberAccess.verify( + record.treeAccess, snapshot: evidence.snapshot!, named: target.url.lastPathComponent, + in: DirectoryHandle(at: parentURL), requirePrivate: true) + } + } + try evidence.validate() + try ancestry.validate(at: parentURL) + return PreparedPrivateMaterialization( + owner: UInt32(geteuid()), receiptGeneration: record?.generation, accessChange: change, + target: target, + evidence: evidence, receiptEvidence: receipt.evidence, memberAccessChanges: memberChanges, + preimageTreeAccess: tree) + } +} + +/// Only materialization generations and local physical evidence belong here. +struct MaterializationReceipts: Codable { + static let fileName = "materializations.json" + var version = 1 + var targets: [String: Record] = [:] + + struct Record: Codable { + let generation: UUID + let rootIdentity: String + let digest: String + let access: FileAccessEvidence + var treeAccess: [TreeMemberAccess]? = nil + var nativeArrays: [PrivateNativeArrayRecord]? = nil + + private enum CodingKeys: String, CodingKey { + case generation, rootIdentity, digest, access, treeAccess, nativeArrays + } + init( + generation: UUID, rootIdentity: String, digest: String, access: FileAccessEvidence, + treeAccess: [TreeMemberAccess]? = nil, nativeArrays: [PrivateNativeArrayRecord]? = nil + ) { + self.generation = generation + self.rootIdentity = rootIdentity + self.digest = digest + self.access = access + self.treeAccess = treeAccess + self.nativeArrays = nativeArrays + } + init(from decoder: any Decoder) throws { + try ReceiptFields.require( + decoder, ["generation", "rootIdentity", "digest", "access", "treeAccess", "nativeArrays"]) + let c = try decoder.container(keyedBy: CodingKeys.self) + generation = try c.decode(UUID.self, forKey: .generation) + rootIdentity = try c.decode(String.self, forKey: .rootIdentity) + digest = try c.decode(String.self, forKey: .digest) + access = try c.decode(FileAccessEvidence.self, forKey: .access) + treeAccess = try c.decodeIfPresent([TreeMemberAccess].self, forKey: .treeAccess) + nativeArrays = try c.decodeIfPresent([PrivateNativeArrayRecord].self, forKey: .nativeArrays) + if c.contains(.nativeArrays), nativeArrays == nil { + throw CoreError.invalidState("invalid private array records") + } + } + } + private enum CodingKeys: String, CodingKey { case version, targets } + init() {} + init(from decoder: any Decoder) throws { + try ReceiptFields.require(decoder, ["version", "targets"]) + let c = try decoder.container(keyedBy: CodingKeys.self) + version = try c.decode(Int.self, forKey: .version) + targets = try c.decode([String: Record].self, forKey: .targets) + guard version == 1 || version == 2, + version != 1 || targets.values.allSatisfy({ $0.nativeArrays == nil }) + else { + throw CoreError.invalidState("unsupported materialization receipt") + } + } + + func validate(store: StateStore) throws { + guard version == 1 || version == 2 else { + throw CoreError.invalidState("unsupported materialization receipt") + } + for (path, record) in targets { + let paths = TransactionPaths(store: store) + let parts: (root: String, descendants: [String]) + if let route = NativeTargetRoute.sharedRoute(path) { + guard path.utf8.elementsEqual((route.root + "/" + route.basename).utf8) else { + throw CoreError.invalidState("invalid physical receipt target") + } + parts = (route.root, [route.basename]) + } else { + parts = try paths.components(path) + } + guard + (parts.root.hasPrefix("instructions-") && parts.root != "instructions-authoring") + || NativeTargetRoute.targetRoute(parts.root) != nil + else { + throw CoreError.invalidState("invalid materialization receipt target") + } + guard + [mode_t(CPlatform.S_IFREG), mode_t(CPlatform.S_IFDIR)].contains( + record.access.identity.kind), + record.access.identity.isDirectory == (record.treeAccess != nil), + record.access.identity.isDirectory + == (NativeTargetRoute.targetRoute(path)?.isContainer == true), + !record.rootIdentity.isEmpty + else { throw CoreError.invalidState("invalid materialization receipt target") } + if let arrays = record.nativeArrays { + guard version == 2, record.access.identity.kind == S_IFREG, + let route = NativeTargetRoute.targetRoute(path), !route.isContainer + else { throw CoreError.invalidState("private arrays require a registered native file") } + try PrivateNativeArrayRecord.validate(arrays) + } + if let members = record.treeAccess { try TreeMemberAccess.validateStructure(members) } + try StateValidation.digest("sha256:" + record.digest) + } + } +} + +extension StateStore { + var materializationReceiptURL: URL { + directory.appendingPathComponent(MaterializationReceipts.fileName) + } + + func materializationRootIdentity(_ root: String) throws -> String { + if let route = try TransactionPaths(store: self).coordinationRoute(for: root) { + guard let context = TransactionLockContext.current(self) else { + throw CoreError.invalidState("shared receipt requires its held footprint") + } + return try context.resource(for: route).identity.orderingKey + } + return try TransactionPaths(store: self).root( + root.split(separator: "/").first.map(String.init) ?? root + ).identity + } + + func materializationReceipts(for path: String = "") throws -> MaterializationReceiptState { + let route = try TransactionPaths(store: self).coordinationRoute(for: path) + let shared = route != nil + let resource: SharedResource? + if let route { + guard let context = TransactionLockContext.current(self) else { + throw CoreError.invalidState("shared receipt requires its held footprint") + } + resource = try context.resource(for: route) + } else { + resource = nil + } + let url: URL + let receiptPath: String + if let resource { + let metadataURL = resource.parent.url.appendingPathComponent(SharedResource.metadataName) + .appendingPathComponent(resource.identity.directoryName) + url = (resource.metadata?.url ?? metadataURL).appendingPathComponent("receipt") + receiptPath = resource.receiptPath + } else { + url = materializationReceiptURL + receiptPath = "state/" + MaterializationReceipts.fileName + } + let evidence = try TargetPrecondition(url) + guard evidence.snapshot != nil else { + return .init(path: receiptPath, url: url, records: .init(), evidence: evidence, access: nil) + } + let directory = try DirectoryHandle(at: url.deletingLastPathComponent()) + let evidenceWithAccess = try evidence.capturingAccess() + let access = try directory.requirePrivateAccess(url.lastPathComponent) + do { + let bytes = try directory.read( + url.lastPathComponent, maximumBytes: LedgerLimits.standard.encodedBytes) + try LedgerAdmission.check(bytes, limits: .standard) + var records = try Self.decode(bytes, as: MaterializationReceipts.self) + try records.validate(store: self) + if let resource { + guard records.targets.count == 1, let (key, record) = records.targets.first, + let recorded = NativeTargetRoute.sharedRoute(key), + recorded.basename.utf8.elementsEqual(resource.identity.basename.utf8), + record.rootIdentity.utf8.elementsEqual(resource.identity.orderingKey.utf8) + else { throw CoreError.invalidState("shared receipt must identify its physical file") } + records.targets = [resource.route.root + "/" + resource.identity.basename: record] + } + if !shared { + var candidates = TransactionLockContext.current(self)?.requestedRoutes ?? [] + if let route = NativeTargetRoute.targetRoute(path) { candidates.insert(route) } + for route in candidates.filter({ !$0.shared }).sorted(by: { + $0.rawValue.utf8.lexicographicallyPrecedes($1.rawValue.utf8) + }) { + let target = try nativeTarget(for: route) + let parentURL = target.url.deletingLastPathComponent() + let ancestry = try DirectoryAccessEvidence.capture(at: parentURL) + guard ancestry.directories.count == parentURL.pathComponents.count else { continue } + let parent = try DirectoryHandle(at: parentURL) + let identity = try parent.identity + let matches = records.targets.filter { key, record in + NativeTargetRoute.targetRoute(key)?.shared == false + && key.split(separator: "/").last.map(String.init)?.utf8.elementsEqual( + route.basename.utf8) == true + && record.rootIdentity == identity + } + guard matches.count <= 1 else { + throw CoreError.invalidState("ambiguous physical materialization receipts") + } + if let (old, record) = matches.first { + records.targets.removeValue(forKey: old) + records.targets[target.path] = record + } + try ancestry.validate(at: parentURL) + } + } + for (key, record) in records.targets { + guard shared == (NativeTargetRoute.sharedRoute(key) != nil), + !shared + || record.rootIdentity.utf8.elementsEqual((resource?.identity.orderingKey ?? "").utf8) + else { throw CoreError.invalidState("receipt belongs to another physical resource") } + } + try evidence.validate() + _ = try directory.requirePrivateAccess(url.lastPathComponent, matching: access) + return .init( + path: receiptPath, url: url, records: records, evidence: evidenceWithAccess, access: access) + } catch { throw CoreError.invalidState("invalid private materialization receipt") } + } +} + +struct MaterializationReceiptState { + let path: String + let url: URL + let records: MaterializationReceipts + let evidence: TargetPrecondition + let access: FileAccessEvidence? +} diff --git a/Sources/AgentsCore/PrivateNativeArrays.swift b/Sources/AgentsCore/PrivateNativeArrays.swift new file mode 100644 index 0000000..025a096 --- /dev/null +++ b/Sources/AgentsCore/PrivateNativeArrays.swift @@ -0,0 +1,215 @@ +import Foundation + +/// Private document coordinates, not edit instructions or filesystem authority. +package enum PrivateNativeAddressStep: Codable, Equatable, Sendable { + case key(String) + case stableID(key: String, value: String) + case position(index: Int) + + private enum CodingKeys: String, CodingKey { case kind, key, value, index } + package init(from decoder: any Decoder) throws { + let fields = try decoder.container(keyedBy: CodingKeys.self) + switch try fields.decode(String.self, forKey: .kind) { + case "key": + try ReceiptFields.require(decoder, ["kind", "key"]) + self = .key(try fields.decode(String.self, forKey: .key)) + case "stableID": + try ReceiptFields.require(decoder, ["kind", "key", "value"]) + self = .stableID( + key: try fields.decode(String.self, forKey: .key), + value: try fields.decode(String.self, forKey: .value)) + case "position": + try ReceiptFields.require(decoder, ["kind", "index"]) + self = .position(index: try fields.decode(Int.self, forKey: .index)) + default: throw CoreError.invalidState("unsupported private array address") + } + } + package func encode(to encoder: any Encoder) throws { + var fields = encoder.container(keyedBy: CodingKeys.self) + switch self { + case .key(let key): + try fields.encode("key", forKey: .kind) + try fields.encode(key, forKey: .key) + case .stableID(let key, let value): + try fields.encode("stableID", forKey: .kind) + try fields.encode(key, forKey: .key) + try fields.encode(value, forKey: .value) + case .position(let index): + try fields.encode("position", forKey: .kind) + try fields.encode(index, forKey: .index) + } + } + package static func == (a: Self, b: Self) -> Bool { + switch (a, b) { + case (.key(let a), .key(let b)): return Data(a.utf8) == Data(b.utf8) + case (.stableID(let ak, let av), .stableID(let bk, let bv)): + return Data(ak.utf8) == Data(bk.utf8) && Data(av.utf8) == Data(bv.utf8) + case (.position(let a), .position(let b)): return a == b + default: return false + } + } +} + +/// Only the private receipt encodes this evidence. Diagnostic reflection is redacted. +package struct PrivateNativeArrayRecord: Codable, Equatable, Sendable, CustomStringConvertible, + CustomDebugStringConvertible, CustomReflectable +{ + package let path: [PrivateNativeAddressStep] + package let documentFormat: String + package let token: UUID + package let semanticFormat: String + package let semanticDigest: String + package var description: String { "" } + package var debugDescription: String { description } + package var customMirror: Mirror { Mirror(self, children: [Mirror.Child]()) } + + package init( + path: [PrivateNativeAddressStep], documentFormat: String, token: UUID, + semanticFormat: String = "native-array@1", semanticDigest: String + ) { + self.path = path + self.documentFormat = documentFormat + self.token = token + self.semanticFormat = semanticFormat + self.semanticDigest = semanticDigest + } + private enum CodingKeys: String, CodingKey { + case path, documentFormat, token, semanticFormat, semanticDigest + } + package init(from decoder: any Decoder) throws { + try ReceiptFields.require( + decoder, ["path", "documentFormat", "token", "semanticFormat", "semanticDigest"]) + let c = try decoder.container(keyedBy: CodingKeys.self) + path = try c.decode([PrivateNativeAddressStep].self, forKey: .path) + documentFormat = try c.decode(String.self, forKey: .documentFormat) + token = try c.decode(UUID.self, forKey: .token) + semanticFormat = try c.decode(String.self, forKey: .semanticFormat) + semanticDigest = try c.decode(String.self, forKey: .semanticDigest) + } +} + +/// E/F supplies same-edit structural proof; Core validates coverage and the sealed preimage. +package struct PrivateNativeArrayTransition { + package let previous: PrivateNativeArrayRecord? + package let current: PrivateNativeArrayRecord? + package init(previous: PrivateNativeArrayRecord?, current: PrivateNativeArrayRecord?) { + self.previous = previous + self.current = current + } +} + +/// Ephemeral actual render output. It has no encoding or payload diagnostic representation. +package struct PrivateMaterializationResult: CustomStringConvertible, CustomDebugStringConvertible, + CustomReflectable +{ + let bytes: Data + let nativeArrayTransitions: [PrivateNativeArrayTransition]? + package init(bytes: Data, nativeArrayTransitions: [PrivateNativeArrayTransition]? = nil) { + self.bytes = bytes + self.nativeArrayTransitions = nativeArrayTransitions + } + package var description: String { "" } + package var debugDescription: String { description } + package var customMirror: Mirror { Mirror(self, children: [Mirror.Child]()) } +} + +/// Unknown fields, including null, are rejected before decoding receipt records. +enum ReceiptFields { + private struct Key: CodingKey { + var stringValue: String + var intValue: Int? { nil } + init?(stringValue: String) { self.stringValue = stringValue } + init?(intValue: Int) { return nil } + } + static func require(_ decoder: any Decoder, _ allowed: Set) throws { + let fields = try decoder.container(keyedBy: Key.self) + guard Set(fields.allKeys.map(\.stringValue)).isSubset(of: allowed) else { + throw CoreError.invalidState("invalid private receipt fields") + } + } +} + +extension PrivateNativeArrayRecord { + static func validate(_ records: [Self]) throws { + guard records.count <= LedgerLimits.standard.entries else { + throw CoreError.invalidState("private array records exceed limits") + } + let bytes = try StateStore.encode(records) + try LedgerAdmission.check(bytes, limits: .standard) + var paths = Set() + var tokens = Set() + for record in records { + guard ["json", "jsonc", "jsonc-trailing-commas", "toml"].contains(record.documentFormat), + record.documentFormat == records.first?.documentFormat, + record.semanticFormat == "native-array@1", + record.path.count <= LedgerLimits.standard.depth, + tokens.insert(record.token).inserted, + paths.insert(try StateStore.encode(record.path)).inserted + else { throw CoreError.invalidState("invalid private array record") } + for step in record.path { + if case .position(let index) = step, index < 0 { + throw CoreError.invalidState("invalid private array address") + } + } + guard record.semanticDigest.utf8.count == 71, + record.semanticDigest.range(of: #"^sha256:[0-9a-f]{64}$"#, options: .regularExpression) + != nil + else { + throw CoreError.invalidState("invalid private array digest") + } + } + } + + static func applying( + _ result: PrivateMaterializationResult, previous: MaterializationReceipts.Record?, + admitted: Bool, hasPreimage: Bool = true + ) throws -> [Self]? { + let old = previous?.nativeArrays ?? [] + guard let transitions = result.nativeArrayTransitions else { + guard + old.isEmpty || (hasPreimage && previous?.digest == FileHash.sha256Hex(data: result.bytes)) + else { + throw CoreError.invalidState("changed tracked file requires complete array transitions") + } + return previous?.nativeArrays + } + guard admitted else { + throw CoreError.invalidState("array transitions require a registered native file") + } + guard transitions.count <= LedgerLimits.standard.entries else { + throw CoreError.invalidState("private array transitions exceed limits") + } + var oldByToken: [UUID: Self] = [:] + for record in old { + guard oldByToken.updateValue(record, forKey: record.token) == nil else { + throw CoreError.invalidState("duplicate private array records") + } + } + var covered = Set() + var next: [Self] = [] + for transition in transitions { + guard transition.previous != nil || transition.current != nil else { + throw CoreError.invalidState("empty private array transition") + } + if let before = transition.previous { + guard oldByToken[before.token] == before, covered.insert(before.token).inserted else { + throw CoreError.invalidState( + "private array transition does not match the current receipt") + } + } + if let after = transition.current { + if let existing = oldByToken[after.token] { + guard hasPreimage, transition.previous == existing, after == existing else { + throw CoreError.invalidState("changed private array requires a new continuity token") + } + } + next.append(after) + } + } + guard covered == Set(old.map(\.token)) else { + throw CoreError.invalidState("incomplete private array transitions") + } + try validate(next) + return next.isEmpty ? nil : next + } +} diff --git a/Sources/AgentsCore/PrivateSourceRecovery.swift b/Sources/AgentsCore/PrivateSourceRecovery.swift new file mode 100644 index 0000000..bdd4c38 --- /dev/null +++ b/Sources/AgentsCore/PrivateSourceRecovery.swift @@ -0,0 +1,245 @@ +import CPlatform +import Foundation + +#if canImport(FoundationNetworking) + import FoundationNetworking +#endif + +/// Independent of shared acquisitions and any project location. Only ZIPs constitute recovery +/// authority. Each scope reservation protects both its visible generation and the pending one. +struct PrivateSourceRecovery { + struct Reference: Hashable, Sendable { + let transport: String + let archive: SourceArchiveEvidence + + var key: String { + AcquisitionCache.key([ + ("repository", Data(transport.utf8)), + ("request", Data(archive.effectiveURL.absoluteString.utf8)), + ("flavor", Data(archive.flavor.rawValue.utf8)), + ("tree", Data(archive.treeDigest.utf8)), + ("representation", Data((archive.requiredArchiveDigest ?? "tree").utf8)), + ]) + } + } + + let environment: RuntimeEnvironment + + private var root: URL { + environment.homeDirectory.appendingPathComponent(".agents-source-recovery", isDirectory: true) + } + + static func makeWorkspace(prefix: String) throws -> DirectoryHandle { + let parent = try DirectoryHandle( + at: FileManager.default.temporaryDirectory.resolvingSymlinksInPath()) + return try parent.createPrivateDirectory(prefix + UUID().uuidString) + } + + func requirePublicationAccess() throws { + let home = root.deletingLastPathComponent() + let parent = try DirectoryHandle(at: home) + _ = try DirectoryAccessEvidence.capture(at: home) + guard platform_access(parent.descriptor, ".", W_OK | X_OK) == 0 else { + throw SourceAccessError.recoveryUnavailable + } + if let store = try directory(create: false), + platform_access(store.descriptor, ".", W_OK | X_OK) != 0 + { + throw SourceAccessError.recoveryUnavailable + } + } + + func treeURL(_ reference: Reference) -> URL { + root.appendingPathComponent(reference.key).appendingPathComponent("tree", isDirectory: true) + } + + func read(_ reference: Reference) throws -> (Data, VerifiedVCSArchive)? { + guard let store = try directory(create: false), + try store.info(reference.key) != nil + else { return nil } + _ = try store.requirePrivateAccess(reference.key) + return try read(reference, entry: store.child(reference.key)) + } + + private func read( + _ reference: Reference, entry: DirectoryHandle + ) throws -> (Data, VerifiedVCSArchive)? { + guard try entry.info("archive") != nil else { return nil } + let access = try entry.requirePrivateAccess("archive") + guard access.mode == 0o600 else { throw SourceAccessError.recoveryUnavailable } + let stored = try entry.read("archive", maximumBytes: VerifiedVCSArchive.compressedLimit + 71) + guard stored.count >= 71 else { throw SourceAccessError.invalidArchive } + let digest = String(decoding: stored.prefix(71), as: UTF8.self) + let bytes = Data(stored.dropFirst(71)) + guard "sha256:" + FileHash.sha256Hex(data: bytes) == digest else { + throw SourceAccessError.invalidArchive + } + let verified = try VerifiedVCSArchive(bytes) + try reference.archive.verify(verified) + return (bytes, verified) + } + + func withPublication( + store scope: StateStore, previous: Set, next: Set, + captures: GitAcquisitionCaptures?, policy: EffectiveSourcePolicy, + offline: Bool, checkpoint: (String) throws -> Void, _ body: () throws -> T + ) throws -> T { + guard !previous.isEmpty || !next.isEmpty || FileManager.default.fileExists(atPath: root.path) + else { + return try body() + } + let store = try directory(create: true)! + return try FileLock.withLock(in: store, named: "lock") { + let reservation = reservationName(scope) + for (index, reference) in next.sorted(by: { $0.key < $1.key }).enumerated() { + let route = try SourceRoute( + SourceDeclaration(kind: .git, location: reference.transport), + environment: environment, policy: policy) + guard let request = try route.requireRecordedArchive(reference.archive) else { + throw SourceAccessError.routeChanged + } + let entry = + try store.info(reference.key) == nil + ? store.createPrivateDirectory(reference.key) : store.child(reference.key) + _ = try store.requirePrivateAccess(reference.key) + let verified: VerifiedVCSArchive + if let (_, existing) = try read(reference, entry: entry) { + verified = existing + } else { + let bytes: Data + if let captured = try captures?.readArchive(reference) { + bytes = captured + } else { + guard !offline else { throw SourceAccessError.recoveryUnavailable } + bytes = try Self.download(request, route: route, environment: environment) + } + verified = try VerifiedVCSArchive(bytes) + try reference.archive.verify(verified) + try entry.removeFiles(["archive-next"]) + let file = try entry.createPrivateFile("archive-next") + try file.write(Data(verified.byteDigest.utf8) + bytes) + guard renameat(entry.descriptor, "archive-next", entry.descriptor, "archive") == 0 else { + throw SourceAccessError.recoveryUnavailable + } + try entry.sync() + } + try checkpoint("archive.recovery.\(index).bytes") + let tree = entry.url.appendingPathComponent("tree") + if try !verified.matches(tree) { + let staging = "tree-" + UUID().uuidString + _ = try verified.extract(named: staging, in: entry, environment: environment) + try entry.replaceRecoveryTree(staging: staging) + } + } + // Keep both generations until the scope transaction has committed. A crashed publish + // leaves the superset; only this scope reconciles it after its journal is recovered. + try record(previous.union(next), name: reservation, in: store) + try checkpoint("archive.recovery.reserved") + let result = try body() + try record(next, name: reservation, in: store) + try checkpoint("archive.recovery.committed") + try prune(store) + return result + } + } + + func reconcile(scope: StateStore) throws { + guard FileManager.default.fileExists(atPath: root.path), + let store = try directory(create: false) + else { return } + try FileLock.withLock(in: store, named: "lock") { + let name = reservationName(scope) + guard try store.info(name) != nil else { return } + try record(scope.retentionReferences().archives, name: name, in: store) + try prune(store) + } + } + + private func reservationName(_ scope: StateStore) -> String { + let directory = scope.directory.resolvingSymlinksInPath().standardizedFileURL + return "scope-" + FileHash.sha256Hex(data: Data(directory.path.utf8)) + } + + private func record(_ references: Set, name: String, in store: DirectoryHandle) throws + { + if references.isEmpty { + try store.removeFiles([name]) + } else { + let keys = Set(references.map(\.key)).sorted() + try store.replaceFile( + name, through: name + ".next", with: StateStore.encode(keys), + afterWrite: {}, afterRename: {}) + } + } + + private func prune(_ store: DirectoryHandle) throws { + let names = try store.names() + var retained = Set() + for name in names where name.hasPrefix("scope-") && name.count == 70 { + _ = try store.requirePrivateAccess(name) + let bytes = try store.read(name, maximumBytes: LedgerLimits.standard.encodedBytes) + let keys = try JSONDecoder().decode([String].self, from: bytes) + guard keys.allSatisfy(Self.isKey) else { throw SourceAccessError.recoveryUnavailable } + retained.formUnion(keys) + } + for name in names where Self.isKey(name) && !retained.contains(name) { + _ = try store.requirePrivateAccess(name) + try FileManager.default.removeItem(at: store.url.appendingPathComponent(name)) + } + try store.sync() + } + + private static func isKey(_ name: String) -> Bool { + name.utf8.count == 64 + && name.utf8.allSatisfy { (48...57).contains($0) || (97...102).contains($0) } + } + + private func directory(create: Bool) throws -> DirectoryHandle? { + let home = root.deletingLastPathComponent() + _ = try DirectoryAccessEvidence.capture(at: home) + guard let parent = try? DirectoryHandle(at: home) else { + if create { throw SourceAccessError.recoveryUnavailable } + return nil + } + let name = root.lastPathComponent + if try parent.info(name) == nil { + guard create else { return nil } + do { _ = try parent.createPrivateDirectory(name) } catch { + guard try parent.info(name) != nil else { throw error } + } + } + let access = try parent.requirePrivateAccess(name) + guard access.mode == 0o700 else { throw SourceAccessError.recoveryUnavailable } + return try parent.child(name) + } + + static func download( + _ request: VCSArchiveRequest, route: SourceRoute, environment: RuntimeEnvironment + ) throws -> Data { + var get = URLRequest(url: request.url) + get.httpMethod = "GET" + get.setValue("application/zip", forHTTPHeaderField: "Accept") + if let binding = try route.credential(environment.sourceAccess) { + get.setValue("Bearer " + (try binding.value()), forHTTPHeaderField: "Authorization") + } + let response = try PackageSourceHTTP.read(get, maximumBytes: VerifiedVCSArchive.compressedLimit) + guard response.status == 200 else { throw SourceAccessError.requestFailed } + return response.body + } +} + +extension DirectoryHandle { + fileprivate func replaceRecoveryTree(staging: String) throws { + if try info("tree") == nil { + guard renameat(descriptor, staging, descriptor, "tree") == 0 else { + throw SourceAccessError.recoveryUnavailable + } + } else { + guard platform_exchange(descriptor, staging, descriptor, "tree") == 0 else { + throw SourceAccessError.recoveryUnavailable + } + try FileManager.default.removeItem(at: url.appendingPathComponent(staging)) + } + try sync() + } +} diff --git a/Sources/AgentsCore/PrivateTree.swift b/Sources/AgentsCore/PrivateTree.swift new file mode 100644 index 0000000..f238617 --- /dev/null +++ b/Sources/AgentsCore/PrivateTree.swift @@ -0,0 +1,220 @@ +import Foundation + +/// An owned complete candidate. Renderers receive values, never writable filesystem authority. +package struct PrivateTreeEntry { + package enum Content { + case directory + case file(Data, executable: Bool = false) + case boundFile( + bindings: Set, executable: Bool = false, + render: (RuntimeBindingValues) throws -> Data) + case symlink(String) + } + package let relativePath: String + package let content: Content + package init(_ relativePath: String, content: Content) { + self.relativePath = relativePath + self.content = content + } +} + +struct PrivateTree { + let entries: [PrivateTreeEntry] + let provider: any RuntimeBindingProvider + let environment: RuntimeEnvironment + let inputBytes: Int + let metadataBytes: Int + + init( + entries: [PrivateTreeEntry], provider: any RuntimeBindingProvider, + environment: RuntimeEnvironment + ) throws { + let limits = LedgerLimits.standard + guard entries.count <= limits.entries else { + throw CoreError.invalidState("private tree exceeds member limit") + } + var bytes = 0 + var contentBytes = 0 + var paths = Set() + var directories = Set() + var links: [(String, String)] = [] + for entry in entries { + let parts = entry.relativePath.split(separator: "/", omittingEmptySubsequences: false) + guard !parts.isEmpty, parts.count < limits.depth / 4, + parts.allSatisfy({ + !$0.isEmpty && $0 != "." && $0 != ".." && !$0.contains("\\") && !$0.contains("\0") + }), + paths.insert(Data(entry.relativePath.utf8)).inserted + else { throw CoreError.unsafePath("invalid or duplicate private tree member") } + bytes += entry.relativePath.utf8.count + switch entry.content { + case .directory: directories.insert(Data(entry.relativePath.utf8)) + case .file(let data, _): + bytes += data.count + contentBytes += data.count + case .boundFile(let names, _, _): + guard names.allSatisfy({ !$0.isEmpty && !$0.contains("\0") }) else { + throw CoreError.invalidState("invalid private tree bindings") + } + bytes += names.reduce(0) { $0 + $1.utf8.count } + case .symlink(let destination): + links.append((entry.relativePath, destination)) + bytes += destination.utf8.count + } + guard bytes <= limits.resourceBytes else { + throw CoreError.invalidState("private tree exceeds byte limit") + } + } + for entry in entries { + let parts = entry.relativePath.split(separator: "/").dropLast() + for count in 1...max(1, parts.count) where count <= parts.count { + guard directories.contains(Data(parts.prefix(count).joined(separator: "/").utf8)) else { + throw CoreError.unsafePath("private tree member lacks a real directory parent") + } + } + } + // Resolve the closed candidate graph with the same containment/dangling semantics + // as PathSafety.linkStaysInside, before creating anything or requesting bindings. + let destinations = Dictionary(uniqueKeysWithValues: links.map { (Data($0.0.utf8), $0.1) }) + var work = 0 + for (path, destination) in links { + guard !destination.hasPrefix("/"), !destination.isEmpty, !destination.contains("\0") else { + throw CoreError.unsafePath("private tree link escapes container") + } + var pending = destination.split(separator: "/").reversed().map(String.init) + var resolved = path.split(separator: "/").dropLast().map(String.init) + var expansions = 0 + while let component = pending.popLast() { + work += 1 + guard work <= limits.nodes else { + throw CoreError.invalidState("private tree link work limit") + } + if component == "." { continue } + if component == ".." { + guard !resolved.isEmpty else { + throw CoreError.unsafePath("private tree link escapes container") + } + resolved.removeLast() + continue + } + let key = Data((resolved + [component]).joined(separator: "/").utf8) + if let next = destinations[key] { + expansions += 1 + guard expansions <= 32, !next.hasPrefix("/") else { + throw CoreError.unsafePath("private tree link cycle or escape") + } + pending += next.split(separator: "/").reversed().map(String.init) + } else if paths.contains(key) { + resolved.append(component) + } else { + guard !pending.contains("..") else { + throw CoreError.unsafePath("private tree dangling link escapes container") + } + break + } + } + } + self.entries = entries.sorted { + $0.relativePath.utf8.lexicographicallyPrecedes($1.relativePath.utf8) + } + self.provider = provider + self.environment = environment + inputBytes = bytes + metadataBytes = bytes - contentBytes + } + + func construct( + named name: String, in container: DirectoryHandle, bytes: inout Int, + admit: (FileSnapshot, FileAccessEvidence, [TreeMemberAccess]?) throws -> Void, + validate: () throws -> Void + ) + throws + { + let root = try container.createPrivateDirectory(name) + func parent(_ path: String) throws -> (DirectoryHandle, String) { + let parts = path.split(separator: "/").map(String.init) + var directory = root + for component in parts.dropLast() { directory = try directory.child(component) } + return (directory, parts.last!) + } + for entry in entries { + if case .directory = entry.content { + let (directory, name) = try parent(entry.relativePath) + _ = try directory.createPrivateDirectory(name) + } + } + var files: [(PrivateTreeEntry, PrivateFileHandle)] = [] + for entry in entries { + let executable: Bool + switch entry.content { + case .file(_, let flag), .boundFile(_, let flag, _): executable = flag + default: continue + } + let (directory, name) = try parent(entry.relativePath) + files.append((entry, try directory.createPrivateFile(name, executable: executable))) + } + for entry in entries { + if case .symlink(let destination) = entry.content { + let (directory, name) = try parent(entry.relativePath) + try directory.link(name, destination: destination) + } + } + guard let physicalRoot = PathSafety.realPath(root.url.path) else { + throw CoreError.invalidState("private tree root changed during construction") + } + for entry in entries { + if case .symlink = entry.content { + guard + try PathSafety.linkStaysInside( + root.url.appendingPathComponent(entry.relativePath), root: physicalRoot) + else { + throw CoreError.unsafePath("private tree link escapes container") + } + } + } + try validate() + let emptySnapshot = try FileSnapshot.read(name, from: container)! + let rootAccess = try container.requirePrivateAccess(name) + let memberAccess = try TreeMemberAccess.capture( + name, in: container, snapshot: emptySnapshot, requirePrivate: true) + try admit(emptySnapshot, rootAccess, memberAccess) + var names = Set() + for entry in entries { + if case .boundFile(let bindings, _, _) = entry.content { names.formUnion(bindings) } + } + var values: [String: Data] = [:] + guard metadataBytes <= LedgerLimits.standard.resourceBytes - bytes else { + throw CoreError.invalidState("private trees exceed byte limit") + } + bytes += metadataBytes + do { + for binding in names.sorted() { + let data = try provider.value(for: binding, environment: environment) + guard data.count <= LedgerLimits.standard.resourceBytes - bytes else { + throw CoreError.invalidState("private tree exceeds byte limit") + } + bytes += data.count + values[binding] = data + } + let bound = RuntimeBindingValues(values) + for (entry, file) in files { + let data: Data + switch entry.content { + case .file(let bytes, _): data = bytes + case .boundFile(_, _, let render): data = try render(bound) + default: preconditionFailure() + } + guard data.count <= LedgerLimits.standard.resourceBytes - bytes else { + throw CoreError.invalidState("private tree exceeds byte limit") + } + bytes += data.count + try validate() + try file.write(data) + } + } catch { + throw CoreError.invalidState("private tree could not resolve or construct its content") + } + let sealed = try FileSnapshot.read(name, from: container)! + try container.synchronize(name, as: sealed) + } +} diff --git a/Sources/AgentsCore/ProcessLimits.swift b/Sources/AgentsCore/ProcessLimits.swift new file mode 100644 index 0000000..1ce5e40 --- /dev/null +++ b/Sources/AgentsCore/ProcessLimits.swift @@ -0,0 +1,10 @@ +import CPlatform + +public enum ProcessLimits { + /// Best-effort increase of this process's soft open-file limit. + /// Call from the owning executable at startup, before beginning scope operations. + /// The hard limit is preserved. If the OS refuses, operations use the existing limit. + public static func raiseOpenFileLimit() { + platform_raise_open_file_limit() + } +} diff --git a/Sources/AgentsCore/ProcessRunner.swift b/Sources/AgentsCore/ProcessRunner.swift index 84a9a6f..119c9e8 100644 --- a/Sources/AgentsCore/ProcessRunner.swift +++ b/Sources/AgentsCore/ProcessRunner.swift @@ -1,11 +1,6 @@ +import CPlatform import Foundation -#if canImport(Darwin) - import Darwin -#else - import Glibc -#endif - package struct ProcessOutput: Equatable, Sendable { package var stdout: String package var stderr: String @@ -13,6 +8,24 @@ package struct ProcessOutput: Equatable, Sendable { } 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 + ) throws -> ProcessOutput { + let 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", + "GIT_CEILING_DIRECTORIES": directory.deletingLastPathComponent().path, + ] + 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) + } + @discardableResult package static func run( _ executable: String, arguments: [String], workingDirectory: URL? = nil, @@ -31,11 +44,18 @@ package enum ProcessRunner { @discardableResult package static func git( _ arguments: [String], operation: GitError.Operation, source: String, - replacingPaths paths: [URL] = [], inheritingLock descriptor: Int32? = nil + replacingPaths paths: [URL] = [], inheritingLock descriptor: Int32? = nil, + offline: Bool = false, managed: ManagedSourceGit? = nil, managedMirror: URL? = nil ) throws -> ProcessOutput { + if let managed { return try managed.command(arguments, lock: descriptor, in: managedMirror) } var environment = ProcessInfo.processInfo.environment environment["GIT_TERMINAL_PROMPT"] = "0" environment["GCM_INTERACTIVE"] = "never" + if offline { + environment["GIT_NO_LAZY_FETCH"] = "1" + environment["GIT_ALLOW_PROTOCOL"] = "" + environment["GIT_NO_REPLACE_OBJECTS"] = "1" + } let arguments = ["git"] + arguments let output = try execute( "/usr/bin/env", arguments: arguments, workingDirectory: nil, @@ -48,7 +68,71 @@ package enum ProcessRunner { return output } - private static func execute( + /// Runs the system Git from a clean workspace with an allowlisted child environment. + static func isolatedGit( + _ arguments: [String], in workspace: URL, operation: GitError.Operation, source: String, + network: Bool = false, certificateAuthority: URL? = nil + ) throws -> String { + let executable = "/usr/bin/git" + let environment = isolatedGitEnvironment(in: workspace, network: network) + var options = isolatedGitOptions + if let certificateAuthority { + options += ["-c", "http.sslCAInfo=" + certificateAuthority.path] + } + let args = options + arguments + let output = try execute( + executable, arguments: args, workingDirectory: workspace, environment: environment, lock: nil) + guard output.exitCode == 0 else { + throw GitError( + operation: operation, source: source, stderr: output.stderr, + command: [executable] + args, exitCode: output.exitCode, replacingPaths: [workspace]) + } + return output.stdout.trimmingCharacters(in: .newlines) + } + + static func isolatedGitEnvironment(in workspace: URL, network: Bool) -> [String: String] { + [ + "PATH": "/usr/bin:/bin", + "HOME": workspace.path, + "XDG_CONFIG_HOME": workspace.path, + "CURL_HOME": workspace.path, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": "/dev/null", + "GIT_TERMINAL_PROMPT": "0", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_ALLOW_PROTOCOL": network ? "https" : "", + "LC_ALL": "C", + ] + } + + static let isolatedGitOptions = [ + "-c", "core.hooksPath=/dev/null", + "-c", "credential.helper=", + "-c", "http.extraHeader=", + "-c", "http.proxy=", + "-c", "http.followRedirects=false", + "-c", "http.sslVerify=true", + "-c", "http.lowSpeedLimit=1", + "-c", "http.lowSpeedTime=30", + "-c", "fetch.fsckObjects=true", + "-c", "transfer.fsckObjects=true", + "-c", "gc.auto=0", + "-c", "maintenance.auto=false", + "-c", "core.fsync=objects,reference,pack-metadata", + "-c", "core.fsyncMethod=fsync", + ] + + static func unpackGitArchive(_ archive: URL, into directory: URL) throws { + let output = try execute( + "/usr/bin/tar", arguments: ["-xf", archive.path, "-C", directory.path], + workingDirectory: directory, environment: ["PATH": "/usr/bin:/bin"], lock: nil) + guard output.exitCode == 0 else { + throw CoreError.invalidSource("could not extract Git archive") + } + } + + static func execute( _ executable: String, arguments: [String], workingDirectory: URL?, environment: [String: String], lock: Int32? ) throws -> ProcessOutput { @@ -106,21 +190,6 @@ package enum ProcessRunner { // Capture stdin before pipes can reuse a closed standard descriptor. A lock // occupying stdin is internal state, not input for the child. let inputIsOpen = lock != STDIN_FILENO && fcntl(STDIN_FILENO, F_GETFD) >= 0 - var actions: posix_spawn_file_actions_t? - try check(posix_spawn_file_actions_init(&actions)) - defer { posix_spawn_file_actions_destroy(&actions) } - var attributes: posix_spawnattr_t? - try check(posix_spawnattr_init(&attributes)) - defer { posix_spawnattr_destroy(&attributes) } - try check(posix_spawnattr_setflags(&attributes, Int16(POSIX_SPAWN_CLOEXEC_DEFAULT))) - if inputIsOpen { - try check(posix_spawn_file_actions_addinherit_np(&actions, STDIN_FILENO)) - } else { - try check(posix_spawn_file_actions_addopen(&actions, STDIN_FILENO, "/dev/null", O_RDONLY, 0)) - } - if let workingDirectory { - try check(posix_spawn_file_actions_addchdir_np(&actions, workingDirectory.path)) - } let stdout = Pipe() let stderr = Pipe() defer { @@ -143,10 +212,17 @@ package enum ProcessRunner { defer { close(output) } let error = try duplicate(stderr.fileHandleForWriting.fileDescriptor) defer { close(error) } - try check(posix_spawn_file_actions_addinherit_np(&actions, inheritedLock)) - try check(posix_spawn_file_actions_adddup2(&actions, output, STDOUT_FILENO)) - try check(posix_spawn_file_actions_adddup2(&actions, error, STDERR_FILENO)) - try check(posix_spawn(&pid, executable, &actions, &attributes, argv, environment)) + func launch(_ directory: UnsafePointer?) throws { + try check( + platform_spawn( + &pid, executable, argv, environment, directory, inheritedLock, inputIsOpen, output, + error)) + } + if let workingDirectory { + try workingDirectory.path.withCString { try launch($0) } + } else { + try launch(nil) + } }() stdout.fileHandleForWriting.closeFile() stderr.fileHandleForWriting.closeFile() diff --git a/Sources/AgentsCore/ReadDependency.swift b/Sources/AgentsCore/ReadDependency.swift new file mode 100644 index 0000000..fc557cd --- /dev/null +++ b/Sources/AgentsCore/ReadDependency.swift @@ -0,0 +1,15 @@ +import Foundation + +/// Producer-owned invalidation interest. Entry dependencies observe the path and its ancestors; +/// subtree dependencies also observe descendants. An independent subtree interest remains valid +/// when an entry dependency names the same path. +public enum ReadDependency: Sendable, Hashable, Codable { + case entry(URL) + case subtree(URL) + + public var url: URL { + switch self { + case .entry(let url), .subtree(let url): url + } + } +} diff --git a/Sources/AgentsCore/ResolvedLedger.swift b/Sources/AgentsCore/ResolvedLedger.swift new file mode 100644 index 0000000..9fbc8af --- /dev/null +++ b/Sources/AgentsCore/ResolvedLedger.swift @@ -0,0 +1,647 @@ +import Foundation + +/// Version 2 of the scope's single resolved file. Arrays preserve contribution and render order. +public struct ResolvedLedger: Codable, Equatable, Sendable { + public var version = 2 + public var sources: [String: LedgerSource] = [:] + public var sourceUses: [LedgerSourceUse] = [] + public var components: [String: LedgerComponent] = [:] + public var occurrences: [LedgerOccurrence] = [] + public var groups: [LedgerGroup] = [] + public var resources: [String: LedgerResource] = [:] + public var deployments: [LedgerDeployment] = [] + public var lowerings: [LockedLowering] = [] + /// Local regional evidence; nil grants no occurrence or container creation rights. + package var nativeAuthorities: [LedgerNativeAuthority]? + /// Digest-keyed non-secret bytes. These are authoritative; materializations are disposable. + public var contentObjects: [String: Data] = [:] + /// Nil represents a scope without installed marketplace packages. + public var marketplacePackages: [MarketplacePin]? + /// Exact releases and contributions for roots authored with marketplace requirements. + public var marketplaceGraph: MarketplaceGraph? + package var pendingDeployment: MarketplacePendingDeploymentRecord? + + /// A reviewed resolution awaiting explicit deployment. The ledger otherwise records deployed state. + public var pendingMarketplaceDeployment: MarketplacePendingDeployment? { pendingDeployment?.info } + + private enum CodingKeys: String, CodingKey { + case version, sources, sourceUses, components, occurrences, groups, resources, deployments + case lowerings, nativeAuthorities, contentObjects, marketplacePackages, marketplaceGraph + case pendingDeployment = "pendingMarketplaceDeployment" + } + + public init() {} +} + +public struct MarketplacePendingDeployment: Codable, Equatable, Sendable { + public let digest: String + /// Nil when the resolution removes the last marketplace root. + public let graph: MarketplaceGraph? +} + +package struct MarketplacePendingDeploymentRecord: Codable, Equatable, Sendable { + private indirect enum Snapshot: Equatable, Sendable { + case ledger(ResolvedLedger) + } + + private let snapshot: Snapshot + private let sharedObjects: [String] + private let deployedDigest: String + package let digest: String + package let declarationDigest: String + + package var info: MarketplacePendingDeployment { + .init(digest: digest, graph: storedLedger.marketplaceGraph) + } + + var storedLedger: ResolvedLedger { + switch snapshot { + case .ledger(let ledger): ledger + } + } + + package init( + ledger: ResolvedLedger, deployed: ResolvedLedger, declarationDigest: String + ) throws { + var stored = ledger + sharedObjects = ledger.contentObjects.keys.filter { deployed.contentObjects[$0] != nil } + .sorted() + for id in sharedObjects { stored.contentObjects.removeValue(forKey: id) } + snapshot = .ledger(stored) + deployedDigest = try Self.digest(of: deployed) + digest = try ResolvedLedgerCodec.digest(ledger) + self.declarationDigest = declarationDigest + } + + private enum CodingKeys: String, CodingKey { + case ledger, sharedObjects, deployedDigest, digest, declarationDigest + } + + package init(from decoder: any Decoder) throws { + let fields = try decoder.container(keyedBy: CodingKeys.self) + snapshot = .ledger(try fields.decode(ResolvedLedger.self, forKey: .ledger)) + sharedObjects = try fields.decode([String].self, forKey: .sharedObjects) + deployedDigest = try fields.decode(String.self, forKey: .deployedDigest) + digest = try fields.decode(String.self, forKey: .digest) + declarationDigest = try fields.decode(String.self, forKey: .declarationDigest) + } + + package func encode(to encoder: any Encoder) throws { + var fields = encoder.container(keyedBy: CodingKeys.self) + try fields.encode(storedLedger, forKey: .ledger) + try fields.encode(sharedObjects, forKey: .sharedObjects) + try fields.encode(deployedDigest, forKey: .deployedDigest) + try fields.encode(digest, forKey: .digest) + try fields.encode(declarationDigest, forKey: .declarationDigest) + } + + package func desired(in deployed: ResolvedLedger) throws -> ResolvedLedger { + var ledger = storedLedger + for id in sharedObjects { + guard ledger.contentObjects[id] == nil, let bytes = deployed.contentObjects[id] else { + throw CoreError.invalidState("invalid shared object in pending marketplace deployment") + } + ledger.contentObjects[id] = bytes + } + return ledger + } + + func validate(in deployed: ResolvedLedger) throws { + let ledger = try desired(in: deployed) + guard ledger.pendingDeployment == nil, ledger.nativeAuthorities == nil, + try deployedDigest == Self.digest(of: deployed), + try ResolvedLedgerCodec.digest(ledger) == digest + else { throw CoreError.invalidState("invalid pending marketplace deployment") } + try StateValidation.digest(declarationDigest) + try ledger.validate() + } + + private static func digest(of deployed: ResolvedLedger) throws -> String { + var deployed = deployed + deployed.pendingDeployment = nil + return try ResolvedLedgerCodec.digest(deployed) + } +} + +public struct LedgerSource: Codable, Equatable, Sendable { + public var kind: SourceKind + public var transport: String? + public var location: LedgerLocation? + public var revision: String + public var version: String? + public var container: String? + public var namespace: String? + public var archive: SourceArchiveEvidence? + /// Sources recorded by the content-addressed producer for an imported bundle member. + public var bundleSources: [PortableSourceEvidence]? + package var bundlePackageName: String? + + public init( + kind: SourceKind, transport: String? = nil, location: LedgerLocation? = nil, revision: String, + version: String? = nil, container: String? = nil, namespace: String? = nil, + bundleSources: [PortableSourceEvidence]? = nil, archive: SourceArchiveEvidence? = nil + ) { + self.kind = kind + self.transport = transport + self.location = location + self.revision = revision + self.version = version + self.container = container + self.namespace = namespace + self.archive = archive + self.bundleSources = bundleSources + bundlePackageName = nil + } +} + +public struct LedgerSourceUse: Codable, Equatable, Sendable { + public var source: String + public var root: String + public var requirement: SourceRequirement? + package var organizationRequirements: [SourceRequirement]? + + public static func == (lhs: Self, rhs: Self) -> Bool { + lhs.source == rhs.source && lhs.root == rhs.root + && ledgerRequirementsEqual(lhs.requirement, rhs.requirement) + && lhs.organizationRequirements == rhs.organizationRequirements + } + + public init(source: String, root: String, requirement: SourceRequirement? = nil) { + self.source = source + self.root = root + self.requirement = requirement + organizationRequirements = nil + } + + package init( + source: String, root: String, requirement: SourceRequirement?, + organizationRequirements: [SourceRequirement]? + ) { + self.init(source: source, root: root, requirement: requirement) + self.organizationRequirements = organizationRequirements + } +} + +/// Physical URLs are supplied by the caller. Absolute authored locations retain their meaning. +public struct LedgerLocation: Codable, Equatable, Hashable, Sendable { + public enum Kind: String, Codable, Sendable { case registered, authoringRelative, absolute } + public var kind: Kind + public var root: String? + public var path: String + + package func resolve(roots: [String: URL]) throws -> URL { + try validate() + if kind == .absolute { return URL(fileURLWithPath: path) } + guard let root, let directory = roots[root] else { + throw CoreError.invalidState("missing registered ledger root") + } + if kind == .authoringRelative { + return directory.appendingPathComponent(path).standardizedFileURL + } + return try PathSafety.resolvedChild(base: directory, subpath: path) + } + + package func validate() throws { + switch kind { + case .absolute: + guard root == nil, path.hasPrefix("/"), !path.contains("\0"), !path.contains("\\") else { + throw CoreError.invalidState("invalid absolute ledger location") + } + case .authoringRelative: + guard let root, !root.isEmpty, !path.isEmpty, !path.hasPrefix("/"), + !path.hasPrefix("~"), !path.contains("\0"), !path.contains("\\"), + path.split(separator: "/", omittingEmptySubsequences: false).allSatisfy({ !$0.isEmpty }) + else { + throw CoreError.invalidState("invalid authoring-relative location") + } + case .registered: + guard let root, !root.isEmpty else { throw CoreError.invalidState("missing ledger root") } + try ledgerPath(path) + } + } + + public init(kind: Kind, root: String? = nil, path: String) { + self.kind = kind + self.root = root + self.path = path + } + + package var ledgerValue: LedgerValue { + var fields: [String: LedgerValue] = ["kind": .init(kind.rawValue), "path": .init(path)] + fields["root"] = root.map { .init($0) } + return .init(object: fields) + } + + package init(ledgerValue value: LedgerValue) throws { + try value.validate() + guard let fields = value.object, + Set(fields.keys).isSubset(of: ["kind", "root", "path"]), + let kind = fields["kind"], kind.kind == .string, + let parsed = kind.text.flatMap(Kind.init(rawValue:)), + let path = fields["path"], path.kind == .string, let text = path.text, + fields["root"] == nil || fields["root"]?.kind == .string + else { throw CoreError.invalidState("invalid ledger location payload") } + self.init(kind: parsed, root: fields["root"]?.text, path: text) + try validate() + } + + /// Consumer operations read current bytes only after validating lexical and real containment. + /// Frozen replay consumes resource records and never calls this operation. + package func readContainedFile(roots: [String: URL]) throws -> Data { + guard kind == .registered, let root, let base = roots[root] else { + throw CoreError.invalidState("current file needs a registered root") + } + let file = try resolve(roots: roots) + guard + PathSafety.isContained( + file.resolvingSymlinksInPath(), in: base.resolvingSymlinksInPath()) + else { throw CoreError.unsafePath("current file escapes its registered root") } + return try FileSystem.read(at: file) + } +} + +/// A closed tagged value vocabulary, independent of Swift's synthesized enum representation. +public struct LedgerValue: Codable, Equatable, Sendable { + public enum Kind: String, Codable, Sendable { + case string, integer, decimal, boolean, null, array, object, literal, environment, secret + } + public var kind: Kind + public var text: String? + public var integer: Int? + public var boolean: Bool? + public var array: [LedgerValue]? + public var object: [String: LedgerValue]? + + public init(_ text: String, kind: Kind = .string) { + self.kind = kind + self.text = text + } + public init(integer: Int) { + kind = .integer + self.integer = integer + } + public init(boolean: Bool) { + kind = .boolean + self.boolean = boolean + } + public init(array: [LedgerValue]) { + kind = .array + self.array = array + } + public init(object: [String: LedgerValue]) { + kind = .object + self.object = object + } + public init() { kind = .null } + + package func validate() throws { + let fields = [text != nil, integer != nil, boolean != nil, array != nil, object != nil] + let expected: Int? + switch kind { + case .string, .decimal, .literal, .environment, .secret: expected = 0 + case .integer: expected = 1 + case .boolean: expected = 2 + case .array: expected = 3 + case .object: expected = 4 + case .null: expected = nil + } + guard fields.enumerated().allSatisfy({ $0.element == ($0.offset == expected) }) else { + throw CoreError.invalidState("invalid tagged ledger value") + } + for value in array ?? [] { try value.validate() } + for value in object?.values ?? [String: LedgerValue]().values { try value.validate() } + } +} + +public struct LedgerCondition: Codable, Equatable, Sendable { + public var agents: [AgentID]? + public var scopes: [InstallScope]? + public var platforms: [String]? + + public init(_ condition: DeclarationCondition) { + agents = condition.agents + scopes = condition.scopes + platforms = condition.platforms?.map(\.rawValue) + } +} + +public struct LedgerComponent: Codable, Equatable, Sendable { + public var declaringSource: String + public var source: String + public var root: String + public var group: String? + public var containerRoot: String? + public var kind: String + public var name: String + public var revision: String? + public var version: String? + public var mcpRegistry: MCPRegistryEvidence? + public var payload: LedgerValue + public var conditions: [LedgerCondition] + public var recipients: [AgentID] + public var chatGPT: Bool + public var resources: [String] + + public init( + declaringSource: String, source: String, root: String, group: String? = nil, + containerRoot: String? = nil, kind: String, + name: String, revision: String? = nil, version: String? = nil, payload: LedgerValue, + conditions: [LedgerCondition], recipients: [AgentID], chatGPT: Bool, resources: [String], + mcpRegistry: MCPRegistryEvidence? = nil + ) { + self.source = source + self.root = root + self.declaringSource = declaringSource + self.group = group + self.containerRoot = containerRoot + self.kind = kind + self.name = name + self.revision = revision + self.version = version + self.mcpRegistry = mcpRegistry + self.payload = payload + self.conditions = conditions + self.recipients = recipients + self.chatGPT = chatGPT + self.resources = resources + } +} + +public struct LedgerOccurrence: Codable, Equatable, Sendable { + public var declaringSource: String + public var manifestPath: String + public var id: Int + public var component: String + public var reference: Int? + public var dependencies: [String] + public var condition: LedgerCondition + public var recipients: [AgentID] + public var consumerEditable: Bool + package var pluginMember: LedgerPluginMember? + package var input: LedgerInputProvenance? + package var pluginExpansion: LedgerPluginExpansion? + + public init( + declaringSource: String, manifestPath: String, id: Int, component: String, + reference: Int? = nil, dependencies: [String], condition: LedgerCondition, + recipients: [AgentID], consumerEditable: Bool + ) { + self.init( + declaringSource: declaringSource, manifestPath: manifestPath, id: id, component: component, + reference: reference, dependencies: dependencies, condition: condition, + recipients: recipients, consumerEditable: consumerEditable, pluginMember: nil, + input: nil, pluginExpansion: nil) + } + + package init( + declaringSource: String, manifestPath: String, id: Int, component: String, + reference: Int? = nil, dependencies: [String], condition: LedgerCondition, + recipients: [AgentID], consumerEditable: Bool, pluginMember: LedgerPluginMember?, + input: LedgerInputProvenance?, pluginExpansion: LedgerPluginExpansion? + ) { + self.id = id + self.declaringSource = declaringSource + self.manifestPath = manifestPath + self.component = component + self.reference = reference + self.dependencies = dependencies + self.condition = condition + self.recipients = recipients + self.consumerEditable = consumerEditable + self.pluginMember = pluginMember + self.input = input + self.pluginExpansion = pluginExpansion + } +} + +/// Native conversion provenance; diagnostic pointers never participate in logical identity. +package struct LedgerInputProvenance: Codable, Equatable, Sendable { + package var format: String + package var adapterVersion: String + package var pointer: String? + package init(format: String, adapterVersion: String, pointer: String? = nil) { + self.format = format + self.adapterVersion = adapterVersion + self.pointer = pointer + } +} + +package struct LedgerPluginMember: Codable, Equatable, Sendable { + package var parent: Int + package var kind: String + package var name: String + package init(parent: Int, kind: String, name: String) { + self.parent = parent + self.kind = kind + self.name = name + } + + package static func == (lhs: Self, rhs: Self) -> Bool { + lhs.parent == rhs.parent && lhs.kind.utf8.elementsEqual(rhs.kind.utf8) + && lhs.name.utf8.elementsEqual(rhs.name.utf8) + } +} + +/// Complete ordered direct-member closure, including a successfully expanded empty selection. +package struct LedgerPluginExpansion: Codable, Equatable, Sendable { + package var source: String + package var root: String + package var containerRoot: String + package var document: String + package var input: LedgerInputProvenance + package var children: [Int] + package init( + source: String, root: String, containerRoot: String, document: String, + input: LedgerInputProvenance, children: [Int] + ) { + self.source = source + self.root = root + self.containerRoot = containerRoot + self.document = document + self.input = input + self.children = children + } + + package static func == (lhs: Self, rhs: Self) -> Bool { + lhs.source.utf8.elementsEqual(rhs.source.utf8) && lhs.root.utf8.elementsEqual(rhs.root.utf8) + && lhs.containerRoot.utf8.elementsEqual(rhs.containerRoot.utf8) + && lhs.document.utf8.elementsEqual(rhs.document.utf8) + && lhs.input == rhs.input && lhs.children == rhs.children + } +} + +public struct LedgerGroup: Codable, Equatable, Sendable { + public var id: Int + public var parent: Int? + public var source: String + public var root: String + public var name: String + public var requirement: SourceRequirement? + public var manifestHash: String + public var children: [Int] + + public static func == (lhs: Self, rhs: Self) -> Bool { + lhs.id == rhs.id && lhs.parent == rhs.parent && lhs.source == rhs.source && lhs.root == rhs.root + && lhs.name == rhs.name && lhs.manifestHash == rhs.manifestHash + && lhs.children == rhs.children && ledgerRequirementsEqual(lhs.requirement, rhs.requirement) + } + + public init( + id: Int, parent: Int? = nil, source: String, root: String, name: String, + requirement: SourceRequirement? = nil, manifestHash: String, children: [Int] + ) { + self.id = id + self.parent = parent + self.source = source + self.root = root + self.name = name + self.requirement = requirement + self.manifestHash = manifestHash + self.children = children + } +} + +public struct LedgerEntry: Codable, Equatable, Sendable { + public enum Kind: String, Codable, Sendable { case file, directory, symlink } + public var path: String + public var kind: Kind + public var object: String? + public var link: String? + public var executable: Bool + public var byteCount: Int? + + public init( + path: String, kind: Kind, object: String? = nil, link: String? = nil, executable: Bool, + byteCount: Int? = nil + ) { + self.path = path + self.kind = kind + self.object = object + self.link = link + self.executable = executable + self.byteCount = byteCount + } +} + +public struct LedgerResource: Codable, Equatable, Sendable { + public enum Kind: String, Codable, Sendable { case git, archive, artifact, embedded, liveEdit } + public var kind: Kind + public var source: String + public var path: String + public var hash: String + /// Single files use path "."; directory entries are relative to the selected resource. + public var entries: [LedgerEntry] + public var support: [LedgerEntry] + public var artifact: LockedArtifact? + public var location: LedgerLocation? + + public init( + kind: Kind, source: String, path: String, hash: String, entries: [LedgerEntry], + support: [LedgerEntry] = [], artifact: LockedArtifact? = nil, location: LedgerLocation? = nil + ) { + self.kind = kind + self.source = source + self.path = path + self.hash = hash + self.entries = entries + self.support = support + self.artifact = artifact + self.location = location + } +} + +public struct LedgerDeployment: Codable, Equatable, Sendable { + public enum Ownership: String, Codable, Sendable { case generated, importBlock, ownedValues } + public var id: String + public var target: LedgerLocation + public var route: String + public var owners: [String] + public var recipients: [AgentID] + public var ownership: Ownership + public var expectedHash: String + public var created: Bool + public var importReference: String? + public var headingOffset: Int? + + public init( + id: String, target: LedgerLocation, route: String, owners: [String], recipients: [AgentID], + ownership: Ownership, expectedHash: String, created: Bool, importReference: String? = nil, + headingOffset: Int? = nil + ) { + self.id = id + self.target = target + self.route = route + self.owners = owners + self.recipients = recipients + self.ownership = ownership + self.expectedHash = expectedHash + self.created = created + self.importReference = importReference + self.headingOffset = headingOffset + } +} + +/// Format identity fixes schema, ordering, paths, resource mappings and serialization semantics. +public struct LockedLowering: Codable, Equatable, Sendable { + package static let instructionCopyFormat = "agents/instruction-copy@1" + + public var id: String + public var format: String + public var inputs: [String] + public var resources: [String] + public var deployments: [String] + public var layout: LedgerValue + public var platform: String + public var artifacts: [LedgerArtifactDigest] + + package var instructionCopyRecipient: InstructionRecipient? { + guard format == Self.instructionCopyFormat, + let raw = layout.object?["recipient"]?.text, + let recipient = InstructionRecipient(rawValue: raw), recipient.localAgent == nil + else { return nil } + return recipient + } + + public init( + id: String, format: String, inputs: [String], resources: [String], deployments: [String], + layout: LedgerValue, platform: String, artifacts: [LedgerArtifactDigest] + ) { + self.id = id + self.format = format + self.inputs = inputs + self.resources = resources + self.deployments = deployments + self.layout = layout + self.platform = platform + self.artifacts = artifacts + } +} + +public struct LedgerArtifactDigest: Codable, Equatable, Sendable { + public enum Kind: String, Codable, Sendable { case file, tree, ownedValues, registration, link } + public var name: String + public var kind: Kind + public var hash: String + + public init(name: String, kind: Kind, hash: String) { + self.name = name + self.kind = kind + self.hash = hash + } +} + +package func ledgerPath(_ path: String) throws { + guard !path.hasPrefix("/"), !path.hasPrefix("~"), + try PathSafety.sanitizeSubpath(path) == path + else { + throw CoreError.invalidState("noncanonical ledger path") + } +} + +private func ledgerRequirementsEqual(_ lhs: SourceRequirement?, _ rhs: SourceRequirement?) -> Bool { + switch (lhs, rhs) { + case (nil, nil): true + case (.some(let left), .some(let right)): left == right || left.declarationEquivalent(to: right) + default: false + } +} diff --git a/Sources/AgentsCore/ResolvedLedgerCodec.swift b/Sources/AgentsCore/ResolvedLedgerCodec.swift new file mode 100644 index 0000000..4f0f5cc --- /dev/null +++ b/Sources/AgentsCore/ResolvedLedgerCodec.swift @@ -0,0 +1,245 @@ +import Foundation + +package enum ResolvedLedgerCodec { + package static func decode(_ data: Data, limits: LedgerLimits) throws -> ResolvedLedger { + try LedgerAdmission.check(data, limits: limits) + let ledger = try JSONDecoder().decode(ResolvedLedger.self, from: data) + try checkModel(ledger, limits: limits) + try ledger.validate() + guard ledger.resources.values.reduce(0, { $0 + $1.entries.count }) <= limits.entries else { + throw CoreError.invalidState("ledger entry budget") + } + // Admission bounds these allocations. Comparing against the wire shape also refuses fields + // a Codable decoder would discard, including unknown fields whose value is null. + let input = try JSONSerialization.jsonObject(with: data) + let encoded = try JSONSerialization.jsonObject(with: bytes(ledger)) + try fields(input, encoded, shape: .ledger) + return ledger + } + + package static func encode(_ ledger: ResolvedLedger, limits: LedgerLimits) throws -> Data { + try checkModel(ledger, limits: limits) + try ledger.validate() + let result = try bytes(ledger) + _ = try decode(result, limits: limits) + return result + } + + /// Nil means the caller must retain the original bytes, including their layout. + package static func replacement( + _ ledger: ResolvedLedger, existing: Data?, limits: LedgerLimits + ) throws -> Data? { + try checkModel(ledger, limits: limits) + try ledger.validate() + if let existing { + let original = try decode(existing, limits: limits) + try LedgerAdmission.check(bytes(ledger), limits: limits) + var comparison = ledger + for index in 0.. SourceRequirement? { + guard let requirement, let original, requirement.isVersionRequirement, + requirement.declarationEquivalent(to: original) + else { return requirement } + return original + } + + package static func checkModel(_ ledger: ResolvedLedger, limits: LedgerLimits) throws { + if let pending = ledger.pendingDeployment { + guard pending.storedLedger.pendingDeployment == nil else { + throw CoreError.invalidState("nested pending marketplace deployment") + } + try checkModel(pending.desired(in: ledger), limits: limits) + } + var bytes = 0 + for object in ledger.contentObjects.values { + guard object.count <= limits.objectBytes - bytes else { + throw CoreError.invalidState("ledger content byte budget") + } + bytes += object.count + } + var entries = 0 + var expanded = 0 + for resource in ledger.resources.values { + guard resource.entries.count + resource.support.count <= limits.entries - entries else { + throw CoreError.invalidState("ledger entry budget") + } + entries += resource.entries.count + resource.support.count + for entry in resource.entries + resource.support where entry.kind == .file { + guard let count = entry.byteCount, count >= 0, count <= limits.resourceBytes - expanded + else { + throw CoreError.invalidState("ledger expanded resource budget") + } + expanded += count + } + } + var pending = + ledger.components.values.map { ($0.payload, 0) } + + ledger.lowerings.map { ($0.layout, 0) } + var nodes = ledger.occurrences.count + ledger.groups.count + let ordered = ledger.occurrences.sorted { $0.id < $1.id } + var pluginDepth: [Int: Int] = [:] + for occurrence in ordered { + if let member = occurrence.pluginMember { + let depth = (pluginDepth[member.parent] ?? 0) + 1 + guard depth < limits.depth else { + throw CoreError.invalidState("ledger plugin depth budget") + } + pluginDepth[occurrence.id] = depth + } + nodes += occurrence.pluginExpansion?.children.count ?? 0 + guard nodes <= limits.nodes else { throw CoreError.invalidState("ledger relation budget") } + } + for authority in ledger.nativeAuthorities ?? [] { + func charge(_ count: Int) throws { + guard count <= limits.nodes - nodes else { + throw CoreError.invalidState("ledger authority budget") + } + nodes += count + } + try charge(1) + for (deployments, path) in authority.regions.map({ ($0.deployments, $0.path) }) + + authority.createdContainers.map({ ($0.deployments, $0.path) }) + { + guard path.count < limits.depth else { + throw CoreError.invalidState("ledger native path depth budget") + } + try charge(1) + try charge(deployments.count) + try charge(path.count) + for step in path { + if case .position = step { try charge(1) } + } + } + } + while let (value, depth) = pending.popLast() { + nodes += 1 + guard depth < limits.depth / 2, nodes <= limits.nodes else { + throw CoreError.invalidState("ledger value budget") + } + pending += (value.array ?? []).map { ($0, depth + 1) } + pending += (value.object?.values ?? [String: LedgerValue]().values).map { ($0, depth + 1) } + } + } + + package static func digest(_ value: T) throws -> String { + "sha256:" + FileHash.sha256Hex(data: try bytes(value)) + } + + package static func bytes(_ value: T) throws -> Data { + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes] + var bytes = try encoder.encode(value) + bytes.append(10) + return bytes + } + + /// Nullable members belong to their wire record, not to a spelling used elsewhere in JSON. + private indirect enum WireShape { + case ledger, pendingDeployment, source, location, sourceUse, component, condition, occurrence + case group + case resource, entry, deployment, lowering, value, artifact, requirement, scalar + case pluginMember, input, pluginExpansion + case nativeAuthority, nativeRegion, nativeContainer, nativeStep, nativeEvidence + case map(WireShape) + case list(WireShape) + + var nullable: Set { + switch self { + case .ledger: + [ + "nativeAuthorities", "marketplacePackages", "marketplaceGraph", + "pendingMarketplaceDeployment", + ] + case .source: ["transport", "location", "version", "container", "namespace"] + case .location: ["root"] + case .sourceUse: ["requirement"] + case .requirement: ["to"] + case .component: ["group", "revision", "version", "containerRoot"] + case .condition: ["agents", "scopes", "platforms"] + case .occurrence: ["reference", "pluginMember", "input", "pluginExpansion"] + case .input: ["pointer"] + case .group: ["parent", "requirement"] + case .resource: ["artifact", "location"] + case .entry: ["object", "link", "byteCount"] + case .deployment: ["importReference", "headingOffset"] + case .value: ["text", "integer", "boolean", "array", "object"] + case .artifact: ["files"] + default: [] + } + } + + func member(_ key: String) -> Self { + switch (self, key) { + case (.ledger, "pendingMarketplaceDeployment"): .pendingDeployment + case (.pendingDeployment, "ledger"): .ledger + case (.ledger, "nativeAuthorities"): .list(.nativeAuthority) + case (.nativeAuthority, "target"): .location + case (.nativeAuthority, "regions"): .list(.nativeRegion) + case (.nativeAuthority, "createdContainers"): .list(.nativeContainer) + case (.nativeRegion, "path"), (.nativeContainer, "path"): .list(.nativeStep) + case (.nativeStep, "evidence"): .nativeEvidence + case (.ledger, "sources"): .map(.source) + case (.ledger, "sourceUses"): .list(.sourceUse) + case (.ledger, "components"): .map(.component) + case (.ledger, "occurrences"): .list(.occurrence) + case (.ledger, "groups"): .list(.group) + case (.ledger, "resources"): .map(.resource) + case (.ledger, "deployments"): .list(.deployment) + case (.ledger, "lowerings"): .list(.lowering) + case (.source, "location"), (.resource, "location"), (.deployment, "target"): .location + case (.sourceUse, "requirement"), (.group, "requirement"): .requirement + case (.component, "payload"), (.lowering, "layout"): .value + case (.component, "conditions"): .list(.condition) + case (.occurrence, "condition"): .condition + case (.occurrence, "pluginMember"): .pluginMember + case (.occurrence, "input"), (.pluginExpansion, "input"): .input + case (.occurrence, "pluginExpansion"): .pluginExpansion + case (.resource, "entries"), (.resource, "support"): .list(.entry) + case (.resource, "artifact"): .artifact + case (.value, "array"): .list(.value) + case (.value, "object"): .map(.value) + case (.map(let element), _): element + default: .scalar + } + } + + var element: Self { + if case .list(let element) = self { return element } + return .scalar + } + } + + private static func fields(_ input: Any, _ encoded: Any, shape: WireShape) throws { + if let input = input as? [String: Any], let encoded = encoded as? [String: Any] { + for (key, value) in input { + guard let counterpart = encoded[key] else { + if value is NSNull, shape.nullable.contains(key) { continue } + throw CoreError.invalidState("unknown ledger field") + } + try fields(value, counterpart, shape: shape.member(key)) + } + } else if let input = input as? [Any], let encoded = encoded as? [Any] { + guard input.count == encoded.count else { throw CoreError.invalidState("ledger array shape") } + for (value, counterpart) in zip(input, encoded) { + try fields(value, counterpart, shape: shape.element) + } + } + } +} diff --git a/Sources/AgentsCore/ResolvedState.swift b/Sources/AgentsCore/ResolvedState.swift index 28299ef..7de8947 100644 --- a/Sources/AgentsCore/ResolvedState.swift +++ b/Sources/AgentsCore/ResolvedState.swift @@ -11,9 +11,30 @@ public struct LockedSource: Codable, Equatable, Sendable { ) { self.kind = kind self.url = url - self.requirement = requirement + self.requirement = requirement?.canonical self.path = path } + + /// Location spelling is not identity; range spelling is not selection intent. + public static func == (lhs: LockedSource, rhs: LockedSource) -> Bool { + guard lhs.kind == rhs.kind, lhs.discoveryRoot == rhs.discoveryRoot else { return false } + if lhs.kind == .git, let left = lhs.url, let right = rhs.url { + let a = try? SourceDeclaration(kind: .git, location: left).transportIdentity() + let b = try? SourceDeclaration(kind: .git, location: right).transportIdentity() + guard a != nil && b != nil ? a == b : left == right else { return false } + } else if lhs.url != rhs.url { + return false + } + switch (lhs.requirement, rhs.requirement) { + case (nil, nil): return true + case (.some(let a), .some(let b)): return a == b || a.declarationEquivalent(to: b) + default: return false + } + } + + private var discoveryRoot: String { + (try? PathSafety.sanitizeSubpath(path ?? ".")) ?? (path ?? ".") + } } public struct ArtifactFile: Codable, Equatable, Sendable { @@ -163,7 +184,7 @@ public struct LockedInstructions: Codable, Equatable, Sendable { } } -/// Version 1 of agents.resolved. Every item carries its independent immutable pin. +/// Skill/instruction inventory projection. The persisted ledger owns pins and deployments. public struct ResolvedState: Codable, Equatable, Sendable { public var version: Int public var sources: [String: LockedSource] @@ -284,6 +305,10 @@ public struct ResolvedState: Codable, Equatable, Sendable { package var normalized: ResolvedState { var result = self + for id in result.sources.keys { + let requirement = result.sources[id]?.requirement?.canonical + result.sources[id]?.requirement = requirement + } for name in result.skills.keys { result.skills[name]?.artifact?.files?.sort { $0.path < $1.path } } diff --git a/Sources/AgentsCore/RetentionReferences.swift b/Sources/AgentsCore/RetentionReferences.swift new file mode 100644 index 0000000..5f20a5c --- /dev/null +++ b/Sources/AgentsCore/RetentionReferences.swift @@ -0,0 +1,71 @@ +import Foundation + +/// Validated live cache references. Publication owns when a reduced set becomes authoritative. +package struct RetentionReferences: Sendable { + package struct Git: Hashable, Sendable { + package var source: String + package var revision: String + } + var archives: Set = [] + package var git: Set = [] + package var artifacts: Set = [] + package var live: [URL] = [] + package var sourceLocations: [String: String] = [:] + + package init() {} + + package init(ledger: ResolvedLedger, roots: [String: URL]) throws { + try ledger.validate() + 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 { + guard source.container == nil else { continue } + if let archive = source.archive, let transport = source.transport { + archives.insert(.init(transport: transport, archive: archive)) + continue + } + guard source.kind != .wellKnown, SourceCache.isObjectID(source.revision) else { continue } + let location: String + let identity: String + if let transport = source.transport { + location = transport + identity = try SourceDeclaration(kind: .git, location: transport).identity( + environment: RuntimeEnvironment()) + } else if let authored = source.location { + location = try authored.resolve(roots: roots).path + identity = "local:" + location + } else { + throw CoreError.invalidState("missing retained source coordinates") + } + git.insert(.init(source: identity, revision: source.revision)) + sourceLocations[identity] = location + } + 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()) + } + } + } + + package mutating func include(watch: WatchState) throws { + try watch.validate() + for (id, source) in watch.sources { + if sourceLocations[id] == nil { + sourceLocations[id] = id.hasPrefix("local:") ? String(id.dropFirst(6)) : id + } + switch source.seen { + case .revision(let revision): git.insert(.init(source: id, revision: revision)) + case .artifacts(let objects): artifacts.formUnion(objects.values) + } + } + } + + private mutating func retain(_ artifact: LockedArtifact) { + artifacts.insert(artifact.digest) + artifacts.formUnion((artifact.files ?? []).map(\.digest)) + } +} diff --git a/Sources/AgentsCore/SourceAccessAddress.swift b/Sources/AgentsCore/SourceAccessAddress.swift new file mode 100644 index 0000000..9544007 --- /dev/null +++ b/Sources/AgentsCore/SourceAccessAddress.swift @@ -0,0 +1,168 @@ +import Foundation + +public enum SourceProvider: String, Sendable, Codable { + case github, gitlab +} + +extension SourceProvider { + static func standard(for authority: SourceAuthority, scheme: String = "https") -> Self? { + guard authority.port == ["https": 443, "ssh": 22, "http": 80][scheme] else { return nil } + switch authority.host { + case "github.com": return .github + case "gitlab.com": return .gitlab + default: return nil + } + } + + func admitsIdentityEndpoint(_ endpoint: URLComponents, authority: SourceAuthority) -> Bool { + guard let destination = try? SourceAuthority(endpoint) else { return false } + if self == .github, authority.host == "github.com", authority.port == 443 { + return destination.host == "api.github.com" && destination.port == 443 + && endpoint.percentEncodedPath == "/user" + } + let path = self == .github ? "/api/v3/user" : "/api/v4/user" + return destination == authority && endpoint.percentEncodedPath == path + } +} + +/// A network authority with an explicit port. An omitted HTTPS port means 443. +public struct SourceAuthority: Hashable, Sendable { + public let host: String + public let port: Int + + public init(host: String, port: Int = 443) throws { + guard (1...65535).contains(port), + host.utf8.allSatisfy({ $0 < 128 }), + let value = URLComponents(string: "https://\(host):\(port)"), + value.port == port, value.path.isEmpty, value.query == nil, + let authority = try SourceOrigin.http(value.string ?? "").identity, + let canonical = URLComponents(string: authority)?.host + else { throw SourceAccessError.invalidConfiguration } + self.host = canonical + self.port = port + } + + init(_ url: URLComponents, defaultPort: Int = 443) throws { + guard let host = url.host else { throw SourceAccessError.invalidRepository } + try self.init(host: host, port: url.port ?? defaultPort) + } + + package var display: String { port == 443 ? host : "\(host):\(port)" } +} + +public struct SourceArchiveMirror: Equatable, Sendable { + public enum Flavor: String, Sendable, Codable { + case github, gitlab, artifactory + } + + public let source: SourceAuthority + public let base: URL + public let flavor: Flavor + public let supportsQualifiedGitLabRefs: Bool + public let requiresExactArchiveBytes: Bool + package let authority: SourceAuthority + package let baseSegments: [String] + + public init( + source: SourceAuthority, base: URL, flavor: Flavor, + supportsQualifiedGitLabRefs: Bool = false, requiresExactArchiveBytes: Bool = false + ) throws { + let parts = try SourceURL.https(base) + guard parts.query == nil else { throw SourceAccessError.invalidConfiguration } + authority = try SourceAuthority(parts) + baseSegments = try SourceURL.segments(parts.percentEncodedPath, allowingRoot: true) + self.source = source + self.base = base + self.flavor = flavor + self.supportsQualifiedGitLabRefs = supportsQualifiedGitLabRefs + self.requiresExactArchiveBytes = requiresExactArchiveBytes + } +} + +public enum SourceAccessError: Error, Sendable, Equatable, LocalizedError { + case invalidConfiguration, invalidRepository, ambiguousRoute, egressDenied + case unsupportedMirror, discoveryUnavailable, historyUnavailable, routeChanged + case ambiguousCredential, credentialUnavailable, exportRefused + case requestFailed, invalidArchive, archiveChanged, recoveryUnavailable + + public var errorDescription: String? { + switch self { + case .invalidConfiguration: "The trusted package source access configuration is invalid." + case .invalidRepository: "A trusted source route requires a valid repository URL." + case .ambiguousRoute: "Multiple archive mirrors are configured for this source authority." + case .egressDenied: "Current egress policy does not admit this package source route." + case .unsupportedMirror: "This archive mirror flavor has no supported request mapper." + case .discoveryUnavailable: + "This archive route cannot discover or disambiguate the requested ref." + case .historyUnavailable: "This operation requires Git history." + case .routeChanged: "The locked source route differs from the current source configuration." + case .ambiguousCredential: "More than one credential binding matches this source route." + case .credentialUnavailable: "The selected source credential is unavailable." + case .exportRefused: "Credential export requires an exportable binding and pipe-backed stdout." + case .requestFailed: "The package source HTTPS request failed." + case .invalidArchive: "The source archive failed verification." + case .archiveChanged: "The source archive differs from its locked content authority." + case .recoveryUnavailable: "Verified private source recovery is unavailable." + } + } +} + +enum SourceURL { + static func https(_ url: URL) throws -> URLComponents { + guard let value = URLComponents(url: url, resolvingAgainstBaseURL: false), + value.scheme == "https", value.user == nil, value.password == nil, + value.fragment == nil, (try? SourceOrigin.http(url.absoluteString)) != nil + else { throw SourceAccessError.invalidConfiguration } + return value + } + + static func segments(_ path: String, allowingRoot: Bool = false) throws -> [String] { + guard path.isEmpty || path.hasPrefix("/") else { throw SourceAccessError.invalidRepository } + var input = path.dropFirst() + if input.hasSuffix("/") { input.removeLast() } + if input.isEmpty { + guard allowingRoot else { throw SourceAccessError.invalidRepository } + return [] + } + return try input.split(separator: "/", omittingEmptySubsequences: false).map { + guard let segment = $0.removingPercentEncoding, safeSegment(segment) else { + throw SourceAccessError.invalidRepository + } + return segment + } + } + + static func credentialPath(_ path: String, direct: Bool) throws -> String { + var segments = try segments(path, allowingRoot: !direct) + if direct, let last = segments.last, last.hasSuffix(".git") { + let name = String(last.dropLast(4)) + guard safeSegment(name) else { throw SourceAccessError.invalidConfiguration } + segments[segments.count - 1] = name + } + return "/" + segments.joined(separator: "/") + } + + static func safeSegment(_ segment: String, literalRef: Bool = false) -> Bool { + func safe(_ value: String) -> Bool { + !value.isEmpty && value != "." && value != ".." + && !value.contains("/") && !value.contains("\\") + && value.unicodeScalars.allSatisfy { $0.value >= 32 && $0.value != 127 } + } + guard safe(segment) else { return false } + guard literalRef else { return !segment.contains("%") } + // Ref text is literal. Also refuse a spelling that decodes to a path escape + // if a reverse proxy decodes the path again. + var value = segment + while let decoded = value.removingPercentEncoding, decoded != value { + guard safe(decoded) else { return false } + value = decoded + } + return true + } + + static func encode(_ value: String) -> String { + let unreserved = CharacterSet( + charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~") + return value.addingPercentEncoding(withAllowedCharacters: unreserved)! + } +} diff --git a/Sources/AgentsCore/SourceAccessConfiguration.swift b/Sources/AgentsCore/SourceAccessConfiguration.swift new file mode 100644 index 0000000..7d6e47c --- /dev/null +++ b/Sources/AgentsCore/SourceAccessConfiguration.swift @@ -0,0 +1,147 @@ +import Foundation + +/// Limits a trusted credential binding to an authority and, optionally, one exact request path. +public struct SourceCredentialBinding: Sendable, CustomReflectable { + public typealias Route = SourceAccessProfile.Credential.Route + public enum Category: String, Sendable, Codable { case supplied, environment, opaque } + + public let route: Route + public let authority: SourceAuthority + public let path: String? + public let category: Category + public let exportable: Bool + let validationEndpoint: URL? + let gitUsername: String + private let resolve: @Sendable () -> String? + + /// The host supplies narrowly scoped bytes. Core does not discover credentials or invoke + /// providers during inspection. A missing value is represented by nil. + public init( + route: Route, authority: SourceAuthority, path: String? = nil, + category: Category = .supplied, available: Bool = true, exportable: Bool = false, + validationEndpoint: URL? = nil, gitUsername: String = "oauth2", + resolve: @escaping @Sendable () -> String? + ) throws { + let canonicalPath = try path.map { try SourceURL.credentialPath($0, direct: route == .direct) } + if let validationEndpoint { + _ = try SourceURL.https(validationEndpoint) + } + guard Self.valid(gitUsername), !gitUsername.isEmpty else { + throw SourceAccessError.invalidConfiguration + } + self.route = route + self.authority = authority + self.path = canonicalPath + self.category = category + self.available = available + self.exportable = exportable && category != .opaque + self.validationEndpoint = validationEndpoint + self.gitUsername = gitUsername + self.resolve = resolve + } + + public let available: Bool + + func value() throws -> String { + guard available, let value = resolve(), Self.valid(value), !value.isEmpty else { + throw SourceAccessError.credentialUnavailable + } + return value + } + + static func valid(_ value: String) -> Bool { + value.utf8.count <= 4096 && value.utf8.allSatisfy { (33...126).contains($0) } + } + + public var customMirror: Mirror { Mirror(self, children: ["category": category]) } +} + +/// Trusted runtime input. Declarations and locks cannot register providers, routes or credentials. +public struct SourceAccessConfiguration: Sendable { + public typealias Egress = SourceAccessProfile.Egress + + private enum UserSettings: Sendable { + case captured(SourceAccessSettingsFile, SourceAccessSettingsFile.Snapshot) + case invalid(any Error) + } + + private var userSettings: UserSettings? + + public let egress: Egress + public let providers: [SourceAuthority: SourceProvider] + public let mirrors: [SourceArchiveMirror] + public let credentials: [SourceCredentialBinding] + + public init( + egress: Egress = .directAllowed, providers: [SourceAuthority: SourceProvider] = [:], + mirrors: [SourceArchiveMirror] = [], credentials: [SourceCredentialBinding] = [] + ) { + self.egress = egress + self.providers = providers + self.mirrors = mirrors + self.credentials = credentials + } + + func provider(for authority: SourceAuthority, scheme: String = "https") -> SourceProvider? { + SourceProvider.standard(for: authority, scheme: scheme) ?? providers[authority] + } + + static func loadUserSettings(home: URL, environment: [String: String]) -> Self { + let file = SourceAccessSettingsFile(homeDirectory: home) + do { + let snapshot = try file.read() + let profile = try file.profile(in: snapshot) + let credentials = try (profile?.credentials ?? []).map { entry in + let value = environment[entry.environmentVariable] + return try SourceCredentialBinding( + route: entry.route, authority: entry.authority, path: entry.path, category: .environment, + available: value.map { !$0.isEmpty && SourceCredentialBinding.valid($0) } ?? false, + exportable: entry.exportable, validationEndpoint: entry.validationEndpoint + ) { value } + } + var access = Self( + egress: profile?.egress ?? .directAllowed, + providers: Dictionary( + uniqueKeysWithValues: (profile?.providers ?? []).map { ($0.authority, $0.provider) }), + mirrors: profile?.mirrors ?? [], credentials: credentials) + access.userSettings = .captured(file, snapshot) + return access + } catch { + var access = Self(egress: .proxyOnly) + access.userSettings = .invalid( + error is OpenFileLimitError + ? error : (error as? SourceAccessSettingsError ?? .unsafeLocation(file.url))) + return access + } + } + + var usesUserSettings: Bool { userSettings != nil } + + package var settingsURL: URL? { + if case .captured(let file, _) = userSettings { return file.url } + return nil + } + + /// Local generation of the admitted profile. This only identifies metadata. + public var settingsFingerprint: String? { + if case .captured(_, let snapshot) = userSettings { return snapshot.fingerprint } + return nil + } + + package func requireCurrentSettings() throws { + switch userSettings { + case nil: return + case .invalid(let error): throw error + case .captured(let file, let snapshot): + guard try file.read() == snapshot else { throw SourceAccessSettingsError.changed(file.url) } + } + } + + package func requireDirectHTTP( + _ url: URL, policy: EffectiveSourcePolicy = .init() + ) throws { + try requireCurrentSettings() + guard egress == .directAllowed else { throw SourceAccessError.egressDenied } + try policy.require(.http(url.absoluteString)) + } +} diff --git a/Sources/AgentsCore/SourceAccessProfile.swift b/Sources/AgentsCore/SourceAccessProfile.swift new file mode 100644 index 0000000..df5c451 --- /dev/null +++ b/Sources/AgentsCore/SourceAccessProfile.swift @@ -0,0 +1,278 @@ +import Foundation +import Yams + +/// User-owned route metadata. A credential entry names one process environment variable. +public struct SourceAccessProfile: Equatable, Sendable { + public enum Egress: String, Sendable { case directAllowed, proxyOnly } + + public struct ProviderRegistration: Equatable, Sendable { + public let authority: SourceAuthority + public let provider: SourceProvider + + public init(authority: SourceAuthority, provider: SourceProvider) { + self.authority = authority + self.provider = provider + } + } + + public struct Credential: Equatable, Sendable { + public enum Route: String, Sendable, Codable { case direct, mirror } + + public let route: Route + public let authority: SourceAuthority + public let path: String? + public let environmentVariable: String + public let exportable: Bool + public let validationEndpoint: URL? + private let matchingPath: String? + + public init( + route: Route, authority: SourceAuthority, path: String? = nil, + environmentVariable: String, exportable: Bool = false, validationEndpoint: URL? = nil + ) throws { + let name = environmentVariable.utf8 + func letterOrUnderscore(_ byte: UInt8) -> Bool { + (65...90).contains(byte) || (97...122).contains(byte) || byte == 95 + } + guard let first = name.first, letterOrUnderscore(first), + name.dropFirst().allSatisfy({ letterOrUnderscore($0) || (48...57).contains($0) }) + else { throw SourceAccessSettingsError.invalidProfile("Invalid environment variable name.") } + if let validationEndpoint { + guard route == .direct, let parts = try? SourceURL.https(validationEndpoint), + parts.query == nil + else { throw SourceAccessSettingsError.invalidProfile("Invalid validationEndpoint.") } + } + self.route = route + self.authority = authority + self.path = path + matchingPath = try path.map { try SourceURL.credentialPath($0, direct: route == .direct) } + self.environmentVariable = environmentVariable + self.exportable = exportable + self.validationEndpoint = validationEndpoint + } + + private struct Slot: Hashable { + let route: Route + let authority: SourceAuthority + let path: Data? + } + + fileprivate static func hasDistinctSlots(_ credentials: [Self]) -> Bool { + Set( + credentials.map { + Slot( + route: $0.route, authority: $0.authority, path: $0.matchingPath.map { Data($0.utf8) }) + } + ).count == credentials.count + } + } + + public let egress: Egress + public let providers: [ProviderRegistration] + public let mirrors: [SourceArchiveMirror] + public let credentials: [Credential] + + public init( + egress: Egress, providers: [ProviderRegistration] = [], mirrors: [SourceArchiveMirror] = [], + credentials: [Credential] = [] + ) throws { + guard Set(providers.map(\.authority)).count == providers.count else { + throw SourceAccessSettingsError.invalidProfile("Duplicate provider authority.") + } + guard Set(mirrors.map(\.source)).count == mirrors.count else { + throw SourceAccessSettingsError.invalidProfile("Duplicate mirror source authority.") + } + guard + mirrors.allSatisfy({ + $0.flavor != .artifactory && (!$0.supportsQualifiedGitLabRefs || $0.flavor == .gitlab) + }) + else { throw SourceAccessSettingsError.invalidProfile("Unsupported mirror flavor or options.") } + let providersByAuthority = Dictionary( + uniqueKeysWithValues: providers.map { ($0.authority, $0.provider) }) + for (authority, provider) in providersByAuthority { + if let standard = SourceProvider.standard(for: authority), standard != provider { + throw SourceAccessSettingsError.invalidProfile( + "Conflicting standard provider registration.") + } + } + for credential in credentials { + guard let endpoint = credential.validationEndpoint else { continue } + let authority = credential.authority + guard + let provider = SourceProvider.standard(for: authority) ?? providersByAuthority[authority], + let parts = try? SourceURL.https(endpoint), + provider.admitsIdentityEndpoint(parts, authority: authority) + else { throw SourceAccessSettingsError.invalidProfile("Unauthorized validationEndpoint.") } + } + guard Credential.hasDistinctSlots(credentials) else { + throw SourceAccessSettingsError.invalidProfile("Duplicate credential binding.") + } + self.egress = egress + self.providers = providers + self.mirrors = mirrors + self.credentials = credentials + } + + static let maximumBytes = 64 * 1024 + + /// Parses one version 1 settings document. Diagnostics exclude YAML values. + public static func parse(_ bytes: Data) throws -> Self { + guard bytes.count <= maximumBytes, let text = String(data: bytes, encoding: .utf8) else { + throw SourceAccessSettingsError.invalidProfile("Expected UTF-8 YAML up to 64 KiB.") + } + let node: Node + do { + guard let root = try Yams.compose(yaml: text) else { + throw SourceAccessSettingsError.invalidProfile("Expected a YAML mapping.") + } + node = root + } catch { + throw SourceAccessSettingsError.invalidProfile("Expected one valid YAML document.") + } + let root = try SettingsFields( + node, + keys: [ + "version", "egress", "providers", "mirrors", + "credentials", + ]) + guard try root.integer("version") == 1 else { + throw SourceAccessSettingsError.invalidProfile("Expected version 1.") + } + return try Self( + egress: root.value("egress", as: Egress.self), + providers: root.items("providers").map { node in + let item = try SettingsFields(node, keys: ["host", "port", "provider"]) + return try ProviderRegistration( + authority: item.authority(), provider: item.value("provider", as: SourceProvider.self)) + }, + mirrors: root.items("mirrors").map { node in + let item = try SettingsFields( + node, + keys: [ + "source", "base", "flavor", "supportsQualifiedGitLabRefs", + "requiresExactArchiveBytes", + ]) + let source = try SettingsFields(item.required("source"), keys: ["host", "port"]) + let authority = try source.authority() + let base = try item.url("base") + let flavor = try item.value("flavor", as: SourceArchiveMirror.Flavor.self) + let qualified = try item.flag("supportsQualifiedGitLabRefs") + let exact = try item.flag("requiresExactArchiveBytes") + do { + return try SourceArchiveMirror( + source: authority, base: base, flavor: flavor, supportsQualifiedGitLabRefs: qualified, + requiresExactArchiveBytes: exact) + } catch { + throw SettingsFields.failure("base") + } + }, + credentials: root.items("credentials").map { node in + let item = try SettingsFields( + node, + keys: [ + "route", "host", "port", "path", "environmentVariable", "exportable", + "validationEndpoint", + ]) + let path = try item.optionalString("path") + let route = try item.value("route", as: Credential.Route.self) + let authority = try item.authority() + let variable = try item.string("environmentVariable") + let exportable = try item.flag("exportable") + let endpoint = try item.fields["validationEndpoint"].map { _ in + try item.url("validationEndpoint") + } + do { + return try Credential( + route: route, authority: authority, path: path, environmentVariable: variable, + exportable: exportable, validationEndpoint: endpoint) + } catch let error as SourceAccessSettingsError { + throw error + } catch { + throw SettingsFields.failure("path") + } + }) + } +} + +private struct SettingsFields { + let fields: [String: Node] + + init(_ node: Node, keys: Set) throws { + guard node.tag == Tag(.map), let mapping = node.mapping else { + throw SourceAccessSettingsError.invalidProfile("Expected a mapping.") + } + var fields: [String: Node] = [:] + for (key, value) in mapping { + guard key.tag == Tag(.str), let name = key.scalar?.string, keys.contains(name), + fields.updateValue(value, forKey: name) == nil + else { throw SourceAccessSettingsError.invalidProfile("Unknown or duplicate field.") } + } + self.fields = fields + } + + static func failure(_ key: String) -> SourceAccessSettingsError { + .invalidProfile("Missing or invalid \(key).") + } + + func required(_ key: String) throws -> Node { + guard let node = fields[key] else { throw Self.failure(key) } + return node + } + + func string(_ key: String) throws -> String { + let node = try required(key) + guard node.tag == Tag(.str), let value = node.scalar?.string, !value.isEmpty else { + throw Self.failure(key) + } + return value + } + + func optionalString(_ key: String) throws -> String? { + try fields[key].map { _ in try string(key) } + } + + func integer(_ key: String) throws -> Int { + let node = try required(key) + guard node.tag == Tag(.int), let text = node.scalar?.string, + text.utf8.allSatisfy({ (48...57).contains($0) }), let value = Int(text) + else { throw Self.failure(key) } + return value + } + + func flag(_ key: String) throws -> Bool { + guard let node = fields[key] else { return false } + guard node.tag == Tag(.bool), let text = node.scalar?.string, let value = Bool(text) else { + throw Self.failure(key) + } + return value + } + + func value(_ key: String, as type: T.Type) throws -> T + where T.RawValue == String { + guard let value = T(rawValue: try string(key)) else { throw Self.failure(key) } + return value + } + + func url(_ key: String) throws -> URL { + guard let url = URL(string: try string(key), encodingInvalidCharacters: false) else { + throw Self.failure(key) + } + return url + } + + func items(_ key: String) throws -> [Node] { + guard let node = fields[key] else { return [] } + guard node.tag == Tag(.seq), let sequence = node.sequence else { throw Self.failure(key) } + return Array(sequence) + } + + func authority() throws -> SourceAuthority { + let host = try string("host") + let port = try fields["port"].map { _ in try integer("port") } ?? 443 + do { + return try SourceAuthority(host: host, port: port) + } catch { + throw Self.failure("host or port") + } + } +} diff --git a/Sources/AgentsCore/SourceAccessSettingsEditor.swift b/Sources/AgentsCore/SourceAccessSettingsEditor.swift new file mode 100644 index 0000000..6c29c0c --- /dev/null +++ b/Sources/AgentsCore/SourceAccessSettingsEditor.swift @@ -0,0 +1,72 @@ +import Foundation + +public enum SourceAccessSettingsError: Error, Equatable, Sendable, LocalizedError { + case invalidProfile(String) + case invalidFile(URL, reason: String) + case unsafeLocation(URL) + case changed(URL) + + public var errorDescription: String? { + switch self { + case .invalidProfile(let reason): + "Invalid source access settings. \(reason)" + case .invalidFile(let url, let reason): + "Invalid source access settings at \(url.path). \(reason)" + case .unsafeLocation(let url): + "Cannot establish user control of source access settings at \(url.path)." + case .changed(let url): + "Source access settings at \(url.path) changed. Reload them and try again." + } + } +} + +/// A validated edit or reset based on one observed generation of the user settings. +public struct SourceAccessSettingsPreview: Sendable { + public let url: URL + public let profile: SourceAccessProfile? + public let hasChanges: Bool + fileprivate let bytes: Data? + fileprivate let original: SourceAccessSettingsFile.Snapshot +} + +/// Opens the operator profile without creating directories. Malformed YAML can be +/// read as bytes and repaired without first admitting it for package operations. +public struct SourceAccessSettingsEditor: Sendable { + public let url: URL + /// Original bytes when within the profile size limit. Inspect distinguishes an + /// oversized profile from a missing file. + public var original: Data? { snapshot.bytes } + private let file: SourceAccessSettingsFile + private let snapshot: SourceAccessSettingsFile.Snapshot + + public static func settingsURL(environment: RuntimeEnvironment = RuntimeEnvironment()) -> URL { + SourceAccessSettingsFile(homeDirectory: environment.homeDirectory).url + } + + public init(environment: RuntimeEnvironment = RuntimeEnvironment()) throws { + let file = SourceAccessSettingsFile(homeDirectory: environment.homeDirectory) + self.file = file + url = file.url + snapshot = try file.read() + } + + public func inspect() throws -> SourceAccessProfile? { + try file.profile(in: snapshot) + } + + /// Validate the proposed YAML. Pass nil to preview a reset to ordinary defaults. + public func preview(_ bytes: Data?) throws -> SourceAccessSettingsPreview { + let profile = try bytes.map(SourceAccessProfile.parse) + return SourceAccessSettingsPreview( + url: url, profile: profile, hasChanges: file.writesChanges(bytes, comparedTo: snapshot), + bytes: bytes, original: snapshot) + } + + /// Atomically publish a preview if its original settings generation is still current. + public func save(_ preview: SourceAccessSettingsPreview) throws { + guard preview.url == url, preview.original == snapshot else { + throw SourceAccessSettingsError.changed(url) + } + try file.save(preview.bytes, replacing: snapshot) + } +} diff --git a/Sources/AgentsCore/SourceAccessSettingsFile.swift b/Sources/AgentsCore/SourceAccessSettingsFile.swift new file mode 100644 index 0000000..7e862dd --- /dev/null +++ b/Sources/AgentsCore/SourceAccessSettingsFile.swift @@ -0,0 +1,172 @@ +import Foundation + +struct SourceAccessSettingsFile: Sendable { + private static let name = "source-access.yaml" + private static let lock = ".source-access.lock" + private let home: URL + private let directory: URL + let url: URL + + init(homeDirectory: URL) { + home = homeDirectory + directory = home.appendingPathComponent(".agents", isDirectory: true) + url = directory.appendingPathComponent(Self.name) + } + + struct Snapshot: Equatable, Sendable { + let bytes: Data? + fileprivate let entry: stat? + fileprivate let ancestry: DirectoryAccessEvidence? + + var exists: Bool { entry != nil } + + var fingerprint: String? { + guard let entry, let bytes else { return nil } + #if os(macOS) + let changed = entry.st_ctimespec + #else + let changed = entry.st_ctim + #endif + let generation = "\(entry.st_dev):\(entry.st_ino):\(changed.tv_sec):\(changed.tv_nsec)\n" + return FileHash.sha256Hex(data: Data(generation.utf8) + bytes) + } + + static let absent = Self(bytes: nil, entry: nil, ancestry: nil) + + static func == (lhs: Self, rhs: Self) -> Bool { + switch (lhs.entry, rhs.entry) { + case (nil, nil): true + case (.some(let first), .some(let second)): + DirectoryHandle.sameGeneration(first, second) && lhs.ancestry == rhs.ancestry + && lhs.bytes == rhs.bytes + default: false + } + } + } + + func read() throws -> Snapshot { + guard let (parent, ancestry) = try openParent(create: false) else { return .absent } + return try read(from: parent, ancestry: ancestry) + } + + func profile(in snapshot: Snapshot) throws -> SourceAccessProfile? { + if snapshot.exists, snapshot.bytes == nil { + throw SourceAccessSettingsError.invalidFile(url, reason: "Expected YAML up to 64 KiB.") + } + do { + return try snapshot.bytes.map(SourceAccessProfile.parse) + } catch SourceAccessSettingsError.invalidProfile(let reason) { + throw SourceAccessSettingsError.invalidFile(url, reason: reason) + } + } + + private func read(from parent: DirectoryHandle, ancestry: DirectoryAccessEvidence) throws + -> Snapshot + { + do { + guard let entry = try parent.info(Self.name) else { return .absent } + guard entry.st_mode & S_IFMT == S_IFREG, entry.st_nlink == 1, + entry.st_uid == geteuid() + else { throw SourceAccessSettingsError.unsafeLocation(url) } + try parent.requireUserControlledFile(Self.name, matching: entry) + let bytes = + entry.st_size > SourceAccessProfile.maximumBytes + ? nil + : try parent.read( + Self.name, matching: entry, maximumBytes: SourceAccessProfile.maximumBytes) + try parent.requireUserControlledFile(Self.name, matching: entry) + try ancestry.validate(at: directory) + return Snapshot(bytes: bytes, entry: entry, ancestry: ancestry) + } catch let exhaustion as OpenFileLimitError { + throw exhaustion + } catch { + throw SourceAccessSettingsError.unsafeLocation(url) + } + } + + func writesChanges(_ bytes: Data?, comparedTo original: Snapshot) -> Bool { + if let bytes { return bytes != original.bytes } + return original.exists + } + + func save(_ bytes: Data?, replacing original: Snapshot) throws { + guard try read() == original else { throw SourceAccessSettingsError.changed(url) } + guard writesChanges(bytes, comparedTo: original) else { return } + guard let (parent, ancestry) = try openParent(create: bytes != nil) else { + throw SourceAccessSettingsError.changed(url) + } + try FileLock.withDescriptor(in: parent, name: Self.lock) { descriptor in + let lock = try FileAccessEvidence.requirePrivate(descriptor: descriptor) + try parent.requirePrivateAccess(Self.lock, matching: lock) + try require(original, in: parent, ancestry: ancestry) + if let bytes { + let staging = ".source-access-\(UUID().uuidString)" + let temporary = try parent.createPrivateFile(staging) + defer { try? parent.remove(staging, identity: temporary.evidence.identity) } + try temporary.write(bytes) + try require(original, in: parent, ancestry: ancestry) + if original.entry == nil { + let rename = parent.atomicRename(staging, to: parent, named: Self.name, mode: .exclusive) + if case .exists = rename { throw SourceAccessSettingsError.changed(url) } + try rename.requireSuccess("publish source access settings") + } else { + guard renameat(parent.descriptor, staging, parent.descriptor, Self.name) == 0 else { + throw FileSystem.posixError( + errno, at: url, otherwise: .invalidState("cannot publish source access settings")) + } + } + try parent.sync() + } else { + try parent.remove(Self.name, identity: original.entry.map(FileObjectIdentity.init)) + } + } + } + + private func require( + _ original: Snapshot, in parent: DirectoryHandle, ancestry: DirectoryAccessEvidence + ) throws { + try ancestry.validate(at: directory) + guard try read(from: parent, ancestry: ancestry) == original else { + throw SourceAccessSettingsError.changed(url) + } + } + + private func openParent(create: Bool) throws -> (DirectoryHandle, DirectoryAccessEvidence)? { + do { + guard home.isFileURL, home.path != "/" else { + throw SourceAccessSettingsError.unsafeLocation(url) + } + var ancestry = try DirectoryAccessEvidence.capture(at: directory) + let homeDepth = home.pathComponents.count + if ancestry.directories.count == homeDepth, create { + guard ancestry.directories.last?.owner == geteuid() else { + throw SourceAccessSettingsError.unsafeLocation(url) + } + let homeHandle = try DirectoryHandle(at: home) + guard try homeHandle.objectIdentity == ancestry.directories.last?.identity else { + throw SourceAccessSettingsError.changed(url) + } + do { + _ = try homeHandle.createPrivateDirectory(".agents") + } catch { + // Another writer may have installed the directory in the same user home. + guard try homeHandle.info(".agents") != nil else { throw error } + } + ancestry = try DirectoryAccessEvidence.capture(at: directory) + } + guard ancestry.directories.count == directory.pathComponents.count else { return nil } + guard ancestry.directories[homeDepth - 1].owner == geteuid(), + let evidence = ancestry.directories.last, evidence.owner == geteuid() + else { throw SourceAccessSettingsError.unsafeLocation(url) } + let parent = try DirectoryHandle(at: directory) + try evidence.validate(descriptor: parent.descriptor) + return (parent, ancestry) + } catch let error as SourceAccessSettingsError { + throw error + } catch let exhaustion as OpenFileLimitError { + throw exhaustion + } catch { + throw SourceAccessSettingsError.unsafeLocation(url) + } + } +} diff --git a/Sources/AgentsCore/SourceArchiveEvidence.swift b/Sources/AgentsCore/SourceArchiveEvidence.swift new file mode 100644 index 0000000..960e8d0 --- /dev/null +++ b/Sources/AgentsCore/SourceArchiveEvidence.swift @@ -0,0 +1,99 @@ +import Foundation + +/// Immutable authority for a source obtained from a VCS archive endpoint. +public struct SourceArchiveEvidence: Codable, Hashable, Sendable { + public let effectiveURL: URL + public let flavor: SourceArchiveMirror.Flavor + public let ref: VCSArchiveRef + public let treeDigest: String + public let observedArchiveDigest: String + public let requiredArchiveDigest: String? + + package init( + effectiveURL: URL, flavor: SourceArchiveMirror.Flavor, ref: VCSArchiveRef, + treeDigest: String, observedArchiveDigest: String, requiredArchiveDigest: String? + ) { + self.effectiveURL = effectiveURL + self.flavor = flavor + self.ref = ref + self.treeDigest = treeDigest + self.observedArchiveDigest = observedArchiveDigest + self.requiredArchiveDigest = requiredArchiveDigest + } + + func validate() throws { + _ = try SourceURL.https(effectiveURL) + guard flavor != .artifactory, + requiredArchiveDigest == nil || requiredArchiveDigest == observedArchiveDigest + else { throw SourceAccessError.invalidArchive } + try ref.validate() + try StateValidation.digest(treeDigest) + try StateValidation.digest(observedArchiveDigest) + } + + func require( + repository: SourceRepository, profile: SourceArchiveMirror + ) throws -> VCSArchiveRequest { + try validate() + let request = try VCSArchiveRequest(repository: repository, ref: ref, mirror: profile) + guard request.url.absoluteString == effectiveURL.absoluteString, profile.flavor == flavor, + !profile.requiresExactArchiveBytes || requiredArchiveDigest != nil + else { throw SourceAccessError.routeChanged } + return request + } + + func verify(_ archive: VerifiedVCSArchive) throws { + guard archive.treeDigest == treeDigest, + requiredArchiveDigest == nil || requiredArchiveDigest == archive.byteDigest + else { throw SourceAccessError.archiveChanged } + } + + package func admits(_ requirement: SourceRequirement?, version: String?) -> Bool { + guard let requirement else { return true } + if requirement.isVersionRequirement { + return version.map(requirement.admitsMarketplaceVersion) ?? false + } + return (try? VCSArchiveRef(requirement: requirement)) == ref + } +} + +extension VCSArchiveRef { + private enum Keys: String, CodingKey { case kind, name } + private enum Kind: String, Codable { case commit, tag, branch } + + public init(from decoder: any Decoder) throws { + let fields = try decoder.container(keyedBy: Keys.self) + let name = try fields.decode(String.self, forKey: .name) + switch try fields.decode(Kind.self, forKey: .kind) { + case .commit: self = .commit(name) + case .tag: self = .tag(name) + case .branch: self = .branch(name) + } + try validate() + } + + public func encode(to encoder: any Encoder) throws { + var fields = encoder.container(keyedBy: Keys.self) + let kind: Kind + switch self { + case .commit: kind = .commit + case .tag: kind = .tag + case .branch: kind = .branch + } + try fields.encode(kind, forKey: .kind) + try fields.encode(name, forKey: .name) + } +} + +extension SourceRoute { + func requireRecordedArchive(_ evidence: SourceArchiveEvidence?) throws -> VCSArchiveRequest? { + switch (self, evidence) { + case (.archive(let repository, let profile), .some(let evidence)): + return try evidence.require(repository: repository, profile: profile) + case (.archive, nil), (_, .some): + throw SourceAccessError.routeChanged + default: + return nil + } + } +} diff --git a/Sources/AgentsCore/SourceArgument.swift b/Sources/AgentsCore/SourceArgument.swift index e749283..b8cee1b 100644 --- a/Sources/AgentsCore/SourceArgument.swift +++ b/Sources/AgentsCore/SourceArgument.swift @@ -10,7 +10,7 @@ package struct SourceArgument: Equatable, Sendable { package var name: String? private static let requirementLabels: Set = [ - "branch", "revision", "ref", "exact", "from", "minor", + "branch", "tag", "revision", "ref", "exact", "from", "minor", ] private static let labels = requirementLabels.union(["path", "skill"]) @@ -47,6 +47,7 @@ package struct SourceArgument: Equatable, Sendable { let parsed: SourceRequirement = switch label { case "branch": .branch(value) + case "tag": .revision("refs/tags/" + value) // A ref names any branch, tag or commit; Git resolves it like a revision. case "revision", "ref": .revision(value) case "exact": .exact(value) @@ -69,21 +70,42 @@ package struct SourceArgument: Equatable, Sendable { ) throws -> SourceSelection { let requirements = [requirement, explicitRequirement].compactMap { $0 } let paths = try [path, explicitPath.map(PathSafety.sanitizeSubpath)].compactMap { $0 } - guard requirements.allSatisfy({ $0 == requirements.first }) else { + guard requirements.allSatisfy({ $0.declarationEquivalent(to: requirements[0]) }) else { throw CoreError.invalidSource("the source selector and option give different requirements") } guard paths.allSatisfy({ $0 == paths.first }) else { throw CoreError.invalidSource("the source selector and option give different paths") } if let declared = declaration.sources[location] { - return SourceSelection(source: declared, requirement: requirements.first, path: paths.first) + return SourceSelection( + source: declared, requirement: requirements.first?.canonical, path: paths.first) } let parsed = try SourceParser.parse( location, currentDirectory: environment.projectDirectory, - homeDirectory: environment.homeDirectory) + homeDirectory: environment.homeDirectory, sourceAccess: environment.sourceAccess) return SourceSelection( source: SourceDeclaration(kind: parsed.type, location: parsed.localPath ?? parsed.url), - requirement: requirements.first ?? parsed.requirement, path: paths.first ?? parsed.subpath) + requirement: (requirements.first ?? parsed.requirement)?.canonical, + path: paths.first ?? parsed.subpath) + } + + /// A named alias keeps its identity even when an explicit selector changes its root. + /// A repository argument reuses the alias whose normalized discovery root it selects. + package func existingAlias( + in declaration: Declaration, sourceID: String, path: String?, + environment: RuntimeEnvironment, matchUniqueSource: Bool = false + ) throws -> String? { + if declaration.sources[location] != nil { return location } + let root = try PathSafety.sanitizeSubpath(path ?? ".") + let matches = try declaration.sourceDeclarations.filter { + try $0.source.identity(environment: environment) == sourceID + } + if let match = try matches.first(where: { + try PathSafety.sanitizeSubpath($0.source.path ?? ".") == root + }) { + return match.name + } + return matchUniqueSource && matches.count == 1 ? matches.first?.name : nil } private static func selectorStart(in input: String) -> String.Index? { @@ -109,7 +131,7 @@ package struct SourceSelection: Equatable, Sendable { /// `declared` with the command's requirement and path replacing its own. package func applied(to declared: SourceDeclaration) -> SourceDeclaration { var result = declared - if let requirement { result.requirement = requirement } + if let requirement { result.requirement = requirement.canonical } if let path { result.path = path } return result } diff --git a/Sources/AgentsCore/SourceCache.swift b/Sources/AgentsCore/SourceCache.swift index 2d28e27..4a057cf 100644 --- a/Sources/AgentsCore/SourceCache.swift +++ b/Sources/AgentsCore/SourceCache.swift @@ -4,10 +4,14 @@ import Foundation package struct SourceRevision: Equatable, Sendable { package var revision: String package var version: String? + package var archive: SourceArchiveEvidence? - package init(revision: String, version: String? = nil) { + package init( + revision: String, version: String? = nil, archive: SourceArchiveEvidence? = nil + ) { self.revision = revision self.version = version + self.archive = archive } } @@ -17,11 +21,29 @@ package struct SourceRevision: Equatable, Sendable { package struct SourceCache { package let store: StateStore + private let sourcePolicy: EffectiveSourcePolicy + private let requireRecordedTransport: Bool private let checkpoint: (String) throws -> Void + private let acquisitions: GitAcquisitionCaptures? - package init(store: StateStore, checkpoint: @escaping (String) throws -> Void = { _ in }) { + package init( + store: StateStore, sourcePolicy: EffectiveSourcePolicy = .init(), + requireRecordedTransport: Bool = false, acquisitions: GitAcquisitionCaptures? = nil, + checkpoint: @escaping (String) throws -> Void = { _ in } + ) { self.store = store + self.sourcePolicy = sourcePolicy + self.requireRecordedTransport = requireRecordedTransport || sourcePolicy.isConfigured self.checkpoint = checkpoint + self.acquisitions = acquisitions + } + + func route(_ source: SourceDeclaration) throws -> SourceRoute { + try SourceRoute(source, environment: store.environment, policy: sourcePolicy) + } + + package func requireGit(_ source: SourceDeclaration) throws { + try route(source).requireGitObjects() } package func mirrorURL(sourceID: String) -> URL { @@ -33,6 +55,127 @@ package struct SourceCache { "materialized/\(key(sourceID))/\(revision)", isDirectory: true) } + package func existingPinnedTree(sourceID: String, revision: String) throws -> URL? { + guard Self.isObjectID(revision) else { + throw CoreError.invalidState("snapshot requires an exact Git object") + } + let tree = materializedURL(sourceID: sourceID, revision: revision) + try validatePath(tree) + return FileManager.default.fileExists(atPath: tree.path) ? tree : nil + } + + /// Proves that replayed bytes match the exact regular Git blob, even if archive attributes + /// or a materialized tree changed the spelling or contents presented to the renderer. + package func withPinnedGitBlobCheck( + sourceID: String, revision: String, + _ body: (_ matches: (String, Data, Bool) throws -> Bool) throws -> T + ) throws -> T { + guard Self.isObjectID(revision) else { + throw CoreError.invalidState("producer patch needs an exact Git commit") + } + func unavailable() -> CoreError { .notFound("locked producer Git commit " + revision) } + guard + let result = try withExistingMirror( + sourceID: sourceID, + { mirror, lock in + 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") + } + let commit = try ProcessRunner.isolatedGit( + ["rev-parse", "--verify", revision + "^{commit}"], in: mirror, inheritingLock: lock) + guard commit.exitCode == 0, commit.stdout == revision + "\n" else { throw unavailable() } + let result = try body { path, bytes, executable in + let entry = try ProcessRunner.isolatedGit( + ["--literal-pathspecs", "ls-tree", "-z", "--full-tree", revision, "--", path], + in: mirror, inheritingLock: lock) + guard entry.exitCode == 0 else { throw unavailable() } + let fields = entry.stdout.split(separator: "\t", maxSplits: 1) + guard fields.count == 2, fields[1].utf8.elementsEqual((path + "\u{0}").utf8) + else { return false } + let metadata = fields[0].split(separator: " ") + return metadata.count == 3 && metadata[0] == (executable ? "100755" : "100644") + && metadata[1] == "blob" + && FileHash.matchesGitBlob(bytes, object: String(metadata[2])) + } + guard try DirectoryHandle(at: mirror).objectIdentity == directory.objectIdentity else { + throw unavailable() + } + return result + }) + else { + throw unavailable() + } + return result + } + + /// Reads an existing materialization or exports the exact commit from local objects. + /// The callback receives whether its tree is a durable cache entry or a disposable export. + package func withOfflineSnapshot( + sourceID: String, source: LockedSource, revision: String, useMaterializedTree: Bool = true, + lockedPaths: [String]? = nil, + _ body: (URL, Bool) throws -> T + ) throws -> T { + let declared = try declaration(sourceID: sourceID, source: source) + try requireGit(declared) + if useMaterializedTree, + let tree = try existingPinnedTree(sourceID: sourceID, revision: revision) + { + 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)") + } + package func artifactURL(digest: String) throws -> URL { try StateValidation.digest(digest) let url = store.cacheDirectory.appendingPathComponent("artifacts/\(digest.dropFirst(7))") @@ -40,6 +183,19 @@ package struct SourceCache { return url } + package static func artifactContentLocation(digest: String) throws -> LedgerLocation { + try StateValidation.digest(digest) + return .init( + kind: .registered, root: "state", path: "cache/artifact-content/\(digest.dropFirst(7))") + } + + package func artifactContentURL(digest: String) throws -> URL { + let location = try Self.artifactContentLocation(digest: digest) + let url = try location.resolve(roots: ["state": store.directory]) + try validatePath(url) + return url + } + /// Fetching only changes the bare mirror. No installed or materialized tree moves. package func resolve(_ source: SourceDeclaration) throws -> SourceRevision { let id = try source.identity(environment: store.environment) @@ -54,6 +210,77 @@ package struct SourceCache { return SourceRevision(revision: revision, version: ref.version) } + /// Captures all advertised refs in an owned mirror. The caller uses a disposable cache. + func referenceCatalog( + _ source: SourceDeclaration, spending: (Int) throws -> Void = { _ in } + ) throws -> SourceCatalog { + let mirror = try fetch(source, id: source.identity(environment: store.environment)) + let output = try git( + mirror, ["show-ref", "--head", "--dereference"], operation: .listTags, + source: source.location) + var references: [String: String] = [:] + var tags: [String: String] = [:] + for line in output.split(separator: "\n") { + try spending(1) + let fields = line.split(separator: " ", maxSplits: 1).map(String.init) + guard fields.count == 2 else { continue } + references[fields[1]] = fields[0] + } + for name in references.keys.sorted() + where name.hasPrefix("refs/tags/") && !name.hasSuffix("^{}") { + let commit = references[name + "^{}"] ?? references[name] + references[name] = commit + tags[String(name.dropFirst(10))] = commit + } + return SourceCatalog(tags: tags, references: references) + } + + /// Resolves an expression against the already frozen mirror, without fetching new evidence. + func catalogRevision(_ expression: String, source: SourceDeclaration) throws -> String? { + try requireGit(source) + try source.requirement?.validate() + return try withExistingMirror(sourceID: source.identity(environment: store.environment)) { + mirror, descriptor in + do { + return try git( + mirror, + [ + "--no-optional-locks", "rev-parse", "--quiet", "--verify", "--end-of-options", + expression + "^{commit}", + ], + operation: .resolveRevision(revision: expression), source: source.location, + lock: descriptor) + } catch let error as GitError where error.exitCode == 1 && error.stderr.isEmpty { + return nil + } + } ?? nil + } + + /// Acquires a known object in an owned cache, without enumerating or selecting mutable refs. + func acquireCommit(_ object: String, source: SourceDeclaration) throws -> String { + guard Self.isObjectID(object) else { + throw CoreError.invalidSource("expected an exact Git object") + } + try requireGit(source) + if let commit = try catalogRevision(object, source: source) { return commit } + if let acquisition = anonymousAcquisition(source), + let pack = try attemptAnonymous({ try acquisition.exact(object) }) + { + acquisition.remember(pack) + if acquisitions == nil { + _ = try importAnonymous( + pack, from: acquisition, + sourceID: source.identity( + environment: store.environment)) + } + return pack.revision + } + let mirror = try fetch(source, id: source.identity(environment: store.environment)) + return try git( + mirror, ["rev-parse", "--verify", object + "^{commit}"], + operation: .resolveRevision(revision: object), source: source.location) + } + /// Subscriptions follow branches even when installations select a tag or version range. func watchRevision(_ source: SourceDeclaration, revision: String? = nil) throws -> String { let id = try source.identity(environment: store.environment) @@ -134,6 +361,7 @@ package struct SourceCache { } /// The marker precedes ref preparation or a state change that can release an existing pin. + /// An existing marker is synced again; only its creation is a checkpoint. func beginWatchReferenceUpdate() throws { guard let directory = try store.openDirectoryIfPresent(), try directory.info("cache") != nil, @@ -141,22 +369,22 @@ package struct SourceCache { else { return } if try directory.info("watch-refs.pending") == nil { try directory.write("watch-refs.pending", data: Data()) + try checkpoint("watch.references.pending") } else { guard try directory.read("watch-refs.pending").isEmpty else { throw CoreError.invalidState("invalid watch ref cleanup marker") } try directory.syncFile("watch-refs.pending") } - try checkpoint("watch.references.pending") } /// Run only after journal recovery or successful commit, while holding the scope lock. /// The marker survives interruptions until every deletion and its parent are durable. func recoverWatchReferences() throws -> Bool { guard let directory = try store.openDirectoryIfPresent() else { return false } - guard try directory.info("transaction.json") == nil, - try directory.info("transaction.new") == nil - else { throw CoreError.invalidState("transaction recovery must precede watch ref cleanup") } + guard try !TransactionJournal.isPresent(in: directory) else { + throw CoreError.invalidState("transaction recovery must precede watch ref cleanup") + } if try directory.info("watch-refs.pending") != nil, try !directory.read("watch-refs.pending").isEmpty { @@ -165,31 +393,15 @@ package struct SourceCache { try recoverMirrorLocks(in: directory) guard try directory.info("watch-refs.pending") != nil else { return false } let watch = try store.readWatch() - let resolved = try store.readResolved() - var sourceLocations: [String: String] = [:] - for id in watch.sources.keys { - sourceLocations[key(id) + ".git"] = - id.hasPrefix("local:") ? String(id.dropFirst("local:".count)) : id - } - for (id, source) in resolved.sources where source.kind != .wellKnown { - sourceLocations[key(id) + ".git"] = try declaration(sourceID: id, source: source).location - } - for source in try store.readDeclaration().sources.values where source.kind != .wellKnown { - let id = try source.identity(environment: store.environment) - sourceLocations[key(id) + ".git"] = source.location - } + var references = try store.retentionReferences() + try references.include(watch: watch) + let sourceLocations = Dictionary( + uniqueKeysWithValues: references.sourceLocations.map { + (key($0.key) + ".git", $0.value) + }) var retained: [String: Set] = [:] - func retain(_ source: String, _ revision: String?) { - if let revision { retained[key(source) + ".git", default: []].insert(revision) } - } - for (source, state) in watch.sources { - if case .revision(let revision) = state.seen { retain(source, revision) } - } - for skill in resolved.skills.values { retain(skill.source, skill.revision) } - for section in resolved.instructions.sections - + resolved.instructions.chatgpt.values.flatMap(\.sections) - { - retain(section.source, section.revision) + for pin in references.git { + retained[key(pin.source) + ".git", default: []].insert(pin.revision) } // Even a manually supplied generation must reach storage before its obsolete pins go away. for file in ["agents.watch", "agents.resolved"] where try directory.info(file) != nil { @@ -200,7 +412,8 @@ package struct SourceCache { let cache = try directory.child("cache") if try cache.info("mirrors") != nil { let mirrors = try cache.child("mirrors") - for name in try mirrors.names() where name.hasSuffix(".git") { + // Checkpoints are numbered by mirror and by deletion within this reconciliation. + for (ordinal, name) in try mirrors.names().filter({ $0.hasSuffix(".git") }).enumerated() { try withMirrorLock(at: mirrors.url.appendingPathComponent(name)) { descriptor in let mirror = try mirrors.child(name) let source = try sourceLocations[name] ?? mirrorSource(mirror.url, lock: descriptor) @@ -211,6 +424,7 @@ package struct SourceCache { mirror.url, ["for-each-ref", "--format=%(refname) %(objectname)", "refs/agents-watch/"], operation: .listReferences, source: source, lock: descriptor) + var deleted = 0 for line in references.split(separator: "\n") { let parts = line.split(separator: " ").map(String.init) guard parts.count == 2, parts[0] == "refs/agents-watch/" + parts[1], @@ -223,7 +437,8 @@ package struct SourceCache { mirror.url, ["update-ref", "--no-deref", "-d", parts[0], parts[1]], operation: .deleteReference, source: source, lock: descriptor ) - try checkpoint("watch.references.deleted") + try checkpoint("watch.references.\(ordinal).\(deleted).deleted") + deleted += 1 } // A previous attempt may have unlinked the final loose ref or rewritten packed-refs. // Flush their parents even when enumeration now finds no obsolete refs. @@ -231,7 +446,7 @@ package struct SourceCache { if try refs.info("agents-watch") != nil { try refs.child("agents-watch").sync() } try refs.sync() try mirror.sync() - try checkpoint("watch.references.synced") + try checkpoint("watch.references.\(ordinal).synced") } } } @@ -248,15 +463,17 @@ package struct SourceCache { let cache = try directory.child("cache") guard try cache.info("mirrors") != nil else { return } let mirrors = try cache.child("mirrors") - for name in try mirrors.names() where name.hasSuffix(".git") { + for (ordinal, name) in try mirrors.names().filter({ $0.hasSuffix(".git") }).enumerated() { try withMirrorLock(at: mirrors.url.appendingPathComponent(name)) { _ in - try recoverGitLocks(in: mirrors.child(name), scope: directory) + try recoverGitLocks(in: mirrors.child(name), ordinal: ordinal, scope: directory) } } } - private func recoverGitLocks(in mirror: DirectoryHandle, scope directory: DirectoryHandle) throws - { + /// Checkpoints are numbered by the mirror's ordinal and the lock's position in traversal. + private func recoverGitLocks( + in mirror: DirectoryHandle, ordinal: Int, scope directory: DirectoryHandle + ) throws { var locks: [(DirectoryHandle, String)] = [] func inspect(_ parent: DirectoryHandle, isMirrorRoot: Bool = false) throws { for name in try parent.names() { @@ -275,8 +492,10 @@ package struct SourceCache { try inspect(mirror, isMirrorRoot: true) if !locks.isEmpty { try beginWatchReferenceUpdate() } guard try directory.info("watch-refs.pending") != nil else { return } - for (parent, name) in locks { - try parent.remove(name) { try checkpoint("watch.git-lock.\($0)") } + for (index, (parent, name)) in locks.enumerated() { + try parent.remove(name) { + try checkpoint("watch.git-lock.\(ordinal).\(index).\($0.step.rawValue)") + } } // A killed cleanup may have unlinked the last lock before syncing its parent. // The pending marker requires these barriers even if no lock remains visible. @@ -296,6 +515,7 @@ package struct SourceCache { 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( @@ -305,11 +525,13 @@ package struct SourceCache { if FileManager.default.fileExists(atPath: destination.path) { return destination } let mirror = try pinnedMirror(sourceID: sourceID, source: source, revision: revision) let transaction = FileTransaction(store: store, checkpoint: checkpoint) - try transaction.prepare(destination) { work in - try extract( - revision: revision, mirror: mirror, - source: declaration(sourceID: sourceID, source: source).location, root: work) - } + try transaction.replace( + destination, + with: .prepared { work in + try extract( + revision: revision, mirror: mirror, + source: declaration(sourceID: sourceID, source: source).location, root: work) + }) try transaction.commit() return destination } @@ -321,11 +543,103 @@ package struct SourceCache { package func withResolvedSnapshot( _ source: SourceDeclaration, cacheSource: Bool = true, _ body: (SourceRevision, URL) throws -> T + ) throws -> T { + if case .archive = try route(source) { + return try SourceResolutionSession.withTemporaryRead( + store: store, sourcePolicy: sourcePolicy, acquisitions: acquisitions + ) { session in + guard + let pin = try session.candidates(for: source, requirements: [source.requirement]).first + else { throw SourceAccessError.discoveryUnavailable } + let snapshot = try session.snapshot(source, at: pin) + return try body(pin, snapshot.root) + } + } + try requireGit(source) + if let acquisition = anonymousAcquisition(source) { + let exact: String? + if case .revision(let object) = source.requirement, Self.isObjectID(object) { + exact = object + } else { + exact = nil + } + let borrowed = + exact.map { object in + acquisitions?.containsAnonymousCommit( + source, revision: object, environment: store.environment) == true + } ?? false + let scoped = try exact.flatMap { try catalogRevision($0, source: source) } + if borrowed || scoped == nil, + let selected = try attemptAnonymous({ + try self.selectAnonymous(source, acquisition: acquisition, exact: exact) + }) + { + return try withAnonymousTree(acquisition, pack: selected.pack) { tree in + acquisition.remember(selected.pack) + if let (reference, time) = selected.observed { + acquisition.note(reference, pack: selected.pack, observedAt: time) + } + return try body( + SourceRevision(revision: selected.pack.revision, version: selected.version), tree) + } + } + } + return try withScopedResolvedSnapshot(source, cacheSource: cacheSource, body) + } + + func anonymousAcquisition(_ source: SourceDeclaration) -> GitAcquisition? { + guard (try? requireGit(source)) != nil else { return nil } + return GitAcquisition(source, environment: store.environment, captures: acquisitions) + } + + /// Failed anonymous attempts fall back to the established scoped transport. Cancellation + /// and policy failures are handled outside this optional acquisition. + func attemptAnonymous(_ acquire: () throws -> T?) throws -> T? { + do { return try acquire() } catch { + try Task.checkCancellation() + return nil + } + } + + private func selectAnonymous( + _ source: SourceDeclaration, acquisition: GitAcquisition, exact: String? + ) throws -> (pack: GitAcquisition.Pack, version: String?, observed: (String, Date)?)? { + if let exact { + guard let pack = try acquisition.exact(exact) else { return nil } + return (pack, nil, nil) + } + let discovered = try acquisition.discover() + let requirement = try SourceReference( + requirement: source.requirement, tags: Array(discovered.catalog.tags.keys)) + guard + let (reference, object) = GitAcquisition.reference( + requirement.name, in: discovered.catalog), + let pack = try acquisition.exact(object), pack.revision == object + else { return nil } + return (pack, requirement.version, (reference, discovered.time)) + } + + private func withAnonymousTree( + _ acquisition: GitAcquisition, pack: GitAcquisition.Pack, _ 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) + 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)) + } + } + + private func withScopedResolvedSnapshot( + _ source: SourceDeclaration, cacheSource: Bool, _ body: (SourceRevision, URL) throws -> T ) throws -> T { if !cacheSource { let root = FileManager.default.temporaryDirectory.appendingPathComponent( "agents-discovery-" + UUID().uuidString) - try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + try FileSystem.createDirectory(at: root) defer { try? FileManager.default.removeItem(at: root) } if case .revision(let object) = source.requirement, Self.isObjectID(object), let cached = try withExistingMirror( @@ -353,9 +667,32 @@ package struct SourceCache { } var environment = store.environment environment.projectDirectory = root - let cache = SourceCache(store: StateStore(scope: .project, environment: environment)) - return try cache.withResolvedSnapshot(source, body) + let cache = SourceCache( + store: StateStore(scope: .project, environment: environment), sourcePolicy: sourcePolicy, + requireRecordedTransport: requireRecordedTransport) + return try cache.withScopedResolvedSnapshot(source, cacheSource: true, body) + } + if case .revision(let object) = source.requirement, Self.isObjectID(object) { + let id = try source.identity(environment: store.environment) + var mirror = mirrorURL(sourceID: id) + // An immutable object may be an annotated tag. Peel it without selecting mutable refs. + if (try? git( + mirror, ["cat-file", "-e", object + "^{commit}"], + operation: .resolveRevision(revision: object), source: source.location)) == nil + { + mirror = try fetch(source, id: id) + } + let revision = try git( + mirror, ["rev-parse", "--verify", object + "^{commit}"], + operation: .resolveRevision(revision: object), source: source.location) + let locked = LockedSource( + kind: source.kind, url: source.kind == .git ? source.gitURL : nil, + requirement: .revision(object), path: source.path) + return try withSnapshot(sourceID: id, source: locked, revision: revision) { + try body(SourceRevision(revision: revision), $0) + } } + let pin = try resolve(source) let locked = LockedSource( kind: source.kind, url: source.kind == .git ? source.gitURL : nil, @@ -370,10 +707,11 @@ 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 FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + try FileSystem.createDirectory(at: root) defer { try? FileManager.default.removeItem(at: root) } return try body( extract( @@ -381,8 +719,9 @@ package struct SourceCache { source: declaration(sourceID: sourceID, source: source).location, root: root)) } - private func pinnedMirror(sourceID: String, source: LockedSource, revision: String) throws -> URL - { + private func pinnedMirror( + sourceID: String, source: LockedSource, revision: String, offline: Bool = false + ) 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") @@ -390,32 +729,115 @@ package struct SourceCache { try validatePath(mirrorURL(sourceID: sourceID)) var mirror = mirrorURL(sourceID: sourceID) let declaration = try declaration(sourceID: sourceID, source: source) + try requireGit(declaration) if (try? git( mirror, ["cat-file", "-e", revision + "^{commit}"], - operation: .resolveRevision(revision: revision), source: declaration.location)) == nil + operation: .resolveRevision(revision: revision), source: declaration.location, + offline: offline)) == nil { - mirror = try fetch(declaration, id: sourceID) + 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) + 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) + } } guard try git( mirror, ["rev-parse", "--verify", revision + "^{commit}"], - operation: .resolveRevision(revision: revision), source: declaration.location) == revision + operation: .resolveRevision(revision: revision), source: declaration.location, + offline: offline) == revision else { throw CoreError.invalidState("locked commit is unavailable") } return mirror } + /// Copies a verified pack into the scope's own object database while holding its mirror lock. + /// The scope never opens a Git config from the shared cache and owns every copied byte. + private func importAnonymous( + _ pack: GitAcquisition.Pack, from acquisition: GitAcquisition, sourceID: String + ) 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) + return mirror + } + } + } + + private func installPack(_ repository: URL, stem: String, into mirror: DirectoryHandle) throws { + let source = try DirectoryHandle(at: repository).child("objects").child("pack") + let objects = try mirror.child("objects") + if let info = try objects.directory("info"), + try info.info("alternates") != nil || info.info("http-alternates") != nil + { + throw CoreError.invalidState("scope Git objects must be self-contained") + } + let destination = try objects.child("pack") + for suffix in [".pack", ".idx"] { + let name = stem + suffix + let bytes = try source.read(name, maximumBytes: GitAcquisition.packLimit) + if let previous = try destination.info(name) { + guard previous.st_nlink == 1, + try destination.read( + name, matching: previous, maximumBytes: GitAcquisition.packLimit) == bytes + else { + throw CoreError.invalidState("scope Git pack differs from the verified acquisition") + } + } else { + let staging = ".agents-pack-" + UUID().uuidString + try destination.write(staging, data: bytes) + defer { try? destination.remove(staging) } + try destination.move(staging, to: destination, named: name, mode: .exclusive) + } + } + try destination.sync() + try objects.sync() + try mirror.sync() + } + private func extract( - revision: String, mirror: URL, source: String, root: URL, lock: Int32? = nil + revision: String, mirror: URL, source: String, root: URL, lock: Int32? = nil, + offline: Bool = false, lockedPaths: [String]? = nil ) throws -> URL { let archive = root.appendingPathComponent("tree.tar") - let tree = root.appendingPathComponent("tree") - try FileManager.default.createDirectory(at: tree, withIntermediateDirectories: true) let arguments = [ "--no-optional-locks", "archive", "--format=tar", "--output=" + archive.path, revision, ] - if let lock { + 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) @@ -424,7 +846,13 @@ package struct SourceCache { mirror, arguments, operation: .extractRevision, source: source, replacingPaths: [root]) } - try ProcessRunner.run("/usr/bin/env", arguments: ["tar", "-xf", archive.path, "-C", tree.path]) + 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) return tree } @@ -435,12 +863,12 @@ package struct SourceCache { } let url = try artifactURL(digest: digest) if FileManager.default.fileExists(atPath: url.path) { - guard try Data(contentsOf: url) == data else { + guard try FileSystem.read(at: url) == data else { throw CoreError.invalidState("cached artifact digest mismatch") } } else { let transaction = FileTransaction(store: store, checkpoint: checkpoint) - try transaction.replace(url, content: nil, data: data, expectedHash: digest) + try transaction.replace(url, with: .data(data), expectedHash: digest) try transaction.commit() } return url @@ -448,66 +876,84 @@ package struct SourceCache { /// Publishes a verified expansion under the scope lock; interrupted staging is journaled. package func materializeArtifact(_ directory: URL, digest: String, hash: String) throws -> URL { - try StateValidation.digest(digest) try StateValidation.digest(hash) - let destination = store.cacheDirectory.appendingPathComponent( - "artifact-content/\(digest.dropFirst(7))") - try validatePath(destination) + let destination = try artifactContentURL(digest: digest) if FileManager.default.fileExists(atPath: destination.path) { guard try "sha256:" + FileHash.folderHash(destination) == hash else { throw CoreError.invalidState("cached artifact content mismatch") } } else { let transaction = FileTransaction(store: store, checkpoint: checkpoint) - try transaction.replace(destination, content: directory, expectedHash: hash) + try transaction.replace(destination, with: .copy(directory), expectedHash: hash) try transaction.commit() } return destination } - /// Retains pins and any cache tree containing a live edit source. - /// The caller holds the scope lock, including during failure cleanup. - package func prune( - referencedBy lock: ResolvedState, watch: WatchState? = nil, - transaction: FileTransaction? = nil - ) throws { - let watch = try watch ?? store.readWatch() - guard let scope = try store.openDirectoryIfPresent(), try scope.info("cache") != nil else { - return - } - let cache = try scope.child("cache") - let transactionToUse = transaction ?? FileTransaction(store: store) - var paths = Set() - var digests = Set() - for state in watch.sources.values { - if case .artifacts(let artifacts) = state.seen { - digests.formUnion(artifacts.values.map { String($0.dropFirst(7)) }) - } - } - var edits: [URL] = [] - func retain(source: String, revision: String?, artifact: LockedArtifact?) { - if let revision { - paths.insert(materializedURL(sourceID: source, revision: revision).standardizedFileURL.path) - } - if let artifact { - digests.insert(String(artifact.digest.dropFirst(7))) - for file in artifact.files ?? [] { digests.insert(String(file.digest.dropFirst(7))) } + /// 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 { + 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) } - for skill in lock.skills.values { - retain(source: skill.source, revision: skill.revision, artifact: skill.artifact) - if skill.installs.values.contains(.edit), let source = lock.sources[skill.source] { - let local = try declaration(sourceID: skill.source, source: source).localURL( - environment: store.environment) - edits.append( - try PathSafety.resolvedChild(base: local, subpath: skill.path ?? ".") - .resolvingSymlinksInPath()) - } + } + + package func withArchivePublication( + previous: RetentionReferences, next: RetentionReferences, offline: Bool, + _ body: () throws -> T + ) throws -> T { + try PrivateSourceRecovery(environment: store.environment).withPublication( + store: store, previous: previous.archives, next: next.archives, captures: acquisitions, + policy: sourcePolicy, offline: offline, checkpoint: checkpoint, body) + } + + package static func privateWorkspace(prefix: String) throws -> URL { + try PrivateSourceRecovery.makeWorkspace(prefix: prefix).url + } + + package func requireArchivePublicationAccess() throws { + try PrivateSourceRecovery(environment: store.environment).requirePublicationAccess() + } + + package func archiveTree(transport: String, evidence: SourceArchiveEvidence) -> URL { + PrivateSourceRecovery(environment: store.environment).treeURL( + .init(transport: transport, archive: evidence)) + } + + /// The caller stages pruning with its state generation and commits only after validation. + package func prune(references: RetentionReferences, transaction: FileTransaction) throws { + guard let scope = try store.openDirectoryIfPresent(), try scope.info("cache") != nil else { + return } - for section in lock.instructions.sections + lock.instructions.chatgpt.values.flatMap(\.sections) - { - retain(source: section.source, revision: section.revision, artifact: section.artifact) + guard try !TransactionJournal.isPresent(in: scope) else { + throw CoreError.invalidState("transaction recovery must precede pruning") } + let cache = try scope.child("cache") + let transactionToUse = transaction + let paths = Set( + references.git.map { + materializedURL(sourceID: $0.source, revision: $0.revision).standardizedFileURL.path + }) + let digests = Set(references.artifacts.map { String($0.dropFirst(7)) }) + let edits = references.live func edited(_ url: URL) -> Bool { edits.contains { PathSafety.isContained($0, in: url) } } @@ -521,10 +967,13 @@ package struct SourceCache { let tree = try source.child(pin) if !paths.contains(tree.url.path) && !edited(tree.url) { unused.append(pin) } } - if unused.count == pins.count { - try transactionToUse.remove(name, from: materialized) + 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.remove(pin, from: source) } + for pin in unused { try transactionToUse.delete(source.url.appendingPathComponent(pin)) } } } } @@ -538,11 +987,10 @@ package struct SourceCache { throw CoreError.unsafePath("unexpected artifact cache entry") } if !digests.contains(name) && !edited(url) { - try transactionToUse.remove(name, from: directory) + try transactionToUse.delete(url) } } } - if transaction == nil { try transactionToUse.commit() } } package func validatePath(_ url: URL, directory: Bool = true) throws { @@ -575,37 +1023,53 @@ package struct SourceCache { } private func fetch(_ source: SourceDeclaration, id: String) throws -> URL { - try withMirrorLock(at: mirrorURL(sourceID: id)) { descriptor in + try requireGit(source) + return try withMirrorLock(at: mirrorURL(sourceID: id)) { descriptor in try fetchMirror(source, id: id, lock: descriptor) } } private func fetchMirror(_ source: SourceDeclaration, id: String, lock: Int32) throws -> URL { + let selected = try route(source) + try selected.requireGitObjects() + if let managed = try ManagedSourceGit.select(selected, environment: store.environment) { + return try fetchManaged(managed, id: id, lock: lock) + } guard source.kind != .wellKnown else { throw CoreError.invalidSource("well-known sources have no Git mirror") } let url = source.kind == .local ? source.localURL(environment: store.environment).path : source.gitURL let mirror = mirrorURL(sourceID: id) - try FileManager.default.createDirectory( - at: mirror.deletingLastPathComponent(), withIntermediateDirectories: true) - if FileManager.default.fileExists(atPath: mirror.path) { + let exists = FileManager.default.fileExists(atPath: mirror.path) + let transportOptions = try recordedGitOptions( + url, context: exists ? ["-C", mirror.path] : [], lock: lock) + try FileSystem.createDirectory(at: mirror.deletingLastPathComponent()) + if exists { _ = try git( mirror, - ["fetch", "--prune", "origin", "+refs/heads/*:refs/heads/*", "+refs/tags/*:refs/tags/*"], + transportOptions + [ + "fetch", "--prune", "--", requireRecordedTransport ? url : "origin", + "+refs/heads/*:refs/heads/*", "+refs/tags/*:refs/tags/*", + ], operation: .fetch, source: source.location, lock: lock) } else { let staging = mirror.appendingPathExtension("staging-" + UUID().uuidString) defer { try? FileManager.default.removeItem(at: staging) } try ProcessRunner.git( - Self.gitOptions + ["clone", "--mirror", "--no-local", "--", url, staging.path], + Self.gitOptions + transportOptions + [ + "clone", "--mirror", "--no-local", "--", url, staging.path, + ], operation: .clone, source: source.location, replacingPaths: [staging, store.cacheDirectory], inheritingLock: lock) - try FileManager.default.moveItem(at: staging, to: mirror) + try FileSystem.withAccessErrors(at: mirror) { + try FileManager.default.moveItem(at: staging, to: mirror) + } } // A remote can change its default branch after the initial clone. let head = try ProcessRunner.git( - ["ls-remote", "--symref", url, "HEAD"], operation: .listRemoteReferences, + transportOptions + (requireRecordedTransport && exists ? ["-C", mirror.path] : []) + + ["ls-remote", "--symref", "--", url, "HEAD"], operation: .listRemoteReferences, source: source.location, inheritingLock: lock ).stdout if let line = head.split(separator: "\n").first(where: { $0.hasPrefix("ref: refs/heads/") }), @@ -618,6 +1082,80 @@ package struct SourceCache { return mirror } + func recordedGitOptions(_ url: String, context: [String] = [], lock: Int32? = nil) + throws -> [String] + { + guard requireRecordedTransport else { return [] } + // An admitted direct transport cannot be changed by a Git URL rewrite. + let rewritten = try ProcessRunner.git( + context + ["ls-remote", "--get-url", "--", url], operation: .readOrigin, + source: "admitted source", inheritingLock: lock + ).stdout.trimmingCharacters(in: .newlines) + guard rewritten.utf8.elementsEqual(url.utf8) else { + throw CoreError.invalidSource("Git rewrites the admitted source URL") + } + let scheme = URLComponents(string: url)?.scheme?.lowercased() + guard scheme == "http" || scheme == "https" else { return [] } + var options = ["-c", "http.followRedirects=false"] + if !url.contains("=") { options += ["-c", "http.\(url).followRedirects=false"] } + let redirects = try ProcessRunner.git( + options + context + ["config", "--get-urlmatch", "http.followRedirects", url], + operation: .readOrigin, source: "admitted source", inheritingLock: lock + ).stdout.trimmingCharacters(in: .whitespacesAndNewlines) + guard redirects == "false" else { + throw CoreError.invalidSource("Git enables HTTP redirects for the admitted source") + } + return options + } + + private func fetchManaged(_ managed: ManagedSourceGit, id: String, lock: Int32) throws -> URL { + let mirror = mirrorURL(sourceID: id) + let parentURL = mirror.deletingLastPathComponent() + _ = try DirectoryAccessEvidence.capture(at: parentURL) + try FileSystem.createDirectory(at: parentURL) + _ = try DirectoryAccessEvidence.capture(at: parentURL) + let parent = try DirectoryHandle(at: parentURL) + if try parent.info(mirror.lastPathComponent) != nil { + _ = try parent.requirePrivateAccess(mirror.lastPathComponent) + _ = try ProcessRunner.git( + [ + "fetch", "--no-recurse-submodules", "--prune", "--", managed.repository.url, + "+refs/heads/*:refs/heads/*", "+refs/tags/*:refs/tags/*", + ], + operation: .fetch, source: "admitted source", inheritingLock: lock, + managed: managed, managedMirror: mirror) + } else { + let name = "managed-" + UUID().uuidString + let staging = try parent.createPrivateDirectory(name) + defer { try? FileManager.default.removeItem(at: staging.url) } + let bare = staging.url.appendingPathComponent("mirror.git") + _ = try ProcessRunner.git( + [ + "clone", "--mirror", "--no-local", "--template=", "--no-recurse-submodules", "--", + managed.repository.url, bare.path, + ], + operation: .clone, source: "admitted source", inheritingLock: lock, managed: managed) + guard chmod(bare.path, 0o700) == 0 else { throw SourceAccessError.requestFailed } + try managed.sealClonedConfiguration(bare) + _ = try staging.requirePrivateAccess("mirror.git") + try FileManager.default.moveItem(at: bare, to: mirror) + try parent.sync() + } + let head = try ProcessRunner.git( + ["ls-remote", "--symref", "--", managed.repository.url, "HEAD"], + operation: .listRemoteReferences, source: "admitted source", inheritingLock: lock, + managed: managed + ).stdout + if let line = head.split(separator: "\n").first(where: { $0.hasPrefix("ref: refs/heads/") }), + let reference = line.split(separator: "\t").first + { + _ = try git( + mirror, ["symbolic-ref", "HEAD", String(reference.dropFirst(5))], + operation: .updateDefaultBranch, source: managed.repository.url, lock: lock, offline: true) + } + return mirror + } + private func withMirrorLock(at mirror: URL, _ body: (Int32) throws -> T) throws -> T { let locks = store.cacheDirectory.appendingPathComponent("locks") try validatePath(locks) @@ -633,12 +1171,12 @@ package struct SourceCache { private func git( _ repository: URL, _ arguments: [String], operation: GitError.Operation, source: String, - replacingPaths paths: [URL] = [] + replacingPaths paths: [URL] = [], offline: Bool = false ) throws -> String { try withMirrorLock(at: repository) { descriptor in try git( repository, arguments, operation: operation, source: source, replacingPaths: paths, - lock: descriptor) + lock: descriptor, offline: offline) } } @@ -668,7 +1206,7 @@ package struct SourceCache { private func git( _ repository: URL, _ arguments: [String], operation: GitError.Operation, source: String, - replacingPaths paths: [URL] = [], lock: Int32 + replacingPaths paths: [URL] = [], lock: Int32, offline: Bool = false ) throws -> String { let mirror = try DirectoryHandle(at: repository) guard let config = try mirror.info("config"), config.st_mode & 0o170000 == 0o100000 else { @@ -676,13 +1214,15 @@ package struct SourceCache { } return try ProcessRunner.git( Self.gitOptions + ["-C", repository.path] + arguments, operation: operation, source: source, - replacingPaths: paths + [repository, store.cacheDirectory], inheritingLock: lock + replacingPaths: paths + [repository, store.cacheDirectory], inheritingLock: lock, + offline: offline || operation != .fetch ) .stdout.trimmingCharacters(in: .whitespacesAndNewlines) } private func mirrorSource(_ mirror: URL, lock: Int32) throws -> String { - // Orphaned mirrors outlive their declarations; the clone's origin retains the source location. + // Recovery never reads the declaration. A mirror that neither watch state nor the lock + // names, including an orphan, is identified by its clone's origin. let source: String do { source = try git( diff --git a/Sources/AgentsCore/SourceCatalog.swift b/Sources/AgentsCore/SourceCatalog.swift new file mode 100644 index 0000000..c6588ed --- /dev/null +++ b/Sources/AgentsCore/SourceCatalog.swift @@ -0,0 +1,66 @@ +import Foundation + +/// Frozen Git reference evidence for a resolution session. Tags at the same version retain +/// the existing lexical tie break; branches and revision expressions must name one commit. +struct SourceCatalog { + var tags: [String: String] + var references: [String: String] + + func candidates( + requirements: [SourceRequirement?], spending: (Int) throws -> Void = { _ in } + ) throws -> [SourceRevision] { + for requirement in requirements { + try spending(1) + try requirement?.validate() + } + let constraints = requirements.compactMap { $0 } + let fixed = constraints.compactMap { requirement -> String? in + switch requirement { + case .branch(let name): return references["refs/heads/" + name] + case .revision(let name): return references[name] + default: return nil + } + } + let fixedCount = constraints.filter { !$0.isVersionRequirement }.count + guard fixed.count == fixedCount, Set(fixed).count <= 1 else { return [] } + let versions = constraints.filter(\.isVersionRequirement) + let ordered = try tags.compactMap { name, commit -> (String, SemanticVersion, String)? in + try spending(1) + return SemanticVersion(name).map { (name, $0, commit) } + }.sorted { + try spending(1) + return $0.1 == $1.1 ? $0.0 > $1.0 : $0.1 > $1.1 + } + if let commit = fixed.first, versions.isEmpty { + return [SourceRevision(revision: commit)] + } + var seen = Set() + let candidates = try ordered.filter { entry in + try spending(versions.count + 1) + return + (fixed.first == nil || fixed.first == entry.2) + && versions.allSatisfy { $0.matches(version: entry.1) } + && seen.insert(entry.2).inserted + }.map { SourceRevision(revision: $0.2, version: $0.1.description) } + if !candidates.isEmpty || !versions.isEmpty || !ordered.isEmpty { return candidates } + return references["HEAD"].map { [SourceRevision(revision: $0)] } ?? [] + } +} + +extension SourceRequirement { + func matches(version: SemanticVersion) -> Bool { + guard let lower = SemanticVersion(value) else { return false } + switch self { + case .exact: return version.description == lower.description + case .upToNextMajor: + return version.isInRange( + from: lower, to: SemanticVersion(major: lower.major + 1, minor: 0, patch: 0)) + case .upToNextMinor: + return version.isInRange( + from: lower, to: SemanticVersion(major: lower.major, minor: lower.minor + 1, patch: 0)) + case .range(_, let upper): + return SemanticVersion(upper).map { version.isInRange(from: lower, to: $0) } ?? false + case .branch, .revision: return false + } + } +} diff --git a/Sources/AgentsCore/SourceCredentialOperations.swift b/Sources/AgentsCore/SourceCredentialOperations.swift new file mode 100644 index 0000000..c5697a6 --- /dev/null +++ b/Sources/AgentsCore/SourceCredentialOperations.swift @@ -0,0 +1,208 @@ +import Foundation + +#if canImport(FoundationNetworking) + import FoundationNetworking +#endif +#if canImport(Darwin) + import Darwin +#else + import Glibc +#endif + +public struct SourceCredentialReport: Equatable, Encodable, Sendable { + public enum Transport: String, Encodable, Sendable { case local, git, http, https, ssh, archive } + public enum Availability: String, Encodable, Sendable { + case available, unavailable, unconfigured + case delegatedUnverified = "delegated/unverified" + case sshManaged = "ssh-managed" + } + public enum Validation: String, Encodable, Sendable { case accepted, refused, indeterminate } + + public let provider: SourceProvider? + public let effectiveHost: String? + public let transport: Transport + public let credentialSource: SourceCredentialBinding.Category? + public let availability: Availability + public let validation: Validation? +} + +/// Read-only source credential status and explicit, pipe-only export. +public enum SourceCredentialOperations { + public static func inspect( + source selector: String, declaration: Declaration, environment: RuntimeEnvironment, + policy: EffectiveSourcePolicy + ) throws -> SourceCredentialReport { + let route = try route( + selector, declaration: declaration, environment: environment, policy: policy) + return try report(route, environment: environment, validation: nil) + } + + /// Host-only inspection considers host-wide bindings. A path-scoped binding requires a source. + public static func inspect( + host: SourceAuthority, environment: RuntimeEnvironment + ) throws -> SourceCredentialReport { + let access = try environment.resolvedSourceAccess() + let direct = try SourceRoute.binding(access, route: .direct, authority: host, path: nil) + let mirror = try SourceRoute.binding(access, route: .mirror, authority: host, path: nil) + guard direct == nil || mirror == nil else { throw SourceAccessError.ambiguousCredential } + let binding = direct ?? mirror + return .init( + provider: access.provider(for: host), effectiveHost: host.display, + transport: mirror == nil ? .https : .archive, credentialSource: binding?.category, + availability: binding == nil && delegatesGit(host, environment: environment) + ? .delegatedUnverified : availability(binding), validation: nil) + } + + /// Validates only an explicitly authorized provider identity endpoint on the same authority. + public static func validate( + source selector: String, declaration: Declaration, environment: RuntimeEnvironment, + policy: EffectiveSourcePolicy + ) throws -> SourceCredentialReport { + let route = try route( + selector, declaration: declaration, environment: environment, policy: policy) + var result = SourceCredentialReport.Validation.indeterminate + let access = try environment.resolvedSourceAccess() + if case .git(let repository?) = route, repository.scheme == "https", + let binding = try route.credential(access), binding.available, + let provider = access.provider(for: repository.authority), + let endpoint = binding.validationEndpoint, + let parts = try? SourceURL.https(endpoint), parts.query == nil, + provider.admitsIdentityEndpoint(parts, authority: repository.authority), + (try? access.requireDirectHTTP(endpoint, policy: policy)) != nil, + let secret = try? binding.value() + { + var request = URLRequest(url: endpoint) + request.setValue("Bearer " + secret, forHTTPHeaderField: "Authorization") + switch (try? PackageSourceHTTP.read(request, maximumBytes: nil))?.status { + case .some(200): result = .accepted + case .some(401): result = .refused + default: break + } + } + return try report(route, environment: environment, validation: result) + } + + /// Writes the selected value to a caller-owned pipe. The recipient controls its use. + public static func export( + source selector: String, declaration: Declaration, environment: RuntimeEnvironment, + policy: EffectiveSourcePolicy, to descriptor: Int32 = STDOUT_FILENO + ) throws { + let route = try route( + selector, declaration: declaration, environment: environment, policy: policy) + let output = fcntl(descriptor, F_DUPFD_CLOEXEC, 3) + guard output >= 0 else { throw SourceAccessError.exportRefused } + defer { close(output) } + var info = stat() + let access = fcntl(output, F_GETFL) + guard access >= 0, access & O_ACCMODE != O_RDONLY, fstat(output, &info) == 0, + info.st_mode & S_IFMT == S_IFIFO, + isatty(output) == 0, + let binding = try route.credential(environment.sourceAccess), binding.exportable + else { throw SourceAccessError.exportRefused } + + var signal = sigset_t() + sigemptyset(&signal) + sigaddset(&signal, SIGPIPE) + var previous = sigset_t() + guard pthread_sigmask(SIG_BLOCK, &signal, &previous) == 0 else { + throw SourceAccessError.exportRefused + } + defer { pthread_sigmask(SIG_SETMASK, &previous, nil) } + var pending = sigset_t() + sigpending(&pending) + let alreadyPending = sigismember(&pending, SIGPIPE) == 1 + let bytes = Data(try binding.value().utf8) + try bytes.withUnsafeBytes { buffer in + var offset = 0 + while offset < buffer.count { + let written = write(output, buffer.baseAddress!.advanced(by: offset), buffer.count - offset) + if written > 0 { + offset += written + } else if written == -1 && errno == EINTR { + continue + } else { + if written == -1 && errno == EPIPE && !alreadyPending { + // Consume only the signal generated by this write, before restoring the mask. + sigpending(&pending) + if sigismember(&pending, SIGPIPE) == 1 { + var received: Int32 = 0 + sigwait(&signal, &received) + } + } + throw SourceAccessError.exportRefused + } + } + } + } + + private static func route( + _ selector: String, declaration: Declaration, environment: RuntimeEnvironment, + policy: EffectiveSourcePolicy + ) throws -> SourceRoute { + let selection = try SourceArgument(selector).selection( + in: declaration, requirement: nil, path: nil, environment: environment) + return try SourceRoute(selection.source, environment: environment, policy: policy) + } + + private static func availability(_ binding: SourceCredentialBinding?) + -> SourceCredentialReport.Availability + { + guard let binding else { return .unconfigured } + return binding.available ? .available : .unavailable + } + + private static func report( + _ route: SourceRoute, environment: RuntimeEnvironment, + validation: SourceCredentialReport.Validation? + ) throws -> SourceCredentialReport { + let access = try environment.resolvedSourceAccess() + let binding = try route.credential(access) + let transport: SourceCredentialReport.Transport + let host: SourceAuthority? + let provider: SourceProvider? + switch route { + case .local: + transport = .local + host = nil + provider = nil + case .http(let url): + transport = url.scheme == "http" ? .http : .https + host = URLComponents(url: url, resolvingAgainstBaseURL: false).flatMap { + try? SourceAuthority($0, defaultPort: url.scheme == "http" ? 80 : 443) + } + provider = nil + case .git(let repository): + switch repository?.scheme { + case "ssh": transport = .ssh + case "https": transport = .https + default: transport = .git + } + host = repository?.authority + provider = repository.flatMap { access.provider(for: $0.authority, scheme: $0.scheme) } + case .archive(let repository, let profile): + transport = .archive + host = profile.authority + provider = access.provider(for: repository.authority, scheme: repository.scheme) + } + let status: SourceCredentialReport.Availability + if transport == .ssh { + status = .sshManaged + } else if case .git = route, binding == nil, let host, + delegatesGit(host, environment: environment) + { + status = .delegatedUnverified + } else { + status = availability(binding) + } + return .init( + provider: provider, effectiveHost: host?.display, transport: transport, + credentialSource: binding?.category, availability: status, validation: validation) + } + + private static func delegatesGit(_ host: SourceAuthority, environment: RuntimeEnvironment) -> Bool + { + environment.credentialedGitHosts.contains { + $0.caseInsensitiveCompare(host.host) == .orderedSame + } + } +} diff --git a/Sources/AgentsCore/SourceParser.swift b/Sources/AgentsCore/SourceParser.swift index 0902cc0..5a5392e 100644 --- a/Sources/AgentsCore/SourceParser.swift +++ b/Sources/AgentsCore/SourceParser.swift @@ -24,7 +24,8 @@ public enum SourceParser { public static func parse( _ rawInput: String, currentDirectory: URL = URL(fileURLWithPath: FileManager.default.currentDirectoryPath), - homeDirectory: URL = FileManager.default.homeDirectoryForCurrentUser + homeDirectory: URL = RuntimeEnvironment(sourceAccess: .init()).homeDirectory, + sourceAccess: SourceAccessConfiguration? = nil ) throws -> ParsedSource { let input = rawInput.trimmingCharacters(in: .whitespacesAndNewlines) guard !input.isEmpty, !input.contains("\0") else { @@ -52,7 +53,7 @@ public enum SourceParser { || input.range(of: #"^[^/@]+@[^/:]+:.+$"#, options: .regularExpression) != nil { _ = try SourceDeclaration(kind: .git, location: input).identity( - environment: RuntimeEnvironment()) + environment: RuntimeEnvironment(sourceAccess: .init())) return ParsedSource(type: .git, url: input) } if !input.contains("://") { @@ -67,16 +68,30 @@ public enum SourceParser { let hostQualified = parts[0].contains(".") || parts[0].contains(":") let url = hostQualified ? "https://" + input : "https://github.com/" + input _ = try SourceDeclaration(kind: .git, location: url).identity( - environment: RuntimeEnvironment()) + environment: RuntimeEnvironment(sourceAccess: .init())) return ParsedSource(type: .git, url: url) } guard let url = URL(string: input), ["http", "https"].contains(url.scheme), let host = url.host else { throw CoreError.invalidSource("unsupported source URL") } + let access = sourceAccess ?? RuntimeEnvironment(homeDirectory: homeDirectory).sourceAccess + try access.requireCurrentSettings() + let authority = URLComponents(url: url, resolvingAgainstBaseURL: false).flatMap { + try? SourceAuthority($0, defaultPort: url.scheme == "https" ? 443 : 80) + } + let provider = authority.flatMap { access.provider(for: $0, scheme: url.scheme!) } let parts = url.path.split(separator: "/").map(String.init) - if let marker = parts.firstIndex(of: "tree"), marker + 1 < parts.count, - host.lowercased() == "github.com" || (marker > 0 && parts[marker - 1] == "-") - { - let end = host.lowercased() == "github.com" ? marker : marker - 1 + let treeMarker: Int? + switch provider { + case .github: + treeMarker = parts.count > 3 && parts[2] == "tree" ? 2 : nil + case .gitlab: + treeMarker = parts.indices.dropFirst(3).first { + $0 + 1 < parts.count && parts[$0 - 1] == "-" && parts[$0] == "tree" + } + case nil: treeMarker = nil + } + if let marker = treeMarker { + let end = provider == .github ? marker : marker - 1 let repository = parts[.. Self { + let path = PathSafety.realPath(url.path) ?? url.resolvingSymlinksInPath().path + return local(path: path) + } + + /// A rule naming one absolute, standardized local source root. + package static func local(path: String) -> Self { + .init(.local, URL(fileURLWithPath: path).standardizedFileURL.path) + } + + public static func git(_ location: String) throws -> Self { + let transport = SourceDeclaration(kind: .git, location: location).gitURL + let url: String + if !transport.contains("://"), let colon = transport.firstIndex(of: ":") { + let repository = transport[transport.index(after: colon)...] + let separator = repository.hasPrefix("/") ? "" : "/" + url = "ssh://" + transport[..= 32 && $0.value != 127 }), + segments.allSatisfy({ !$0.isEmpty && $0 != "." && $0 != ".." }) + else { throw CoreError.invalidSource("invalid Git policy repository path") } + if path.hasSuffix(".git") { path.removeLast(4) } + if host == "github.com" { + var parts = path.split(separator: "/").map(String.init) + for index in parts.indices.prefix(2) { parts[index] = parts[index].lowercased() } + path = "/" + parts.joined(separator: "/") + } + guard path.last != "/" else { throw CoreError.invalidSource("empty Git policy repository") } + let port = parts.port.flatMap { $0 == defaultPort ? nil : ":\($0)" } ?? "" + var canonical = URLComponents() + canonical.path = path + let prefix = scheme == "http" || scheme == "git" ? scheme + "://" : "" + return .init(.git, prefix + host + port + canonical.percentEncodedPath) + } + + public static func http(_ location: String) throws -> Self { + guard let parts = URLComponents(string: location), let scheme = parts.scheme?.lowercased(), + let defaultPort = ["https": 443, "http": 80][scheme], let host = normalizedHost(parts), + parts.user == nil, parts.password == nil, parts.fragment == nil, validPort(parts.port) + else { throw CoreError.invalidSource("invalid HTTP policy origin") } + let port = parts.port.flatMap { $0 == defaultPort ? nil : ":\($0)" } ?? "" + return .init(.http, scheme + "://" + host + port) + } + + private static func normalizedHost(_ parts: URLComponents) -> String? { + guard var host = parts.url?.host?.lowercased(), !host.isEmpty, + !host.contains("%"), host.utf8.allSatisfy({ $0 < 128 }) + else { return nil } + if host.hasSuffix(".") { host.removeLast() } + if host.contains(":") { + var address = in6_addr() + var output = [CChar](repeating: 0, count: Int(INET6_ADDRSTRLEN)) + let literal = + host.hasPrefix("[") && host.hasSuffix("]") + ? String(host.dropFirst().dropLast()) : host + guard inet_pton(AF_INET6, literal, &address) == 1, + inet_ntop(AF_INET6, &address, &output, socklen_t(output.count)) != nil + else { return nil } + return "[" + + String(decoding: output.prefix { $0 != 0 }.map(UInt8.init(bitPattern:)), as: UTF8.self) + + "]" + } + var address = in_addr() + if inet_aton(host, &address) == 1 { + var output = [CChar](repeating: 0, count: Int(INET_ADDRSTRLEN)) + guard inet_ntop(AF_INET, &address, &output, socklen_t(output.count)) != nil else { + return nil + } + return String(decoding: output.prefix { $0 != 0 }.map(UInt8.init(bitPattern:)), as: UTF8.self) + } + guard !host.isEmpty, !host.hasSuffix(".") else { return nil } + return host + } + + private static func validPort(_ port: Int?) -> Bool { + port.map { (1...65535).contains($0) } ?? true + } + + package var policyLocator: String? { + guard let identity, kind == .git else { return identity } + if identity.contains("://") { return identity + ".git" } + let authority = identity.prefix(while: { $0 != "/" }) + let scheme = authority.hasSuffix(":443") ? "ssh://" : "https://" + return scheme + identity + ".git" + } + + public var description: String { + identity.map { kind.rawValue + " " + $0 } ?? kind.rawValue + } + + package static func declared(_ source: SourceDeclaration, in environment: RuntimeEnvironment) + throws -> Self + { + switch source.kind { + case .git: try git(source.gitURL) + case .wellKnown: try http(source.location) + case .local: local(at: source.localURL(environment: environment)) + } + } +} + +/// Within a layer, a deny rule wins. An omitted allow list admits known origins not denied there. +/// An explicitly empty allow list admits nothing. Missing provenance requires explicit admission. +public struct SourcePolicyRules: Equatable, Sendable, Encodable { + public let allow: [SourceOrigin]? + public let deny: [SourceOrigin] + private let allowedOrigins: Set? + private let deniedOrigins: Set + + private enum CodingKeys: String, CodingKey { case allow, deny } + + public init(allow: [SourceOrigin]? = nil, deny: [SourceOrigin] = []) { + self.allow = allow + self.deny = deny + allowedOrigins = allow.map(Set.init) + deniedOrigins = Set(deny) + } + + fileprivate func rejection(of origin: SourceOrigin) -> SourcePolicyViolation.Reason? { + func contains(_ rules: Set) -> Bool { + rules.contains(origin) || (origin.kind == .local && rules.contains(.local)) + } + if contains(deniedOrigins) { return .denied } + if let allowedOrigins, contains(allowedOrigins) { return nil } + if origin == .missing { return .missingOrigin } + return allowedOrigins == nil ? nil : .notAllowed + } +} + +public struct SourcePolicyLayer: Equatable, Sendable, Encodable { + public enum Scope: String, Sendable, Encodable { case user, project, organization } + + public let scope: Scope + public let url: URL + public let rules: SourcePolicyRules + + public init(scope: Scope, url: URL, rules: SourcePolicyRules) { + self.scope = scope + self.url = url + self.rules = rules + } +} + +/// `reference` identifies the source, resource or component causing the check. Callers use +/// stable references without credentials or other sensitive source input. +public struct SourcePolicyViolation: Equatable, Sendable, Encodable { + public enum Reason: String, Sendable, Encodable { case denied, notAllowed, missingOrigin } + + public let scope: SourcePolicyLayer.Scope + public let policyURL: URL + public let origin: SourceOrigin + public let reference: String? + public let reason: Reason +} + +public struct SourcePolicyFailure: Error, Sendable, CustomStringConvertible { + public let violations: [SourcePolicyViolation] + public let context: [SourceSpan] + + package init(violations: [SourcePolicyViolation], context: [SourceSpan] = []) { + self.violations = violations + self.context = context + } + + public var description: String { + violations.map { violation in + let reference = violation.reference.map { " (\($0))" } ?? "" + return "\(violation.scope.rawValue) source policy: \(violation.reason.rawValue) " + + "\(violation.origin)\(reference) [\(violation.policyURL.path)]" + }.joined(separator: "\n") + + context.map { span in + "\n at \(span.document.rawValue):\(span.line):\(span.column)" + }.joined() + } +} + +/// Effective policy is an intersection. A layer cannot grant access rejected by another layer. +public struct EffectiveSourcePolicy: Equatable, Sendable, Encodable { + public let layers: [SourcePolicyLayer] + public var isConfigured: Bool { !layers.isEmpty } + + public init(layers: [SourcePolicyLayer] = []) { + self.layers = layers + } + + public func violations(for origin: SourceOrigin, reference: String? = nil) + -> [SourcePolicyViolation] + { + layers.compactMap { layer in + layer.rules.rejection(of: origin).map { reason in + .init( + scope: layer.scope, policyURL: layer.url, origin: origin, reference: reference, + reason: reason) + } + } + } + + public func require(_ origin: SourceOrigin, reference: String? = nil) throws { + let failures = violations(for: origin, reference: reference) + guard failures.isEmpty else { throw SourcePolicyFailure(violations: failures) } + } + + package func require(_ source: SourceDeclaration, environment: RuntimeEnvironment) throws { + guard isConfigured else { return } + try require(.declared(source, in: environment)) + } + + package func require(_ artifact: LockedArtifact) throws { + guard isConfigured else { return } + for origin in Self.artifactOrigins(artifact) { try require(origin) } + } + + package static func artifactOrigins(_ artifact: LockedArtifact) -> [SourceOrigin] { + ([artifact.url] + (artifact.files ?? []).map(\.url)).map { (try? .http($0)) ?? .missing } + } +} diff --git a/Sources/AgentsCore/SourceProvenance.swift b/Sources/AgentsCore/SourceProvenance.swift new file mode 100644 index 0000000..a39acd7 --- /dev/null +++ b/Sources/AgentsCore/SourceProvenance.swift @@ -0,0 +1,74 @@ +public struct DocumentIdentity: Sendable, Hashable { + public let rawValue: String + public init(_ rawValue: String) { self.rawValue = rawValue } +} + +/// Half-open UTF-8 byte offsets and the 1-based line and byte column of the start. +public struct SourceSpan: Sendable, Hashable { + public let document: DocumentIdentity + public let start: Int + public let end: Int + public let line: Int + public let column: Int + + public init(document: DocumentIdentity, start: Int, end: Int, line: Int, column: Int) { + self.document = document + self.start = start + self.end = end + self.line = line + self.column = column + } +} + +/// Stable source coordinates, independent of a checkout or cache location. +public struct SourceProvenance: Sendable, Equatable { + public let sourceIdentity: String + public let revision: String? + public let artifactDigest: String? + public let relativePath: String + public let format: String + public let adapterVersion: String + public let group: String? + public let referenceChain: [SourceSpan] + public let pointer: String? + + public init( + sourceIdentity: String, revision: String? = nil, artifactDigest: String? = nil, + relativePath: String, format: String, adapterVersion: String, group: String? = nil, + referenceChain: [SourceSpan] = [], pointer: String? = nil + ) { + self.sourceIdentity = sourceIdentity + self.revision = revision + self.artifactDigest = artifactDigest + self.relativePath = relativePath + self.format = format + self.adapterVersion = adapterVersion + self.group = group + self.referenceChain = referenceChain + self.pointer = pointer + } +} + +public struct SourceMapEntry: Sendable, Equatable { + public let pointer: String + public let span: SourceSpan + public let origins: [SourceSpan] + public let defaulted: Bool + + public init( + pointer: String, span: SourceSpan, origins: [SourceSpan] = [], defaulted: Bool = false + ) { + self.pointer = pointer + self.span = span + self.origins = origins + self.defaulted = defaulted + } +} + +public struct DeclarationSourceMap: Sendable, Equatable { + public let entries: [SourceMapEntry] + public init(entries: [SourceMapEntry]) { self.entries = entries } + public func locations(at pointer: String) -> [SourceMapEntry] { + entries.filter { $0.pointer == pointer } + } +} diff --git a/Sources/AgentsCore/SourceReference.swift b/Sources/AgentsCore/SourceReference.swift index 3207dc1..0b9c001 100644 --- a/Sources/AgentsCore/SourceReference.swift +++ b/Sources/AgentsCore/SourceReference.swift @@ -23,26 +23,7 @@ struct SourceReference { return default: break } - guard let lower = SemanticVersion(requirement.value) else { - throw CoreError.invalidSource("invalid semantic version") - } - let candidates: [(String, SemanticVersion)] - if requirement.kind == "exact" { - candidates = tags.filter { $0.1.description == lower.description } - } else { - let upper: SemanticVersion - switch requirement { - case .upToNextMajor: upper = SemanticVersion(major: lower.major + 1, minor: 0, patch: 0) - case .upToNextMinor: - upper = SemanticVersion(major: lower.major, minor: lower.minor + 1, patch: 0) - default: - guard let bound = requirement.upperBound, let parsed = SemanticVersion(bound) else { - throw CoreError.invalidSource("missing version upper bound") - } - upper = parsed - } - candidates = tags.filter { $0.1.isInRange(from: lower, to: upper) } - } + let candidates = tags.filter { requirement.matches(version: $0.1) } guard let selected = candidates.last else { throw CoreError.notFound("no tag matches source requirement") } diff --git a/Sources/AgentsCore/SourceRequirement.swift b/Sources/AgentsCore/SourceRequirement.swift index a6b2f70..23e7995 100644 --- a/Sources/AgentsCore/SourceRequirement.swift +++ b/Sources/AgentsCore/SourceRequirement.swift @@ -44,7 +44,7 @@ public enum SourceRequirement: Codable, Equatable, Sendable { self = requirement } - static func decodeIfPresent(from decoder: Decoder) throws -> SourceRequirement? { + package static func decodeIfPresent(from decoder: Decoder) throws -> SourceRequirement? { let container = try decoder.container(keyedBy: CodingKeys.self) let keys: [CodingKeys] = [.branch, .revision, .exact, .from, .upToNextMinor] let present = keys.filter { container.contains($0) } @@ -99,7 +99,7 @@ public enum SourceRequirement: Codable, Equatable, Sendable { } } - private var isVersionRequirement: Bool { + var isVersionRequirement: Bool { switch kind { case "exact", "from", "minor", "range": return true @@ -225,3 +225,80 @@ struct SemanticVersion: Comparable, Equatable, Sendable, CustomStringConvertible } } } + +extension SourceRequirement { + /// Canonical spelling for new declaration and ledger fields. Decoding keeps stored spelling. + public func canonicalized() throws -> SourceRequirement { + try validate() + switch self { + case .branch, .revision: return self + case .exact(let version): return .exact(SemanticVersion(version)!.description) + default: + let (lower, upper) = declarationBounds! + let (major, majorOverflow) = lower.major.addingReportingOverflow(1) + if !majorOverflow, upper == SemanticVersion(major: major, minor: 0, patch: 0) { + return .upToNextMajor(from: lower.description) + } + let (minor, minorOverflow) = lower.minor.addingReportingOverflow(1) + if !minorOverflow, upper == SemanticVersion(major: lower.major, minor: minor, patch: 0) { + return .upToNextMinor(from: lower.description) + } + return .range(from: lower.description, to: upper.description) + } + } + + package var canonical: SourceRequirement { (try? canonicalized()) ?? self } + + /// Declaration comparison expands range spellings; exact requirements retain metadata. + package func declarationEquivalent(to other: SourceRequirement) -> Bool { + switch (self, other) { + case (.branch(let lhs), .branch(let rhs)), (.revision(let lhs), .revision(let rhs)): + return lhs == rhs + case (.exact(let lhs), .exact(let rhs)): + guard let left = SemanticVersion(lhs), let right = SemanticVersion(rhs) else { return false } + return left.description == right.description + default: + guard let left = declarationBounds, let right = other.declarationBounds else { return false } + return left.0 == right.0 && left.1 == right.1 + } + } + + package func validateMarketplaceVersion() throws { + try validate() + guard isVersionRequirement, value.utf8.count <= 128, + upperBound.map({ $0.utf8.count <= 128 }) ?? true, + self == canonical + else { throw MarketplaceError.invalidPackage("invalid version requirement: " + value) } + } + + package func admitsMarketplaceVersion(_ version: String) -> Bool { + if case .exact(let exact) = self { return version == exact } + guard let parsed = SemanticVersion(version), let (lower, upper) = declarationBounds else { + return false + } + return parsed.isInRange(from: lower, to: upper) + } + + package var marketplaceDescription: String { + if case .exact(let exact) = self { return exact } + guard let (lower, upper) = declarationBounds else { return value } + return ">=\(lower), <\(upper)" + } + + private var declarationBounds: (SemanticVersion, SemanticVersion)? { + switch self { + case .range(let from, let to): + guard let lower = SemanticVersion(from), let upper = SemanticVersion(to) else { return nil } + return (lower, upper) + case .upToNextMajor(let from), .upToNextMinor(let from): + guard let lower = SemanticVersion(from) else { return nil } + if case .upToNextMajor = self { + let (major, overflow) = lower.major.addingReportingOverflow(1) + return overflow ? nil : (lower, SemanticVersion(major: major, minor: 0, patch: 0)) + } + let (minor, overflow) = lower.minor.addingReportingOverflow(1) + return overflow ? nil : (lower, SemanticVersion(major: lower.major, minor: minor, patch: 0)) + default: return nil + } + } +} diff --git a/Sources/AgentsCore/SourceResolutionSession.swift b/Sources/AgentsCore/SourceResolutionSession.swift index 93a8c5f..728f8b4 100644 --- a/Sources/AgentsCore/SourceResolutionSession.swift +++ b/Sources/AgentsCore/SourceResolutionSession.swift @@ -8,24 +8,628 @@ package final class SourceResolutionSession { let pin: SourceRevision let root: URL } + package let sourcePolicy: EffectiveSourcePolicy + package var sourceAccess: SourceAccessConfiguration { store.environment.sourceAccess } + package let acquisitions: GitAcquisitionCaptures private let store: StateStore + private let stagedLocalSources: [String: URL] private let cache: SourceCache + package enum ReadMode { case persistentCache, temporary } + private let mode: ReadMode + private let temporaryCache: SourceCache + /// Exact-object acquisition cannot update the mirror behind frozen reference evidence. + private let objectCache: SourceCache + private var archiveTrees: [PrivateSourceRecovery.Reference: URL] = [:] + private var commits: [SourceSnapshotID: String] = [:] + private var catalogs: [String: SourceCatalog] = [:] + private var advertisements: [String: GitAcquisition.Advertisement] = [:] + private var observedSelections: [SourceSnapshotID: Set] = [:] + private var exact: [SourceSnapshotID: SourceSnapshot] = [:] + private var localTrees: [String: SourceSnapshot] = [:] + private var closed = false + private var borrowed: [SourceSnapshotID: SourceSnapshot] = [:] + private var evidence: [SourceSnapshotID: SourceSnapshotEvidence] = [:] + package private(set) var bundlePackageNames: [SourceSnapshotID: String] = [:] + package private(set) var bundleSources: [SourceSnapshotID: [PortableSourceEvidence]] = [:] private let workspace: URL private var snapshots: [Snapshot] = [] - package init(store: StateStore) throws { + package init( + store: StateStore, mode: ReadMode = .persistentCache, + sourcePolicy: EffectiveSourcePolicy = .init(), requireRecordedTransport: Bool = false, + stagedLocalSources: [String: URL] = [:], acquisitions: GitAcquisitionCaptures? = nil + ) throws { + self.sourcePolicy = sourcePolicy + let acquisitions = acquisitions ?? GitAcquisitionCaptures() + self.acquisitions = acquisitions + self.stagedLocalSources = stagedLocalSources + self.mode = mode self.store = store - cache = SourceCache(store: store) - workspace = FileManager.default.temporaryDirectory.appendingPathComponent( - "agents-resolution-" + UUID().uuidString) - try FileManager.default.createDirectory(at: workspace, withIntermediateDirectories: true) + cache = SourceCache( + store: store, sourcePolicy: sourcePolicy, requireRecordedTransport: requireRecordedTransport, + acquisitions: acquisitions) + workspace = try PrivateSourceRecovery.makeWorkspace(prefix: "agents-resolution-").url + var environment = store.environment + environment.projectDirectory = workspace.appendingPathComponent("sources") + temporaryCache = SourceCache( + store: StateStore(scope: .project, environment: environment), sourcePolicy: sourcePolicy, + requireRecordedTransport: requireRecordedTransport, acquisitions: acquisitions) + environment.projectDirectory = workspace.appendingPathComponent("objects") + objectCache = SourceCache( + store: StateStore(scope: .project, environment: environment), sourcePolicy: sourcePolicy, + requireRecordedTransport: requireRecordedTransport, acquisitions: acquisitions) } deinit { try? FileManager.default.removeItem(at: workspace) } + /// All borrowed views must be consumed inside this closure. Cleanup errors are observable. + package static func withTemporaryRead( + store: StateStore, sourcePolicy: EffectiveSourcePolicy = .init(), + requireRecordedTransport: Bool = false, stagedLocalSources: [String: URL] = [:], + acquisitions: GitAcquisitionCaptures? = nil, + _ body: (SourceResolutionSession) throws -> T + ) throws -> T { + let session = try SourceResolutionSession( + store: store, mode: .temporary, sourcePolicy: sourcePolicy, + requireRecordedTransport: requireRecordedTransport, stagedLocalSources: stagedLocalSources, + acquisitions: acquisitions) + do { + let result = try body(session) + try Task.checkCancellation() + try session.close() + return result + } catch { + try session.close() + throw error + } + } + + package func close() throws { + guard !closed else { return } + try FileManager.default.removeItem(at: workspace) + closed = true + snapshots.removeAll() + exact.removeAll() + localTrees.removeAll() + borrowed.removeAll() + evidence.removeAll() + archiveTrees.removeAll() + bundleSources.removeAll() + bundlePackageNames.removeAll() + commits.removeAll() + advertisements.removeAll() + observedSelections.removeAll() + } + + private func requireOpen() throws { + guard !closed else { throw CoreError.invalidState("source session is closed") } + if mode == .temporary { try Task.checkCancellation() } + } + + /// Bundle storage has its own admission path, where the seal is checked before copying. + package func requireSource(_ source: SourceDeclaration) throws { + if source.kind == .local, + BundleSourceLocation.container(of: source.localURL(environment: store.environment), in: store) + != nil + { + guard source.requirement == nil else { + throw CoreError.invalidSource("bundle sources cannot select Git revisions") + } + return + } + _ = try cache.route(source) + } + + /// Candidate evidence is captured once per normalized source, including revision expressions + /// first encountered later during backtracking. No persistent mirror or ref is written. + package func candidates( + for source: SourceDeclaration, requirements: [SourceRequirement?], + spending: (Int) throws -> Void = { _ in } + ) throws -> [SourceRevision] { + try requireOpen() + let route = try cache.route(source) + for requirement in requirements { try requirement?.validate() } + if case .archive(let repository, let profile) = route { + let selectors = try requirements.compactMap { requirement in + try requirement.map { try VCSArchiveRef(requirement: $0) } + } + guard let ref = selectors.first else { throw SourceAccessError.discoveryUnavailable } + guard selectors.allSatisfy({ $0 == ref }) else { return [] } + try spending(1) + let request = try VCSArchiveRequest(repository: repository, ref: ref, mirror: profile) + return [try observeArchive(source, route: route, request: request, profile: profile)] + } + let source = declaringSource(source) + let id = try source.identity(environment: store.environment) + let exactObjects = requirements.compactMap { requirement -> String? in + if case .revision(let object) = requirement, SourceCache.isObjectID(object) { return object } + return nil + } + if exactObjects.count == requirements.compactMap({ $0 }).count, !exactObjects.isEmpty { + let selected = try exactObjects.map { object in + try spending(1) + return try commit(object, source: source) + } + return Set(selected).count == 1 ? [SourceRevision(revision: selected[0])] : [] + } + if catalogs[id] == nil { + if let acquisition = cache.anonymousAcquisition(source), + let advertisement = try cache.attemptAnonymous({ try acquisition.discover() }), + remoteResolves(requirements, in: advertisement.catalog) + { + for _ in advertisement.catalog.references { try spending(1) } + advertisements[id] = advertisement + catalogs[id] = advertisement.catalog + } else { + catalogs[id] = try temporaryCache.referenceCatalog(source, spending: spending) + } + try Task.checkCancellation() + } else if let advertisement = advertisements[id], + !remoteResolves(requirements, in: advertisement.catalog) + { + let complete = try temporaryCache.referenceCatalog(source, spending: spending) + guard + advertisement.catalog.references.filter({ + $0.key == "HEAD" || $0.key.hasPrefix("refs/heads/") || $0.key.hasPrefix("refs/tags/") + }) + == complete.references.filter({ + $0.key == "HEAD" || $0.key.hasPrefix("refs/heads/") || $0.key.hasPrefix("refs/tags/") + }) + else { throw CoreError.invalidState("Git references changed during source resolution") } + catalogs[id] = complete + advertisements[id] = nil + } + var catalog = catalogs[id]! + for requirement in requirements { + if case .revision(let expression) = requirement, catalog.references[expression] == nil { + if SourceCache.isObjectID(expression) { + try spending(1) + catalog.references[expression] = try commit(expression, source: source) + } else if let advertisement = advertisements[id] { + catalog.references[expression] = + GitAcquisition.reference( + expression, in: advertisement.catalog)?.1 + } else { + catalog.references[expression] = try temporaryCache.catalogRevision( + expression, source: source) + } + } + } + catalogs[id] = catalog + let selected = try catalog.candidates(requirements: requirements, spending: spending) + if let advertisement = advertisements[id] { + for pin in selected { + let availableTags = advertisement.catalog.tags.filter { $0.value == pin.revision } + let key = SourceSnapshotID(source: id, revision: pin.revision) + for requirement in requirements.isEmpty ? [nil] : requirements { + if case .revision(let object) = requirement, SourceCache.isObjectID(object) { continue } + if let reference = try? SourceReference( + requirement: requirement, tags: Array(availableTags.keys)), + let (name, object) = GitAcquisition.reference( + reference.name, in: advertisement.catalog), object == pin.revision + { + observedSelections[key, default: []].insert(name) + } + } + } + } + return selected + } + + private func observeArchive( + _ source: SourceDeclaration, route: SourceRoute, request: VCSArchiveRequest, + profile: SourceArchiveMirror + ) throws -> SourceRevision { + let key = source.gitURL + "\0" + request.url.absoluteString + if let prior = acquisitions.archiveSelections[key] { return prior } + let bytes = try PrivateSourceRecovery.download( + request, route: route, environment: store.environment) + let verified = try VerifiedVCSArchive(bytes) + let archive = SourceArchiveEvidence( + effectiveURL: request.url, flavor: profile.flavor, ref: request.ref, + treeDigest: verified.treeDigest, observedArchiveDigest: verified.byteDigest, + requiredArchiveDigest: profile.requiresExactArchiveBytes ? verified.byteDigest : nil) + var version: String? + if case .tag(let name) = request.ref { version = SemanticVersion(name)?.description } + let pin = SourceRevision(revision: archive.treeDigest, version: version, archive: archive) + let reference = PrivateSourceRecovery.Reference(transport: source.gitURL, archive: archive) + try acquisitions.captureArchive(bytes, verified: verified, reference: reference) + acquisitions.archiveSelections[key] = pin + return pin + } + + private func archiveSnapshot( + _ source: SourceDeclaration, pin: SourceRevision, reference: PrivateSourceRecovery.Reference, + route: SourceRoute, request: VCSArchiveRequest, offline: Bool + ) throws -> SourceSnapshot { + guard pin.revision == reference.archive.treeDigest else { + throw SourceAccessError.archiveChanged + } + let environment = store.environment + let root: URL + if let existing = archiveTrees[reference] { + root = existing + } else { + let verified: VerifiedVCSArchive + if let data = try acquisitions.readArchive(reference) { + verified = try VerifiedVCSArchive(data) + } else if let (_, retained) = try PrivateSourceRecovery(environment: environment).read( + reference) + { + verified = retained + } else { + guard !offline else { throw SourceAccessError.recoveryUnavailable } + let bytes = try PrivateSourceRecovery.download( + request, route: route, environment: environment) + verified = try VerifiedVCSArchive(bytes) + try reference.archive.verify(verified) + try acquisitions.captureArchive(bytes, verified: verified, reference: reference) + } + try reference.archive.verify(verified) + root = try verified.extract( + named: UUID().uuidString, in: DirectoryHandle(at: workspace), environment: environment) + archiveTrees[reference] = root + } + let key = try SourceSnapshotID( + source: source.identity(environment: environment), revision: pin.revision) + let base = try SourceSnapshot(snapshot: key, pin: pin, root: root) + if let previous = evidence[key]?.archive, previous != reference.archive { + throw SourceAccessError.ambiguousRoute + } + register(base, source: LockedSource(kind: .git, url: source.gitURL)) + return try SourceSnapshot( + snapshot: key, pin: pin, root: root, discoveryPath: source.path ?? ".") + } + + private func remoteResolves( + _ requirements: [SourceRequirement?], in catalog: SourceCatalog + ) -> Bool { + requirements.allSatisfy { requirement in + guard case .revision(let expression) = requirement, !SourceCache.isObjectID(expression) + else { return true } + return GitAcquisition.reference(expression, in: catalog) != nil + } + } + + package func snapshot( + _ source: SourceDeclaration, at pin: SourceRevision, offline: Bool = false + ) throws -> SourceSnapshot { + try requireOpen() + let route = try cache.route(source) + if let request = try route.requireRecordedArchive(pin.archive), let archive = pin.archive { + return try archiveSnapshot( + source, pin: pin, reference: .init(transport: source.gitURL, archive: archive), + route: route, request: request, offline: offline) + } + let source = declaringSource(source) + var pin = pin + pin.revision = try commit(pin.revision, source: source) + let id = try source.identity(environment: store.environment) + let key = SourceSnapshotID(source: id, revision: pin.revision) + let base: SourceSnapshot + if let existing = exact[key] { + base = existing + } else { + var selected = source + selected.requirement = .revision(pin.revision) + selected.path = nil + func copy(_ tree: URL) throws -> SourceSnapshot { + let root = workspace.appendingPathComponent(UUID().uuidString) + try FileManager.default.copyItem(at: tree, to: root) + return try SourceSnapshot( + snapshot: key, pin: pin, root: root, + localEnvironment: localEnvironment(for: source), + liveRoot: source.kind == .local && source.requirement == nil + ? source.localURL(environment: store.environment) : nil) + } + 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) + } + } + if let refs = observedSelections[key], let advertisement = advertisements[id], + let acquisition = cache.anonymousAcquisition(source), + let pack = try acquisition.exact(pin.revision, offline: true) + { + for ref in refs.sorted() { + 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 ?? ".", + localEnvironment: localEnvironment(for: source), + liveRoot: source.kind == .local && source.requirement == nil + ? source.localURL(environment: store.environment) : nil) + } + + private func commit(_ object: String, source: SourceDeclaration) throws -> String { + guard SourceCache.isObjectID(object) else { + throw CoreError.invalidState("snapshot requires an exact Git object") + } + let key = try SourceSnapshotID( + source: source.identity(environment: store.environment), revision: object) + if let existing = commits[key] { return existing } + let resolved: String + if advertisements[key.source] != nil, + let acquisition = cache.anonymousAcquisition(source), + let pack = try cache.attemptAnonymous({ try acquisition.exact(object) }) + { + acquisition.remember(pack) + resolved = pack.revision + } else if let cached = try cache.catalogRevision(object, source: source) { + resolved = cached + } else if let frozen = try temporaryCache.catalogRevision(object, source: source) { + resolved = frozen + } else { + resolved = try objectCache.acquireCommit(object, source: source) + } + commits[key] = resolved + commits[SourceSnapshotID(source: key.source, revision: resolved)] = resolved + try Task.checkCancellation() + return resolved + } + + private func declaringSource(_ source: SourceDeclaration) -> SourceDeclaration { + var source = source + if source.environment == nil { + source.environment = SourceEnvironment( + projectDirectory: store.environment.projectDirectory, + homeDirectory: store.environment.homeDirectory) + } + return source + } + + /// Non-Git local producers are copied once, then identified by bytes and executable flags. + package func localSnapshot(_ source: SourceDeclaration) throws -> SourceSnapshot { + try requireOpen() + let id = try source.identity(environment: store.environment) + let live = source.localURL(environment: store.environment) + let bundleContainer = BundleSourceLocation.container(of: live, in: store) + try requireSource(source) + let bundled = bundleContainer != nil + let local = bundled ? nil : localEnvironment(for: source) + if let existing = localTrees[id] { + return try SourceSnapshot( + snapshot: existing.snapshot, pin: nil, root: existing.root, + discoveryPath: source.path ?? ".", localEnvironment: local, + liveRoot: existing.liveRoot) + } + guard source.kind == .local, source.requirement == nil else { + throw CoreError.invalidSource("a non-Git source cannot have a Git requirement") + } + let root = workspace.appendingPathComponent(UUID().uuidString) + let input: URL + if let staged = stagedLocalSources[id] { + guard bundleContainer != nil else { + throw CoreError.invalidState("invalid staged bundle source") + } + input = staged.resolvingSymlinksInPath() + } else if let bundleContainer { + // Only the caller's configured base may resolve an alias. The bundle store and its + // contents are opened through no-follow directory handles. + let base = store.directory.deletingLastPathComponent().resolvingSymlinksInPath() + input = base.appendingPathComponent(store.directory.lastPathComponent) + .appendingPathComponent(BundleSourceLocation.directory) + .appendingPathComponent(bundleContainer.lastPathComponent) + .appendingPathComponent(BundleSourceLocation.tree) + } else { + input = live.resolvingSymlinksInPath() + } + let marker = + try bundled ? BundleStoredSource.readMarker(input.deletingLastPathComponent()) : nil + if let marker { + try sourcePolicy.requireBundleSources( + marker.sources, reference: bundleContainer!.lastPathComponent) + } + let origin = try DirectoryHandle(at: input) + let destination = try DirectoryHandle(at: workspace) + try destination.copy(root.lastPathComponent, from: origin, named: ".") { _ in + try Task.checkCancellation() + } + try Self.validateLinks(root) + try marker?.validateTree(root) + let flags = try FileHash.executableFlags(root) + let content = try FileHash.folderHash(root) + let evidence = FileHash.hashRecords( + [("content", Data(content.utf8))] + + flags.keys.sorted().map { + ("execute\0" + $0, Data([flags[$0]! ? 1 : 0])) + }) + let result = try SourceSnapshot( + snapshot: SourceSnapshotID( + source: id, revision: "sha256:" + evidence), + pin: nil, root: root, discoveryPath: source.path ?? ".", + localEnvironment: local, liveRoot: bundled ? nil : live) + localTrees[id] = result + bundleSources[result.snapshot] = marker?.sources + if marker?.marketplaceNode == nil { bundlePackageNames[result.snapshot] = marker?.package.name } + register(result) + try Task.checkCancellation() + return result + } + + /// Registers only a borrowed view; closing the session invalidates all resource access. + package func register(_ view: SourceSnapshot, source: LockedSource? = nil) { + borrowed[view.snapshot] = view + if source == nil, evidence[view.snapshot] != nil { return } + let container = + view.packageIdentity == view.snapshot.source + ? nil + : SourceSnapshotID( + source: view.packageIdentity, revision: view.snapshot.revision) + let descriptor = + source + ?? (container == nil + ? LockedSource( + kind: view.snapshot.source.hasPrefix("local:") ? .local : .wellKnown) : nil) + evidence[view.snapshot] = SourceSnapshotEvidence( + snapshot: view.snapshot, + pin: view.pin.map { pin in + pin.archive == nil ? SourceRevision(revision: pin.revision) : pin + }, source: descriptor, container: container, + archive: container == nil ? view.pin?.archive : nil) + } + + package func sourceEvidence(for snapshots: Set) -> [SourceSnapshotEvidence] { + var required = snapshots + var pending = Array(snapshots) + while let snapshot = pending.popLast() { + if let container = evidence[snapshot]?.container, required.insert(container).inserted { + pending.append(container) + } + } + return required.compactMap { evidence[$0] }.sorted { + $0.snapshot.source == $1.snapshot.source + ? $0.snapshot.revision < $1.snapshot.revision : $0.snapshot.source < $1.snapshot.source + } + } + + package func resource(snapshot: SourceSnapshotID, path: String) throws -> URL { + try requireOpen() + guard let view = borrowed[snapshot] else { throw CoreError.notFound("source snapshot") } + return try view.resource(path) + } + + package func fileSnapshot( + source: String, revision: String, files: [String: Data], executableFlags: [String: Bool] = [:] + ) throws + -> SourceSnapshot + { + try requireOpen() + let id = SourceSnapshotID(source: source, revision: revision) + if let existing = borrowed[id] { return existing } + let root = workspace.appendingPathComponent(UUID().uuidString) + try FileSystem.createDirectory(at: root) + for path in files.keys.sorted() { + try Task.checkCancellation() + let file = try PathSafety.resolvedChild(base: root, subpath: path) + try FileSystem.createDirectory(at: file.deletingLastPathComponent()) + try FileSystem.write(files[path]!, to: file) + try FileManager.default.setAttributes( + [.posixPermissions: executableFlags[path] == true ? 0o755 : 0o644], ofItemAtPath: file.path) + } + let result = try SourceSnapshot(snapshot: id, pin: nil, root: root) + register(result) + return result + } + + /// Reborrows an admitted artifact closure without consulting its index or download coordinates. + package func artifactSnapshot( + source: String, resource: LedgerResource, objects: [String: Data] + ) throws -> SourceSnapshot { + try requireOpen() + guard resource.kind == .artifact, let artifact = resource.artifact else { + throw CoreError.invalidState("missing pinned artifact resource") + } + try artifact.validate() + let id = SourceSnapshotID(source: source, revision: artifact.digest) + if let existing = borrowed[id] { return existing } + let root = workspace.appendingPathComponent(UUID().uuidString) + let destination = + resource.support.isEmpty + ? try PathSafety.resolvedChild(base: root, subpath: resource.path) : root + var embedded = resource + embedded.kind = .embedded + try LedgerResources.materialize(embedded, objects: objects, at: destination) + let result = try SourceSnapshot(snapshot: id, pin: nil, root: root) + let captured = try LedgerResources.capture( + result.resource(resource.path), embed: false, limits: .standard, sourceRoot: root) + guard captured.hash == resource.hash else { + throw CoreError.invalidState("pinned artifact resource hash mismatch") + } + register(result) + return result + } + + package func liveSnapshot(_ source: SourceDeclaration) throws -> SourceSnapshot { + try requireOpen() + try sourcePolicy.require(source, environment: store.environment) + guard source.kind == .local, source.requirement == nil else { + throw CoreError.invalidSource("edit requires an actual local source with no requirement") + } + let root = source.localURL(environment: store.environment) + guard BundleSourceLocation.container(of: root, in: store) == nil else { + throw CoreError.invalidSource("bundle sources are immutable") + } + let result = try SourceSnapshot( + snapshot: SourceSnapshotID( + source: source.identity(environment: store.environment), revision: "live"), + pin: nil, root: root, discoveryPath: source.path ?? ".", + localEnvironment: localEnvironment(for: source), liveRoot: root) + register(result) + return result + } + + package func isGitSource(_ source: SourceDeclaration) throws -> Bool { + try requireSource(source) + 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 + } + + private func localEnvironment(for source: SourceDeclaration) -> SourceEnvironment? { + guard source.kind == .local else { return nil } + return SourceEnvironment( + projectDirectory: source.localURL(environment: store.environment), + homeDirectory: source.environment?.homeDirectory ?? store.environment.homeDirectory) + } + + private static func validateLinks(_ root: URL) throws { + guard let real = PathSafety.realPath(root.path), + let entries = FileManager.default.enumerator( + at: root, includingPropertiesForKeys: [.isSymbolicLinkKey]) + else { return } + for case let entry as URL in entries { + try Task.checkCancellation() + if try entry.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink == true, + try !PathSafety.linkStaysInside(entry, root: real) + { + throw CoreError.unsafePath("local source symlink escapes snapshot") + } + } + } + package func withSnapshot( _ source: SourceDeclaration, _ body: (SourceRevision, URL) throws -> T ) throws -> T { + try requireOpen() + try sourcePolicy.require(source, environment: store.environment) let identity = try source.identity(environment: store.environment) let effective = LockedSource( kind: source.kind, url: source.kind == .git ? source.gitURL : nil, @@ -34,9 +638,12 @@ package final class SourceResolutionSession { { return try body(snapshot.pin, snapshot.root) } - let snapshot = try cache.withResolvedSnapshot(source) { pin, tree in + let snapshot = try cache.withResolvedSnapshot(source, cacheSource: mode == .persistentCache) { + pin, tree in let root = workspace.appendingPathComponent(UUID().uuidString) - try FileManager.default.copyItem(at: tree, to: root) + try FileSystem.withAccessErrors(at: root) { + try FileManager.default.copyItem(at: tree, to: root) + } return Snapshot(identity: identity, source: effective, pin: pin, root: root) } snapshots.append(snapshot) diff --git a/Sources/AgentsCore/SourceRevisionInspection.swift b/Sources/AgentsCore/SourceRevisionInspection.swift index 9822df9..b783a07 100644 --- a/Sources/AgentsCore/SourceRevisionInspection.swift +++ b/Sources/AgentsCore/SourceRevisionInspection.swift @@ -1,9 +1,13 @@ import Foundation extension SourceCache { - /// Resolves selection intent without fetching, creating a cache or refreshing an index. - /// Full object IDs must resolve to commits through cached objects or advertised refs. + /// Resolves selection intent without committing acquisition state. Direct Git inspects + /// cached objects and advertised refs. Archive routes verify one exact archive request. package func inspectRevision(_ source: SourceDeclaration) throws -> SourceRevision { + let route = try route(source) + 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 { @@ -34,9 +38,11 @@ extension SourceCache { { return SourceRevision(revision: commit) } + let managed = try ManagedSourceGit.select(route, environment: store.environment) + let options = managed == nil ? try recordedGitOptions(source.gitURL) : [] let output = try ProcessRunner.git( - ["--no-optional-locks", "ls-remote", "--", source.gitURL], - operation: .listRemoteReferences, source: source.location + options + ["--no-optional-locks", "ls-remote", "--", source.gitURL], + operation: .listRemoteReferences, source: source.location, managed: managed ).stdout var refs: [String: String] = [:] for line in output.split(separator: "\n") { @@ -71,7 +77,7 @@ extension SourceCache { throw CoreError.notFound("source reference cannot be resolved without fetching: \(ref.name)") } - static func isObjectID(_ value: String) -> Bool { + package static func isObjectID(_ value: String) -> Bool { value.range(of: #"^[0-9a-f]{40}([0-9a-f]{24})?$"#, options: .regularExpression) != nil } } diff --git a/Sources/AgentsCore/SourceSnapshot.swift b/Sources/AgentsCore/SourceSnapshot.swift new file mode 100644 index 0000000..28da20b --- /dev/null +++ b/Sources/AgentsCore/SourceSnapshot.swift @@ -0,0 +1,85 @@ +import Foundation + +/// Exact content identity. Discovery roots are namespaces within this content, not versions. +package struct SourceSnapshotID: Hashable, Sendable { + package let source: String + package let revision: String + + package init(source: String, revision: String) { + self.source = source + self.revision = revision + } +} + +/// A borrowed view, valid only while its source session is open. Stable output uses `snapshot` +/// and relative paths. `liveRoot` exists only for actual local authoring sources. +package struct SourceSnapshot { + package let snapshot: SourceSnapshotID + package let pin: SourceRevision? + package let root: URL + package let discoveryPath: String + /// Actual local source root before `discoveryPath`, with its declaring home. Pinned local + /// sources retain this origin; remote-contained syntax has none. It does not permit editing. + package let localEnvironment: SourceEnvironment? + package let liveRoot: URL? + package let packageIdentity: String + + package init( + snapshot: SourceSnapshotID, pin: SourceRevision?, root: URL, discoveryPath: String = ".", + localEnvironment: SourceEnvironment? = nil, liveRoot: URL? = nil, + packageIdentity: String? = nil + ) throws { + self.snapshot = snapshot + self.packageIdentity = packageIdentity ?? snapshot.source + self.pin = pin + self.root = root + self.discoveryPath = try PathSafety.sanitizeSubpath(discoveryPath) + self.localEnvironment = localEnvironment + self.liveRoot = liveRoot + _ = try directory() + } + + package func directory() throws -> URL { try resource(discoveryPath) } + + /// Both authored spelling and real symlink resolution must remain in the snapshot. + package func resource(_ path: String) throws -> URL { + guard !path.hasPrefix("~") else { throw CoreError.unsafePath("resource must be relative") } + let file = try PathSafety.resolvedChild(base: root, subpath: path) + guard PathSafety.isContained(file.resolvingSymlinksInPath(), in: root.resolvingSymlinksInPath()) + else { throw CoreError.unsafePath("resource escapes its source snapshot: \(path)") } + return file + } + + /// Directory resources may contain links below their top-level entry as well. + package func validateResourceTree(_ directory: URL) throws { + _ = try relativePath(directory) + guard let real = PathSafety.realPath(root.path), + let entries = FileManager.default.enumerator( + at: directory, includingPropertiesForKeys: [.isSymbolicLinkKey]) + else { return } + for case let entry as URL in entries { + try Task.checkCancellation() + if try entry.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink == true, + try !PathSafety.linkStaysInside(entry, root: real) + { + throw CoreError.unsafePath("resource symlink escapes source snapshot") + } + } + } + + package func relativePath(_ url: URL) throws -> String { + let path = PathSafety.relativePath(url.path, to: root.path) + _ = try resource(path) + return path + } +} + +/// Stable reconstruction coordinates. Contained sources borrow the enclosing package's exact +/// tree; resource paths remain relative to that tree. No borrowed URL is part of this evidence. +package struct SourceSnapshotEvidence: Equatable, Sendable { + package let snapshot: SourceSnapshotID + package let pin: SourceRevision? + package let source: LockedSource? + package let container: SourceSnapshotID? + package var archive: SourceArchiveEvidence? = nil +} diff --git a/Sources/AgentsCore/StateInspection.swift b/Sources/AgentsCore/StateInspection.swift index 20617c3..f589c2d 100644 --- a/Sources/AgentsCore/StateInspection.swift +++ b/Sources/AgentsCore/StateInspection.swift @@ -1,19 +1,71 @@ +import CPlatform import Foundation -#if canImport(Darwin) - import Darwin -#else - import Glibc -#endif - extension StateStore { + package func validateHeldScope() throws { + guard let context = TransactionLockContext.current(self) else { + throw CoreError.invalidState("publication requires scope coordination") + } + try context.requireHeldScope() + } + + package var configurationJSONURL: URL? { + scope == .user ? directory.appendingPathComponent(Self.configurationJSONFileName) : nil + } + + package func stateEntryExists(_ name: String) throws -> Bool { + try openDirectoryIfPresent()?.info(name) != nil + } + + package func configurationInputBytes(_ name: String) throws -> Data? { + guard let directory = try openDirectoryIfPresent(), + try directory.info(name) != nil + else { return nil } + return try directory.read(name, maximumBytes: LedgerLimits.standard.encodedBytes) + } + + /// Metadata and admission entries, including absent paths. Only the supplied scope root + /// resolves through links; state-directory and lock links do not grant new path authority. + package var metadataReadLocations: [URL] { + let root = scope == .project ? environment.projectDirectory : environment.homeDirectory + let roots = [root, root.resolvingSymlinksInPath()] + return roots + + roots.flatMap { root in + let directory = root.appendingPathComponent(self.directory.lastPathComponent) + return [directory] + + [ + Self.declarationFileName, Self.resolvedFileName, Self.watchFileName, ".agents.lock", + TransactionJournal.fileName, TransactionJournal.incompleteFileName, + "watch-refs.pending", + ].map { directory.appendingPathComponent($0) } + + (scope == .user + ? [directory.appendingPathComponent(Self.configurationJSONFileName)] : []) + } + } + /// Takes an existing scope lock without creating files or replaying recovery. - /// Pending recovery runs the diagnostic callback instead of inspecting inconsistent state. + /// Pending recovery runs the diagnostic callback instead of inspecting inconsistent state; + /// by default it throws `CoreError.recoveryPending`. /// The body may be retried when a first writer creates the scope lock. + /// The location callback reports external shared admission dependencies before opening them, + /// including failed attempts, and may report a location more than once during re-admission. package func withReadLock( - onPendingRecovery: () throws -> T = { - throw CoreError.invalidState("transaction recovery is required before inspection") - }, + onPendingRecovery: (() throws -> T)? = nil, + footprint: Set = [], + installations: [SkillInstallationTarget] = [], + onReadLocation: ((URL) -> Void)? = nil, + _ body: () throws -> T + ) throws -> T { + try withCoordination( + routes: footprint, installations: installations, writable: false, + onReadLocation: onReadLocation + ) { + try withScopeReadLock(onPendingRecovery: onPendingRecovery, body) + } + } + + private func withScopeReadLock( + onPendingRecovery: (() throws -> T)? = nil, _ body: () throws -> T ) throws -> T { while true { @@ -23,17 +75,30 @@ extension StateStore { openat($0.descriptor, ".agents.lock", O_RDONLY | O_NOFOLLOW | O_CLOEXEC) } ?? -1 if directory != nil, descriptor < 0, errno != ENOENT { - throw CoreError.invalidState("cannot open scope lock for inspection") + throw FileSystem.posixError( + errno, at: self.directory.appendingPathComponent(".agents.lock"), + otherwise: .invalidState("cannot open scope lock for inspection")) } defer { if descriptor >= 0 { close(descriptor) } } if descriptor >= 0 { - while flock(descriptor, LOCK_SH) != 0 { + while platform_flock(descriptor, LOCK_SH) != 0 { if errno != EINTR { throw CoreError.invalidState("cannot acquire scope inspection lock") } } } - defer { if descriptor >= 0 { flock(descriptor, LOCK_UN) } } + defer { if descriptor >= 0 { platform_flock(descriptor, LOCK_UN) } } + if descriptor >= 0, let directory { + try TransactionLockContext.current(self)?.bindScope(directory, descriptor: descriptor) + } + try verifyCoordinationAdmission() let pending = try hasPendingRecovery(in: directory) - let result = Result { try pending ? onPendingRecovery() : body() } + let result = Result { + guard pending else { return try body() } + guard let onPendingRecovery else { + throw CoreError.recoveryPending( + FileTransaction.recoveryDiagnostic(store: self).message) + } + return try onPendingRecovery() + } // Writers create the lock before mutation and never remove it. A failed // unlocked read also needs revalidation before its error can be trusted. if descriptor < 0, let current = try openDirectoryIfPresent(), @@ -46,7 +111,8 @@ extension StateStore { } private func hasPendingRecovery(in directory: DirectoryHandle?) throws -> Bool { - try directory?.info("transaction.json") != nil || directory?.info("transaction.new") != nil - || directory?.info("watch-refs.pending") != nil + guard let directory else { return false } + return try TransactionJournal.isPresent(in: directory) + || directory.info("watch-refs.pending") != nil } } diff --git a/Sources/AgentsCore/StateJSON.swift b/Sources/AgentsCore/StateJSON.swift index 4ecd595..abc73ba 100644 --- a/Sources/AgentsCore/StateJSON.swift +++ b/Sources/AgentsCore/StateJSON.swift @@ -1,10 +1,10 @@ import Foundation -/// The layout of `agents.json` and `agents.resolved`, as Prettier writes JSON with its default -/// 80-column width: two-space indentation, `"key": value`, every non-empty object expanded one -/// member per line, empty containers as `{}` and `[]`, and an array on one line when it holds no -/// object and fits, else one element per line. Keys keep the encoder's sorted order and string -/// bytes are copied as encoded. +/// The layout of `agents.resolved`, as Prettier writes JSON with its default 80-column width: +/// two-space indentation, `"key": value`, every non-empty object expanded one member per line, +/// empty containers as `{}` and `[]`, and an array on one line when it holds no object and fits, +/// else one element per line. Keys keep the encoder's sorted order and string bytes are copied +/// as encoded. enum StateJSON { private static let width = 80 diff --git a/Sources/AgentsCore/StateStore.swift b/Sources/AgentsCore/StateStore.swift index f2cd90e..6980909 100644 --- a/Sources/AgentsCore/StateStore.swift +++ b/Sources/AgentsCore/StateStore.swift @@ -15,114 +15,216 @@ public struct StateStore: Sendable { ? environment.projectDirectory.appendingPathComponent(".agent") : environment.homeDirectory.appendingPathComponent(".agents") } - public var declarationURL: URL { directory.appendingPathComponent("agents.json") } - public var resolvedURL: URL { directory.appendingPathComponent("agents.resolved") } - public var watchURL: URL { directory.appendingPathComponent("agents.watch") } + public var declarationURL: URL { directory.appendingPathComponent(Self.declarationFileName) } + public var resolvedURL: URL { directory.appendingPathComponent(Self.resolvedFileName) } + public var watchURL: URL { directory.appendingPathComponent(Self.watchFileName) } public var cacheDirectory: URL { directory.appendingPathComponent("cache") } - public func loadDeclaration() throws -> Declaration { - try withLock(createIfMissing: false) { try readDeclaration() } - } + package static let declarationFileName = "agents.yaml" + package static let resolvedFileName = "agents.resolved" + package static let watchFileName = "agents.watch" + package static let configurationJSONFileName = "agents.json" + package static let originalLedgerFileName = "agents.resolved.original" + /// The scope files a state transaction may replace. + package static let marketplaceDirectoryFileName = "marketplaces.yaml" + package static let sourcePolicyFileName = "source-policy.yaml" + package static let stateFileNames: Set = [ + declarationFileName, resolvedFileName, watchFileName, MaterializationReceipts.fileName, + ] - package func readDeclaration() throws -> Declaration { - let declaration: Declaration = try load(declarationURL) ?? Declaration() - try declaration.validate(environment: environment) - return declaration + /// The declaration's bytes, or nil when the scope has no declaration and no lock or watch + /// state. Lock or watch state without a declaration is `CoreError.missingDeclaration`; a + /// prepared generation answers from its captured bytes. + package func declarationBytes(prepared: StatePrecondition? = nil) throws -> Data? { + func bytes(_ url: URL) throws -> Data? { + try prepared.map { try $0.bytes(for: url) } ?? existingData(url) + } + if let declaration = try bytes(declarationURL) { return declaration } + guard try bytes(resolvedURL) == nil, try bytes(watchURL) == nil else { + throw CoreError.missingDeclaration(declarationURL.path) + } + return nil } + /// Reads the lock under a shared lock, without recovery or creating files. public func loadResolved() throws -> ResolvedState { - try withLock(createIfMissing: false) { try readResolved() } + try withReadLock { + _ = try declarationBytes() + return try readResolved() + } } - package func readResolved() throws -> ResolvedState { - let lock: ResolvedState = try load(resolvedURL) ?? ResolvedState() - try lock.validate() - return lock + package func readResolved(prepared: StatePrecondition? = nil) throws -> ResolvedState { + try readLedger(prepared: prepared).domainProjection(roots: ledgerRoots) } + /// Reads watch state under a shared lock, without recovery or creating files. public func loadWatch() throws -> WatchState { - try withLock(createIfMissing: false) { try readWatch() } + try withReadLock { + _ = try declarationBytes() + return try readWatch() + } } - package func readWatch() throws -> WatchState { - let watch: WatchState = try load(watchURL) ?? WatchState() + package func readWatch(prepared: StatePrecondition? = nil) throws -> WatchState { + let watch: WatchState = try load(watchURL, prepared: prepared) ?? WatchState() try watch.validate() return watch } - /// Commits state through the scope journal. Omitting watch preserves its existing bytes. - public func save( - declaration: Declaration, resolved: ResolvedState, watch: WatchState? = nil + /// Publishes a planned declaration change in the transaction, expecting the prepared + /// generation. Without a change the declaration stays unchanged. + package func stageDeclaration( + _ change: DeclarationChange?, in transaction: FileTransaction, prepared: StatePrecondition ) throws { - try withLock { - try declaration.validate(environment: environment) - try resolved.validate() - try watch?.validate() - _ = try readDeclaration() - _ = try readResolved() - let transaction = FileTransaction(store: self) - try stageDeclaration(declaration, in: transaction) - try transaction.replace( - resolvedURL, content: nil, data: Self.encodeState(resolved.normalized)) - if let watch { - try transaction.replace(watchURL, content: nil, data: Self.encode(watch)) - } - try transaction.commit() + guard let change else { return } + try transaction.replace( + declarationURL, with: .data(change.bytes), + expecting: prepared.evidence(for: declarationURL)) + } + + package func withLock( + createIfMissing: Bool = true, checkpoint: @escaping (String) throws -> Void = { _ in }, + outcome: TransactionOutcome? = nil, footprint: Set = [], + installations: [SkillInstallationTarget] = [], + existingRoot: ExistingProjectRoot? = nil, + beforeScopeLock: () throws -> Void = {}, + _ body: () throws -> T + ) throws -> T { + let root = try existingRoot?.open(for: self) + return try withCoordination( + routes: footprint, installations: installations, writable: true, checkpoint: checkpoint, + existingRoot: existingRoot, projectRoot: root + ) { + try beforeScopeLock() + return try withScopeLock( + createIfMissing: createIfMissing, checkpoint: checkpoint, outcome: outcome, body) } } - /// Stages the declaration when the file's bytes differ from its standard layout, so a file - /// written by hand or by an earlier version is rewritten even when its content is unchanged. - package func stageDeclaration(_ declaration: Declaration, in transaction: FileTransaction) throws - { - let data = try Self.encodeState(declaration.normalized) - guard try existingData(declarationURL) != data else { return } - try transaction.replace(declarationURL, content: nil, data: data) + /// Imports configuration under the scope writer lock. The import validates its own state + /// files and preserves the existing cache references. + package func withConfigurationImportLock( + checkpoint: @escaping (String) throws -> Void, beforeCreatingLock: () throws -> Void, + _ body: () throws -> T + ) throws -> T { + guard scope == .user, try openDirectoryIfPresent() != nil else { + throw CoreError.invalidState( + "the global configuration directory is missing: \(directory.path)") + } + return try withCoordination( + routes: [], writable: true, checkpoint: checkpoint, admitRecovery: false + ) { + if let directory = try openDirectoryIfPresent(), + try directory.info(".agents.lock") == nil, + try !TransactionJournal.isPresent(in: directory), + try directory.info("watch-refs.pending") == nil + { + try beforeCreatingLock() + } + return try withScopeLock( + createIfMissing: false, checkpoint: checkpoint, importingConfiguration: true, body) + } } - package func withLock( + private func withScopeLock( createIfMissing: Bool = true, checkpoint: @escaping (String) throws -> Void = { _ in }, - outcome: TransactionOutcome? = nil, + outcome: TransactionOutcome? = nil, importingConfiguration: Bool = false, _ body: () throws -> T ) throws -> T { if try openDirectoryIfPresent() == nil, !createIfMissing { + guard TransactionLockContext.current(self)?.resources.isEmpty != false else { + throw CoreError.invalidState("shared mutation requires a scope journal directory") + } return try body() } - if !FileManager.default.fileExists( - atPath: directory.appendingPathComponent(".agents.lock").path), - !FileManager.default.fileExists( - atPath: directory.appendingPathComponent("transaction.json").path) + // Without a scope lock, journal or ref-cleanup marker, invalid or orphaned state stops the + // operation before the scope lock exists. Otherwise recovery precedes these checks. + if !importingConfiguration, + ![".agents.lock", TransactionJournal.fileName, "watch-refs.pending"].contains(where: { + FileManager.default.fileExists(atPath: directory.appendingPathComponent($0).path) + }) { - _ = try readDeclaration() - _ = try readResolved() + _ = try declarationBytes() + _ = try readLedger() _ = try readWatch() } let base = scope == .project ? environment.projectDirectory : environment.homeDirectory let physicalDirectory = base.resolvingSymlinksInPath().appendingPathComponent( directory.lastPathComponent) - return try FileLock.withLock(at: physicalDirectory.appendingPathComponent(".agents.lock")) { - let recovered = try FileTransaction.recover(store: self, checkpoint: checkpoint) + func locked(_ body: (Int32) throws -> T) throws -> T { + if let context = TransactionLockContext.current(self), + let root = context.projectRootDirectory + { + try context.existingProjectRoot?.validate() + let name = directory.lastPathComponent + if try root.info(name) == nil { + try root.makeDirectory(name) { + try checkpoint("scope." + FileLock.ancestryCheckpoint(.created(depth: 0))) + } + try checkpoint("scope." + FileLock.ancestryCheckpoint(.synced(depth: 0))) + } + let parent = try root.child(name) + try context.existingProjectRoot?.validate() + return try FileLock.withDescriptor( + in: parent, name: ".agents.lock", checkpoint: { try checkpoint("scope." + $0) }, body) + } + return try FileLock.withDescriptor( + at: physicalDirectory.appendingPathComponent(".agents.lock"), + checkpoint: { try checkpoint("scope." + $0) }, body) + } + return try locked { descriptor in + guard let context = TransactionLockContext.current(self), + let scopeDirectory = try openDirectoryIfPresent() + else { + throw CoreError.invalidState("missing scope lock admission") + } + try context.bindScope(scopeDirectory, descriptor: descriptor) + if importingConfiguration { + // Confirmation owns only the import journal. A scope operation may have started + // after preview, so inspect its pending markers under the writer lock. + guard try !TransactionJournal.isPresent(in: scopeDirectory), + try scopeDirectory.info("watch-refs.pending") == nil + else { + throw CoreError.recoveryPending( + "A configuration operation is pending at \(directory.path). " + + "Finish it in the tool that started it, then preview again." + ) + } + try verifyCoordinationAdmission() + let result = try body() + try context.validateScope() + return result + } + try verifyCoordinationAdmission() + let recovered = try FileTransaction.recover( + store: self, outcome: outcome, checkpoint: checkpoint) _ = try readWatch() let cache = SourceCache(store: self, checkpoint: checkpoint) let referencesRecovered = try cache.recoverWatchReferences() + let archiveRecovery = PrivateSourceRecovery(environment: environment) + try archiveRecovery.reconcile(scope: self) if recovered || referencesRecovered { throw CoreError.transactionRecovered(directory.path) } let result: T do { result = try body() + try context.validateScope() } catch { // A handled failure can finish rollback now. A killed process leaves the marker // for the next access, which must recover the journal before releasing any ref. do { _ = try FileTransaction.recover(store: self, outcome: outcome) _ = try SourceCache(store: self).recoverWatchReferences() + try archiveRecovery.reconcile(scope: self) } catch { - outcome?.disposition = .recoveryRequired + outcome?.requireRecovery() } throw error } _ = try cache.recoverWatchReferences() + try context.validateScope() return result } } @@ -137,7 +239,7 @@ public struct StateStore: Sendable { return try parent.child(name) } - /// Encodes `agents.json` or `agents.resolved` in the layout `StateJSON` describes. + /// Encodes `agents.resolved` in the layout `StateJSON` describes. package static func encodeState(_ value: T) throws -> Data { let encoder = JSONEncoder() encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes] @@ -154,8 +256,14 @@ public struct StateStore: Sendable { return data } - private func load(_ url: URL) throws -> T? { - guard let data = try existingData(url) else { return nil } + private func load(_ url: URL, prepared: StatePrecondition?) throws -> T? { + let bytes: Data? + if let prepared { + bytes = try prepared.bytes(for: url) + } else { + bytes = try existingData(url) + } + guard let data = bytes else { return nil } do { return try Self.decode(data, as: T.self) } catch { diff --git a/Sources/AgentsCore/TransactionCheckpoint.swift b/Sources/AgentsCore/TransactionCheckpoint.swift new file mode 100644 index 0000000..1e51234 --- /dev/null +++ b/Sources/AgentsCore/TransactionCheckpoint.swift @@ -0,0 +1,92 @@ +import Foundation + +/// Names are unique within one transaction and never contain host path components. A caller +/// that nests transactions under one checkpoint stream prefixes each nested transaction's names. +enum TransactionCheckpoint { + enum Change { + case created, containers + case entry(Int, TransactionJournal.Progress) + case terminal, disposing, reservationsReady, finalized + case conflict(Int, TransactionJournal.Progress) + var name: String { + switch self { + case .created: "created" + case .containers: "containers" + case .entry(let index, let progress): "entry.\(index).\(progress.rawValue)" + case .terminal: "terminal" + case .disposing: "disposing" + case .reservationsReady: "reservationsReady" + case .finalized: "finalized" + case .conflict(let index, let progress): "entry.\(index).\(progress.rawValue).conflict" + } + } + } + enum Stage: String { case preimageSynced, workCreated, workPrepared, writeCreated, constructed } + enum Publication: String { case validated, exchanged, created, deleted, synced } + enum Restoration: String { case validated, exchanged, returned, withdrawn, synced } + enum PersistenceStep: String { case written, renamed } + enum Permission: String { + case publicationGrant = "publish.grant" + case publicationRestore = "publish.restore" + case undoGrant = "undo.grant" + case undoRestore = "undo.restore" + case cancelRestore = "cancel.restore" + case conflictRestore = "conflict.restore" + } + case persisted(TransactionJournal.Phase, Change, PersistenceStep) + case phase(TransactionJournal.Phase) + case progress(Int, TransactionJournal.Progress) + /// Creation of a missing registered root or of its ancestors. + case rootAncestry(String, DirectoryHandle.AncestryStep) + /// Creation of an entry's missing destination parent or of its ancestors below the root. + case parentAncestry(entry: Int, DirectoryHandle.AncestryStep) + case containerCreated(Int) + case containersIdentified + case probe(Int, DirectoryHandle.ProbeStep) + case stage(Int, Stage) + case copy(Int, DirectoryHandle.CopyPoint) + case publication(Int, Publication) + case restoration(Int, Restoration) + case permissions(Int, Permission, TransactionObjectLocation, DirectoryHandle.PermissionStep) + case preconditions, commitValidated, journalSynced, disposalIntent + /// The path is relative to the container; empty names the container itself. + case unlinked(container: Int, path: String) + /// The container's removal and its parent barrier are complete. + case containerRemoved(Int) + case journalUnlinked + case journalRemoved + + var name: String { + switch self { + case .persisted(let phase, let change, let step): + "journal.\(phase.rawValue).\(change.name).\(step.rawValue)" + case .phase(let phase): "journal.\(phase.rawValue)" + case .progress(let index, let progress): "entry.\(index).\(progress.rawValue)" + case .rootAncestry(let root, let step): "ancestry.\(root).\(step.name)" + case .parentAncestry(let index, let step): "ancestry.entry.\(index).\(step.name)" + case .containerCreated(let index): "container.\(index).created" + case .containersIdentified: "containers.identified" + case .probe(let index, let point): "atomic.\(index).\(point.rawValue)" + case .stage(let index, let point): "stage.\(index).\(point.rawValue)" + case .copy(let index, let point): "stage.\(index).copy.\(point.path).\(point.step.rawValue)" + case .publication(let index, let point): "publish.\(index).\(point.rawValue)" + case .restoration(let index, let point): "restore.\(index).\(point.rawValue)" + case .permissions(let index, let purpose, let location, let point): + "permissions.\(index).\(purpose.rawValue).\(location.name).\(point.rawValue)" + case .preconditions: "publication.preconditions" + case .commitValidated: "publication.commitValidated" + case .journalSynced: "journal.synced" + case .disposalIntent: "disposal.intent" + case .unlinked(let index, let path): + "disposal.\(index).unlinked" + (path.isEmpty ? "" : "." + path) + case .containerRemoved(let index): "disposal.\(index).removed" + case .journalUnlinked: "journal.unlinked" + case .journalRemoved: "journal.removed" + } + } + + /// Whether `name` follows the rename that makes a journal generation visible. + static func isJournalPublished(_ name: String) -> Bool { + name.hasPrefix("journal.") && name.hasSuffix("." + PersistenceStep.renamed.rawValue) + } +} diff --git a/Sources/AgentsCore/TransactionDisposal.swift b/Sources/AgentsCore/TransactionDisposal.swift new file mode 100644 index 0000000..15072ec --- /dev/null +++ b/Sources/AgentsCore/TransactionDisposal.swift @@ -0,0 +1,188 @@ +import Foundation + +extension TransactionSession { + /// Verifies every expected distribution and seals disposal evidence for containers that + /// hold user data. A failure is recorded on the entry or container that caused it. + func sealDisposal() throws { + let layouts = try journal.entries.indices.map { index in + do { return try distribution(index) } catch { + try recordConflict(index, error) + throw error + } + } + var userContainers: Set = [] + for (index, layout) in layouts.enumerated() + where [.installed, .reverted].contains(layout.kind) && !layout.objects.isEmpty { + userContainers.insert(journal.entries[index].container) + } + for index in journal.containers.indices { + do { + try sealContainerDisposal( + index, userData: userContainers.contains(index), layouts: layouts) + } catch { + try recordConflict(journal.containers[index].entry, error) + throw error + } + } + for index in journal.entries.indices { journal.entries[index].conflict = nil } + } + + /// Conflicts name the container's representative entry, where they are recorded. + private func sealContainerDisposal(_ index: Int, userData: Bool, layouts: [TransactionLayout]) + throws + { + let record = journal.containers[index] + guard record.identity != nil else { return try validateContainerForDisposal(index) } + let handle = try container(index) + guard userData else { + journal.containers[index].disposal = nil + return + } + let snapshot = try FileSnapshot.read(record.name, from: parents[record.entry]) + guard try handle.objectIdentity == snapshot?.identity else { + throw conflict(record.entry, "container changed while sealing disposal") + } + for entryIndex in journal.entries.indices where journal.entries[entryIndex].container == index { + for (slot, expected) in layouts[entryIndex].objects { + let name = slot.name(entryIndex) + guard snapshot?.child(named: name) == expected else { + throw conflict(record.entry, "user object \(name) changed while sealing disposal") + } + } + } + journal.containers[index].disposal = snapshot + } + + /// Recovery revalidates terminal evidence before disposal. + func revalidateDisposal() throws { + try requireScope() + for index in journal.entries.indices { + do { + if journal.disposing { + try verifyTarget(index) + } else { + _ = try distribution(index) + } + } catch { + try recordConflict(index, error) + throw error + } + } + for index in journal.containers.indices { + do { try validateContainerForDisposal(index) } catch { + try recordConflict(journal.containers[index].entry, error) + throw error + } + } + try dispose() + } + + /// Commit disposes directly: `sealDisposal` verified the distribution and sealed this + /// evidence immediately before the terminal marker. Deletion still verifies every object. + func dispose() throws { + try requireScope() + if !journal.disposing { + journal.disposing = true + try persist(.disposing) + try emit(.disposalIntent) + } + for index in journal.containers.indices { try disposeContainer(index) } + try requireScope() + journal.finalized = true + try persist(.finalized) + try checkpoint("journal.finalized") + try releaseReservations() + try directory.removeFiles( + [TransactionJournal.incompleteFileName, TransactionJournal.fileName] + ) { name in + if name == TransactionJournal.fileName { try emit(.journalUnlinked) } + } + try emit(.journalRemoved) + } + + func verifyTarget(_ index: Int) throws { + let entry = journal.entries[index] + try requireParent(index) + if case .object(let expected) = TransactionLayout.expected(entry)[0].target { + try entry.security.validateObject(expected, named: entry.name, in: parents[index]) + } + // Terminal phases have a single distribution; disposal may have removed its slots. + guard try TransactionLayout.expected(entry)[0].target.matches(entry.name, from: parents[index]) + else { + throw conflict( + index, + journal.phase == .committed + ? "committed destination changed" : "restored destination changed") + } + } + + /// The only disposal check of a container: its identity and sealed evidence, or, without + /// a durable identity, that it is absent or empty. + func validateContainerForDisposal(_ index: Int) throws { + let record = journal.containers[index] + let parent = parents[record.entry] + try requireParent(record.entry) + guard let actual = try parent.info(record.name) else { + if journal.disposing || record.identity == nil { return } + throw conflict(record.entry, "private container disappeared before disposal intent") + } + guard let identity = record.identity else { + guard try parent.child(record.name).names().isEmpty else { + throw conflict(record.entry, "unidentified private container is not empty") + } + return + } + guard FileObjectIdentity(actual) == identity else { + throw conflict(record.entry, "private container identity changed") + } + if journal.entries.contains(where: { $0.container == index && $0.security.isPrivate }) { + let handle = try container(index) + for (entryIndex, entry) in journal.entries.enumerated() where entry.container == index { + for slot in TransactionSlot.objectSlots { + let name = slot.name(entryIndex) + guard let info = try handle.info(name) else { continue } + if let expected = [entry.preimage, entry.staged].compactMap({ $0 }).first(where: { + $0.identity == FileObjectIdentity(info) + }) { + try entry.security.validateObject( + expected, named: name, in: handle, remaining: journal.disposing) + } else if entry.progress == .queued + && entry.security.replacement == .privateMaterialization + && slot == TransactionSlot.staging(for: entry) + { + _ = try handle.requirePrivateAccess(name) + if let snapshot = try FileSnapshot.read(name, from: handle) { + _ = try TreeMemberAccess.capture( + name, in: handle, snapshot: snapshot, requirePrivate: true) + } + } + } + } + } + if let expected = record.disposal { + let current = try FileSnapshot.read(record.name, from: parent) + let matches = + journal.disposing + ? current.map(expected.containsRemaining) == true : current == expected + guard matches else { throw conflict(record.entry, "terminal disposal evidence changed") } + } + } + + private func disposeContainer(_ index: Int) throws { + let record = journal.containers[index] + let parent = parents[record.entry] + try requireScope() + try requireParent(record.entry) + try validateContainerForDisposal(index) + if let identity = record.identity { + try parent.remove(record.name, expecting: record.disposal, identity: identity) { point in + try emit( + point.step == .synced + ? .containerRemoved(index) : .unlinked(container: index, path: point.path)) + } + } else { + try parent.removeEmptyDirectory(record.name) + try emit(.containerRemoved(index)) + } + } +} diff --git a/Sources/AgentsCore/TransactionEvidence.swift b/Sources/AgentsCore/TransactionEvidence.swift new file mode 100644 index 0000000..214eaab --- /dev/null +++ b/Sources/AgentsCore/TransactionEvidence.swift @@ -0,0 +1,499 @@ +import Foundation + +package struct FileObjectIdentity: Codable, Hashable, Sendable { + let device: UInt64 + let inode: UInt64 + let kind: mode_t + + var isDirectory: Bool { kind == S_IFDIR } + + init(_ info: stat) { + device = UInt64(info.st_dev) + inode = UInt64(info.st_ino) + kind = info.st_mode & S_IFMT + } +} + +/// A recorded directory inode whose final mode lacks owner-write. While `publishing` or +/// `restoring` intent is durable it admits the original mode or that mode plus owner-write. +struct DirectoryWriteLease: Equatable { + let identity: FileObjectIdentity + let originalMode: mode_t + + init?(_ snapshot: FileSnapshot) { + guard snapshot.identity.isDirectory, snapshot.mode & 0o200 == 0 else { return nil } + identity = snapshot.identity + originalMode = snapshot.mode + } + + var grantedMode: mode_t { originalMode | 0o200 } + + func admits(_ mode: mode_t) -> Bool { mode == originalMode || mode == grantedMode } +} + +/// 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 { + let identity: FileObjectIdentity + let digest: String + let executable: Bool + /// Final permission bits. Only publishing/restoring may temporarily add directory owner-write. + let mode: mode_t + let children: [Member]? + + struct Member: Codable, Equatable, Sendable { + let name: String + let snapshot: FileSnapshot + static func == (lhs: Self, rhs: Self) -> Bool { + lhs.name.utf8.elementsEqual(rhs.name.utf8) && lhs.snapshot == rhs.snapshot + } + } + + func child(named name: String) -> FileSnapshot? { + children?.first { $0.name.utf8.elementsEqual(name.utf8) }?.snapshot + } + + static func read(at url: URL) throws -> FileSnapshot? { + var info = stat() + if lstat(url.path, &info) != 0 { + if errno == ENOENT { return nil } + throw FileSystem.posixError(errno, at: url, otherwise: .unsafePath("cannot inspect target")) + } + let parent = try DirectoryHandle(at: url.deletingLastPathComponent().resolvingSymlinksInPath()) + return try read(url.lastPathComponent, from: parent) + } + + struct Capture { + let snapshot: FileSnapshot? + let contentHash: String + let executableFlags: [String: Bool] + let bytes: Data? + } + + static func captureFile(at url: URL, maximumFileBytes: Int? = nil) throws -> Capture { + var info = stat() + if lstat(url.path, &info) != 0 { + if errno == ENOENT { + return Capture( + snapshot: nil, contentHash: FileHash.hashRecords([]), executableFlags: [:], bytes: nil) + } + throw FileSystem.posixError(errno, at: url, otherwise: .unsafePath("cannot inspect target")) + } + guard info.st_mode & S_IFMT == S_IFREG else { + throw CoreError.unsafePath("expected regular file: \(url.path)") + } + let parent = try DirectoryHandle(at: url.deletingLastPathComponent().resolvingSymlinksInPath()) + return try capture(url.lastPathComponent, from: parent, maximumFileBytes: maximumFileBytes) + } + + /// The snapshot and content verification consume the same opened-file bytes. + static func capture( + _ name: String, from parent: DirectoryHandle, maximumFileBytes: Int? = nil + ) throws -> Capture { + var records: [(String, Data)] = [] + var rootBytes: Data? + var flags: [String: Bool] = [:] + var budget = CaptureBudget(maximumFileBytes: maximumFileBytes) + let value = try read(name, from: parent, relative: "", budget: &budget) { + path, kind, bytes, executable in + guard !path.isEmpty else { + if kind == S_IFREG { + rootBytes = bytes + flags[""] = executable + } + return + } + switch kind { + case S_IFDIR: records.append((path, Data("directory".utf8))) + case S_IFREG: + records.append((path, Data("file\0".utf8) + bytes)) + flags[path] = executable + case S_IFLNK: records.append((path, Data("link\0".utf8) + bytes)) + default: break + } + } + return Capture( + snapshot: value, + contentHash: value?.isRegular == true ? value!.digest : FileHash.hashRecords(records), + executableFlags: flags, bytes: rootBytes) + } + + static func read(_ name: String, from parent: DirectoryHandle) throws -> FileSnapshot? { + var budget = CaptureBudget() + return try read(name, from: parent, relative: "", budget: &budget, collect: nil) + } + + static func capturePortableTree( + _ name: String, from parent: DirectoryHandle, limits: LedgerLimits, recursive: Bool, + admitting: @escaping (String) throws -> Void + ) throws -> (entries: [LedgerEntry], objects: [String: Data]) { + var budget = CaptureBudget(limits: limits, recursive: recursive) + var entries: [LedgerEntry] = [] + var objects: [String: Data] = [:] + var remaining = limits.objectBytes + let snapshot = try read( + name, from: parent, relative: "", budget: &budget, + admit: { path, info in + try Task.checkCancellation() + if info.st_mode & S_IFMT == S_IFREG, info.st_nlink != 1 { + throw CoreError.unsafePath("shared file in portable tree: " + path) + } + try admitting(path) + }, + collect: { path, kind, bytes, executable in + let path = path.isEmpty ? "." : path + switch kind { + case S_IFDIR: entries.append(.init(path: path, kind: .directory, executable: false)) + case S_IFREG: + let digest = "sha256:" + FileHash.sha256Hex(data: bytes) + if objects[digest] == nil { + guard bytes.count <= remaining else { + throw CoreError.invalidState("portable tree object budget") + } + remaining -= bytes.count + objects[digest] = bytes + } + entries.append( + .init( + path: path, kind: .file, object: digest, executable: executable, + byteCount: bytes.count)) + case S_IFLNK: + guard let link = String(data: bytes, encoding: .utf8) else { + throw CoreError.unsafePath("invalid UTF-8 link in portable tree: " + path) + } + entries.append(.init(path: path, kind: .symlink, link: link, executable: false)) + default: throw CoreError.unsafePath("unsupported portable tree entry: " + path) + } + }) + guard snapshot != nil else { throw CoreError.notFound(name) } + return (entries.sorted { $0.path.utf8.lexicographicallyPrecedes($1.path.utf8) }, objects) + } + + private struct CaptureBudget { + let maximumFileBytes: Int? + let limits: LedgerLimits + let recursive: Bool + var entries = 0 + var bytes = 0 + + init( + maximumFileBytes: Int? = nil, limits: LedgerLimits = .standard, 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) + else { throw CoreError.invalidState("transaction tree exceeds resource limits") } + if let maximumFileBytes, + depth != 0 || info.st_mode & S_IFMT != S_IFREG || size > maximumFileBytes + { + throw CoreError.invalidState("file exceeds the admitted byte limit") + } + bytes += Int(size) + name.utf8.count + } + } + + private static func read( + _ name: String, from parent: DirectoryHandle, relative: String, budget: inout CaptureBudget, + 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 } + try admit?(relative, before) + try budget.consume(name, info: before, depth: relative.split(separator: "/").count) + let children: [Member]? + let payload: Data + switch before.st_mode & S_IFMT { + case S_IFDIR: + let directory = try parent.child(name, matching: before) + var entries: [Member] = [] + let names = + try budget.recursive + ? directory.names(maximumCount: budget.limits.entries - budget.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) + else { + throw CoreError.invalidState("entry changed while reading: \(child)") + } + entries.append(Member(name: child, snapshot: value)) + } + entries.sort { $0.name.utf8.lexicographicallyPrecedes($1.name.utf8) } + children = entries + // Only content enters the digest; ownership is compared independently. + payload = try StateStore.encode( + entries.map { + [$0.name, "\($0.snapshot.identity.kind):\($0.snapshot.executable):\($0.snapshot.digest)"] + }) + case S_IFREG: + children = nil + payload = try parent.read( + name, matching: before, + maximumBytes: budget.maximumFileBytes ?? budget.limits.resourceBytes) + case S_IFLNK: + children = nil + payload = try parent.readLinkData(name) + default: throw CoreError.unsafePath("unsupported transaction entry: \(name)") + } + guard let after = try parent.info(name), DirectoryHandle.sameGeneration(before, after) else { + throw CoreError.invalidState("entry changed while reading: \(name)") + } + try collect?(relative, before.st_mode & S_IFMT, payload, before.st_mode & 0o111 != 0) + return FileSnapshot( + identity: FileObjectIdentity(before), digest: FileHash.sha256Hex(data: payload), + executable: before.st_mode & S_IFMT == S_IFREG && before.st_mode & 0o111 != 0, + mode: before.st_mode & 0o7777, + children: children) + } + + var writeLease: DirectoryWriteLease? { DirectoryWriteLease(self) } + + func matches(_ current: Self, permittingDirectoryWrite: Bool) -> Bool { + if self == current { return true } + guard permittingDirectoryWrite, let lease = writeLease, lease.admits(current.mode) else { + return false + } + return Self( + identity: identity, digest: digest, executable: executable, mode: current.mode, + children: children) == current + } + + var isRegular: Bool { identity.kind == S_IFREG } + var isSymbolicLink: Bool { identity.kind == S_IFLNK } + + func validate() throws { + try StateValidation.digest("sha256:" + digest) + let kinds: [mode_t] = [S_IFDIR, S_IFREG, S_IFLNK] + guard kinds.contains(identity.kind), mode & ~0o7777 == 0, + (identity.kind == S_IFDIR) == (children != nil) + else { throw CoreError.invalidState("invalid transaction object evidence") } + let members = children ?? [] + guard + zip(members, members.dropFirst()).allSatisfy({ + $0.name.utf8.lexicographicallyPrecedes($1.name.utf8) + }) + else { throw CoreError.invalidState("duplicate or unordered transaction descendants") } + for member in members { + let name = member.name + let child = member.snapshot + guard !name.isEmpty, name != ".", name != "..", !name.contains("/"), + !name.contains("\0") + else { throw CoreError.invalidState("invalid transaction descendant") } + try child.validate() + } + } + + func containsRemaining(_ current: FileSnapshot) -> Bool { + guard identity == current.identity else { return false } + guard let children, let remaining = current.children else { return self == current } + 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 + } + } +} + +/// Required journal classification. Optional metadata is required by validation whenever +/// its corresponding object exists in a security-bearing operation. +struct TransactionSecurity: Codable { + enum Classification: String, Codable { case ordinary, privateMaterialization } + var preimage: Classification = .ordinary + var replacement: Classification = .ordinary + var permissionChange = false + var archiveOutput: Bool? + var ancestry: DirectoryAccessEvidence? + var preimageAccess: FileAccessEvidence? + var stagedAccess: FileAccessEvidence? + + var isPrivate: Bool { + preimage == .privateMaterialization || replacement == .privateMaterialization + } + + var preimageTreeAccess: [TreeMemberAccess]? + var stagedTreeAccess: [TreeMemberAccess]? + + func validate(entry: TransactionJournal.Entry) throws { + guard !isPrivate || ancestry != nil, + archiveOutput == nil || (archiveOutput == true && ancestry != nil), + !permissionChange || (replacement == .privateMaterialization && entry.preimage != nil), + !isPrivate + || (entry.preimage == nil || entry.preimage?.identity.kind == S_IFLNK) + == (preimageAccess == nil), + entry.preimage?.identity.kind != S_IFLNK || preimage == .ordinary, + replacement != .privateMaterialization || (entry.staged == nil) == (stagedAccess == nil), + preimage != .privateMaterialization || entry.preimage != nil, + replacement != .privateMaterialization || entry.action == .install + else { throw CoreError.invalidState("missing or contradictory transaction security evidence") } + for (snapshot, access, members) in [ + (entry.preimage, preimageAccess, preimageTreeAccess), + (entry.staged, stagedAccess, stagedTreeAccess), + ] { + if let access { + guard let snapshot, access.identity == snapshot.identity, access.mode == snapshot.mode, + snapshot.isRegular || snapshot.identity.isDirectory + else { + throw CoreError.invalidState("transaction access evidence belongs to another object") + } + try TreeMemberAccess.validate(members, snapshot: snapshot) + } else if members != nil { + throw CoreError.invalidState("tree access requires root access evidence") + } + } + } + + func validateObject( + _ snapshot: FileSnapshot, named name: String, in parent: DirectoryHandle, + remaining: Bool = false, permittingDirectoryWrite: Bool = false + ) + throws + { + let access: FileAccessEvidence? + let classification: Classification + let members: [TreeMemberAccess]? + if snapshot.identity == preimageAccess?.identity { + access = preimageAccess + classification = preimage + members = preimageTreeAccess + } else if snapshot.identity == stagedAccess?.identity { + access = stagedAccess + classification = replacement + members = stagedTreeAccess + } else { + return + } + guard let access else { return } + if classification == .privateMaterialization { + _ = try parent.requirePrivateAccess(name, matching: access) + } else if try parent.accessEvidence(name).map({ + access.admits($0, removal: remaining, directoryWrite: permittingDirectoryWrite) + }) != true { + throw CoreError.invalidState("transaction object access changed") + } + try TreeMemberAccess.verify( + members, snapshot: snapshot, named: name, in: parent, + requirePrivate: classification == .privateMaterialization, remaining: remaining, + permittingDirectoryWrite: permittingDirectoryWrite) + + } +} + +/// Complete, byte-ordered access evidence for real tree members; links remain snapshots. +package struct TreeMemberAccess: Codable, Equatable { + package let path: String + package let access: FileAccessEvidence + + package static func == (lhs: Self, rhs: Self) -> Bool { + lhs.path.utf8.elementsEqual(rhs.path.utf8) && lhs.access == rhs.access + } + + static func capture( + _ name: String, in parent: DirectoryHandle, snapshot: FileSnapshot, + requirePrivate: Bool = false + ) throws -> [Self]? { + guard snapshot.identity.isDirectory else { return nil } + var result: [Self] = [] + func walk(_ directory: DirectoryHandle, _ snapshot: FileSnapshot, prefix: String) throws { + for member in snapshot.children ?? [] { + let path = prefix + member.name + let value = member.snapshot + if value.isSymbolicLink { continue } + guard let access = try directory.accessEvidence(member.name), + access.identity == value.identity, + access.mode == value.mode + else { throw CoreError.invalidState("tree access changed during capture") } + if requirePrivate { _ = try directory.requirePrivateAccess(member.name, matching: access) } + result.append(Self(path: path, access: access)) + if value.identity.isDirectory { + try walk(directory.child(member.name), value, prefix: path + "/") + } + } + } + try walk(parent.child(name), snapshot, prefix: "") + result.sort { $0.path.utf8.lexicographicallyPrecedes($1.path.utf8) } + try validate(result, snapshot: snapshot) + return result + } + + static func validateStructure(_ members: [Self]) throws { + var previous: String? + guard members.count <= LedgerLimits.standard.entries else { + throw CoreError.invalidState("tree access exceeds member limit") + } + for member in members { + let parts = member.path.split(separator: "/", omittingEmptySubsequences: false) + guard !parts.isEmpty, parts.count < LedgerLimits.standard.depth / 4, + parts.allSatisfy({ + !$0.isEmpty && $0 != "." && $0 != ".." && !$0.contains("\\") && !$0.contains("\0") + }), + previous.map({ $0.utf8.lexicographicallyPrecedes(member.path.utf8) }) ?? true, + [mode_t(S_IFREG), mode_t(S_IFDIR)].contains(member.access.identity.kind), + member.access.mode & ~0o7777 == 0 + else { throw CoreError.invalidState("invalid tree access member") } + previous = member.path + } + } + + static func validate(_ members: [Self]?, snapshot: FileSnapshot) throws { + guard snapshot.identity.isDirectory else { + guard members == nil else { + throw CoreError.invalidState("file carries tree access evidence") + } + return + } + guard let members else { throw CoreError.invalidState("directory lacks tree access evidence") } + try validateStructure(members) + var expected: [(String, FileSnapshot)] = [] + func walk(_ value: FileSnapshot, prefix: String) { + for member in value.children ?? [] { + let path = prefix + member.name + if !member.snapshot.isSymbolicLink { expected.append((path, member.snapshot)) } + walk(member.snapshot, prefix: path + "/") + } + } + walk(snapshot, prefix: "") + expected.sort { $0.0.utf8.lexicographicallyPrecedes($1.0.utf8) } + guard members.count == expected.count, + zip(members, expected).allSatisfy({ + $0.path.utf8.elementsEqual($1.0.utf8) && $0.access.identity == $1.1.identity + && $0.access.mode == $1.1.mode + }) + else { throw CoreError.invalidState("incomplete or contradictory tree access evidence") } + } + + static func verify( + _ members: [Self]?, snapshot: FileSnapshot, named name: String, + in parent: DirectoryHandle, requirePrivate: Bool, remaining: Bool = false, + permittingDirectoryWrite: Bool = false + ) throws { + try validate(members, snapshot: snapshot) + guard let members else { return } + let current = try FileSnapshot.read(name, from: parent) + guard let current, + remaining + ? snapshot.containsRemaining(current) + : snapshot.matches(current, permittingDirectoryWrite: permittingDirectoryWrite) + else { + throw CoreError.invalidState("tree changed while checking access") + } + let actual = + try capture(name, in: parent, snapshot: current, requirePrivate: requirePrivate) ?? [] + let recorded = Dictionary(uniqueKeysWithValues: members.map { (Data($0.path.utf8), $0.access) }) + guard + remaining + ? actual.allSatisfy({ item in + recorded[Data(item.path.utf8)]?.admits(item.access, removal: true) == true + }) : actual == members + else { + throw CoreError.invalidState("tree member access changed") + } + } +} diff --git a/Sources/AgentsCore/TransactionJournal.swift b/Sources/AgentsCore/TransactionJournal.swift new file mode 100644 index 0000000..e8208f1 --- /dev/null +++ b/Sources/AgentsCore/TransactionJournal.swift @@ -0,0 +1,281 @@ +import Foundation + +/// The version is independent of declaration, resolved and watch formats. +struct TransactionJournal: Codable { + static let currentVersion = 4 + static let fileName = "transaction.json" + /// The next journal generation before it replaces `fileName`. + static let incompleteFileName = "transaction.new" + var version = currentVersion + var id: UUID + var scope: String + var roots: [String: String] + var phase: Phase = .preparing + var entries: [Entry] + var containers: [Container] + /// Only this durable intent permits absent or partially removed disposal objects. + var disposing = false + /// Durable intents exist before any reservation slot is created. + var footprint: [SharedResourceIdentity] = [] + var reservationsReady = false + /// Disposal is synced; terminal phase retains the committed/rolledBack result. + var finalized = false + + func validateCoordination() throws { + guard zip(footprint, footprint.dropFirst()).allSatisfy({ $0 < $1 }) + else { + throw CoreError.invalidState("unregistered shared transaction footprint") + } + for identity in footprint { try identity.validate() } + guard !finalized || (disposing && (phase == .committed || phase == .rolledBack)), + footprint.isEmpty || reservationsReady || phase == .preparing || phase == .rolledBack + else { throw CoreError.invalidState("invalid transaction coordination evidence") } + if finalized { + let terminalProgress: Set = + phase == .committed + ? [.applied] : [.queued, .ready, .restored, .cancelled] + guard entries.allSatisfy({ terminalProgress.contains($0.progress) }) else { + throw CoreError.invalidState("finalized transaction contradicts its terminal outcome") + } + } + for entry in entries { + let route = + NativeTargetRoute.sharedRoute(entry.path) ?? NativeTargetRoute.metadataRoute(entry.path) + guard entry.coordination.map({ footprint.indices.contains($0) }) ?? (route == nil) else { + throw CoreError.invalidState("invalid entry coordination index") + } + if let root = entry.coordinationRoot { + guard let registered = NativeTargetRoute.sharedRoute(root), + root.utf8.elementsEqual(registered.root.utf8), + let index = entry.coordination, + footprint[index].basename.utf8.elementsEqual(registered.basename.utf8) + else { throw CoreError.invalidState("invalid registered coordination root") } + } else if entry.coordination != nil, route == nil { + throw CoreError.invalidState("coordinated alias lacks its registered root") + } + if let route { + guard let index = entry.coordination, + footprint[index].basename.utf8.elementsEqual(route.basename.utf8) + else { throw CoreError.invalidState("journal route contradicts its coordination") } + } + } + guard Set(entries.compactMap(\.coordination)) == Set(footprint.indices) else { + throw CoreError.invalidState("unreferenced journal footprint") + } + } + + enum Phase: String, Codable { case preparing, applying, committed, rolledBack } + enum Action: String, Codable { case install, delete } + enum Progress: String, Codable { + /// Preimage and container name are durable; construction has no per-object ownership claims. + case queued + /// Construction is verified; staging is sealed and other recovery slots are absent. + case ready + /// Publication and temporary directory-write intent are durable, with original modes. + case publishing + /// Rename parents and original modes are synced; the installed distribution is verified. + case applied + /// Undo and directory-write intent are durable; installed or reverted objects may be present. + case restoring + /// Undo parents and original modes are synced; reverted objects remain until disposal intent. + case restored + /// Original modes are restored; publication did not consume private staging. + case cancelled + + var permitsDirectoryWrite: Bool { self == .publishing || self == .restoring } + } + + struct Conflict: Codable { + let reason: String + /// Scope-relative destinations and container locations, never executable input paths. + let locations: [String] + } + + struct Entry: Codable { + var path: String + var action: Action + var preimage: FileSnapshot? + var parentIdentity: String + var container: Int + /// Non-nil exactly when an install has reached ready; never refreshed after sealing. + /// Modes in both snapshots are the final modes, before any directory-write intent. + var staged: FileSnapshot? + var progress: Progress = .queued + var conflict: Conflict? + var security = TransactionSecurity() + var coordination: Int? + var coordinationRoot: String? + var name: String { String(path.split(separator: "/").last!) } + } + + struct Container: Codable { + /// A representative entry pins the parent; the name is derived from id and this array index. + var entry: Int + var name: String + /// Persisted before inserting any object. Without it only an empty rmdir is allowed. + var identity: FileObjectIdentity? + /// Terminal disposal evidence, present only for a container holding user data. Missing + /// entries are admitted only after `disposing` is durable; private unfinished construction + /// needs no tree evidence. + var disposal: FileSnapshot? + var access: FileAccessEvidence? + } + + static func containerName(id: UUID, index: Int) -> String { ".agents-\(id.uuidString)-\(index)" } + + func containerName(_ index: Int) -> String { containers[index].name } + + /// The scope-relative location of an entry's container, or nil when the record does not name + /// this journal's container for that index. + func containerLocation(of entry: Entry) -> String? { + guard containers.indices.contains(entry.container), + containers[entry.container].name == Self.containerName(id: id, index: entry.container) + else { return nil } + return entry.path.split(separator: "/").dropLast().joined(separator: "/") + "/" + + containers[entry.container].name + } + + static func isPresent(in directory: DirectoryHandle) throws -> Bool { + try directory.info(fileName) != nil || directory.info(incompleteFileName) != nil + } + + var isReservationOnly: Bool { + !footprint.isEmpty && !reservationsReady && !finalized && phase == .preparing + && containers.allSatisfy { $0.identity == nil } + && entries.allSatisfy { $0.progress == .queued } + } + + /// Only journals without reservation intents, identified containers or sealed operations + /// can be discarded without examining owned metadata. + var isUnstarted: Bool { + footprint.isEmpty && !reservationsReady && !finalized && phase == .preparing + && containers.allSatisfy { $0.identity == nil } + && entries.allSatisfy { $0.progress == .queued } + } +} + +/// Entry names inside a private container. At each progress a recovery slot holds either +/// private staging or user data, as each case states. +enum TransactionSlot: String { + /// Private staging for a creation through `ready`; publication moves it out of the container. + case staged + /// Private staging for an exchange through `ready`; user data from publication on: the + /// displaced preimage, and after undo the published object exchanged back out. + case exchanged + /// User data: the object a deletion moved aside, from publication until undo or disposal. + case deleted + /// User data: the published creation that undo moved aside. + case withdrawn + /// Private extraction work for prepared content. + case work + + func name(_ index: Int) -> String { "entry.\(index).\(rawValue)" } + static let objectSlots: [Self] = [.staged, .exchanged, .deleted, .withdrawn] + static let probes = (first: "probe-a", second: "probe-b", moved: "probe-c") + + /// The slot that holds an install's sealed staging. + static func staging(for entry: TransactionJournal.Entry) -> Self { + entry.preimage == nil ? .staged : .exchanged + } +} + +enum TransactionObjectLocation: Equatable { + case target + case slot(TransactionSlot) + + var name: String { + switch self { + case .target: "target" + case .slot(let slot): slot.rawValue + } + } +} + +/// The operation/progress table is the single authority for physical object distribution. +/// A nil expected object means the slot must be absent, not that ownership is unknown. +struct TransactionLayout { + enum Kind { case prepared, installed, reverted, construction } + enum Target { + case any, absent + case object(FileSnapshot) + case externalTo(FileObjectIdentity) + + func matches( + _ name: String, from parent: DirectoryHandle, permittingDirectoryWrite: Bool = false + ) throws -> Bool { + switch self { + case .any: return true + case .absent: return try parent.info(name) == nil + case .externalTo(let identity): + return try parent.info(name).map(FileObjectIdentity.init) != identity + case .object(let expected): + guard try parent.info(name).map(FileObjectIdentity.init) == expected.identity else { + return false + } + return try FileSnapshot.read(name, from: parent).map { + expected.matches($0, permittingDirectoryWrite: permittingDirectoryWrite) + } == true + } + } + } + let kind: Kind + let target: Target + let objects: [TransactionSlot: FileSnapshot] + + static func expected(_ entry: TransactionJournal.Entry) -> [Self] { + let prepared: Self + let installed: Self + let reverted: Self + // Validated records carry staged evidence exactly for installs past construction. + switch (entry.preimage, entry.staged) { + case (let original?, let staged?): + prepared = Self(kind: .prepared, target: .any, objects: [.exchanged: staged]) + installed = Self(kind: .installed, target: .object(staged), objects: [.exchanged: original]) + reverted = Self(kind: .reverted, target: .object(original), objects: [.exchanged: staged]) + case (nil, let staged?): + prepared = Self(kind: .prepared, target: .any, objects: [.staged: staged]) + installed = Self(kind: .installed, target: .object(staged), objects: [:]) + reverted = Self( + kind: .reverted, target: .externalTo(staged.identity), objects: [.withdrawn: staged]) + case (let original?, nil): + prepared = Self(kind: .prepared, target: .any, objects: [:]) + installed = Self(kind: .installed, target: .absent, objects: [.deleted: original]) + reverted = Self(kind: .reverted, target: .object(original), objects: [:]) + case (nil, nil): + prepared = Self(kind: .prepared, target: .any, objects: [:]) + installed = Self(kind: .installed, target: .absent, objects: [:]) + reverted = Self(kind: .reverted, target: .any, objects: [:]) + } + switch entry.progress { + case .queued: return [Self(kind: .construction, target: .any, objects: [:])] + case .ready, .cancelled: return [prepared] + case .publishing: + // A deletion has no slot object before its rename, so only the target can tell a + // prepared deletion from an installed one. + if entry.action == .delete, let original = entry.preimage { + return [Self(kind: .prepared, target: .object(original), objects: [:]), installed] + } + return [installed, prepared] + case .applied: return [installed] + case .restoring: return [reverted, installed] + case .restored: return [reverted] + } + } + + /// Recorded objects and their locations in this distribution. A prepared operation still + /// has its preimage at the target, which the table does not constrain before publication. + func objectLocations( + _ entry: TransactionJournal.Entry + ) -> [(location: TransactionObjectLocation, object: FileSnapshot)] { + var locations: [(location: TransactionObjectLocation, object: FileSnapshot)] = [] + if case .object(let expected) = target { + locations.append((.target, expected)) + } else if kind == .prepared, let original = entry.preimage { + locations.append((.target, original)) + } + for slot in TransactionSlot.objectSlots { + if let expected = objects[slot] { locations.append((.slot(slot), expected)) } + } + return locations + } +} diff --git a/Sources/AgentsCore/TransactionOutcome.swift b/Sources/AgentsCore/TransactionOutcome.swift index 64142c2..41e2ba2 100644 --- a/Sources/AgentsCore/TransactionOutcome.swift +++ b/Sources/AgentsCore/TransactionOutcome.swift @@ -3,8 +3,30 @@ import Foundation /// Tracks the generation established by its own journal, not preparatory cache publications. package final class TransactionOutcome { package enum Disposition { case unchanged, committed, recoveryRequired } - package var disposition: Disposition = .unchanged + private var reportedDisposition: Disposition = .unchanged + package var disposition: Disposition { + get { terminal == .committed ? .committed : reportedDisposition } + set { + reportedDisposition = newValue + if newValue == .recoveryRequired { recoveryPending = true } + } + } + package enum Terminal { case committed, rolledBack } + package private(set) var terminal: Terminal? + package var recoveryPending = false var journalID: UUID? + package var publicationStarted = false + + func recordTerminal(_ phase: TransactionJournal.Phase) { + guard phase == .committed || phase == .rolledBack else { return } + terminal = phase == .committed ? .committed : .rolledBack + disposition = phase == .committed ? .committed : .unchanged + } + + func requireRecovery() { + recoveryPending = true + if terminal == nil { disposition = .recoveryRequired } + } package init() {} } diff --git a/Sources/AgentsCore/TransactionPaths.swift b/Sources/AgentsCore/TransactionPaths.swift index 6a6b34e..7d6b947 100644 --- a/Sources/AgentsCore/TransactionPaths.swift +++ b/Sources/AgentsCore/TransactionPaths.swift @@ -5,11 +5,73 @@ import Foundation struct TransactionPaths { let store: StateStore - func path(for destination: URL) throws -> String { + func path( + for destination: URL, skillInitialization: SkillInitializationTarget? = nil, + installation: SkillInstallationTarget? = nil + ) throws + -> String + { + if let installation, + installation.scope.path.utf8.elementsEqual(store.directory.path.utf8), + installation.url.path.utf8.elementsEqual(destination.standardizedFileURL.path.utf8) + { + try installation.validateAuthority() + let canonical = installation.name.utf8.elementsEqual( + PathSafety.sanitizeName(installation.name).utf8) + let recorded = + canonical ? false : try persistedInstallation(installation.name, agent: installation.agent) + guard canonical || recorded + else { throw CoreError.unsafePath("installation recipient changed") } + if let route = try coordinationRoute(for: installation.path) { + _ = try TransactionLockContext.current(store).requiredResourceForRoute(route) + } + return installation.path + } let base = store.scope == .project ? store.environment.projectDirectory : store.environment.homeDirectory let physicalState = base.resolvingSymlinksInPath().appendingPathComponent( store.directory.lastPathComponent) + let admitted = + Array(TransactionLockContext.current(store)?.requestedRoutes ?? []) + + (TransactionLockContext.current(store)?.admissions.map(\.route) ?? []) + let requested = TransactionLockContext.current(store)?.requestedRoutes ?? [] + let nativeRoutes = Array(Set(admitted + NativeTargetRoute.allCases)).sorted { + if requested.contains($0) != requested.contains($1) { return requested.contains($0) } + if $0.shared != $1.shared { return $0.shared } + if admitted.contains($0) != admitted.contains($1) { return admitted.contains($0) } + return $0.shared == $1.shared ? $0.rawValue < $1.rawValue : $0.shared + } + for route in nativeRoutes where route.shared || route.permits(store.scope) { + guard destination.lastPathComponent.utf8.elementsEqual(route.basename.utf8) else { continue } + let registered = try route.physicalDirectory(store.environment) + .appendingPathComponent(route.basename) + guard registered.path.utf8.elementsEqual(destination.standardizedFileURL.path.utf8) else { + continue + } + guard route.permits(store.scope) else { + throw CoreError.unsafePath("native target belongs to another scope") + } + let target = try store.nativeTarget(for: route) + if target.url.path.utf8.elementsEqual(destination.standardizedFileURL.path.utf8) { + if route.shared { + guard let context = TransactionLockContext.current(store) else { + throw CoreError.invalidState("shared target requires its held footprint") + } + _ = try context.targetDirectory(for: route) + } + if !route.shared { _ = try store.coordinationRoute(for: route) } + return target.path + } + } + try store.requireProjectNativeAuthority(at: destination) + if let initialization = skillInitialization, + initialization.scope.path.utf8.elementsEqual(store.directory.path.utf8), + initialization.file.path.utf8.elementsEqual(destination.standardizedFileURL.path.utf8) + { + let path = "skill-authoring/" + initialization.descendants.joined(separator: "/") + _ = try components(path) + return path + } if store.scope == .project { let relative = PathSafety.relativePath( destination.path, to: base.resolvingSymlinksInPath().path) @@ -29,17 +91,40 @@ struct TransactionPaths { } } } - for agent in AgentID.allCases { + let ruleName = destination.lastPathComponent + let legacy = + store.scope == .user && InstructionLocations.isAntigravityLeaf(ruleName, legacy: true) + if legacy || InstructionLocations.isAntigravityLeaf(ruleName), + try InstructionLocations.antigravityAuthority(store.environment, scope: store.scope) + .plannedPhysicalDirectory.appendingPathComponent(ruleName).path.utf8 + .elementsEqual(destination.standardizedFileURL.path.utf8) + { + _ = try InstructionLocations.antigravityLeaf(ruleName, store: store, legacy: legacy) + return InstructionLocations.ruleRoot(in: store.scope) + "/" + ruleName + } + var matchingInstallation = false + for agent in AgentRegistry.skillAgents { let logical = AgentRegistry.installSkillsDirectory( for: agent, scope: store.scope, environment: store.environment) let physical = logical.resolvingSymlinksInPath() let parent = destination.deletingLastPathComponent().standardizedFileURL - if parent.path == logical.standardizedFileURL.path || parent.path == physical.path { + if parent.path.utf8.elementsEqual(logical.standardizedFileURL.path.utf8) + || parent.path.utf8.elementsEqual(physical.path.utf8) + { + matchingInstallation = true + guard + try PathSafety.sanitizeName(destination.lastPathComponent) + == destination.lastPathComponent + || persistedInstallation(destination.lastPathComponent, agent: agent) + else { continue } let path = agent.rawValue + "/" + destination.lastPathComponent _ = try components(path) return path } } + if matchingInstallation { + throw CoreError.unsafePath("unrecorded noncanonical installation target") + } for state in [store.directory.standardizedFileURL, physicalState] { if PathSafety.isContained(destination.standardizedFileURL, in: state) { let path = "state/" + PathSafety.relativePath(destination.path, to: state.path) @@ -50,34 +135,109 @@ struct TransactionPaths { throw CoreError.unsafePath("transaction destination is outside managed paths") } - func root(_ key: String, create: Bool = false, checkpoint: (String) throws -> Void = { _ in }) - throws -> DirectoryHandle - { + func root( + _ key: String, create: Bool = false, + checkpoint: (DirectoryHandle.AncestryStep) throws -> Void = { _ in } + ) throws -> DirectoryHandle { + let url = try rootURL(key) + if let context = TransactionLockContext.current(store), let root = context.projectRootDirectory, + let observation = context.existingProjectRoot, + let anchored = try observation.descendant( + at: url, from: root, create: create, checkpoint: checkpoint) + { + return anchored + } + return try DirectoryHandle(at: url, create: create, checkpoint: checkpoint) + } + + func rootURL(_ key: String) throws -> URL { let url: URL if key == "state" { let base = store.scope == .project ? store.environment.projectDirectory : store.environment.homeDirectory url = base.resolvingSymlinksInPath().appendingPathComponent(store.directory.lastPathComponent) + } else if let route = NativeTargetRoute.targetRoute(key) { + guard route.permits(store.scope) else { + throw CoreError.unsafePath("project native targets require their project scope") + } + if route.shared { + guard let context = TransactionLockContext.current(store) else { + throw CoreError.invalidState("shared target requires its held footprint") + } + url = try context.targetDirectory(for: route) + } else { + url = try route.physicalDirectory(store.environment) + } + } else if let route = NativeTargetRoute.metadataRoute(key) { + guard let context = TransactionLockContext.current(store), + let metadata = try context.resource(for: route).metadata + else { + throw CoreError.invalidState("shared metadata directory is missing") + } + url = metadata.url + } else if key == "skill-authoring", store.scope == .project { + url = store.environment.projectDirectory.resolvingSymlinksInPath() } else if key == "instructions-project" || key == "instructions-authoring", store.scope == .project { url = store.environment.projectDirectory.resolvingSymlinksInPath() + } else if key == InstructionLocations.ruleRoot(in: store.scope) { + url = try InstructionLocations.antigravityAuthority(store.environment, scope: store.scope) + .physicalDirectory() } else if key.hasPrefix("instructions-"), store.scope == .user, let agent = AgentID(rawValue: String(key.dropFirst("instructions-".count))), let file = InstructionLocations.file(for: agent, scope: .user, environment: store.environment) { url = file.deletingLastPathComponent().resolvingSymlinksInPath() - } else if let agent = AgentID(rawValue: key) { + } else if let agent = AgentID(rawValue: key), agent.supportsSkills { // Configured agent containers are trusted inputs. Resolve that boundary once; // journal descendants are opened without following links and roots are identity-bound. - url = AgentRegistry.installSkillsDirectory( - for: agent, scope: store.scope, environment: store.environment - ).resolvingSymlinksInPath() + url = try NativeRootAuthority( + loader: AgentRegistry.installSkillsDirectory( + for: agent, scope: store.scope, environment: store.environment), descendants: [] + ).physicalDirectory() } else { throw CoreError.invalidState("unknown transaction root") } - return try DirectoryHandle(at: url, create: create, checkpoint: checkpoint) + return url + } + + func nativeRootAuthorities(_ keys: Set) throws -> [String: NativeRootAuthority] { + var result: [String: NativeRootAuthority] = [:] + for key in keys { + if let route = NativeTargetRoute.targetRoute(key), !route.shared { + result[key] = try route.rootAuthority(store.environment) + } else if key == InstructionLocations.ruleRoot(in: store.scope) { + result[key] = InstructionLocations.antigravityAuthority( + store.environment, scope: store.scope) + } else if let agent = AgentID(rawValue: key), agent.supportsSkills { + result[key] = NativeRootAuthority( + loader: AgentRegistry.installSkillsDirectory( + for: agent, scope: store.scope, environment: store.environment), descendants: []) + } + } + return result + } + + /// Only committed exact recipients authorize legacy spellings at the queue boundary. + /// Recovery instead consumes the journal's already-admitted single-component path. + fileprivate func persistedInstallation(_ name: String, agent: AgentID) throws -> Bool { + guard agent.supportsSkills, !name.isEmpty, name != ".", name != "..", !name.contains("/"), + !name.contains("\\"), !name.contains("\0"), + let bytes = try store.existingData(store.resolvedURL) + else { return false } + try LedgerAdmission.check(bytes, limits: .standard) + struct Version: Decodable { let version: Int } + if try JSONDecoder().decode(Version.self, from: bytes).version == 2 { + let ledger = try ResolvedLedgerCodec.decode(bytes, limits: .standard) + return ledger.deployments.contains { + $0.target.kind == .registered && $0.target.root == "skills-" + agent.rawValue + && $0.target.path.utf8.elementsEqual(name.utf8) && $0.recipients.contains(agent) + && $0.route == "agents/skill@1" + } + } + return false } /// A top-level file in the project's own instructions container, `.agent/instructions/.md`. @@ -100,14 +260,31 @@ struct TransactionPaths { if key == "state" { let stateFile = descendants.count == 1 - && ["agents.json", "agents.resolved", "agents.watch"].contains(descendants[0]) + && (StateStore.stateFileNames.contains(descendants[0]) + || descendants[0] == StateStore.sourcePolicyFileName + || descendants[0] == StateStore.marketplaceDirectoryFileName + || (store.scope == .user && descendants[0] == StateStore.originalLedgerFileName)) let cache = descendants.first == "cache" && descendants.count >= 3 && ((descendants[1] == "materialized" && (3...4).contains(descendants.count)) || (["artifacts", "artifact-content"].contains(descendants[1]) && descendants.count == 3)) - guard stateFile || cache else { + let bundle = + descendants.count == 2 && descendants[0] == BundleSourceLocation.directory + && BundleSourceLocation.isKey(descendants[1]) + guard stateFile || cache || bundle else { throw CoreError.unsafePath("unmanaged state transaction path") } + } else if let route = NativeTargetRoute.targetRoute(key) { + guard route.permits(store.scope), descendants == [route.basename] else { + throw CoreError.unsafePath("unregistered native target") + } + } else if NativeTargetRoute.metadataRoute(key) != nil { + guard descendants == ["receipt"] else { + throw CoreError.unsafePath("unregistered shared transaction metadata") + } + } else if key == "skill-authoring", store.scope == .project { + guard (1...3).contains(descendants.count), descendants.last == "SKILL.md" + else { throw CoreError.unsafePath("invalid local skill authoring path") } } else if key == "instructions-project", store.scope == .project { guard InstructionLocations.isProjectTarget(descendants.joined(separator: "/")) else { throw CoreError.unsafePath("unmanaged project instruction path") @@ -116,6 +293,12 @@ struct TransactionPaths { guard isAuthoringFile(descendants) else { throw CoreError.unsafePath("invalid instruction authoring path") } + } else if key == InstructionLocations.ruleRoot(in: store.scope) { + guard descendants.count == 1, + InstructionLocations.isAntigravityLeaf(descendants[0]) + || (store.scope == .user + && InstructionLocations.isAntigravityLeaf(descendants[0], legacy: true)) + else { throw CoreError.unsafePath("unregistered Antigravity rule") } } else if key.hasPrefix("instructions-"), store.scope == .user, let agent = AgentID(rawValue: String(key.dropFirst("instructions-".count))), let file = InstructionLocations.file(for: agent, scope: .user, environment: store.environment) @@ -124,29 +307,161 @@ struct TransactionPaths { throw CoreError.unsafePath("unmanaged user instruction path") } } else { - guard AgentID(rawValue: key) != nil, descendants.count == 1, - PathSafety.sanitizeName(descendants[0]) == descendants[0] + guard AgentID(rawValue: key)?.supportsSkills == true, descendants.count == 1 else { throw CoreError.unsafePath("unmanaged installation transaction path") } } return (key, descendants) } + /// With `create`, each descendant's parent is synced. Checkpoints mark only descendants + /// this call creates; depth counts levels above the returned parent, as for roots. func parent( for path: String, roots: [String: DirectoryHandle], create: Bool = false, - checkpoint: (String) throws -> Void = { _ in } + checkpoint: (DirectoryHandle.AncestryStep) throws -> Void = { _ in } ) throws -> DirectoryHandle { let components = try components(path) guard var directory = roots[components.root] else { throw CoreError.invalidState("missing transaction root") } - for name in components.descendants.dropLast() { + let ancestry = components.descendants.dropLast() + for (index, name) in ancestry.enumerated() { if create { - if try directory.info(name) == nil { try directory.makeDirectory(name) } + let depth = ancestry.count - 1 - index + let created = try directory.info(name) == nil + if created { + try directory.makeDirectory(name) { try checkpoint(.created(depth: depth)) } + } try directory.sync() - try checkpoint("directory.synced.\(name)") + if created { try checkpoint(.synced(depth: depth)) } } directory = try directory.child(name) } return directory } } + +/// Exact closed installation authority; coordination does not change its payload intention. +package struct SkillInstallationTarget: Sendable { + package let url: URL + package let footprint: Set + let path: String + let scope: URL + let agent: AgentID + let name: String + let authority: NativeRootAuthority + let parentIdentity: FileObjectIdentity? + + /// Coalesces identical parent checks without sharing a successful check across phases. + package static func distinctAuthorities(_ targets: [Self]) -> [Self] { + struct Key: Hashable { + let loader: Data + let descendants: [Data] + let parent: Data + let identity: FileObjectIdentity? + } + var seen: Set = [] + return targets.filter { target in + seen.insert( + Key( + loader: Data(target.authority.loader.path.utf8), + descendants: target.authority.descendants.map { Data($0.utf8) }, + parent: Data(target.url.deletingLastPathComponent().path.utf8), + identity: target.parentIdentity) + ).inserted + } + } + + package func validateAuthority() throws { + let parent = try authority.physicalDirectory() + guard parent.path.utf8.elementsEqual(url.deletingLastPathComponent().path.utf8), + try parentIdentity.map({ try DirectoryHandle(at: parent).objectIdentity == $0 }) ?? true + else { throw CoreError.invalidState("installation authority changed") } + } +} + +extension StateStore { + package func skillInstallationTarget(for agent: AgentID, named name: String) throws + -> SkillInstallationTarget + { + var resolver = SkillInstallationTargetResolver(store: self) + return try resolver.target(for: agent, named: name) + } +} + +/// Resolves a set of skills against one fresh observation of each installed root. +package struct SkillInstallationTargetResolver { + private struct Parent { + let url: URL + let authority: NativeRootAuthority + let identity: FileObjectIdentity? + } + + private let paths: TransactionPaths + private var parents: [AgentID: Parent] = [:] + private var routes: NativeTargetRoute.UserRouteLookup + + package init(store: StateStore) { + paths = TransactionPaths(store: store) + routes = .init(environment: store.environment) + } + + private mutating func parent(for agent: AgentID) throws -> Parent { + if let known = parents[agent] { return known } + let authority = NativeRootAuthority( + loader: AgentRegistry.installSkillsDirectory( + for: agent, scope: paths.store.scope, environment: paths.store.environment), + descendants: []) + let url = try authority.physicalDirectory() + let ancestry = try DirectoryAccessEvidence.capture(at: url) + let identity = + ancestry.directories.count == url.pathComponents.count + ? try DirectoryHandle(at: url).objectIdentity : nil + let parent = Parent(url: url, authority: authority, identity: identity) + parents[agent] = parent + return parent + } + + package mutating func target(for agent: AgentID, named name: String) throws + -> SkillInstallationTarget + { + let canonical = name.utf8.elementsEqual(PathSafety.sanitizeName(name).utf8) + let recorded = canonical ? false : try paths.persistedInstallation(name, agent: agent) + guard agent.supportsSkills, !name.isEmpty, name != ".", name != "..", !name.contains("/"), + !name.contains("\\"), !name.contains("\0"), + canonical || recorded + else { throw CoreError.unsafePath("unrecorded installation target") } + let parent = try parent(for: agent) + let url = parent.url.appendingPathComponent(name) + let path = agent.rawValue + "/" + name + let route = try paths.installationCoordinationRoute(for: agent, route: routes.route(at: url)) + return SkillInstallationTarget( + url: url, footprint: Set(route.map { [$0] } ?? []), path: path, scope: paths.store.directory, + agent: agent, name: name, authority: parent.authority, parentIdentity: parent.identity) + } +} + +extension TransactionPaths { + func coordinationRoute(for path: String) throws -> NativeTargetRoute? { + if let metadata = NativeTargetRoute.metadataRoute(path) { return metadata } + if let route = NativeTargetRoute.targetRoute(path) { + return try store.coordinationRoute(for: route) + } + let parts = path.split(separator: "/").map(String.init) + guard parts.count == 2, let agent = AgentID(rawValue: parts[0]) else { return nil } + _ = try components(path) + let target = try rootURL(parts[0]).appendingPathComponent(parts[1]) + return try installationCoordinationRoute( + for: agent, route: NativeTargetRoute.userRoute(at: target, environment: store.environment)) + } + + fileprivate func installationCoordinationRoute(for agent: AgentID, route: NativeTargetRoute?) + throws + -> NativeTargetRoute? + { + guard let route else { return nil } + guard route.isContainer, route.knownReaders.contains(agent) else { + throw CoreError.unsafePath("installation aliases incompatible native readers") + } + return route + } +} diff --git a/Sources/AgentsCore/TransactionPermissions.swift b/Sources/AgentsCore/TransactionPermissions.swift new file mode 100644 index 0000000..2aa3509 --- /dev/null +++ b/Sources/AgentsCore/TransactionPermissions.swift @@ -0,0 +1,92 @@ +import Foundation + +extension TransactionSession { + /// Publishing/restoring intent binds a temporary owner-write bit to the recorded + /// directory inode. It never grants access through an external replacement. + func grantDirectoryPermissions( + _ index: Int, layout: TransactionLayout, purpose: TransactionCheckpoint.Permission + ) throws { + for (location, object) in layout.objectLocations(journal.entries[index]) { + guard let lease = object.writeLease else { continue } + try leasedDirectory(index, location).grant(lease) { + try emit(.permissions(index, purpose, location, $0)) + } + } + } + + /// Mode restoration uses physical identity independently of byte rollback. A + /// changed payload is retained, while a known temporary permission can be undone. + /// Missing inodes or modes outside the recorded pair require owner action. + func restoreDirectoryPermissions(_ index: Int, purpose: TransactionCheckpoint.Permission) + throws + { + try forEachDirectoryLease(index) { location, lease in + try leasedDirectory(index, location).restore(lease) { + try emit(.permissions(index, purpose, location, $0)) + } + } + } + + func inspectDirectoryPermissions(_ index: Int) throws { + guard journal.entries[index].progress.permitsDirectoryWrite else { return } + try forEachDirectoryLease(index) { location, lease in + let (parent, name) = try permissionLocation(index, location) + _ = try parent.child(name).checkedPermissions(lease) + } + } + + /// Candidate locations are those of the progress's expected distributions. Each leased + /// inode is acted on where it is found; one found in no candidate location is a conflict. + private func forEachDirectoryLease( + _ index: Int, body: (TransactionObjectLocation, DirectoryWriteLease) throws -> Void + ) throws { + let entry = journal.entries[index] + var candidates: [(location: TransactionObjectLocation, lease: DirectoryWriteLease)] = [] + for layout in TransactionLayout.expected(entry) { + for (location, object) in layout.objectLocations(entry) { + guard let lease = object.writeLease, + !candidates.contains(where: { $0.location == location && $0.lease == lease }) + else { continue } + candidates.append((location, lease)) + } + } + var found: [FileObjectIdentity] = [] + var errors: [String] = [] + for (location, lease) in candidates { + do { + let (parent, name) = try permissionLocation(index, location) + guard try parent.info(name).map(FileObjectIdentity.init) == lease.identity else { + continue + } + found.append(lease.identity) + try body(location, lease) + } catch { errors.append(String(describing: error)) } + } + if candidates.contains(where: { !found.contains($0.lease.identity) }) { + errors.append("directory mode restoration is missing its recorded inode") + } + guard errors.isEmpty else { throw conflict(index, errors.joined(separator: "; ")) } + } + + private func permissionLocation(_ index: Int, _ location: TransactionObjectLocation) throws + -> (DirectoryHandle, String) + { + try requireParent(index) + switch location { + case .target: return (parents[index], journal.entries[index].name) + case .slot(let slot): + return (try container(journal.entries[index].container), slot.name(index)) + } + } + + /// Mode changes require durable publishing or restoring intent. + private func leasedDirectory(_ index: Int, _ location: TransactionObjectLocation) throws + -> DirectoryHandle + { + guard journal.entries[index].progress.permitsDirectoryWrite else { + throw conflict(index, "directory permission change requires durable intent") + } + let (parent, name) = try permissionLocation(index, location) + return try parent.child(name) + } +} diff --git a/Sources/AgentsCore/TransactionPublication.swift b/Sources/AgentsCore/TransactionPublication.swift new file mode 100644 index 0000000..1aba19b --- /dev/null +++ b/Sources/AgentsCore/TransactionPublication.swift @@ -0,0 +1,344 @@ +import Foundation + +/// Construction, sealing and publication of a commit's operations. +extension TransactionSession { + func createContainers() throws { + for index in journal.containers.indices { + let parent = parents[journal.containers[index].entry] + let needsPrivate = journal.entries.contains { $0.container == index && $0.security.isPrivate } + let created = + try needsPrivate + ? parent.createPrivateDirectory(journal.containerName(index)) + : parent.makeDirectory(journal.containerName(index)) + if needsPrivate { journal.containers[index].access = try created.accessEvidence() } + let identity = try created.objectIdentity + try emit(.containerCreated(index)) + guard try parent.info(journal.containerName(index)).map(FileObjectIdentity.init) == identity + else { + throw conflict( + journal.containers[index].entry, + "private container changed before its identity was durable") + } + journal.containers[index].identity = identity + } + // No object enters any container until all newly created identities are durable. + try persist(.containers) + try emit(.containersIdentified) + } + + func checkCapabilities() throws { + for index in journal.containers.indices { + let container = try self.container(index) + let device = try container.device + guard !capableDevices.contains(device) else { continue } + let names = TransactionSlot.probes + try container.requireAtomicRenames( + first: names.first, second: names.second, moved: names.moved + ) { try emit(.probe(index, $0)) } + capableDevices.insert(device) + } + } + + func stage( + _ index: Int, source: FileTransaction.Source?, expectation: FileTransaction.Expectation, + privateData: (() throws -> PrivateMaterializationResult)? = nil, + privateTree: PrivateTree? = nil, + previousReceipt: MaterializationReceipts.Record? = nil + ) throws { + let entry = journal.entries[index] + let parent = parents[index] + let container = try self.container(entry.container) + if let preimage = entry.preimage { try parent.synchronize(entry.name, as: preimage) } + try emit(.stage(index, .preimageSynced)) + let staging = TransactionSlot.staging(for: entry) + var staged: FileSnapshot? + if 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) + try emit(.stage(index, .constructed)) + let capture = try FileSnapshot.capture(staging.name(index), from: container) + try verify(source, sealed, capture: capture) + guard let snapshot = capture.snapshot else { + throw conflict(index, "missing constructed object") + } + staged = snapshot + if entry.security.replacement == .privateMaterialization { + journal.entries[index].security.stagedAccess = try container.requirePrivateAccess( + staging.name(index)) + journal.entries[index].security.stagedTreeAccess = try TreeMemberAccess.capture( + staging.name(index), in: container, snapshot: snapshot, requirePrivate: true) + } + } else { + try emit(.stage(index, .constructed)) + } + 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") + } + } + try container.sync() + journal.entries[index].staged = staged + try advance(index, to: .ready) + } + + /// Returns the expectation the sealed staging must meet. + private func construct( + _ source: FileTransaction.Source?, expectation: FileTransaction.Expectation, + named name: String, index: Int, container: DirectoryHandle, parent: DirectoryHandle, + privateData: (() throws -> PrivateMaterializationResult)?, privateTree: PrivateTree?, + previousReceipt: MaterializationReceipts.Record? + ) throws -> FileTransaction.Expectation { + let entry = journal.entries[index] + var expectation = expectation + if entry.security.replacement == .privateMaterialization { + if let privateTree { + var bytes = privateTreeBytes + defer { privateTreeBytes = bytes } + try privateTree.construct( + named: name, in: container, bytes: &bytes, + admit: { snapshot, access, members in + // Payload writes change fixed-width digests, not the sealed evidence's shape. + var candidate = self.journal + candidate.entries[index].staged = snapshot + candidate.entries[index].security.stagedAccess = access + candidate.entries[index].security.stagedTreeAccess = members + candidate.entries[index].progress = .ready + try LedgerAdmission.check(StateStore.encode(candidate), limits: .standard) + }, + validate: { try self.requirePreimage(index) }) + expectation.kind = S_IFDIR + expectation.mode = 0o700 + return expectation + } + guard let privateData else { + throw conflict(index, "missing private materialization producer") + } + let file = try container.createPrivateFile(name) + try emit(.stage(index, .writeCreated)) + try requirePreimage(index) + _ = try container.requirePrivateAccess(name, matching: file.evidence) + // The callback is never given a path or unverified descriptor. + let result = try privateData() + let route = NativeTargetRoute.targetRoute(entry.path) + let arrays = try PrivateNativeArrayRecord.applying( + result, previous: previousReceipt, admitted: route != nil && route?.isContainer == false, + hasPreimage: entry.preimage != nil) + try sealNativeArrays(arrays, for: index) + let data = result.bytes + try requireParent(index) + let hash = "sha256:" + FileHash.sha256Hex(data: data) + if let expected = expectation.hash, expected != hash { + throw CoreError.invalidState("staged content digest mismatch") + } + try file.write(data) + expectation.hash = expectation.hash ?? hash + expectation.kind = S_IFREG + expectation.mode = file.evidence.mode + return expectation + } + guard let source else { throw conflict(index, "missing ordinary construction input") } + switch source { + case .data(let data): + let original = entry.preimage?.isRegular == true ? entry.preimage : nil + expectation.mode = original?.mode ?? 0o600 + try container.write( + name, data: data, preservingMetadataOf: original == nil ? nil : entry.name, + originalParent: parent, syncParent: false, + afterCreate: { try emit(.stage(index, .writeCreated)) }) + case .link(let url): + let destination = expectation.linkDestination ?? url.path + expectation.linkDestination = destination + try container.link(name, destination: destination, syncParent: false) + case .copy(let url): + try copy(url, named: name, index: index, container: container) + case .prepared(let produce): + let work = TransactionSlot.work.name(index) + try container.makeDirectory(work, syncParent: false) + try emit(.stage(index, .workCreated)) + let root = container.url.appendingPathComponent(work) + let url = try produce(root) + guard PathSafety.isContained(url.resolvingSymlinksInPath(), in: root) else { + throw CoreError.unsafePath("prepared content escapes transaction staging") + } + let produced = try FileTransaction.copyExpectation( + url, hash: expectation.hash, flags: expectation.executableFlags) + guard expectation.kind == nil || expectation.kind == produced.kind else { + throw CoreError.invalidState("prepared content type contradicts registered target") + } + expectation = produced + try emit(.stage(index, .workPrepared)) + try copy(url, named: name, index: index, container: container) + } + return expectation + } + + private func copy(_ source: URL, named name: String, index: Int, container: DirectoryHandle) + throws + { + try Self.validateCopy(source) + let origin = source.resolvingSymlinksInPath() + try container.copy( + name, from: DirectoryHandle(at: origin.deletingLastPathComponent()), + named: origin.lastPathComponent, syncParent: false + ) { try emit(.copy(index, $0)) } + } + + private func verify( + _ source: FileTransaction.Source?, _ expectation: FileTransaction.Expectation, + capture: FileSnapshot.Capture + ) throws { + let snapshot = capture.snapshot + if let digest = expectation.objectDigest, snapshot?.digest != digest { + throw CoreError.invalidState("staged subtree content or executable intent mismatch") + } + if let kind = expectation.kind, snapshot?.identity.kind != kind { + throw CoreError.invalidState("staged content type mismatch") + } + if case .data? = source, snapshot?.isRegular != true { + throw CoreError.invalidState("staged content type mismatch") + } + if let mode = expectation.mode, snapshot?.mode != mode { + throw CoreError.invalidState("staged content permissions mismatch") + } + var linked: URL? + switch source { + case .data(let data)?: + guard snapshot?.digest == FileHash.sha256Hex(data: data) else { + throw CoreError.invalidState("staged content bytes mismatch") + } + case .link(let url)?: + guard snapshot?.isSymbolicLink == true, let destination = expectation.linkDestination, + snapshot?.digest == FileHash.sha256Hex(data: Data(destination.utf8)) + else { throw CoreError.invalidState("staged symbolic link destination mismatch") } + linked = url + case .copy?, .prepared?, nil: break + } + if let expected = expectation.hash { + let actual = try linked.map(FileHash.folderHash) ?? capture.contentHash + guard "sha256:" + actual == expected else { + throw CoreError.invalidState("staged content digest mismatch") + } + } + if let flags = expectation.executableFlags { + let actual = try linked.map(FileHash.executableFlags) ?? capture.executableFlags + guard actual == flags else { + throw CoreError.invalidState("staged content executable mode mismatch") + } + } + } + + func validatePreimages() throws { + for index in journal.entries.indices { try requirePreimage(index) } + } + + func publish(_ index: Int) throws { + guard journal.footprint.isEmpty || journal.reservationsReady else { + throw CoreError.invalidState("shared reservations are not ready") + } + let entry = journal.entries[index] + let parent = parents[index] + let container = try self.container(entry.container) + let layout = try distribution(index) + guard layout.kind == .prepared else { + throw conflict(index, "operation is not prepared") + } + // A stale preparation cancels from ready; rechecking after the intent narrows the race. + try requirePreimage(index) + try advance(index, to: .publishing) + try requirePreimage(index) + try emit(.publication(index, .validated)) + try requirePreimage(index) + try grantDirectoryPermissions(index, layout: layout, purpose: .publicationGrant) + if entry.action == .install { + let exchange = entry.preimage != nil + try container.move( + TransactionSlot.staging(for: entry).name(index), to: parent, named: entry.name, + mode: exchange ? .exchange : .exclusive + ) { + try emit(.publication(index, exchange ? .exchanged : .created)) + } + } else if entry.preimage != nil { + try parent.move( + entry.name, to: container, named: TransactionSlot.deleted.name(index), mode: .exclusive + ) { + try emit(.publication(index, .deleted)) + } + } + try emit(.publication(index, .synced)) + try restoreDirectoryPermissions(index, purpose: .publicationRestore) + guard try distribution(index).kind == .installed else { + throw conflict(index, "publication did not retain its preimage") + } + try advance(index, to: .applied) + } + + func requirePreimage(_ index: Int) throws { + try requireParent(index) + let entry = journal.entries[index] + if let preimage = entry.preimage { + try entry.security.validateObject(preimage, named: entry.name, in: parents[index]) + } + guard + try FileSnapshot.read(journal.entries[index].name, from: parents[index]) + == journal.entries[index].preimage + else { + throw conflict(index, "preparation is stale; prepare again") + } + } + + func materializationReceipts(previous: MaterializationReceipts, targetRoot: String? = nil) throws + -> MaterializationReceipts + { + + var records = previous + for (index, entry) in journal.entries.enumerated() + where entry.path != "state/" + MaterializationReceipts.fileName + && NativeTargetRoute.metadataRoute(entry.path) == nil + { + let resource = entry.coordination.flatMap { index in + resources.first { $0.identity == journal.footprint[index] } + } + guard resource?.route.root == targetRoot else { continue } + let recordPath = resource.map { $0.route.root + "/" + entry.name } ?? entry.path + if entry.security.replacement == .privateMaterialization, + entry.security.archiveOutput != true + { + guard let snapshot = entry.staged, let access = entry.security.stagedAccess, + let root = entry.path.split(separator: "/").first, + let identity = journal.roots[String(root)] + else { throw CoreError.invalidState("materialization is missing sealed receipt evidence") } + if targetRoot != nil, resource == nil { + throw CoreError.invalidState("receipt resource is outside the transaction footprint") + } + records.targets[recordPath] = .init( + generation: journal.id, + rootIdentity: resource?.identity.orderingKey ?? identity, + digest: snapshot.digest, access: access, treeAccess: entry.security.stagedTreeAccess, + nativeArrays: privateNativeArrays[index]) + if privateNativeArrays[index] != nil { records.version = 2 } + } else { + records.targets.removeValue(forKey: recordPath) + } + } + return records + } + + /// A copied subtree keeps relative links that stay inside it, dangling ones included. + private static func validateCopy(_ source: URL) throws { + guard let root = PathSafety.realPath(source.path), + let entries = FileManager.default.enumerator( + at: URL(fileURLWithPath: root), includingPropertiesForKeys: [.isSymbolicLinkKey]) + else { return } + for case let entry as URL in entries { + if try entry.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink == true { + entries.skipDescendants() + let destination = try FileManager.default.destinationOfSymbolicLink(atPath: entry.path) + guard !destination.hasPrefix("/"), try PathSafety.linkStaysInside(entry, root: root) else { + throw CoreError.unsafePath("copy symlink escapes installed subtree: \(entry.path)") + } + } + } + } +} diff --git a/Sources/AgentsCore/TransactionRecovery.swift b/Sources/AgentsCore/TransactionRecovery.swift new file mode 100644 index 0000000..249717c --- /dev/null +++ b/Sources/AgentsCore/TransactionRecovery.swift @@ -0,0 +1,381 @@ +import Foundation + +package struct TransactionRecoveryDiagnostic { + package let requiresOwner: Bool + package let message: String + + static let pendingMessage = + "Transaction recovery is pending; the next command that changes this scope will recover it." + static let conflictMessage = "Unresolved transaction conflict; owner action is required" +} + +extension FileTransaction { + package static func recover( + store: StateStore, outcome: TransactionOutcome? = nil, + checkpoint: @escaping (String) throws -> Void = { _ in } + ) throws -> Bool { + do { + return try recoverJournal(store: store, outcome: outcome, checkpoint: checkpoint) + } catch { + outcome?.requireRecovery() + throw error + } + } + + private static func recoverJournal( + store: StateStore, outcome: TransactionOutcome?, checkpoint: @escaping (String) throws -> Void + ) throws -> Bool { + guard let directory = try store.openDirectoryIfPresent() else { return false } + let primary = TransactionJournal.fileName + let incomplete = TransactionJournal.incompleteFileName + guard try directory.info(primary) != nil else { + guard try directory.info(incomplete) != nil else { return false } + let bytes = try directory.read(incomplete) + if (try? JSONSerialization.jsonObject(with: bytes)) != nil { + let journal = try readJournal(bytes) + if journal.finalized { + try validateRecoveryCoordination(journal, store: store, directory: directory) + try directory.syncFile(incomplete) + if outcome?.journalID == journal.id { + outcome?.recordTerminal(journal.phase) + outcome?.recoveryPending = true + } + try cleanupFinalized(journal, store: store, directory: directory, checkpoint: checkpoint) + if outcome?.journalID == journal.id { + outcome?.recordTerminal(journal.phase) + outcome?.recoveryPending = false + } + return true + } + if journal.isReservationOnly { + try validateRecoveryCoordination(journal, store: store, directory: directory) + try finalizeReservationConstruction( + journal, store: store, directory: directory, checkpoint: checkpoint) + if outcome?.journalID == journal.id { + outcome?.recordTerminal(.rolledBack) + outcome?.recoveryPending = false + } + return true + } + } + // An unstarted journal owns no object, so it is discarded without a journal barrier. + try requireUnstartedIncompleteJournal(in: directory) + try directory.remove(incomplete) + return true + } + let journal = try readJournal(directory.read(primary)) + try validateRecoveryCoordination(journal, store: store, directory: directory) + if journal.isReservationOnly { + try finalizeReservationConstruction( + journal, store: store, directory: directory, checkpoint: checkpoint) + if outcome?.journalID == journal.id { + outcome?.recordTerminal(.rolledBack) + outcome?.recoveryPending = false + } + return true + } + if journal.finalized { + try directory.syncFile(primary) + if outcome?.journalID == journal.id { + outcome?.recordTerminal(journal.phase) + outcome?.recoveryPending = true + } + try cleanupFinalized(journal, store: store, directory: directory, checkpoint: checkpoint) + if outcome?.journalID == journal.id { + outcome?.recordTerminal(journal.phase) + outcome?.recoveryPending = false + } + return true + } + if outcome?.journalID == journal.id { + // Stabilize the observed terminal before reconstructing data that disposal may reject. + try directory.syncFile(primary) + outcome?.recordTerminal(journal.phase) + if journal.phase == .applying { outcome?.publicationStarted = true } + outcome?.recoveryPending = true + } + let session = try recoverySession( + journal, store: store, directory: directory, checkpoint: checkpoint) + // Validate the incomplete next generation before any recovery mutation. + if try directory.info(incomplete) != nil { _ = try directory.read(incomplete) } + // Any observed journal may have been renamed without its directory barrier. Persist it + // before granting permissions, renaming objects or deleting any resource, including on retry. + if outcome?.journalID != journal.id { try directory.syncFile(primary) } + try session.emit(.journalSynced) + if journal.phase == .applying { try session.rollback() } + if session.journal.phase == .applying || session.journal.phase == .preparing { + try session.sealDisposal() + try session.finish(.rolledBack) + if outcome?.journalID == journal.id { outcome?.recordTerminal(.rolledBack) } + try session.emit(.phase(.rolledBack)) + } + if outcome?.journalID == journal.id { outcome?.recordTerminal(session.journal.phase) } + try session.revalidateDisposal() + if outcome?.journalID == journal.id { outcome?.recoveryPending = false } + return true + } + + package static func recoveryDiagnostic(store: StateStore) -> TransactionRecoveryDiagnostic { + let journalURL = store.directory.appendingPathComponent(TransactionJournal.fileName) + var retained = [journalURL.path] + do { + guard let directory = try store.openDirectoryIfPresent() else { + return .init(requiresOwner: false, message: TransactionRecoveryDiagnostic.pendingMessage) + } + if try directory.info(TransactionJournal.fileName) == nil { + if try directory.info(TransactionJournal.incompleteFileName) != nil { + let bytes = try directory.read(TransactionJournal.incompleteFileName) + if (try? JSONSerialization.jsonObject(with: bytes)) != nil { + let journal = try readJournal(bytes) + if journal.finalized { + try validateRecoveryCoordination(journal, store: store, directory: directory) + return .init( + requiresOwner: false, + message: "Transaction metadata cleanup is pending (\(journal.phase.rawValue)).") + } + if journal.isReservationOnly { + try validateRecoveryCoordination(journal, store: store, directory: directory) + return .init( + requiresOwner: false, message: TransactionRecoveryDiagnostic.pendingMessage) + } + } + try requireUnstartedIncompleteJournal(in: directory) + } + return .init(requiresOwner: false, message: TransactionRecoveryDiagnostic.pendingMessage) + } + let journal = try readJournal(directory.read(TransactionJournal.fileName)) + try validateRecoveryCoordination(journal, store: store, directory: directory) + if journal.finalized { + return .init( + requiresOwner: false, + message: "Transaction metadata cleanup is pending (\(journal.phase.rawValue)).") + } + if journal.isReservationOnly { + return .init(requiresOwner: false, message: TransactionRecoveryDiagnostic.pendingMessage) + } + retained += journal.entries.compactMap(journal.containerLocation(of:)) + let session = try recoverySession( + journal, store: store, directory: directory, checkpoint: { _ in }) + let conflicts = journal.entries.compactMap(\.conflict) + if !conflicts.isEmpty { + let details = conflicts.map { + "\($0.reason); retained locations: \($0.locations.joined(separator: ", "))" + } + return .init( + requiresOwner: true, + message: TransactionRecoveryDiagnostic.conflictMessage + ". " + + details.joined(separator: "; ") + "; journal: " + journalURL.path) + } + try session.inspectRecoveryObjects() + return .init(requiresOwner: false, message: TransactionRecoveryDiagnostic.pendingMessage) + } catch { + return .init( + requiresOwner: true, + message: + "\(TransactionRecoveryDiagnostic.conflictMessage): \(error). Retained locations: \(Set(retained).sorted().joined(separator: ", "))." + ) + } + } + + /// A lone incomplete journal may be discarded only while it is unparseable or unstarted. + private static func requireUnstartedIncompleteJournal(in directory: DirectoryHandle) throws { + let bytes = try directory.read(TransactionJournal.incompleteFileName) + guard (try? JSONSerialization.jsonObject(with: bytes)) != nil else { return } + guard try readJournal(bytes).isUnstarted else { + throw CoreError.invalidState( + "missing primary journal; retained transaction.new needs owner action") + } + } + + static func readJournal(_ bytes: Data) throws -> TransactionJournal { + try LedgerAdmission.check(bytes, limits: .standard) + try JSONKeys.validate(bytes) + let value = try JSONSerialization.jsonObject(with: bytes) as? [String: Any] + guard value?["version"] as? Int == TransactionJournal.currentVersion else { + throw CoreError.invalidState( + "transaction journal was written by another version; recover it with the version that wrote it (journal version: \(value?["version"].map(String.init(describing:)) ?? "missing"))" + ) + } + do { return try StateStore.decode(bytes, as: TransactionJournal.self) } catch { + throw CoreError.invalidState("unresolved transaction journal: \(error)") + } + } + + private static func finalizeReservationConstruction( + _ journal: TransactionJournal, store: StateStore, directory: DirectoryHandle, + checkpoint: @escaping (String) throws -> Void + ) throws { + // Reservation construction precedes every container and publication. No data object + // belongs to this journal yet; a later writer may already have advanced the target. + var terminal = journal + terminal.phase = .rolledBack + terminal.disposing = true + terminal.finalized = true + let session = TransactionSession( + journal: terminal, directory: directory, parents: [], checkpoint: checkpoint) + try session.persist(.finalized) + try checkpoint("journal.finalized") + try cleanupFinalized(terminal, store: store, directory: directory, checkpoint: checkpoint) + } + + private static func validateRecoveryCoordination( + _ journal: TransactionJournal, store: StateStore, directory: DirectoryHandle + ) throws { + try journal.validateCoordination() + guard try directory.identity == journal.scope else { + throw CoreError.invalidState("transaction scope identity changed") + } + if !journal.footprint.isEmpty { + guard let context = TransactionLockContext.current(store) else { + throw CoreError.invalidState("shared recovery requires its held coordination footprint") + } + try context.validate(journal, scope: directory) + if journal.finalized { + for identity in journal.footprint { + try context.resource(identity).validateFinalized(journal) + } + } + } + } + + private static func cleanupFinalized( + _ journal: TransactionJournal, store: StateStore, directory: DirectoryHandle, + checkpoint: (String) throws -> Void + ) throws { + for (index, identity) in journal.footprint.enumerated() { + let resource = try TransactionLockContext.current(store).requiredResource(identity) + try resource.release(journal) { try checkpoint("shared.\(index)." + $0) } + } + try directory.removeFiles([TransactionJournal.incompleteFileName, TransactionJournal.fileName]) + { name in + if name == TransactionJournal.fileName { try checkpoint("journal.unlinked") } + } + try checkpoint("journal.removed") + } + + private static func recoverySession( + _ journal: TransactionJournal, store: StateStore, + directory: DirectoryHandle, checkpoint: @escaping (String) throws -> Void + ) throws -> TransactionSession { + let paths = TransactionPaths(store: store) + var roots: [String: DirectoryHandle] = [:] + for key in journal.roots.keys { + let root = try paths.root(key) + guard try root.identity == journal.roots[key] else { + throw CoreError.invalidState("transaction root identity changed") + } + roots[key] = root + } + let parents = try journal.entries.map { try paths.parent(for: $0.path, roots: roots) } + let session = TransactionSession( + journal: journal, directory: directory, parents: parents, checkpoint: checkpoint, + resources: try journal.footprint.map { identity in + try TransactionLockContext.current(store).requiredResource(identity) + }, nativeRoots: try paths.nativeRootAuthorities(Set(journal.roots.keys))) + try session.validateRecords(store: store) + return session + } +} + +extension TransactionSession { + /// Read-only diagnosis of the distribution recovery would act on. + func inspectRecoveryObjects() throws { + for index in journal.entries.indices { + if journal.disposing { + try verifyTarget(index) + } else { + _ = try distribution(index, permittingDirectoryWrite: true) + try inspectDirectoryPermissions(index) + } + } + for index in journal.containers.indices { try validateContainerForDisposal(index) } + } + + func rollback() throws { + var errors: [String] = [] + for index in journal.entries.indices.reversed() { + do { try rollbackEntry(index) } catch { + var reasons = [String(describing: error)] + if journal.entries[index].progress.permitsDirectoryWrite { + do { try restoreDirectoryPermissions(index, purpose: .conflictRestore) } catch { + reasons.append(String(describing: error)) + } + } + let failure = CoreError.invalidState(reasons.joined(separator: "; ")) + try recordConflict(index, failure) + errors.append(String(describing: failure)) + } + } + guard errors.isEmpty else { + throw CoreError.invalidState( + "unresolved transaction conflicts: " + errors.joined(separator: "; ")) + } + } + + private func rollbackEntry(_ index: Int) throws { + let layout = try distribution(index, permittingDirectoryWrite: true) + let progress = journal.entries[index].progress + if progress == .ready { + try advance(index, to: .cancelled) + return + } + if progress == .cancelled || progress == .restored { return } + if layout.kind == .prepared { + try restoreDirectoryPermissions(index, purpose: .cancelRestore) + _ = try distribution(index) + try advance(index, to: .cancelled) + return + } + if progress != .restoring { try advance(index, to: .restoring) } + if layout.kind == .installed { + try grantDirectoryPermissions(index, layout: layout, purpose: .undoGrant) + try undo(index) + } else { + // A visible undo rename may have been interrupted before either parent barrier. + try parents[index].sync() + try container(journal.entries[index].container).sync() + } + try restoreDirectoryPermissions(index, purpose: .undoRestore) + try emit(.restoration(index, .synced)) + guard try distribution(index).kind == .reverted else { + throw conflict(index, "undo did not restore the expected objects") + } + try advance(index, to: .restored) + } + + private func undo(_ index: Int) throws { + let entry = journal.entries[index] + let parent = parents[index] + let container = try self.container(entry.container) + try emit(.restoration(index, .validated)) + try requireParent(index) + if let preimage = entry.preimage { + let slot: TransactionSlot = entry.action == .install ? .exchanged : .deleted + try entry.security.validateObject( + preimage, named: slot.name(index), in: container, + permittingDirectoryWrite: entry.progress.permitsDirectoryWrite) + } + if entry.preimage != nil { + if entry.action == .install { + try container.move( + TransactionSlot.exchanged.name(index), to: parent, named: entry.name, + mode: .exchange + ) { + try emit(.restoration(index, .exchanged)) + } + } else { + try container.move( + TransactionSlot.deleted.name(index), to: parent, named: entry.name, mode: .exclusive + ) { + try emit(.restoration(index, .returned)) + } + } + } else if entry.action == .install { + try parent.move( + entry.name, to: container, named: TransactionSlot.withdrawn.name(index), mode: .exclusive + ) { + try emit(.restoration(index, .withdrawn)) + } + } + } +} diff --git a/Sources/AgentsCore/TransactionSession.swift b/Sources/AgentsCore/TransactionSession.swift new file mode 100644 index 0000000..619bd3b --- /dev/null +++ b/Sources/AgentsCore/TransactionSession.swift @@ -0,0 +1,354 @@ +import Foundation + +/// One commit or recovery pass over the scope journal under the writer lock. +final class TransactionSession { + var journal: TransactionJournal + let directory: DirectoryHandle + let parents: [DirectoryHandle] + let checkpoint: (String) throws -> Void + let resources: [SharedResource] + private let outcome: TransactionOutcome? + /// Logical project-root authorization is checked separately from opened physical parents. + private let nativeRoots: [String: NativeRootAuthority] + /// Devices whose atomic renames passed a probe during this session only; `st_dev` values + /// can be reused by another filesystem after an unmount. + var capableDevices: Set = [] + + init( + journal: TransactionJournal, directory: DirectoryHandle, parents: [DirectoryHandle], + checkpoint: @escaping (String) throws -> Void, resources: [SharedResource] = [], + nativeRoots: [String: NativeRootAuthority] = [:], outcome: TransactionOutcome? = nil + ) { + self.journal = journal + self.directory = directory + self.parents = parents + self.checkpoint = checkpoint + self.resources = resources + self.nativeRoots = nativeRoots + self.outcome = outcome + } + + var privateTreeBytes = 0 + var privateNativeArrays: [Int: [PrivateNativeArrayRecord]] = [:] + + func sealNativeArrays(_ arrays: [PrivateNativeArrayRecord]?, for index: Int) throws { + var candidate = privateNativeArrays + candidate[index] = arrays + var count = 0 + for records in candidate.values { + guard records.count <= LedgerLimits.standard.entries - count else { + throw CoreError.invalidState("private array candidate exceeds limits") + } + count += records.count + } + try LedgerAdmission.check(StateStore.encode(candidate), limits: .standard) + privateNativeArrays = candidate + } + + func emit(_ point: TransactionCheckpoint) throws { try checkpoint(point.name) } + + func persist(_ change: TransactionCheckpoint.Change) throws { + try requireScope() + let bytes = try StateStore.encode(journal) + try LedgerAdmission.check(bytes, limits: .standard) + try directory.replaceFile( + TransactionJournal.fileName, through: TransactionJournal.incompleteFileName, + with: bytes, + afterWrite: { + try emit(.persisted(journal.phase, change, .written)) + }, + afterRename: { + try emit(.persisted(journal.phase, change, .renamed)) + }) + } + + /// Transitions and their durable evidence promises are changed together. The first + /// publishing entry also moves a preparing journal to applying in the same write. + func advance(_ index: Int, to next: TransactionJournal.Progress) throws { + let previous = journal.entries[index].progress + let legal: [TransactionJournal.Progress: Set] = [ + .queued: [.ready], .ready: [.publishing, .cancelled], + .publishing: [.applied, .restoring, .cancelled], .applied: [.restoring], + .restoring: [.restored], .restored: [], .cancelled: [], + ] + guard legal[previous]?.contains(next) == true else { + throw conflict(index, "illegal progress transition: \(previous) -> \(next)") + } + if next == .publishing, journal.phase == .preparing { try changePhase(to: .applying) } + journal.entries[index].progress = next + journal.entries[index].conflict = nil + try persist(.entry(index, next)) + if next == .publishing { outcome?.publicationStarted = true } + try emit(.progress(index, next)) + } + + /// The terminal marker is durable before any disposal. + func finish(_ phase: TransactionJournal.Phase) throws { + try changePhase(to: phase) + try persist(.terminal) + } + + private func changePhase(to next: TransactionJournal.Phase) throws { + let legal: [TransactionJournal.Phase: Set] = [ + .preparing: [.applying, .rolledBack], .applying: [.committed, .rolledBack], + .committed: [], .rolledBack: [], + ] + guard legal[journal.phase]?.contains(next) == true else { + throw CoreError.invalidState( + "illegal transaction phase transition: \(journal.phase) -> \(next)") + } + journal.phase = next + } + + func requireScope() throws { + try TransactionLockContext.validateHeldScope(journal.scope) + try SharedResource.validateAll(resources) + guard try DirectoryHandle(at: directory.url).identity == journal.scope else { + throw CoreError.invalidState("transaction scope identity changed") + } + } + + func requireParent(_ index: Int) throws { + try requireScope() + let root = String(journal.entries[index].path.split(separator: "/").first!) + if let logical = nativeRoots[root] { + guard try DirectoryHandle(at: logical.physicalDirectory()).identity == journal.roots[root] + else { throw conflict(index, "registered root changed after preparation") } + } + try journal.entries[index].security.ancestry?.validate(at: parents[index].url) + guard + try DirectoryHandle(at: parents[index].url).identity == journal.entries[index].parentIdentity + else { + throw conflict(index, "destination parent changed") + } + } + + func conflict(_ index: Int, _ reason: String) -> CoreError { + .invalidState( + "transaction conflict at \(journal.entries[index].path): \(reason); retained container: \(containerLocation(index))" + ) + } + + func containerLocation(_ index: Int) -> String { + let entry = journal.entries[index] + return journal.containerLocation(of: entry) + ?? "" + } + + func recordConflict(_ index: Int, _ error: Error) throws { + journal.entries[index].conflict = .init( + reason: String(describing: error), + locations: [journal.entries[index].path, containerLocation(index)]) + try persist(.conflict(index, journal.entries[index].progress)) + } + + func container(_ index: Int) throws -> DirectoryHandle { + let record = journal.containers[index] + let parent = parents[record.entry] + guard let expected = record.identity, + try parent.info(record.name).map(FileObjectIdentity.init) == expected + else { + throw conflict(record.entry, "private container identity changed or is missing") + } + let handle = try parent.child(record.name) + guard try handle.objectIdentity == expected else { + throw conflict(record.entry, "private container changed while opening") + } + if journal.entries.contains(where: { $0.container == index && $0.security.isPrivate }) { + guard let access = record.access else { + throw conflict(record.entry, "missing private container access") + } + _ = try FileAccessEvidence.requirePrivate(descriptor: handle.descriptor) + try access.validate(descriptor: handle.descriptor) + } + return handle + } + + func validateRecords(store: StateStore) throws { + try requireScope() + try journal.validateCoordination() + if !journal.footprint.isEmpty { + guard let context = TransactionLockContext.current(store) else { + throw CoreError.invalidState("shared transaction is outside its held writer context") + } + try context.validate(journal, scope: directory) + } + let paths = TransactionPaths(store: store) + let keys = try Set(journal.entries.map { try paths.components($0.path).root }) + guard keys == Set(journal.roots.keys), !journal.entries.isEmpty else { + throw CoreError.invalidState("invalid transaction roots") + } + var targets: [URL] = [] + for (index, entry) in journal.entries.enumerated() { + try requireParent(index) + try entry.security.validate(entry: entry) + let target = parents[index].url.appendingPathComponent(entry.name) + if try paths.coordinationRoute(for: entry.path) != nil, entry.coordination == nil { + throw CoreError.invalidState("shared target lacks physical coordination") + } + if let coordination = entry.coordination { + let identity = journal.footprint[coordination] + if let route = NativeTargetRoute.metadataRoute(entry.path) { + guard let resource = resources.first(where: { $0.identity == identity }), + resource.route.basename.utf8.elementsEqual(route.basename.utf8), + try resource.metadata?.objectIdentity == parents[index].objectIdentity, + entry.name == "receipt" + else { throw CoreError.invalidState("invalid coordinated receipt entry") } + } else { + guard try parents[index].objectIdentity == identity.parent, + entry.name.utf8.elementsEqual(identity.basename.utf8) + else { throw CoreError.invalidState("entry contradicts physical coordination") } + } + } + guard + !targets.contains(where: { + PathSafety.isContained(target, in: $0) || PathSafety.isContained($0, in: target) + }), + journal.containers.indices.contains(entry.container) + else { + throw conflict(index, "overlapping destinations or invalid container") + } + targets.append(target) + try validateProgress(index) + try entry.preimage?.validate() + try entry.staged?.validate() + } + for index in journal.containers.indices { try validateContainerRecord(index) } + for (index, entry) in journal.entries.enumerated() { + if let conflict = entry.conflict, + conflict.locations != [entry.path, containerLocation(index)] + { + throw CoreError.invalidState("invalid transaction conflict locations") + } + } + } + + private func validateContainerRecord(_ index: Int) throws { + let record = journal.containers[index] + guard journal.entries.indices.contains(record.entry), + journal.entries[record.entry].container == index, + record.name == TransactionJournal.containerName(id: journal.id, index: index), + record.identity?.isDirectory != false + else { + throw CoreError.invalidState("invalid private transaction container evidence") + } + for entry in journal.entries where entry.container == index { + guard entry.parentIdentity == journal.entries[record.entry].parentIdentity else { + throw CoreError.invalidState("private container belongs to another parent") + } + guard entry.progress == .queued || record.identity != nil else { + throw CoreError.invalidState("sealed operation is missing private container identity") + } + } + let needsPrivate = journal.entries.contains { $0.container == index && $0.security.isPrivate } + guard !needsPrivate || record.identity == nil || record.access?.identity == record.identity + else { + throw CoreError.invalidState("private container is missing access evidence") + } + try record.disposal?.validate() + if let disposal = record.disposal { + guard disposal.identity == record.identity else { + throw CoreError.invalidState("terminal container evidence has another identity") + } + } + if journal.phase == .committed || journal.phase == .rolledBack { + let containsUserData = journal.entries.filter { $0.container == index }.contains { entry in + [.applied, .restored].contains(entry.progress) + && TransactionLayout.expected(entry).contains { !$0.objects.isEmpty } + } + guard !containsUserData || record.disposal != nil else { + throw CoreError.invalidState("terminal container is missing user-object disposal evidence") + } + } + } + + private func validateProgress(_ index: Int) throws { + let entry = journal.entries[index] + let allowed: Set + switch journal.phase { + case .preparing: allowed = [.queued, .ready] + case .applying: allowed = [.ready, .publishing, .applied, .restoring, .restored, .cancelled] + case .committed: allowed = [.applied] + case .rolledBack: allowed = [.queued, .ready, .restored, .cancelled] + } + let requiresStaging = entry.action == .install && entry.progress != .queued + guard allowed.contains(entry.progress), + (entry.staged != nil) == requiresStaging, + !journal.disposing || journal.phase == .committed || journal.phase == .rolledBack + else { + throw conflict(index, "operation progress contradicts its evidence or journal phase") + } + } + + /// Matches the target and every recovery slot against the operation/progress table. + /// Only interrupted publishing or restoring may observe a leased owner-write bit. + func distribution(_ index: Int, permittingDirectoryWrite: Bool = false) throws + -> TransactionLayout + { + let entry = journal.entries[index] + try requireParent(index) + let layouts = TransactionLayout.expected(entry) + if entry.progress == .queued { + if entry.security.preimage == .privateMaterialization, let original = entry.preimage { + try entry.security.validateObject(original, named: entry.name, in: parents[index]) + } + return layouts[0] + } + let container = try self.container(entry.container) + let permitsWrite = permittingDirectoryWrite && entry.progress.permitsDirectoryWrite + var objects: [TransactionSlot: FileSnapshot] = [:] + for slot in TransactionSlot.objectSlots { + if let value = try FileSnapshot.read(slot.name(index), from: container) { + try entry.security.validateObject( + value, named: slot.name(index), in: container, permittingDirectoryWrite: permitsWrite) + objects[slot] = value + } + } + for layout in layouts where Set(layout.objects.keys) == Set(objects.keys) { + guard + layout.objects.allSatisfy({ slot, expected in + guard let actual = objects[slot] else { return false } + return expected.matches(actual, permittingDirectoryWrite: permitsWrite) + }) + else { continue } + if layout.kind == .prepared, let original = entry.preimage { + try entry.security.validateObject( + original, named: entry.name, in: parents[index], permittingDirectoryWrite: permitsWrite) + } + if case .object(let expected) = layout.target, + try parents[index].info(entry.name).map(FileObjectIdentity.init) == expected.identity + { + try entry.security.validateObject( + expected, named: entry.name, in: parents[index], permittingDirectoryWrite: permitsWrite) + } + if try layout.target.matches( + entry.name, from: parents[index], permittingDirectoryWrite: permitsWrite) + { + return layout + } + } + let expected = Set(layouts.flatMap(\.objects.keys)).map { $0.name(index) }.sorted() + throw conflict( + index, + "missing or changed expected target or recovery slot object; expected slots: " + + (expected.isEmpty ? "none" : expected.joined(separator: ", "))) + } +} + +extension TransactionSession { + func createReservations(owner: String) throws { + guard !journal.footprint.isEmpty else { return } + for (index, resource) in resources.enumerated() { + try resource.reserve(journal, owner: owner) { try checkpoint("shared.\(index)." + $0) } + } + journal.reservationsReady = true + try persist(.reservationsReady) + try checkpoint("shared.ready") + } + + func releaseReservations() throws { + for (index, resource) in resources.enumerated() { + try resource.release(journal) { try checkpoint("shared.\(index)." + $0) } + } + } +} diff --git a/Sources/AgentsCore/UpdatePreconditions.swift b/Sources/AgentsCore/UpdatePreconditions.swift index 355c27e..ec0d6a6 100644 --- a/Sources/AgentsCore/UpdatePreconditions.swift +++ b/Sources/AgentsCore/UpdatePreconditions.swift @@ -1,23 +1,12 @@ import Foundation -#if canImport(Darwin) - import Darwin -#else - import Glibc -#endif - /// Captures existing ancestry and the final entry without following that entry's link. /// Missing ancestors may be created, but existing ancestors cannot be exchanged. -package struct PathIdentity { - private struct Entry: Equatable { - let device: UInt64 - let inode: UInt64 - let kind: UInt32 - } +package struct PathIdentity: Sendable { private let url: URL private let physical: URL - private let entry: Entry? - private let ancestors: [(URL, Entry)] + private let entry: FileObjectIdentity? + private let ancestors: [(URL, FileObjectIdentity)] package init(_ url: URL) throws { self.url = url @@ -25,7 +14,7 @@ package struct PathIdentity { url.deletingLastPathComponent().resolvingSymlinksInPath() .appendingPathComponent(url.lastPathComponent).standardizedFileURL entry = try Self.read(physical) - var ancestors: [(URL, Entry)] = [] + var ancestors: [(URL, FileObjectIdentity)] = [] var parent = physical.deletingLastPathComponent() while parent.path != "/" { if let value = try Self.read(parent) { ancestors.append((parent, value)) } @@ -45,36 +34,274 @@ package struct PathIdentity { } } - private static func read(_ url: URL) throws -> Entry? { + private static func read(_ url: URL) throws -> FileObjectIdentity? { var value = stat() guard lstat(url.path, &value) == 0 else { if errno == ENOENT { return nil } throw CoreError.unsafePath("cannot inspect path: \(url.path)") } - return Entry( - device: UInt64(value.st_dev), inode: UInt64(value.st_ino), - kind: UInt32(value.st_mode & 0o170000)) + return FileObjectIdentity(value) } } +/// Prepared evidence checked again before publication, except for targets that the +/// transaction journal verifies itself. +package protocol PreparedEvidence { + func validate(excludingTargets targets: Set) throws +} + /// State bytes and presence belong to the same generation as the rendered targets. -package struct StatePrecondition { - private let store: StateStore - private let files: [(URL, PathIdentity, Data?)] +package struct StatePrecondition: PreparedEvidence { + private let files: [(url: URL, evidence: TargetPrecondition, bytes: Data?)] package init(store: StateStore) throws { - self.store = store files = try [store.declarationURL, store.resolvedURL, store.watchURL].map { - ($0, try PathIdentity($0), try store.existingData($0)) + let input = try TargetPrecondition.readingFile($0) + return ($0, input.evidence, input.bytes) + } + try validate() + } + + package func evidence(for url: URL) throws -> TargetPrecondition { + try file(for: url).evidence + } + + package func bytes(for url: URL) throws -> Data? { + try file(for: url).bytes + } + + private func file(for url: URL) throws -> (url: URL, evidence: TargetPrecondition, bytes: Data?) { + guard let file = files.first(where: { $0.url.path == url.standardizedFileURL.path }) else { + throw CoreError.invalidState("state precondition does not include target") + } + return file + } + + package func validate(excludingTargets targets: Set = []) throws { + for (url, evidence, _) in files where !targets.contains(url.standardizedFileURL.path) { + try evidence.validate() + } + } +} + +/// The generation captured by a plan is also the journal's expected preimage. +package struct TargetPrecondition: Sendable { + package let url: URL + let snapshot: FileSnapshot? + private let identity: PathIdentity + private let maximumFileBytes: Int? + private(set) var access: TargetAccessPrecondition? + package var exists: Bool { snapshot != nil } + + var physicalURL: URL { + url.deletingLastPathComponent().resolvingSymlinksInPath().appendingPathComponent( + url.lastPathComponent + ).standardizedFileURL + } + + package init(_ url: URL) throws { + self.url = url.standardizedFileURL + maximumFileBytes = nil + identity = try PathIdentity(url) + snapshot = try FileSnapshot.read(at: url) + try identity.validate() + } + + private init(url: URL, snapshot: FileSnapshot?, identity: PathIdentity, maximumFileBytes: Int?) { + self.url = url.standardizedFileURL + self.snapshot = snapshot + self.identity = identity + self.maximumFileBytes = maximumFileBytes + } + + /// Rendering and its expected preimage use the same opened-file bytes and inode. + package static func readingFile(_ url: URL, maximumFileBytes: Int? = nil) throws + -> (bytes: Data?, evidence: Self) + { + let identity = try PathIdentity(url) + let capture = try FileSnapshot.captureFile(at: url, maximumFileBytes: maximumFileBytes) + guard capture.snapshot?.isRegular != false else { + throw CoreError.unsafePath("expected regular file: \(url.path)") } + try identity.validate() + return ( + capture.bytes, + Self( + url: url, snapshot: capture.snapshot, identity: identity, maximumFileBytes: maximumFileBytes + ) + ) } + func capturingAccess() throws -> Self { + var result = self + result.access = try TargetAccessPrecondition.capture(at: physicalURL) + try result.validate() + return result + } + + package func sameGeneration(as other: Self) -> Bool { + url.path == other.url.path && snapshot == other.snapshot && access == other.access + } + + func validateIdentity() throws { try identity.validate() } + package func validate() throws { - for (url, identity, bytes) in files { - try identity.validate() - guard try store.existingData(url) == bytes else { - throw CoreError.invalidState("state changed during preparation: \(url.lastPathComponent)") + try validateIdentity() + try access?.validate(at: physicalURL) + try validateSnapshot() + } + + func validateSnapshot() throws { + let 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)") + } + } +} + +struct TargetAccessPrecondition: Equatable, Sendable { + let ancestry: DirectoryAccessEvidence + let target: FileAccessEvidence? + let linkOwner: UInt32? + let linkGroup: UInt32? + + static func capture(at url: URL) throws -> Self { + let parentURL = url.deletingLastPathComponent() + let ancestry = try DirectoryAccessEvidence.capture(at: parentURL) + let complete = ancestry.directories.count == parentURL.standardizedFileURL.pathComponents.count + var info = stat() + let link = lstat(url.path, &info) == 0 && info.st_mode & S_IFMT == S_IFLNK + let target = + try complete && !link + ? DirectoryHandle(at: parentURL).accessEvidence(url.lastPathComponent) : nil + return Self( + ancestry: ancestry, target: target, linkOwner: link ? info.st_uid : nil, + linkGroup: link ? info.st_gid : nil) + } + + func validate(at url: URL) throws { + guard try Self.capture(at: url) == self else { + throw CoreError.invalidState("target or ancestry access changed during preparation") + } + } +} + +/// An existing selected project, captured without creating lock or state ancestry. +/// Passing this observation never grants authority outside registered transaction targets. +public struct ExistingProjectRoot: Sendable { + public let directory: URL + private let identity: FileObjectIdentity + + fileprivate init(directory: URL) throws { + self.directory = directory.standardizedFileURL + identity = try DirectoryHandle(at: directory.resolvingSymlinksInPath()).objectIdentity + } + + func validate() throws { + guard try DirectoryHandle(at: directory.resolvingSymlinksInPath()).objectIdentity == identity + else { throw CoreError.invalidState("selected project root changed") } + } + + package func validateForLifecycle() throws { try validate() } + + /// Returns nil for a separately registered external loader; selected-root descendants + /// are opened from the pinned descriptor and never recreate the selected pathname. + func descendant( + at url: URL, from root: DirectoryHandle, create: Bool, + checkpoint: (DirectoryHandle.AncestryStep) throws -> Void = { _ in } + ) throws -> DirectoryHandle? { + try validate() + let prefix = Array(root.url.path.utf8) + let bytes = Array(url.path.utf8) + guard bytes == prefix || bytes.starts(with: prefix + [47]) else { return nil } + let relative = String( + decoding: bytes.dropFirst(min(prefix.count + 1, bytes.count)), as: UTF8.self) + let parts = relative.split(separator: "/").map(String.init) + var current = root + for (index, name) in parts.enumerated() { + if create { + let depth = parts.count - index - 1 + if try current.info(name) == nil { + try current.makeDirectory(name) { try checkpoint(.created(depth: depth)) } + try checkpoint(.synced(depth: depth)) + } else { + try current.sync() + } } + current = try current.child(name) + try validate() + } + return current + } + + func open(for store: StateStore) throws -> DirectoryHandle { + guard store.scope == .project, + directory.path.utf8.elementsEqual( + store.environment.projectDirectory.standardizedFileURL.path.utf8) + else { throw CoreError.invalidState("project observation belongs to another scope") } + try validate() + let opened = try DirectoryHandle(at: directory.resolvingSymlinksInPath()) + guard try opened.objectIdentity == identity else { + throw CoreError.invalidState("selected project root changed during admission") } + return opened + } +} + +extension StateStore { + public func captureExistingProjectRoot() throws -> ExistingProjectRoot { + guard scope == .project else { + throw CoreError.invalidState("existing project root requires project scope") + } + return try ExistingProjectRoot(directory: environment.projectDirectory) + } +} + +/// Exact, absent authoring file owned by one explicit local skill initialization. +package struct SkillInitializationTarget { + package let file: URL + let scope: URL + let descendants: [String] + let evidence: TargetPrecondition + + fileprivate init(store: StateStore, name: String?, selectedDirectory: String? = nil) throws { + guard store.scope == .project, + name == nil || (name == PathSafety.sanitizeName(name!) && !name!.contains("/")), + selectedDirectory.map({ + !$0.isEmpty && $0 != "." && $0 != ".." && !$0.contains("/") + && !$0.contains("\\") && !$0.contains("\0") + }) ?? true + else { throw CoreError.unsafePath("invalid local skill initialization target") } + scope = store.directory + descendants = + (selectedDirectory.map { [$0] } ?? []) + + (name.map { [$0] } ?? []) + ["SKILL.md"] + file = descendants.reduce(store.environment.projectDirectory.resolvingSymlinksInPath()) { + $0.appendingPathComponent($1) + } + evidence = try TargetPrecondition(file) + guard evidence.snapshot == nil else { + throw CoreError.invalidSkill("skill file already exists") + } + } +} + +extension StateStore { + package func skillInitializationTarget(named name: String? = nil) throws + -> SkillInitializationTarget + { + try SkillInitializationTarget(store: self, name: name) + } + + /// Preserves an explicitly selected directory spelling below the observed existing parent. + package func skillInitializationTarget( + inChildDirectory directory: String, named name: String? = nil + ) throws + -> SkillInitializationTarget + { + try SkillInitializationTarget(store: self, name: name, selectedDirectory: directory) } } diff --git a/Sources/AgentsCore/VCSArchiveRequest.swift b/Sources/AgentsCore/VCSArchiveRequest.swift new file mode 100644 index 0000000..89f7462 --- /dev/null +++ b/Sources/AgentsCore/VCSArchiveRequest.swift @@ -0,0 +1,208 @@ +import Foundation + +/// The exact ref semantics used by an archive endpoint. +public enum VCSArchiveRef: Hashable, Codable, Sendable { + case commit(String) + case tag(String) + case branch(String) + + public static func == (lhs: Self, rhs: Self) -> Bool { + lhs.qualified.utf8.elementsEqual(rhs.qualified.utf8) + } + + public func hash(into hasher: inout Hasher) { hasher.combine(Data(qualified.utf8)) } + + package var name: String { + switch self { + case .commit(let value), .tag(let value), .branch(let value): value + } + } + + package var qualified: String { + switch self { + case .commit(let value): value + case .tag(let value): "refs/tags/" + value + case .branch(let value): "refs/heads/" + value + } + } + + package init(requirement: SourceRequirement?) throws { + switch requirement { + case .branch(let name): self = .branch(name) + case .revision(let value) where SourceCache.isObjectID(value): self = .commit(value) + case .revision(let value) where value.hasPrefix("refs/tags/"): + self = .tag(String(value.dropFirst("refs/tags/".count))) + case .revision(let value) where value.hasPrefix("refs/heads/"): + self = .branch(String(value.dropFirst("refs/heads/".count))) + default: throw SourceAccessError.discoveryUnavailable + } + try validate() + } + + func validate() throws { + switch self { + case .commit(let id): + guard SourceCache.isObjectID(id) else { throw SourceAccessError.invalidRepository } + case .tag(let value), .branch(let value): + guard !value.isEmpty, value.utf8.count <= 1024, value != "@", !value.contains(".."), + !value.contains("@{"), + !value.hasSuffix("."), !value.hasPrefix("-"), + value.split(separator: "/", omittingEmptySubsequences: false).allSatisfy({ + SourceURL.safeSegment(String($0), literalRef: true) && !$0.hasPrefix(".") + && !$0.hasSuffix(".lock") + && !$0.contains(where: { " ~^:?*[".contains($0) }) + }) + else { throw SourceAccessError.invalidRepository } + } + } +} + +struct SourceRepository { + let url: String + let scheme: String + let authority: SourceAuthority + let segments: [String] + let gitPath: String + + init(_ url: String) throws { + self.url = url + let locator: String + if !url.contains("://"), let colon = url.firstIndex(of: ":") { + let path = url[url.index(after: colon)...] + locator = "ssh://" + url[..= 2 else { throw SourceAccessError.invalidRepository } + if case .commit = ref { + } else if !mirror.supportsQualifiedGitLabRefs { + throw SourceAccessError.discoveryUnavailable + } + suffix = [ + "api", "v4", "projects", SourceURL.encode(repository.segments.joined(separator: "/")), + "repository", "archive", + ] + components.percentEncodedQuery = "sha=" + SourceURL.encode(ref.qualified) + case .artifactory: + throw SourceAccessError.unsupportedMirror + } + components.percentEncodedPath = "/" + (prefix + suffix).joined(separator: "/") + ".zip" + guard let url = components.url else { throw SourceAccessError.invalidConfiguration } + self.url = url + self.ref = ref + } +} + +/// Admit the logical producer first, then its effective destination. Credential selection stays +/// outside the egress decision. +enum SourceRoute { + case local + case http(URL) + case git(SourceRepository?) + case archive(SourceRepository, SourceArchiveMirror) + + init( + _ source: SourceDeclaration, environment: RuntimeEnvironment, policy: EffectiveSourcePolicy + ) throws { + try policy.require(source, environment: environment) + let access = try environment.resolvedSourceAccess() + switch source.kind { + case .local: + self = .local + case .wellKnown: + guard let url = URL(string: source.location) else { + throw SourceAccessError.invalidRepository + } + try access.requireDirectHTTP(url, policy: policy) + self = .http(url) + case .git: + let repository = try? SourceRepository(source.gitURL) + let mirrors = access.mirrors.filter { $0.source == repository?.authority } + guard mirrors.count <= 1 else { throw SourceAccessError.ambiguousRoute } + if let mirror = mirrors.first, let repository { + guard mirror.flavor != .artifactory else { throw SourceAccessError.unsupportedMirror } + try policy.require(.http(mirror.base.absoluteString)) + self = .archive(repository, mirror) + } else { + guard access.egress == .directAllowed else { throw SourceAccessError.egressDenied } + if repository == nil, !access.credentials.isEmpty || !access.mirrors.isEmpty { + throw SourceAccessError.invalidRepository + } + self = .git(repository) + } + } + } + + func requireGitObjects() throws { + if case .archive = self { throw SourceAccessError.historyUnavailable } + } + + func credential(_ access: SourceAccessConfiguration) throws -> SourceCredentialBinding? { + try access.requireCurrentSettings() + let route: SourceCredentialBinding.Route + let authority: SourceAuthority + let path: String + switch self { + case .git(let repository?) where repository.scheme == "https": + route = .direct + authority = repository.authority + path = "/" + repository.segments.joined(separator: "/") + case .archive(let repository, let mirror): + route = .mirror + authority = mirror.authority + path = "/" + (mirror.baseSegments + repository.segments).joined(separator: "/") + default: + return nil + } + return try Self.binding(access, route: route, authority: authority, path: path) + } + + static func binding( + _ access: SourceAccessConfiguration, route: SourceCredentialBinding.Route, + authority: SourceAuthority, path: String? + ) throws -> SourceCredentialBinding? { + let matches = access.credentials.filter { + guard $0.route == route, $0.authority == authority else { return false } + guard let bindingPath = $0.path else { return true } + return path.map { bindingPath.utf8.elementsEqual($0.utf8) } ?? false + } + let exact = matches.filter { $0.path != nil } + let eligible = exact.isEmpty ? matches : exact + guard eligible.count <= 1 else { throw SourceAccessError.ambiguousCredential } + return eligible.first + } +} diff --git a/Sources/AgentsCore/VerifiedVCSArchive.swift b/Sources/AgentsCore/VerifiedVCSArchive.swift new file mode 100644 index 0000000..51710e4 --- /dev/null +++ b/Sources/AgentsCore/VerifiedVCSArchive.swift @@ -0,0 +1,248 @@ +import CPlatform +import Foundation + +/// The central directory and its local headers must agree before any member can be used. +struct VerifiedVCSArchive { + static let compressedLimit = 64 * 1024 * 1024 + static let expandedLimit = 128 * 1024 * 1024 + static let memberLimit = 10_000 + + let treeDigest: String + let byteDigest: String + let entries: [PrivateTreeEntry] + + init(_ bytes: Data) throws { + guard bytes.count <= Self.compressedLimit, bytes.count >= 22 else { + throw SourceAccessError.invalidArchive + } + let members = try bytes.withUnsafeBytes { try Self.members($0) } + entries = members.values.sorted { + $0.relativePath.utf8.lexicographicallyPrecedes($1.relativePath.utf8) + } + treeDigest = + "sha256:" + + FileHash.hashRecords( + entries.map { entry in + switch entry.content { + case .directory: ("directory\0" + entry.relativePath, Data()) + case .file(let content, let executable): + ((executable ? "executable\0" : "file\0") + entry.relativePath, content) + case .symlink(let target): ("link\0" + entry.relativePath, Data(target.utf8)) + case .boundFile: preconditionFailure("archive entries contain only verified bytes") + } + }) + byteDigest = "sha256:" + FileHash.sha256Hex(data: bytes) + } + + func extract( + named name: String, in parent: DirectoryHandle, environment: RuntimeEnvironment + ) throws -> URL { + let tree = try PrivateTree( + entries: entries, provider: NoArchiveBindings(), environment: environment) + var bytes = 0 + try tree.construct( + named: name, in: parent, bytes: &bytes, admit: { _, _, _ in }, validate: {}) + return parent.url.appendingPathComponent(name, isDirectory: true) + } + + func matches(_ root: URL) throws -> Bool { + let parent = try DirectoryHandle(at: root.deletingLastPathComponent()) + guard let snapshot = try FileSnapshot.read(root.lastPathComponent, from: parent) else { + return false + } + do { + _ = try parent.requirePrivateAccess(root.lastPathComponent) + _ = try TreeMemberAccess.capture( + root.lastPathComponent, in: parent, snapshot: snapshot, requirePrivate: true) + } catch { + return false + } + let directory = try parent.child(root.lastPathComponent) + for entry in entries { + let path = entry.relativePath.split(separator: "/").map(String.init) + var container = directory + for name in path.dropLast() { + guard let child = try? container.child(name) else { return false } + container = child + } + let name = path.last! + guard let info = try container.info(name) else { return false } + switch entry.content { + case .directory: + guard info.st_mode & S_IFMT == S_IFDIR, info.st_mode & 0o7777 == 0o700 else { return false } + case .file(let data, let executable): + guard info.st_mode & S_IFMT == S_IFREG, + info.st_mode & 0o7777 == (executable ? 0o700 : 0o600), + info.st_size == data.count, + try container.read(name, matching: info, maximumBytes: data.count) == data + else { return false } + case .symlink(let target): + guard info.st_mode & S_IFMT == S_IFLNK, + try container.readLink(name).utf8.elementsEqual(target.utf8) + else { return false } + case .boundFile: + return false + } + } + var count = 0 + var pending = snapshot.children ?? [] + while let entry = pending.popLast() { + count += 1 + if count > entries.count { return false } + pending += entry.snapshot.children ?? [] + } + return count == entries.count + } + + private static func members(_ buffer: UnsafeRawBufferPointer) throws -> [Data: PrivateTreeEntry] { + func u16(_ at: Int) -> Int { Int(buffer[at]) | Int(buffer[at + 1]) << 8 } + func u32(_ at: Int) -> Int { u16(at) | u16(at + 2) << 16 } + func name(_ offset: Int, _ count: Int) -> String? { + String(bytes: buffer[offset..<(offset + count)], encoding: .utf8) + } + guard + let end = (max(0, buffer.count - 65_557)...(buffer.count - 22)).reversed().first(where: { + u32($0) == 0x0605_4b50 && $0 + 22 + u16($0 + 20) == buffer.count + }) + else { throw SourceAccessError.invalidArchive } + let count = u16(end + 10) + let central = u32(end + 16) + guard u16(end + 4) == 0, u16(end + 6) == 0, u16(end + 8) == count, + count > 0, count <= Self.memberLimit, central + u32(end + 12) == end + else { throw SourceAccessError.invalidArchive } + var cursor = central + var total = 0 + var records: [Range] = [] + var root: Data? + var explicit = Set() + var spellings: [String: Data] = [:] + var result: [Data: PrivateTreeEntry] = [:] + + func put(_ path: String, _ content: PrivateTreeEntry.Content, explicit isExplicit: Bool) throws + { + let key = Data(path.utf8) + let folded = path.precomposedStringWithCanonicalMapping.lowercased() + guard spellings[folded] == nil || spellings[folded] == key, + !isExplicit || explicit.insert(key).inserted + else { throw SourceAccessError.invalidArchive } + spellings[folded] = key + if let existing = result[key] { + guard case .directory = existing.content, case .directory = content else { + throw SourceAccessError.invalidArchive + } + } + guard result.count < Self.memberLimit || result[key] != nil else { + throw SourceAccessError.invalidArchive + } + result[key] = PrivateTreeEntry(path, content: content) + } + + for _ in 0.. 0, length <= 4096, let member = name(start, length), + local + 30 <= central, u32(local) == 0x0403_4b50, u16(local + 6) == flags, + u16(local + 8) == method, u16(local + 26) == length + else { throw SourceAccessError.invalidArchive } + cursor = next + total += expanded + let dataStart = local + 30 + length + u16(local + 28) + var dataEnd = dataStart + compressed + guard dataEnd <= central, + buffer[(local + 30)..<(local + 30 + length)].elementsEqual(buffer[start..<(start + length)]) + else { throw SourceAccessError.invalidArchive } + if flags & 8 != 0 { + if dataEnd + 4 <= central, u32(dataEnd) == 0x0807_4b50 { dataEnd += 4 } + guard dataEnd + 12 <= central, + u32(dataEnd) == crc, u32(dataEnd + 4) == compressed, u32(dataEnd + 8) == expanded + else { throw SourceAccessError.invalidArchive } + dataEnd += 12 + } else { + guard u32(local + 14) == crc, u32(local + 18) == compressed, u32(local + 22) == expanded + else { throw SourceAccessError.invalidArchive } + } + records.append(local..= 32 && $0.value != 127 }) + }) + else { throw SourceAccessError.invalidArchive } + let enclosing = Data(parts[0].utf8) + guard root == nil || root == enclosing else { throw SourceAccessError.invalidArchive } + root = enclosing + let mode = external >> 16 + let type = mode & 0o170000 + guard mode & 0o7000 == 0, + directory + ? (type == 0 || type == 0o040000) && expanded == 0 + : (type == 0 || type == 0o100000 || type == 0o120000) + else { throw SourceAccessError.invalidArchive } + var content = Data(count: expanded) + guard + content.withUnsafeMutableBytes({ (output: UnsafeMutableRawBufferPointer) in + platform_zip_member( + buffer.baseAddress!.advanced(by: dataStart).assumingMemoryBound(to: UInt8.self), + compressed, UInt32(method), output.baseAddress?.assumingMemoryBound(to: UInt8.self), + expanded, UInt32(crc)) + }) + else { throw SourceAccessError.invalidArchive } + if parts.count == 1 { + guard directory, explicit.insert(Data()).inserted else { + throw SourceAccessError.invalidArchive + } + continue + } + let relative = parts.dropFirst() + for depth in 1.. Data { + throw SourceAccessError.invalidArchive + } +} diff --git a/Sources/AgentsCore/WatchModels.swift b/Sources/AgentsCore/WatchModels.swift index de322ea..cce3b79 100644 --- a/Sources/AgentsCore/WatchModels.swift +++ b/Sources/AgentsCore/WatchModels.swift @@ -70,4 +70,20 @@ public struct WatchStatus: Equatable, Sendable { /// Commits reachable from the current head but not from the seen revision; nil for indexes. public let commitCount: Int? public var changes: [WatchItemChange] + /// Durable scope files and local source roots; absent state leaves remain in the footprint. + public var readLocations: [URL] { acknowledgment.readLocations } + package let acknowledgment: WatchMutationPreview +} + +/// Read-only watch results retain their input locations even when there are no subscriptions. +public struct WatchInspection: Equatable, Sendable { + public let statuses: [WatchStatus] + public let readLocations: [URL] +} + +/// A subscription after a watch change. `seen` is the acknowledged baseline, or nil after removal. +public struct WatchChange: Equatable, Sendable { + public let alias: String + public let sourceID: String + public let seen: WatchSeen? } diff --git a/Sources/AgentsCore/WatchOperations.swift b/Sources/AgentsCore/WatchOperations.swift index 100651c..fd0de04 100644 --- a/Sources/AgentsCore/WatchOperations.swift +++ b/Sources/AgentsCore/WatchOperations.swift @@ -1,65 +1,72 @@ import Foundation -/// Scope-bound subscriptions. Discovery and artifact loading are supplied by the owning module. +/// Scope-bound subscriptions. Discovery and artifact loading are supplied by the owning module, +/// and declaration reading and planning by the declaration format's module. public struct WatchOperations: Sendable { private let discoverSkills: @Sendable (URL) throws -> [WatchSkill] private let fetchArtifacts: @Sendable (String) throws -> [WatchArtifact] + private let declarations: DeclarationAccess + private let sourcePolicy: @Sendable (StateStore) throws -> EffectiveSourcePolicy + private let fetchGuardedArtifacts: + (@Sendable (String, EffectiveSourcePolicy) throws -> [WatchArtifact])? private let checkpoint: @Sendable (String) throws -> Void - public init( - discoverSkills: @escaping @Sendable (URL) throws -> [WatchSkill], - fetchArtifacts: @escaping @Sendable (String) throws -> [WatchArtifact] - ) { - self.init(discoverSkills: discoverSkills, fetchArtifacts: fetchArtifacts, checkpoint: { _ in }) - } - package init( discoverSkills: @escaping @Sendable (URL) throws -> [WatchSkill], fetchArtifacts: @escaping @Sendable (String) throws -> [WatchArtifact], - checkpoint: @escaping @Sendable (String) throws -> Void + declarations: DeclarationAccess, + sourcePolicy: @escaping @Sendable (StateStore) throws -> EffectiveSourcePolicy = { _ in .init() + }, + fetchGuardedArtifacts: (@Sendable (String, EffectiveSourcePolicy) throws -> [WatchArtifact])? = + nil, + checkpoint: @escaping @Sendable (String) throws -> Void = { _ in } ) { self.discoverSkills = discoverSkills self.fetchArtifacts = fetchArtifacts + self.declarations = declarations + self.sourcePolicy = sourcePolicy + self.fetchGuardedArtifacts = fetchGuardedArtifacts self.checkpoint = checkpoint } /// Declares a source when needed and acknowledges its current content without installing it. + /// The declaration change is planned before Git or an index is contacted. @discardableResult public func add( _ source: String, alias: String? = nil, requirement: SourceRequirement? = nil, path: String? = nil, scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment() - ) throws -> WatchSeen { + ) throws -> WatchChange { + try add( + source, alias: alias, requirement: requirement, path: path, scope: scope, + environment: environment, expected: nil, outcome: TransactionOutcome()) + } + + private func add( + _ source: String, alias: String?, requirement: SourceRequirement?, path: String?, + scope: InstallScope, environment: RuntimeEnvironment, expected: WatchMutationPreview?, + outcome: TransactionOutcome + ) throws -> WatchChange { let store = StateStore(scope: scope, environment: environment) - return try store.withLock(checkpoint: checkpoint) { - var declaration = try store.readDeclaration() - let lock = try store.readResolved() - var watch = try store.readWatch() - let argument = try SourceArgument(source) - guard argument.name == nil else { - throw CoreError.invalidSource("@skill: selects skills; watch subscribes to whole sources") - } - let selection = try argument.selection( - in: declaration, requirement: requirement, path: path, environment: environment) - let parsed = selection.source - let id = try parsed.identity(environment: environment) - let existing = try declaration.sources.keys.sorted().first { - try declaration.sources[$0]?.identity(environment: environment) == id - } - let name = alias ?? existing ?? declaration.derivedAlias(for: parsed.location) - if let current = declaration.sources[name], - try current.identity(environment: environment) != id - { - throw CoreError.invalidSource("source alias already refers to another source: \(name)") + return try store.withLock(checkpoint: checkpoint, outcome: outcome) { + let baseline = try StatePrecondition(store: store) + let previous = try declarations.read(store, baseline) + let lock = try store.readLedger(prepared: baseline) + var watch = try store.readWatch(prepared: baseline) + let planned = try planAdd( + source, alias: alias, requirement: requirement, path: path, + declaration: previous, store: store, baseline: baseline) + let (name, id, declared, change) = (planned.alias, planned.id, planned.source, planned.change) + if let expected { + try requireFingerprint( + expected, baseline: baseline, change: change, seen: expected.seen, store: store, + alias: name, sourceID: id, removing: false) } - let declared = selection.applied(to: existing.flatMap { declaration.sources[$0] } ?? parsed) - declaration.sources[name] = declared - declaration.watch = Array(Set((declaration.watch ?? []) + [name])).sorted() - try declaration.validate(environment: environment) - let current = try acknowledge(declared, revision: nil, store: store) + let current = try acknowledge(declared, revision: nil, expected: expected?.seen, store: store) watch.sources[id] = WatchSourceState(seen: current) - try commit(declaration: declaration, watch: watch, lock: lock, store: store) - return current + try commit( + change, watch: watch, lock: lock, store: store, baseline: baseline, outcome: outcome) + return WatchChange(alias: name, sourceID: id, seen: current) } } @@ -67,14 +74,28 @@ public struct WatchOperations: Sendable { public func status( scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment() ) throws -> [WatchStatus] { + try inspectStatus(scope: scope, environment: environment).statuses + } + + /// Captures statuses and durable inputs, including absent state files in an empty scope. + public func inspectStatus( + scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> WatchInspection { let store = StateStore(scope: scope, environment: environment) return try store.withReadLock { - let declaration = try store.readDeclaration() - _ = try store.readResolved() - let watch = try store.readWatch() - return try (declaration.watch ?? []).sorted().map { alias in - try inspect(alias: alias, declaration: declaration, watch: watch, store: store) + let baseline = try StatePrecondition(store: store) + let declaration = try declarations.read(store, baseline) + _ = try store.readLedger(prepared: baseline) + let watch = try store.readWatch(prepared: baseline) + let statuses = try (declaration.watch ?? []).sorted().map { alias in + try inspect( + alias: alias, declaration: declaration, watch: watch, store: store, baseline: baseline) } + try baseline.validate() + return WatchInspection( + statuses: statuses, + readLocations: durableReadLocations( + store, sources: (declaration.watch ?? []).compactMap { declaration.sources[$0] })) } } @@ -85,54 +106,320 @@ public struct WatchOperations: Sendable { ) throws -> WatchStatus { let store = StateStore(scope: scope, environment: environment) return try store.withReadLock { - let declaration = try store.readDeclaration() - _ = try store.readResolved() - let watch = try store.readWatch() + let baseline = try StatePrecondition(store: store) + let declaration = try declarations.read(store, baseline) + _ = try store.readLedger(prepared: baseline) + let watch = try store.readWatch(prepared: baseline) let alias = try subscription(source, declaration: declaration, environment: environment) - var result = try inspect(alias: alias, declaration: declaration, watch: watch, store: store) + var result = try inspect( + alias: alias, declaration: declaration, watch: watch, store: store, baseline: baseline) result.changes = result.changes.filter { (name == nil || $0.name == name) && (kind == nil || $0.kind == kind) } + try baseline.validate() return result } } @discardableResult public func seen( - _ source: String, revision: String? = nil, scope: InstallScope = .project, + _ source: String, revision: String? = nil, ifCurrentIs expected: WatchSeen? = nil, + ifSourceIs expectedSource: String? = nil, + scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment() - ) throws -> WatchSeen { + ) throws -> WatchChange { + try seen( + source, revision: revision, ifCurrentIs: expected, ifSourceIs: expectedSource, + scope: scope, environment: environment, preview: nil, outcome: TransactionOutcome()) + } + + private func seen( + _ source: String, revision: String? = nil, ifCurrentIs expected: WatchSeen?, + ifSourceIs expectedSource: String?, scope: InstallScope, environment: RuntimeEnvironment, + preview: WatchMutationPreview?, outcome: TransactionOutcome + ) throws -> WatchChange { let store = StateStore(scope: scope, environment: environment) - return try store.withLock(checkpoint: checkpoint) { - let declaration = try store.readDeclaration() - let lock = try store.readResolved() - var watch = try store.readWatch() + return try store.withLock(checkpoint: checkpoint, outcome: outcome) { + let baseline = try StatePrecondition(store: store) + let declaration = try declarations.read(store, baseline) + let lock = try store.readLedger(prepared: baseline) + var watch = try store.readWatch(prepared: baseline) let alias = try subscription(source, declaration: declaration, environment: environment) let declared = declaration.sources[alias]! let id = try declared.identity(environment: environment) - let current = try acknowledge(declared, revision: revision, store: store) + guard expectedSource == nil || expectedSource == id else { + throw CoreError.invalidState("watch source changed; refresh before acknowledging") + } + if let preview { + try requireFingerprint( + preview, baseline: baseline, change: nil, seen: expected, store: store, + alias: alias, sourceID: id, removing: false) + } + let current = try acknowledge(declared, revision: revision, expected: expected, store: store) + guard expected == nil || expected == current else { + throw CoreError.invalidState("watch content changed; refresh before acknowledging") + } watch.sources[id] = WatchSourceState(seen: current) - try commit(declaration: nil, watch: watch, lock: lock, store: store) - return current + try commit( + nil, watch: watch, lock: lock, store: store, baseline: baseline, outcome: outcome) + return WatchChange(alias: alias, sourceID: id, seen: current) } } + /// Acknowledges exactly the displayed source/content pair, revalidated under the writer lock. + @discardableResult + public func seen( + _ status: WatchStatus, scope: InstallScope = .project, + environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> WatchChange { + guard status.acknowledgment.matches(scope: scope, environment: environment) else { + throw CoreError.invalidState( + "watch scope or environment changed; refresh before acknowledging") + } + return try apply(previewSeen(status)) + } + + /// Confirms the displayed status in its captured scope and environment without acquiring resources. + public func previewSeen(_ status: WatchStatus) -> WatchMutationPreview { + status.acknowledgment + } + /// Removes only the subscription and baseline. Source declarations and installations remain. + @discardableResult public func remove( _ source: String, scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment() - ) throws { + ) throws -> WatchChange { + try remove( + source, scope: scope, environment: environment, expected: nil, outcome: TransactionOutcome()) + } + + private func remove( + _ source: String, scope: InstallScope, environment: RuntimeEnvironment, + expected: WatchMutationPreview?, outcome: TransactionOutcome + ) throws -> WatchChange { let store = StateStore(scope: scope, environment: environment) - try store.withLock(checkpoint: checkpoint) { - var declaration = try store.readDeclaration() - let lock = try store.readResolved() - var watch = try store.readWatch() + return try store.withLock(checkpoint: checkpoint, outcome: outcome) { + let baseline = try StatePrecondition(store: store) + let previous = try declarations.read(store, baseline) + var declaration = previous + let lock = try store.readLedger(prepared: baseline) + var watch = try store.readWatch(prepared: baseline) let alias = try subscription(source, declaration: declaration, environment: environment) let id = try declaration.sources[alias]!.identity(environment: environment) declaration.watch?.removeAll { $0 == alias } watch.sources.removeValue(forKey: id) - try commit(declaration: declaration, watch: watch, lock: lock, store: store) + let change = try declarations.plan(store, previous, declaration, baseline) + if let expected { + try requireFingerprint( + expected, baseline: baseline, change: change, seen: nil, store: store, alias: alias, + sourceID: id, removing: true) + } + try commit( + change, watch: watch, lock: lock, store: store, baseline: baseline, outcome: outcome) + return WatchChange(alias: alias, sourceID: id, seen: nil) + } + } + + /// Resolves acknowledgment in disposable storage without retaining refs or recovering the scope. + public func previewAdd( + _ source: String, alias: String? = nil, requirement: SourceRequirement? = nil, + path: String? = nil, scope: InstallScope = .project, + environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> WatchMutationPreview { + let store = StateStore(scope: scope, environment: environment) + return try store.withReadLock { + let baseline = try StatePrecondition(store: store) + let previous = try declarations.read(store, baseline) + _ = try store.readLedger(prepared: baseline) + _ = try store.readWatch(prepared: baseline) + let planned = try planAdd( + source, alias: alias, requirement: requirement, path: path, + declaration: previous, store: store, baseline: baseline) + let seen = try observe(planned.source, store: store) + let fingerprint = try mutationFingerprint( + baseline: baseline, change: planned.change, seen: seen, store: store, alias: planned.alias, + sourceID: planned.id, removing: false) + try baseline.validate() + return WatchMutationPreview( + action: .add(source, alias, requirement, path), store: store, + alias: planned.alias, sourceID: planned.id, seen: seen, displayedFingerprint: fingerprint, + readLocations: mutationReadLocations(store, source: planned.source)) + } + } + + public func previewRemove( + _ source: String, scope: InstallScope = .project, + environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> WatchMutationPreview { + let store = StateStore(scope: scope, environment: environment) + return try store.withReadLock { + let baseline = try StatePrecondition(store: store) + let previous = try declarations.read(store, baseline) + var declaration = previous + _ = try store.readLedger(prepared: baseline) + _ = try store.readWatch(prepared: baseline) + let alias = try subscription(source, declaration: declaration, environment: environment) + let selected = declaration.sources[alias]! + let id = try selected.identity(environment: environment) + declaration.watch?.removeAll { $0 == alias } + let change = try declarations.plan(store, previous, declaration, baseline) + let fingerprint = try mutationFingerprint( + baseline: baseline, change: change, seen: nil, store: store, alias: alias, sourceID: id, + removing: true) + try baseline.validate() + return WatchMutationPreview( + action: .remove(source), store: store, + alias: alias, sourceID: id, seen: nil, displayedFingerprint: fingerprint, + readLocations: mutationReadLocations(store, source: selected)) + } + } + + /// Revalidates exactly the displayed subscription mutation inside its sole scope writer. + @discardableResult + public func apply(_ preview: WatchMutationPreview) throws -> WatchChange { + try apply(preview, outcome: TransactionOutcome()) + } + + package func apply(_ preview: WatchMutationPreview, outcome: TransactionOutcome) throws + -> WatchChange + { + switch preview.action { + case .add(let source, let alias, let requirement, let path): + return try add( + source, alias: alias, requirement: requirement, path: path, + scope: preview.store.scope, environment: preview.store.environment, expected: preview, + outcome: outcome) + case .seen(let source): + return try seen( + source, ifCurrentIs: preview.seen, ifSourceIs: preview.sourceID, + scope: preview.store.scope, environment: preview.store.environment, + preview: preview, outcome: outcome) + case .remove(let source): + return try remove( + source, scope: preview.store.scope, environment: preview.store.environment, + expected: preview, outcome: outcome) + } + } + + private func mutationReadLocations(_ store: StateStore, source: SourceDeclaration) -> [URL] { + durableReadLocations(store, sources: [source]) + } + + private func durableReadLocations(_ store: StateStore, sources: [SourceDeclaration]) -> [URL] { + let paths = + [store.declarationURL, store.resolvedURL, store.watchURL] + + sources.filter { $0.kind == .local }.map { $0.localURL(environment: store.environment) } + return Array(Set(paths.map(\.standardizedFileURL))).sorted { $0.path < $1.path } + } + + private func mutationFingerprint( + baseline: StatePrecondition, change: DeclarationChange?, + seen: WatchSeen?, store: StateStore, alias: String, sourceID: String, removing: Bool + ) throws -> String { + struct Evidence: Encodable { + let scope: InstallScope + let projectDirectory: String + let homeDirectory: String + let alias: String + let sourceID: String + let removing: Bool + let state: [String?] + let declaration: String? + let seen: WatchSeen? + } + return try ResolvedLedgerCodec.digest( + Evidence( + scope: store.scope, projectDirectory: store.environment.projectDirectory.path, + homeDirectory: store.environment.homeDirectory.path, + alias: alias, sourceID: sourceID, removing: removing, + state: [store.declarationURL, store.resolvedURL, store.watchURL].map { + try baseline.bytes(for: $0).map { FileHash.sha256Hex(data: $0) } + }, declaration: change.map { FileHash.sha256Hex(data: $0.bytes) }, seen: seen)) + } + + private func requireFingerprint( + _ preview: WatchMutationPreview, baseline: StatePrecondition, + change: DeclarationChange?, seen: WatchSeen?, store: StateStore, alias: String, + sourceID: String, removing: Bool + ) throws { + guard + try mutationFingerprint( + baseline: baseline, change: change, seen: seen, store: store, alias: alias, + sourceID: sourceID, removing: removing) == preview.displayedFingerprint + else { + throw CoreError.invalidState("subscription changed; refresh before confirming") + } + } + + private func observe(_ source: SourceDeclaration, store: StateStore) throws -> WatchSeen { + if source.kind == .wellKnown { + return .artifacts( + Dictionary( + uniqueKeysWithValues: try artifacts(source, store: store).map { + ($0.name, $0.artifact.digest) + })) + } + let temporary = FileManager.default.temporaryDirectory.appendingPathComponent( + "agents-watch-preview-" + UUID().uuidString) + try FileSystem.createDirectory(at: temporary) + defer { try? FileManager.default.removeItem(at: temporary) } + var source = source + if source.kind == .local { + source.location = source.localURL(environment: store.environment).path } + var environment = store.environment + environment.projectDirectory = temporary + return .revision( + try SourceCache( + store: StateStore(scope: .project, environment: environment), + sourcePolicy: sourcePolicy(store) + ).watchRevision(source)) + } + + private struct AddPlan { + let alias: String + let id: String + let source: SourceDeclaration + let change: DeclarationChange? + } + + private func planAdd( + _ source: String, alias: String?, requirement: SourceRequirement?, path: String?, + declaration previous: Declaration, store: StateStore, baseline: StatePrecondition + ) throws -> AddPlan { + let environment = store.environment + var declaration = previous + var argument = try SourceArgument(source) + guard argument.name == nil else { + throw CoreError.invalidSource("@skill: selects skills; watch subscribes to whole sources") + } + // Watch also accepts a canonical source ID and can amend a sole declared root. + if let named = try argument.existingAlias( + in: declaration, sourceID: argument.location, path: argument.path ?? path, + environment: environment, matchUniqueSource: true) + { + argument.location = named + } + let selection = try argument.selection( + in: declaration, requirement: requirement, path: path, environment: environment) + let parsed = selection.source + let id = try parsed.identity(environment: environment) + let existing = try argument.existingAlias( + in: declaration, sourceID: id, path: selection.path ?? parsed.path, + environment: environment, matchUniqueSource: true) + let name = alias ?? existing ?? declaration.derivedAlias(for: parsed.location) + if let current = declaration.sources[name], + try current.identity(environment: environment) != id + { + throw CoreError.invalidSource("source alias already refers to another source: \(name)") + } + let declared = selection.applied(to: existing.flatMap { declaration.sources[$0] } ?? parsed) + declaration.sources[name] = declared + declaration.watch = Array(Set((declaration.watch ?? []) + [name])).sorted() + try declaration.validate(environment: environment) + let change = try declarations.plan(store, previous, declaration, baseline) + return AddPlan(alias: name, id: id, source: declared, change: change) } private func sourceDeclaration( @@ -141,7 +428,7 @@ public struct WatchOperations: Sendable { if let source = declaration.sources[input] { return source } let parsed = try SourceParser.parse( input, currentDirectory: environment.projectDirectory, - homeDirectory: environment.homeDirectory) + homeDirectory: environment.homeDirectory, sourceAccess: environment.sourceAccess) return SourceDeclaration( kind: parsed.type, location: parsed.localPath ?? parsed.url, requirement: parsed.requirement, path: parsed.subpath) @@ -164,26 +451,36 @@ public struct WatchOperations: Sendable { throw CoreError.notFound("source is not subscribed: \(input)") } + /// The prepared generation, captured before any network acknowledgment, is the journal's + /// preimage evidence and also guards the lock that pruning follows. private func commit( - declaration: Declaration?, watch: WatchState, lock: ResolvedState, store: StateStore + _ change: DeclarationChange?, watch: WatchState, lock: ResolvedLedger, store: StateStore, + baseline: StatePrecondition, outcome: TransactionOutcome = TransactionOutcome() ) throws { try watch.validate() - let transaction = FileTransaction(store: store, checkpoint: checkpoint) - if let declaration { - try store.stageDeclaration(declaration, in: transaction) - } - try transaction.replace(store.watchURL, content: nil, data: StateStore.encode(watch)) - try SourceCache(store: store).prune(referencedBy: lock, watch: watch, transaction: transaction) + let transaction = FileTransaction(store: store, outcome: outcome, checkpoint: checkpoint) + transaction.requireUnchanged(since: baseline) + try store.stageDeclaration(change, in: transaction, prepared: baseline) + try transaction.replace( + store.watchURL, with: .data(StateStore.encode(watch)), + expecting: baseline.evidence(for: store.watchURL)) + var references = try RetentionReferences(ledger: lock, roots: store.ledgerRoots) + try references.include(watch: watch) + try SourceCache(store: store).prune(references: references, transaction: transaction) try transaction.commit() } private func acknowledge( - _ source: SourceDeclaration, revision: String?, store: StateStore + _ source: SourceDeclaration, revision: String?, expected: WatchSeen? = nil, store: StateStore ) throws -> WatchSeen { - let cache = SourceCache(store: store, checkpoint: checkpoint) + let cache = try SourceCache( + store: store, sourcePolicy: sourcePolicy(store), checkpoint: checkpoint) let id = try source.identity(environment: store.environment) if source.kind != .wellKnown { let head = try cache.watchRevision(source, revision: revision) + guard expected == nil || expected == .revision(head) else { + throw CoreError.invalidState("watch content changed; refresh before acknowledging") + } try checkpoint("watch.mirror.fetched") try cache.retainWatchRevision(sourceID: id, source: source.location, revision: head) return .revision(head) @@ -191,22 +488,35 @@ public struct WatchOperations: Sendable { guard revision == nil else { throw CoreError.invalidSource("well-known subscriptions do not accept Git revisions") } - let artifacts = try artifacts(source) + let artifacts = try artifacts(source, store: store) + let current = WatchSeen.artifacts( + Dictionary(uniqueKeysWithValues: artifacts.map { ($0.name, $0.artifact.digest) })) + guard expected == nil || expected == current else { + throw CoreError.invalidState("watch content changed; refresh before acknowledging") + } let root = FileManager.default.temporaryDirectory.appendingPathComponent( "agents-watch-" + UUID().uuidString) - try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + try FileSystem.createDirectory(at: root) defer { try? FileManager.default.removeItem(at: root) } - for artifact in artifacts { + // Each nested cache transaction names its checkpoints within its artifact and role, so + // they stay distinct from one another and from the watch commit. + func artifactCache(_ scope: String) -> SourceCache { + SourceCache(store: store) { try checkpoint("watch.artifact." + scope + "." + $0) } + } + for (index, artifact) in artifacts.enumerated() { let directory = root.appendingPathComponent(artifact.name) - try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + try FileSystem.createDirectory(at: directory) for (path, data) in artifact.files { let destination = try PathSafety.resolvedChild(base: directory, subpath: path) - try FileManager.default.createDirectory( - at: destination.deletingLastPathComponent(), withIntermediateDirectories: true) - try data.write(to: destination) + try FileSystem.createDirectory(at: destination.deletingLastPathComponent()) + try FileSystem.write(data, to: destination) + } + for (payload, (digest, data)) in artifact.payloads.sorted(by: { $0.key < $1.key }) + .enumerated() + { + _ = try artifactCache("\(index).payload.\(payload)").storeArtifact(data, digest: digest) } - for (digest, data) in artifact.payloads { _ = try cache.storeArtifact(data, digest: digest) } - _ = try cache.materializeArtifact( + _ = try artifactCache("\(index).content").materializeArtifact( directory, digest: artifact.artifact.digest, hash: "sha256:" + FileHash.folderHash(directory)) } @@ -214,8 +524,12 @@ public struct WatchOperations: Sendable { Dictionary(uniqueKeysWithValues: artifacts.map { ($0.name, $0.artifact.digest) })) } - private func artifacts(_ source: SourceDeclaration) throws -> [WatchArtifact] { - let artifacts = try fetchArtifacts(source.location) + private func artifacts(_ source: SourceDeclaration, store: StateStore) throws -> [WatchArtifact] { + let policy = try sourcePolicy(store) + _ = try SourceRoute(source, environment: store.environment, policy: policy) + let artifacts = + try (policy.isConfigured ? fetchGuardedArtifacts?(source.location, policy) : nil) + ?? fetchArtifacts(source.location) try Declaration.validateNames(artifacts.map(\.name)) for artifact in artifacts { try artifact.artifact.validate() @@ -250,14 +564,15 @@ public struct WatchOperations: Sendable { } private func inspect( - alias: String, declaration: Declaration, watch: WatchState, store: StateStore + alias: String, declaration: Declaration, watch: WatchState, store: StateStore, + baseline: StatePrecondition ) throws -> WatchStatus { let source = declaration.sources[alias]! let id = try source.identity(environment: store.environment) guard let seen = watch.sources[id]?.seen else { throw CoreError.invalidState("subscription has no seen state: \(alias)") } - let cache = SourceCache(store: store) + let cache = try SourceCache(store: store, sourcePolicy: sourcePolicy(store)) let current: WatchSeen let count: Int? let before: [WatchItemKey: WatchUnit] @@ -273,15 +588,13 @@ public struct WatchOperations: Sendable { after = revision == head ? before : try units(source, revision: head, cache: cache) case .artifacts(let digests): guard source.kind == .wellKnown else { throw CoreError.invalidState("watch kind mismatch") } - let artifacts = try artifacts(source) + let artifacts = try artifacts(source, store: store) current = .artifacts( Dictionary(uniqueKeysWithValues: artifacts.map { ($0.name, $0.artifact.digest) })) count = nil var old: [WatchItemKey: WatchUnit] = [:] for (name, digest) in digests { - let directory = store.cacheDirectory.appendingPathComponent( - "artifact-content/\(digest.dropFirst(7))") - try cache.validatePath(directory) + let directory = try cache.artifactContentURL(digest: digest) old[WatchItemKey(kind: .artifact, name: name)] = WatchUnit( path: nil, digest: digest, files: try WatchUnit.read(directory)) } @@ -315,9 +628,17 @@ public struct WatchOperations: Sendable { oldPath: old?.path, newPath: new?.path, oldDigest: old?.digest, newDigest: new?.digest, files: files) } + let acknowledgment = WatchMutationPreview( + action: .seen(alias), store: store, alias: alias, sourceID: id, seen: current, + displayedFingerprint: try mutationFingerprint( + baseline: baseline, change: nil, seen: current, store: store, alias: alias, + sourceID: id, removing: false), + readLocations: mutationReadLocations(store, source: source)) return WatchStatus( - alias: alias, sourceID: id, seen: seen, current: current, commitCount: count, changes: changes - ) + alias: alias, sourceID: id, seen: seen, current: current, commitCount: count, + changes: changes, + acknowledgment: acknowledgment) + } private func units( @@ -407,3 +728,34 @@ private struct WatchUnit: Equatable { } } } + +/// Immutable subscription confirmation; no locks or borrowed resources escape preview. +public struct WatchMutationPreview: Equatable, Sendable { + fileprivate enum Action: Equatable, Sendable { + case add(String, String?, SourceRequirement?, String?) + case remove(String) + case seen(String) + } + fileprivate let action: Action + package let store: StateStore + public let alias: String + public let sourceID: String + public let seen: WatchSeen? + public let displayedFingerprint: String + public let readLocations: [URL] + + fileprivate func matches(scope: InstallScope, environment: RuntimeEnvironment) -> Bool { + store.scope == scope + && store.environment.projectDirectory == environment.projectDirectory + && store.environment.homeDirectory == environment.homeDirectory + && store.environment.environment == environment.environment + } + + public static func == (lhs: Self, rhs: Self) -> Bool { + lhs.action == rhs.action + && lhs.matches(scope: rhs.store.scope, environment: rhs.store.environment) + && lhs.alias == rhs.alias && lhs.sourceID == rhs.sourceID && lhs.seen == rhs.seen + && lhs.displayedFingerprint == rhs.displayedFingerprint + && lhs.readLocations == rhs.readLocations + } +} diff --git a/Sources/AgentsInstructions/InstructionCompatibility.swift b/Sources/AgentsInstructions/InstructionCompatibility.swift new file mode 100644 index 0000000..0f02a87 --- /dev/null +++ b/Sources/AgentsInstructions/InstructionCompatibility.swift @@ -0,0 +1,84 @@ +import AgentsCore +import Foundation + +/// Existing instruction ownership semantics, usable by locked reconstruction and conversion +/// validation without discovery, target selection or filesystem mutation. +package enum InstructionCompatibility { + package static func antigravityMarker(_ leaf: String) -> String { + "" + } + + package static func ownsAntigravityRule(_ bytes: Data, leaf: String, scope: InstallScope) -> Bool + { + let lines = String(decoding: bytes, as: UTF8.self).split( + separator: "\n", maxSplits: 7, omittingEmptySubsequences: false) + guard lines.count >= 7, lines[0] == "---" else { return false } + let description: Int + switch lines[1] { + case "trigger: always_on": description = 2 + case "trigger: glob" + where scope == .project && lines.count == 8 && lines[2].hasPrefix("globs: "): + description = 3 + default: return false + } + return lines[description].hasPrefix("description: ") && lines[description + 1] == "---" + && lines[description + 2].isEmpty && lines[description + 3] == antigravityMarker(leaf) + } + + package static func obsolete(_ deployment: LedgerDeployment, before: Data?) throws -> Data? { + guard let before else { return nil } + switch deployment.ownership { + case .generated: + return Instructions.hash(before) == deployment.expectedHash ? nil : before + case .importBlock: + let edit = try Instructions.removeBlock(from: before) + return deployment.created && !edit.hasCustomContent ? nil : edit.bytes + case .ownedValues: + throw CoreError.invalidState("structured ownership requires its locked document format") + } + } + + package static func renderPrompt( + _ bytes: [Data], ids: [String], append: Data?, byteLimit: Int? = nil + ) throws -> Data { + guard bytes.count == ids.count else { throw CoreError.invalidState("prompt input count") } + let sections = try zip(bytes, ids).map { + try Instructions.validateSource($0.0, id: $0.1, allowRestrictions: true) + } + try checkOutput(sections, notice: false, append: append, byteLimit: byteLimit) + return try Instructions.renderChatGPT(sections: sections, customContent: append) + } + + package static func renderSections(_ bytes: [Data], ids: [String], byteLimit: Int? = nil) throws + -> Data + { + guard bytes.count == ids.count else { throw CoreError.invalidState("instruction input count") } + let sections = try zip(bytes, ids).map { + try Instructions.validateSource($0.0, id: $0.1, allowRestrictions: true) + } + try checkOutput(sections, notice: true, append: nil, byteLimit: byteLimit) + return Data(try Instructions.render(sections).utf8) + } + + private static func checkOutput( + _ sections: [InstructionSection], notice: Bool, append: Data?, byteLimit: Int? + ) throws { + guard var remaining = byteLimit else { return } + func charge(_ count: Int) throws { + guard count <= remaining else { + throw CoreError.invalidState("rendered instruction byte budget") + } + remaining -= count + } + if notice { try charge(Instructions.notice.utf8.count + 2) } + for (index, section) in sections.enumerated() { + if index > 0 { try charge(2) } + try charge(section.content.utf8.count) + } + try charge(1) + if let append, !append.isEmpty { + try charge(1) + try charge(append.count) + } + } +} diff --git a/Sources/AgentsInstructions/InstructionDoctor.swift b/Sources/AgentsInstructions/InstructionDoctor.swift index 4f9114a..8ad1e29 100644 --- a/Sources/AgentsInstructions/InstructionDoctor.swift +++ b/Sources/AgentsInstructions/InstructionDoctor.swift @@ -1,4 +1,5 @@ import AgentsCore +import AgentsManifest import Foundation extension InstructionOperations { @@ -12,19 +13,19 @@ extension InstructionOperations { let store = StateStore(scope: scope, environment: environment) let other = StateStore(scope: scope == .project ? .user : .project, environment: environment) func pendingRecovery(_ store: StateStore) -> InstructionDiagnostic { - InstructionDiagnostic( - kind: .pendingRecovery, - message: - "Transaction recovery is pending; the next command that changes this scope will recover it.", + let recovery = FileTransaction.recoveryDiagnostic(store: store) + return InstructionDiagnostic( + kind: recovery.requiresOwner ? .unresolvedTransaction : .pendingRecovery, + message: recovery.message, path: store.directory) } - let otherSections: [LockedSection]? = try other.withReadLock( - onPendingRecovery: { nil }, - { - _ = try other.readDeclaration() - return try other.readResolved().instructions.sections - }) - let otherDiagnostics = otherSections == nil ? [pendingRecovery(other)] : [] + let (otherSections, otherDiagnostics): ([LockedSection]?, [InstructionDiagnostic]) = + try other.withReadLock( + onPendingRecovery: { (nil, [pendingRecovery(other)]) }, + { + _ = try other.readDeclaration() + return (try other.readResolved().instructions.sections, []) + }) let root = scope == .project ? environment.projectDirectory : environment.homeDirectory return try store.withReadLock( onPendingRecovery: { @@ -33,14 +34,25 @@ extension InstructionOperations { }, { let declaration = try store.readDeclaration() - let lock = try store.readResolved() + let ledger = try store.readLedger() + let roots = store.ledgerRoots(recordedIn: ledger) + let lock = try ledger.domainProjection(roots: roots) + let owners = try Dictionary( + ledger.deployments.filter { $0.route == "agents/instructions@1" }.map { + (try ledger.instructionTargetKey($0.target, roots: roots), $0.owners) + }, uniquingKeysWith: { _, latest in latest }) var diagnostics = otherDiagnostics func report(_ kind: InstructionDiagnostic.Kind, _ message: String, _ path: URL? = nil) { diagnostics.append(InstructionDiagnostic(kind: kind, message: message, path: path)) } if !FileManager.default.fileExists(atPath: store.resolvedURL.path), - !(declaration.instructions?.sections.isEmpty ?? true) - || !(declaration.instructions?.chatgpt?.isEmpty ?? true) + declaration.components.contains(where: { + if case .instructions(let s) = $0 { + !s.sectionReferences.isEmpty || !s.prompts.isEmpty + } else { + false + } + }) { report( .missingLock, "Instruction declaration has no lock; update can reconstruct it.", @@ -57,7 +69,7 @@ extension InstructionOperations { for record in records where record.source == InstructionSources.own && seen.insert(record.path).inserted { let file = project.appendingPathComponent(record.path) - let current = try? Data(contentsOf: file) + let current = try FileSystem.readUnlessDenied(at: file) if current.map(Instructions.hash) != record.hash { unchanged = false report( @@ -67,15 +79,32 @@ extension InstructionOperations { } } } - let sections = - unchanged - ? try? sources.restore( - lock.instructions.sections, sources: lock.sources, cachedOnly: true - ).map(\.section) : nil + // Targets already reported as unreadable; the Codex chain must not report them again. + var unreadableTargets = Set() for (key, target) in lock.instructions.targets.sorted(by: { $0.key < $1.key }) { do { let file = try InstructionLocations.file(for: key, store: store) - let bytes = try InstructionTargets.read(file) + if target.agents == [.antigravity] { + if let bytes = try InstructionTargets.read(file) { + if !InstructionCompatibility.ownsAntigravityRule( + bytes, leaf: file.lastPathComponent, scope: store.scope) + { + report(.foreignTarget, "Antigravity rule has lost its ownership marker.", file) + } else if Instructions.hash(bytes) != target.blockHash { + report(.drift, "Antigravity rule differs from its lock.", file) + } + } else { + report(.missingTarget, "Managed Antigravity rule is missing.", file) + } + continue + } + let bytes: Data? + do { + bytes = try InstructionTargets.read(file) + } catch { + unreadableTargets.insert(file.resolvingSymlinksInPath().path) + throw error + } if target.import != nil { switch try Instructions.detectDrift( in: bytes ?? Data(), lockedBlockHash: target.blockHash) @@ -93,14 +122,13 @@ extension InstructionOperations { } else if bytes == nil { report(.missingTarget, "Generated instructions file is missing.", file) } - if let sections { - let directory = (key as NSString).deletingLastPathComponent - let group = sections.filter { scope == .user || $0.directory == directory } - if !group.isEmpty { - let text = try Instructions.render(group) - for problem in targets.linkProblems(in: text, file: file, key: key) { - report(.invalidLink, "Link '\(problem.destination)' \(problem.reason).", file) - } + 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) } } } catch { @@ -117,8 +145,15 @@ extension InstructionOperations { report(.duplicateScope, "Section is installed at both scopes: \(id)") } } - let agents = Set(lock.instructions.targets.values.flatMap(\.agents)) - .union(declaration.instructions?.agents ?? declaration.defaultAgents) + let selections = declaration.components.compactMap { + component -> InstructionsDeclaration? in + if case .instructions(let selection) = component { selection } else { nil } + } + let declaredAgents = + selections.isEmpty + ? declaration.defaultAgents + : selections.flatMap { $0.agents ?? declaration.defaultAgents } + let agents = Set(lock.instructions.targets.values.flatMap(\.agents)).union(declaredAgents) let claudeTargets = lock.instructions.targets.filter { $0.value.import == nil && $0.value.agents.contains(.claudeCode) }.keys.sorted() @@ -171,10 +206,13 @@ extension InstructionOperations { } if agents.contains(.codex), scope == .user || otherSections != nil { diagnostics += InstructionDoctor.codex( - scope: scope, environment: environment, lock: lock, configuration: codexConfiguration) + scope: scope, environment: environment, lock: lock, configuration: codexConfiguration, + reportedUnreadable: unreadableTargets) } diagnostics += InstructionSourceDiagnostics.inspect( - store: store, declaration: declaration, lock: lock) + store: store, declaration: declaration, lock: lock, + sourcePolicy: try SourcePolicySnapshot(store: store).effective, + bundledSources: try ledger.bundledSourceIdentities(in: store, roots: roots)) return InstructionDoctorReport( root: root, diagnostics: diagnostics) @@ -219,9 +257,11 @@ private enum InstructionDoctor { return result } + /// `reportedUnreadable` holds resolved paths the caller already reported as unreadable. static func codex( scope: InstallScope, environment: RuntimeEnvironment, lock: ResolvedState, - configuration supplied: CodexInstructionConfiguration? + configuration supplied: CodexInstructionConfiguration?, + reportedUnreadable: Set = [] ) -> [InstructionDiagnostic] { var result: [InstructionDiagnostic] = [] let user = InstructionLocations.file(for: .codex, scope: .user, environment: environment)! @@ -229,7 +269,7 @@ private enum InstructionDoctor { var configuration = supplied ?? CodexInstructionConfiguration() do { if supplied == nil, FileManager.default.fileExists(atPath: config.path) { - configuration = try CodexInstructionConfiguration(Data(contentsOf: config)) + configuration = try CodexInstructionConfiguration(FileSystem.read(at: config)) } } catch { result.append( @@ -244,14 +284,25 @@ private enum InstructionDoctor { value.agents.contains(.codex) && (try? InstructionLocations.file(for: key, store: store)) == InstructionLocations.physical(file) - } || (try? Data(contentsOf: file)).map(Instructions.isGenerated) == true + } || content(file).map(Instructions.isGenerated) == true } + var unreadable = reportedUnreadable func content(_ file: URL) -> Data? { var isDirectory: ObjCBool = false guard FileManager.default.fileExists(atPath: file.path, isDirectory: &isDirectory), !isDirectory.boolValue else { return nil } - return (try? Data(contentsOf: file)) ?? Data() + do { + return try FileSystem.readUnlessDenied(at: file) ?? Data() + } catch { + // The chain visits a file once per leaf and once for ownership; report it once. + if unreadable.insert(file.resolvingSymlinksInPath().path).inserted { + result.append( + InstructionDiagnostic( + kind: .invalidTarget, message: "Cannot read instructions: \(error)", path: file)) + } + return Data() + } } func blank(_ data: Data) -> Bool { String(decoding: data, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines).isEmpty diff --git a/Sources/AgentsInstructions/InstructionExport.swift b/Sources/AgentsInstructions/InstructionExport.swift index 1d52361..b1580e4 100644 --- a/Sources/AgentsInstructions/InstructionExport.swift +++ b/Sources/AgentsInstructions/InstructionExport.swift @@ -1,4 +1,5 @@ import AgentsCore +import AgentsManifest import Foundation /// One scope's locked instruction mapping. It describes the lock, not the files on disk. @@ -24,10 +25,12 @@ public struct InstructionMapping: Sendable, Equatable { public let root: URL public let status: Status public let targets: [Target] - /// Project sections whose placement needs content that is not available without fetching: an - /// own file changed since the lock, or a source section missing from the cache. + /// Locked sections without a target assignment. public let unplaced: [LockedSection] public let prompts: [String: [LockedSection]] + /// Scope metadata and read-admission entries, including absent paths and logical/physical + /// root aliases. Retained for every status; bodies, append files and target bytes are not read. + public let readDependencies: [ReadDependency] } extension InstructionOperations { @@ -51,48 +54,59 @@ extension InstructionOperations { { let store = StateStore(scope: scope, environment: environment) let root = scope == .project ? environment.projectDirectory : environment.homeDirectory + var readLocations = Set(store.metadataReadLocations.map(\.standardizedFileURL)) + func dependencies() -> [ReadDependency] { + readLocations.sorted { $0.path < $1.path }.map(ReadDependency.entry) + } func empty(_ status: InstructionMapping.Status) -> InstructionMapping { InstructionMapping( - scope: scope, root: root, status: status, targets: [], unplaced: [], prompts: [:]) + scope: scope, root: root, status: status, targets: [], unplaced: [], prompts: [:], + readDependencies: dependencies()) } do { return try store.withReadLock( onPendingRecovery: { empty(.pendingRecovery) }, + onReadLocation: { readLocations.insert($0.standardizedFileURL) }, { _ = try store.readDeclaration() guard try store.existingData(store.resolvedURL) != nil else { return empty(.missingLock) } - let lock = try store.readResolved() - let sources = InstructionSources(store: store) - var directories: [String: String] = [:] - var unplaced: [LockedSection] = [] - // User targets receive every section, so their placement needs no content. - for record in lock.instructions.sections { - if scope == .user { - directories[InstructionSources.identity(record)] = "" - } else if let unit = try? sources.restore( - [record], sources: lock.sources, cachedOnly: true - ).first { - directories[InstructionSources.identity(record)] = unit.section.directory - } else { - unplaced.append(record) + let ledger = try store.readLedger() + let roots = store.ledgerRoots(recordedIn: ledger) + let lock = try ledger.domainProjection(roots: roots) + let targets = try ledger.deployments.filter { + InstructionLocations.isInstructionFormat($0.route) + }.map { deployment in + let file = try deployment.target.resolve(roots: roots) + let key = InstructionLocations.key(for: file, store: store) + var seenResources = Set() + let sections = try deployment.owners.compactMap { ledger.components[$0] }.compactMap { + component throws -> LockedSection? in + guard deployment.ownership != .importBlock, let id = component.resources.first, + let resource = ledger.resources[id], seenResources.insert(id).inserted + else { return nil } + let source = try ledger.sourceIdentity(component.source, roots: roots) + let own = + resource.path.hasPrefix(".agent/instructions/") + && ledger.sources[component.source]?.revision == "live" + && ledger.sources[component.source]?.location?.root == "project" + return LockedSection( + name: component.name, source: own ? "." : source, + revision: component.revision, version: component.version, + artifact: resource.artifact, + path: resource.path, + hash: component.payload.object?["sourceHash"]?.text ?? resource.hash) } - } - let targets = lock.instructions.targets.sorted { $0.key < $1.key }.map { key, value in - let directory = scope == .project ? (key as NSString).deletingLastPathComponent : "" return InstructionMapping.Target( - target: key, agents: value.agents, - sections: value.import != nil - ? [] - : lock.instructions.sections.filter { - directories[InstructionSources.identity($0)] == directory - }, - import: value.import) - } + target: key, agents: deployment.recipients, sections: sections, + import: deployment.importReference) + }.sorted { $0.target < $1.target } + return InstructionMapping( - scope: scope, root: root, status: .locked, targets: targets, unplaced: unplaced, - prompts: lock.instructions.chatgpt.mapValues(\.sections)) + scope: scope, root: root, status: .locked, targets: targets, unplaced: [], + prompts: lock.instructions.chatgpt.mapValues(\.sections), + readDependencies: dependencies()) }) } catch { return empty(.unavailable(String(describing: error))) diff --git a/Sources/AgentsInstructions/InstructionFrontMatter.swift b/Sources/AgentsInstructions/InstructionFrontMatter.swift index 542cce9..56ce5a4 100644 --- a/Sources/AgentsInstructions/InstructionFrontMatter.swift +++ b/Sources/AgentsInstructions/InstructionFrontMatter.swift @@ -1,3 +1,4 @@ +import AgentsCore import Foundation /// The fixed front matter of an instructions file: a required `description` and optional `paths`. @@ -6,14 +7,16 @@ import Foundation struct InstructionFrontMatter: Equatable { let description: String let paths: [String] + let condition: DeclarationCondition struct Failure: Error { let reason: String } - static func parse(_ lines: [String]) throws -> Self { + static func parse(_ lines: [String], allowRestrictions: Bool = false) throws -> Self { var description: String? var paths: [String]? + var restrictions: [String: [String]] = [:] var index = 0 func fail(_ reason: String) -> Failure { Failure(reason: reason) } while index < lines.count { @@ -24,12 +27,17 @@ struct InstructionFrontMatter: Equatable { else { throw fail("front matter line \(index + 1) is not a 'key: value' entry.") } let key = String(line[.. String { diff --git a/Sources/AgentsInstructions/InstructionInitialization.swift b/Sources/AgentsInstructions/InstructionInitialization.swift new file mode 100644 index 0000000..7dda8a8 --- /dev/null +++ b/Sources/AgentsInstructions/InstructionInitialization.swift @@ -0,0 +1,50 @@ +import AgentsCore +import Foundation + +package struct InstructionInitialization: Sendable { + package let store: StateStore + package let root: ExistingProjectRoot + package let file: URL + package let template: Data + + package init(named name: String, environment: RuntimeEnvironment, validateState: Bool = true) + throws + { + guard Declaration.isInstructionName(name), !name.contains("/") else { + throw CoreError.invalidSource( + "instruction names use lowercase letters, digits and hyphens: \(name)") + } + store = StateStore(scope: .project, environment: environment) + root = try store.captureExistingProjectRoot() + file = root.directory.resolvingSymlinksInPath() + .appendingPathComponent(InstructionSources.ownContainer).appendingPathComponent(name + ".md") + template = Data( + "---\ndescription: Describe what these instructions make the agent do.\n---\n# \(name)\n\nWrite the instructions here.\n" + .utf8) + _ = try Instructions.validateSource(template, id: name) + if validateState { + try store.withReadLock { + _ = try store.declarationBytes() + guard try InstructionTargets.read(file) == nil else { + throw CoreError.invalidSource("instruction file already exists: \(file.path)") + } + } + } + } + + package func apply(outcome: TransactionOutcome, checkpoint: @escaping (String) throws -> Void) + throws -> URL + { + try store.withLock(checkpoint: checkpoint, outcome: outcome, existingRoot: root) { + _ = try store.declarationBytes() + let evidence = try TargetPrecondition(file) + guard try InstructionTargets.read(file) == nil else { + throw CoreError.invalidSource("instruction file already exists: \(file.path)") + } + let transaction = FileTransaction(store: store, outcome: outcome, checkpoint: checkpoint) + try transaction.replace(file, with: .data(template), expecting: evidence) + try transaction.commit() + return file + } + } +} diff --git a/Sources/AgentsInstructions/InstructionLifecycleModels.swift b/Sources/AgentsInstructions/InstructionLifecycleModels.swift index 3d97b97..2d5cbb6 100644 --- a/Sources/AgentsInstructions/InstructionLifecycleModels.swift +++ b/Sources/AgentsInstructions/InstructionLifecycleModels.swift @@ -47,14 +47,25 @@ public struct InstructionAddOutcome: Sendable { public let available: [InstructionUnit] /// Nil means source inspection or a multi-unit source awaiting a selection. public let result: InstructionUpdateReport? + + package init(sourceID: String, available: [InstructionUnit], result: InstructionUpdateReport?) { + self.sourceID = sourceID + self.available = available + self.result = result + } } -public struct InstructionSectionChange: Sendable, Equatable { +public struct InstructionSectionChange: Codable, Sendable, Equatable { public let before: LockedSection? public let after: LockedSection? + + package init(before: LockedSection?, after: LockedSection?) { + self.before = before + self.after = after + } } -public struct InstructionTargetChange: Sendable, Equatable { +public struct InstructionTargetChange: Codable, Sendable, Equatable { /// The lock's physical target key; user paths outside home are absolute. public let target: String public let url: URL @@ -77,9 +88,42 @@ public struct InstructionTargetChange: Sendable, Equatable { /// A missing previous entry (`beforeAgents == nil`) differs from any planned list. /// Use `InstructionUpdateReport.hasChanges` to detect any update in the report. public var agentsChanged: Bool { beforeAgents != afterAgents } + + package init( + target: String, url: URL, before: Data?, after: Data?, beforeAgents: [AgentID]?, + afterAgents: [AgentID], drift: InstructionDrift?, foreign: Bool + ) { + self.target = target + self.url = url + self.before = before + self.after = after + self.beforeAgents = beforeAgents + self.afterAgents = afterAgents + self.drift = drift + self.foreign = foreign + } +} + +public struct InstructionBuildOutput: Codable, Sendable, Equatable, Identifiable { + public let id: String + public let recipient: InstructionRecipient + public let displayName: String + /// The local target URL. Copyable app products have no file URL. + public let fileURL: URL? + public let content: Data + + package init( + id: String, recipient: InstructionRecipient, displayName: String, fileURL: URL?, content: Data + ) { + self.id = id + self.recipient = recipient + self.displayName = displayName + self.fileURL = fileURL + self.content = content + } } -public struct InstructionUpdateReport: Sendable, Equatable { +public struct InstructionUpdateReport: Codable, Sendable, Equatable { public let sections: [InstructionSectionChange] /// Every affected target, including unchanged files recorded again after loss of a lock. public let targets: [InstructionTargetChange] @@ -87,10 +131,42 @@ public struct InstructionUpdateReport: Sendable, Equatable { public let changedPrompts: [String] public let lockMissing: Bool + private let buildOutputs: [InstructionBuildOutput]? + private let advisoryMessages: [String]? + private let conflictMessages: [String]? + /// Complete candidate bytes for each selected recipient and target, including unchanged files. + public var outputs: [InstructionBuildOutput] { buildOutputs ?? [] } + /// Informational guidance about applying the selected instructions. + public var advisories: [String] { advisoryMessages ?? [] } + /// Conflicts that block publication and must be resolved before applying. + public var conflicts: [String] { conflictMessages ?? [] } + + private enum CodingKeys: String, CodingKey { + case sections, targets, changedPrompts, lockMissing, hasChanges + case buildOutputs = "outputs" + case advisoryMessages = "advisories" + case conflictMessages = "conflicts" + } + /// Whether applying changes the declaration, locked state (including section order and pins, /// target recipients, and prompts), target bytes, or reconstructs a missing lock with targets. /// Consumers should use this property to detect updates, including changes with identical bytes. public let hasChanges: Bool + + package init( + sections: [InstructionSectionChange], targets: [InstructionTargetChange], + changedPrompts: [String], lockMissing: Bool, hasChanges: Bool, + outputs: [InstructionBuildOutput] = [], advisories: [String] = [], conflicts: [String] = [] + ) { + self.sections = sections + self.targets = targets + self.changedPrompts = changedPrompts + self.lockMissing = lockMissing + self.hasChanges = hasChanges + buildOutputs = outputs.isEmpty ? nil : outputs + advisoryMessages = advisories.isEmpty ? nil : advisories + conflictMessages = conflicts.isEmpty ? nil : conflicts + } } public struct InstructionDiagnostic: Sendable, Equatable { @@ -112,7 +188,7 @@ public struct InstructionDiagnostic: Sendable, Equatable { case sourceResolutionFailed case invalidConfiguration case stateUnavailable - case pendingRecovery + case pendingRecovery, unresolvedTransaction } public let kind: Kind diff --git a/Sources/AgentsInstructions/InstructionModels.swift b/Sources/AgentsInstructions/InstructionModels.swift index 7451983..995e754 100644 --- a/Sources/AgentsInstructions/InstructionModels.swift +++ b/Sources/AgentsInstructions/InstructionModels.swift @@ -1,3 +1,4 @@ +import AgentsCore import Foundation public struct InstructionSection: Sendable, Equatable { @@ -10,17 +11,18 @@ public struct InstructionSection: Sendable, Equatable { public let description: String /// Project-relative glob patterns that scope the section, in source order. public let paths: [String] + package let condition: DeclarationCondition /// SHA-256 of the original source bytes, including their line endings and any byte order mark. public let hash: String /// The body as written into targets: no front matter, LF endings, no leading or trailing /// blank lines, and the `paths` line after the first heading. - let content: String + package let content: String /// The project-relative directory whose `AGENTS.md` receives the section; empty for the root. public var directory: String { Instructions.directory(for: paths) } } -public enum InstructionDrift: Sendable, Equatable { +public enum InstructionDrift: Codable, Sendable, Equatable { case clean case drifted case missing @@ -59,6 +61,7 @@ public enum InstructionError: Error, Sendable, Equatable, CustomStringConvertibl case invalidLockedBlock case invalidLinks([InstructionLinkProblem]) case unownedTargets([String]) + case antigravityConflicts([String]) case ownChanged(name: String) case emptyPrompt @@ -87,6 +90,8 @@ public enum InstructionError: Error, Sendable, Equatable, CustomStringConvertibl case .unownedTargets(let targets): return "Files that agents did not generate are in the way: \(targets.joined(separator: ", "))." + case .antigravityConflicts(let messages): + return messages.joined(separator: "\n") case .ownChanged(let name): return "Own instructions file '\(name)' changed since the lock." case .emptyPrompt: diff --git a/Sources/AgentsInstructions/InstructionOperations.swift b/Sources/AgentsInstructions/InstructionOperations.swift index 55a94dc..5665521 100644 --- a/Sources/AgentsInstructions/InstructionOperations.swift +++ b/Sources/AgentsInstructions/InstructionOperations.swift @@ -1,119 +1,15 @@ import AgentsCore +import AgentsManifest import Foundation -/// Scope-bound instruction workflows. Consumers own argument parsing and difference presentation. public enum InstructionOperations { - /// A thrown callback cancels before target, declaration or lock replacements. - public static func add( - _ options: InstructionAddOptions, - beforeApply: ((InstructionUpdateReport) throws -> Void)? = nil - ) throws -> InstructionAddOutcome { - var automaticSelection: (sourceID: String, name: String)? - if options.listOnly || (options.names.isEmpty && !options.all) { - let outcome = try add(options, apply: false, beforeApply: nil) - if options.listOnly || outcome.available.count > 1 { return outcome } - automaticSelection = outcome.available.first.map { (outcome.sourceID, $0.record.name) } - } - return try add( - options, apply: true, automaticSelection: automaticSelection, beforeApply: beforeApply) - } - - private static func add( - _ options: InstructionAddOptions, apply: Bool, - automaticSelection: (sourceID: String, name: String)? = nil, - beforeApply: ((InstructionUpdateReport) throws -> Void)? - ) throws -> InstructionAddOutcome { - let store = StateStore(scope: options.scope, environment: options.environment) - return try operate(store, apply: apply) { previousDeclaration, previous in - var declaration = previousDeclaration - let selectionChanged = CoreError.invalidState( - "automatic instruction selection changed during discovery; retry the command") - let sources = InstructionSources(store: store) - let id: String - let alias: String? - let available: [InstructionUnit] - if options.source == InstructionSources.own { - id = InstructionSources.own - alias = nil - // Named files are read alone, so an unfinished draft beside them does not stop the add. - available = - options.names.isEmpty || options.listOnly - ? try sources.own() : try options.names.map(sources.own(named:)) - } else { - let source: SourceDeclaration - do { - source = try sourceDeclaration(options, declaration: declaration) - id = try source.identity(environment: options.environment) - } catch { - if automaticSelection != nil { throw selectionChanged } - throw error - } - if let automaticSelection, automaticSelection.sourceID != id { throw selectionChanged } - let existing = try declaration.sources.keys.sorted().first { - try declaration.sources[$0]?.identity(environment: options.environment) == id - } - let name = options.alias ?? existing ?? declaration.derivedAlias(for: source.location) - if let current = declaration.sources[name], - try current.identity(environment: options.environment) != id - { - throw CoreError.invalidSource("source alias already refers to another source: \(name)") - } - declaration.sources[name] = source - try declaration.validate(environment: options.environment) - alias = name - available = try sources.discover(source, cacheSource: apply) - } - guard options.listOnly || automaticSelection != nil || !available.isEmpty else { - throw CoreError.notFound("source provides no instructions") - } - if !apply { - return InstructionAddOutcome(sourceID: id, available: available, result: nil) - } - let selected: [InstructionUnit] - if let automaticSelection { - guard let unit = available.first(where: { $0.record.name == automaticSelection.name }) - else { throw selectionChanged } - selected = [unit] - } else if options.names.isEmpty { - selected = available - } else { - selected = try options.names.map { name in - guard let unit = available.first(where: { $0.record.name == name }) else { - throw CoreError.notFound("instruction section: \(name)") - } - return unit - } - } - guard !selected.isEmpty else { throw CoreError.notFound("source provides no instructions") } - var instructions = declaration.instructions ?? InstructionsDeclaration() - if let agents = options.agents { instructions.agents = agents } - let references = selected.map { (alias.map { $0 + ":" } ?? "") + $0.record.name } - for reference in references where !instructions.sections.contains(reference) { - instructions.sections.append(reference) - } - declaration.instructions = instructions - let prepared = try prepare( - declaration: declaration, previous: previous, sources: sources, resolving: Set(references)) - let plan = try plan( - declaration: declaration, previousDeclaration: previousDeclaration, - previous: previous, prepared: prepared, store: store) - try plan.lock.validate() - if !options.replace { try requireOwnership(plan.report) } - try beforeApply?(plan.report) - try Self.apply( - declaration: declaration, next: plan.lock, report: plan.report, sources: sources) - return InstructionAddOutcome(sourceID: id, available: available, result: plan.report) - } - } - - /// Returns committed, validated units. Inspection may fetch mirror objects but never publishes pins. public static func list( source: SourceDeclaration, scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment() ) throws -> [InstructionUnit] { let store = StateStore(scope: scope, environment: environment) return try operate(store, apply: false) { _, _ in - try InstructionSources(store: store).discover(source) + try inspectSource(source, store: store) } } @@ -134,336 +30,78 @@ public enum InstructionOperations { } } - /// Resolves declared content and reports every affected target before any replacement. - /// `agents` replaces the scope's instruction recipients when applying. Applying over a file that - /// agents did not generate requires `replace`. - public static func updateInstalled( - scope: InstallScope = .project, agents: [AgentID]? = nil, - environment: RuntimeEnvironment = RuntimeEnvironment(), apply: Bool = false, - replace: Bool = false, - beforeApply: ((InstructionUpdateReport) throws -> Void)? = nil - ) throws -> InstructionUpdateReport { - let store = StateStore(scope: scope, environment: environment) - return try operate(store, apply: apply) { previousDeclaration, previous in - var declaration = previousDeclaration - if let agents { - var instructions = declaration.instructions ?? InstructionsDeclaration() - instructions.agents = agents - declaration.instructions = instructions - } - let baseline = try StatePrecondition(store: store) - let resolutions = try SourceResolutionSession(store: store) - let plan = try prepareUpdate( - store: store, declaration: declaration, previousDeclaration: previousDeclaration, - previous: previous, resolutions: resolutions, replace: replace) - try plan.next.validate() - if apply { - if !replace { try requireOwnership(plan.report) } - try beforeApply?(plan.report) - try baseline.validate() - try plan.validate() - try plan.retain() - try baseline.validate() - try plan.validate() - let transaction = FileTransaction(store: store) - try plan.stage(transaction: transaction) - try store.stageDeclaration(declaration, in: transaction) - try transaction.replace( - store.resolvedURL, content: nil, data: StateStore.encodeState(plan.next.normalized)) - try SourceCache(store: store).prune(referencedBy: plan.next, transaction: transaction) - try transaction.commit() - } - return plan.report - } - } - - /// Prepares instruction-owned records; the caller validates the complete generation after assembly. - /// Validation fails when the plan writes over a file agents did not generate without `replace`. - package static func prepareUpdate( - store: StateStore, declaration: Declaration, previousDeclaration: Declaration, - previous: ResolvedState, resolutions: SourceResolutionSession, replace: Bool = false - ) throws -> InstructionUpdatePlan { - let sources = InstructionSources(store: store, resolutions: resolutions) - let prepared = try prepare(declaration: declaration, previous: previous, sources: sources) - let plan = try plan( - declaration: declaration, previousDeclaration: previousDeclaration, - previous: previous, prepared: prepared, store: store) - return try InstructionUpdatePlan( - next: plan.lock, report: plan.report, sources: sources, replace: replace) - } - - /// Restores only recorded pins and targets, without changing either state file. - public static func installResolvedReport( - scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment() - ) throws -> InstructionUpdateReport { - let store = StateStore(scope: scope, environment: environment) - return try operate(store, apply: true) { declaration, lock in - let sources = InstructionSources(store: store) - let sections = try sources.restore(lock.instructions.sections, sources: lock.sources) - for prompt in lock.instructions.chatgpt.values { - _ = try Instructions.renderChatGPT( - sections: sources.restore(prompt.sections, sources: lock.sources).map(\.section)) - } - let targets = try InstructionTargets(store: store).plan( - sections: sections.map(\.section), agents: [], previous: lock.instructions, - restoring: true) - let report = InstructionUpdateReport( - sections: [], targets: targets.changes, changedPrompts: [], - lockMissing: !FileManager.default.fileExists(atPath: store.resolvedURL.path), - hasChanges: targets.changes.contains(where: \.changed)) - try requireOwnership(report) - try apply( - declaration: declaration, next: lock, report: report, sources: sources, writeState: false) - return report - } - } - - /// Removes selected references from file targets and named prompts. A name equal to a declared - /// reference selects it; another bare name must match exactly one source reference. - @discardableResult - public static func remove( - names: [String], scope: InstallScope = .project, agents: [AgentID]? = nil, - environment: RuntimeEnvironment = RuntimeEnvironment(), - beforeApply: ((InstructionUpdateReport) throws -> Void)? = nil - ) throws -> InstructionUpdateReport { - let store = StateStore(scope: scope, environment: environment) - return try operate(store, apply: true) { previousDeclaration, previous in - var declaration = previousDeclaration - var instructions = declaration.instructions ?? InstructionsDeclaration() - let references = Set( - instructions.sections + (instructions.chatgpt ?? [:]).values.flatMap(\.sections)) - var removed = Set() - for name in names { - // A declared reference matches itself, such as an own file's bare name; otherwise a bare - // name matches a source reference with that name. - let exact = references.filter { $0 == name } - let matches = - exact.isEmpty - ? references.filter { InstructionSources.split($0)?.name == name } : exact - guard matches.count == 1, let reference = matches.first else { - throw CoreError.notFound("instruction name is missing or ambiguous: \(name)") - } - removed.insert(reference) - } - instructions.sections.removeAll { removed.contains($0) } - for name in (instructions.chatgpt ?? [:]).keys { - instructions.chatgpt?[name]?.sections.removeAll { removed.contains($0) } - if instructions.chatgpt?[name]?.sections.isEmpty == true { - instructions.chatgpt?[name] = nil - } - } - if let agents { instructions.agents = agents } - declaration.instructions = instructions - let sources = InstructionSources(store: store) - let prepared = try prepare( - declaration: declaration, previous: previous, sources: sources, resolving: []) - let plan = try plan( - declaration: declaration, previousDeclaration: previousDeclaration, - previous: previous, prepared: prepared, store: store) - try plan.lock.validate() - try requireOwnership(plan.report) - try beforeApply?(plan.report) - try apply(declaration: declaration, next: plan.lock, report: plan.report, sources: sources) - return plan.report - } - } - - /// Appends the current custom file to verified locked sections; never resolves declared requirements. - public static func renderChatGPT( - prompt name: String, scope: InstallScope = .project, - environment: RuntimeEnvironment = RuntimeEnvironment() - ) throws -> Data { - let store = StateStore(scope: scope, environment: environment) - return try operate(store, apply: false) { _, lock in - guard let prompt = lock.instructions.chatgpt[name], !prompt.sections.isEmpty else { - throw InstructionError.emptyPrompt - } - let sections = try InstructionSources(store: store).restore( - prompt.sections, sources: lock.sources) - var custom: Data? - if let append = prompt.append { - let root = scope == .project ? environment.projectDirectory : environment.homeDirectory - let file = try PathSafety.resolvedChild(base: root, subpath: append) - try InstructionSources.contained(file, in: root) - custom = try Data(contentsOf: file) - } - return try Instructions.renderChatGPT( - sections: sections.map(\.section), customContent: custom) - } - } - /// Creates the project's own `.agent/instructions/.md` with the required front matter, - /// without replacing an existing entry or creating a declaration or lock. + /// without replacing an existing entry or creating a declaration or resolved ledger. @discardableResult public static func initializeInstructions( named name: String, environment: RuntimeEnvironment = RuntimeEnvironment() ) throws -> URL { - guard Declaration.isInstructionName(name), !name.contains("/") else { - throw CoreError.invalidSource( - "instruction names use lowercase letters, digits and hyphens: \(name)") - } - let store = StateStore(scope: .project, environment: environment) - return try store.withLock { - let file = environment.projectDirectory.resolvingSymlinksInPath() - .appendingPathComponent(InstructionSources.ownContainer) - .appendingPathComponent(name + ".md") - guard try InstructionTargets.read(file) == nil else { - throw CoreError.invalidSource("instruction file already exists: \(file.path)") - } - let bytes = Data( - "---\ndescription: Describe what these instructions make the agent do.\n---\n# \(name)\n\nWrite the instructions here.\n" - .utf8) - _ = try Instructions.validateSource(bytes, id: name) - let transaction = FileTransaction(store: store) - try transaction.replace(file, content: nil, data: bytes) - try transaction.commit() - return file - } + try InstructionInitialization(named: name, environment: environment, validateState: false) + .apply(outcome: TransactionOutcome(), checkpoint: { _ in }) } - private static func prepare( - declaration: Declaration, previous: ResolvedState, sources: InstructionSources, - resolving: Set? = nil - ) throws -> (lock: ResolvedState, sections: [InstructionSection]) { - try declaration.validate(environment: sources.store.environment) - var next = previous - next.instructions = LockedInstructions() - let old = - previous.instructions.sections + previous.instructions.chatgpt.values.flatMap(\.sections) - func units(_ references: [String], locked: [LockedSection]) throws -> [InstructionUnit] { - try references.map { reference in - // Own instructions are never pinned, so they always resolve from the working tree. - if let (alias, name) = InstructionSources.split(reference), let resolving, - !resolving.contains(reference) - { - let id = try declaration.sources[alias]!.identity(environment: sources.store.environment) - if let record = (locked + old).first(where: { $0.source == id && $0.name == name }) { - return try sources.restore([record], sources: previous.sources)[0] - } - } - return try sources.resolve(references: [reference], declaration: declaration, lock: &next)[ - 0] + static func operate( + _ store: StateStore, apply: Bool, _ body: (Declaration, ResolvedState) throws -> T + ) throws -> T { + if apply { + return try store.withLock { + try body(store.readDeclaration(), store.readResolved()) } } - let sections = try units( - declaration.instructions?.sections ?? [], locked: previous.instructions.sections) - next.instructions.sections = sections.map(\.record) - for (name, prompt) in (declaration.instructions?.chatgpt ?? [:]).sorted(by: { $0.key < $1.key }) - { - let selected = try units( - prompt.sections, locked: previous.instructions.chatgpt[name]?.sections ?? []) - _ = try Instructions.renderChatGPT(sections: selected.map(\.section)) - next.instructions.chatgpt[name] = LockedPrompt( - sections: selected.map(\.record), append: prompt.append) + return try store.withReadLock { + try body(store.readDeclaration(), store.readResolved()) } - return (next, sections.map(\.section)) } - private static func plan( - declaration: Declaration, previousDeclaration: Declaration, previous: ResolvedState, - prepared: (lock: ResolvedState, sections: [InstructionSection]), store: StateStore - ) throws -> (lock: ResolvedState, report: InstructionUpdateReport) { - var next = prepared.lock - let targets = try InstructionTargets(store: store).plan( - sections: prepared.sections, - agents: declaration.instructions?.agents ?? declaration.defaultAgents, - previous: previous.instructions) - next.instructions.targets = targets.targets - try InstructionTargets.validateSourceDirectories(targets.changes, sources: next.sources) - let before = previous.instructions.sections - let after = next.instructions.sections - let identities = Set((before + after).map(InstructionSources.identity)) - let changes = identities.sorted().compactMap { id -> InstructionSectionChange? in - let old = before.first { InstructionSources.identity($0) == id } - let new = after.first { InstructionSources.identity($0) == id } - return old == new ? nil : InstructionSectionChange(before: old, after: new) - } - let prompts = Set(previous.instructions.chatgpt.keys).union(next.instructions.chatgpt.keys) - .sorted().filter { name in - let old = previous.instructions.chatgpt[name] - let new = next.instructions.chatgpt[name] - return old?.append != new?.append - || old?.sections.map { InstructionSources.identity($0) + $0.hash } - != new?.sections.map { InstructionSources.identity($0) + $0.hash } - } - let lockMissing = !FileManager.default.fileExists(atPath: store.resolvedURL.path) - let hasChanges = - declaration.normalized != previousDeclaration.normalized - || next.normalized != previous.normalized || targets.changes.contains(where: \.changed) - || (lockMissing && !targets.changes.isEmpty) - return ( - next, - InstructionUpdateReport( - sections: changes, targets: targets.changes, changedPrompts: prompts, - lockMissing: lockMissing, hasChanges: hasChanges) - ) - } - - /// Stops a write over files that agents did not generate, naming them. - static func requireOwnership(_ report: InstructionUpdateReport) throws { - let foreign = report.targets.filter(\.foreign).map(\.target) - guard foreign.isEmpty else { throw InstructionError.unownedTargets(foreign) } - } +} - private static func apply( - declaration: Declaration, next: ResolvedState, report: InstructionUpdateReport, - sources: InstructionSources, writeState: Bool = true - ) throws { - let store = sources.store - try declaration.validate(environment: store.environment) - try next.validate() - // User callbacks can inspect or cancel, but cannot silently invalidate the prepared differences. - for change in report.targets { - guard try InstructionTargets.read(change.url) == change.before else { - throw CoreError.invalidState( - "instruction target changed during preparation: \(change.target)") - } - } - try InstructionTargets.validateSourceDirectories(report.targets, sources: next.sources) - do { - try sources.retain(next) - let transaction = FileTransaction(store: store) - for change in report.targets { - guard try InstructionTargets.read(change.url) == change.before else { - throw CoreError.invalidState( - "instruction target changed during preparation: \(change.target)") - } - if change.changed { try transaction.replace(change.url, content: nil, data: change.after) } - } - if writeState { - try store.stageDeclaration(declaration, in: transaction) - try transaction.replace( - store.resolvedURL, content: nil, data: StateStore.encodeState(next.normalized)) - } - try sources.cache.prune(referencedBy: next, transaction: transaction) - try transaction.commit() - } catch { - if let recovered = try? store.readResolved() { - try? sources.cache.prune(referencedBy: recovered) - } - throw error - } +extension InstructionOperations { + package static func inspectOwn(names: [String], environment: RuntimeEnvironment) throws + -> [InstructionUnit] + { + let sources = InstructionSources(store: StateStore(scope: .project, environment: environment)) + return try names.isEmpty ? sources.own() : names.map(sources.own(named:)) } +} - static func operate( - _ store: StateStore, apply: Bool, _ body: (Declaration, ResolvedState) throws -> T - ) throws -> T { - if apply { - return try store.withLock { try body(store.readDeclaration(), store.readResolved()) } +extension InstructionOperations { + package static func inspectSource(_ source: SourceDeclaration, store: StateStore) throws + -> [InstructionUnit] + { + let policy = try SourcePolicySnapshot(store: store) + return try SourceResolutionSession.withTemporaryRead( + store: store, sourcePolicy: policy.effective + ) { session in + guard source.kind != .wellKnown else { + throw CoreError.unsupported("instructions require source files") + } + if try session.isGitSource(source) { + let units = try InstructionSources(store: store, resolutions: session).discover( + source, cacheSource: false) + try policy.validate() + return units + } + let view = try session.localSnapshot(source) + let units = try InstructionSnapshotReader.read(view).map { unit in + InstructionUnit( + record: LockedSection( + name: unit.name, source: view.snapshot.source, + revision: view.pin?.revision, version: view.pin?.version, + path: unit.path, hash: unit.section.hash), section: unit.section) + } + try policy.validate() + return units } - return try store.withReadLock { try body(store.readDeclaration(), store.readResolved()) } } +} - private static func sourceDeclaration(_ options: InstructionAddOptions, declaration: Declaration) - throws -> SourceDeclaration +extension InstructionOperations { + /// Includes the absent own container and explicitly selected leaves for file-event invalidation. + package static func ownReadLocations(names: [String] = [], environment: RuntimeEnvironment) + -> [URL] { - let argument = try SourceArgument(options.source) - guard argument.name == nil else { - throw CoreError.invalidSource("@skill: selects skills; pass section names separately") - } - let selection = try argument.selection( - in: declaration, requirement: options.sourceRequirement, path: options.path, - environment: options.environment) - return selection.applied(to: selection.source) + let directory = environment.projectDirectory.resolvingSymlinksInPath() + .appendingPathComponent(InstructionSources.ownContainer) + return [directory] + names.map { directory.appendingPathComponent($0 + ".md") } } } diff --git a/Sources/AgentsInstructions/InstructionPromptReadback.swift b/Sources/AgentsInstructions/InstructionPromptReadback.swift new file mode 100644 index 0000000..7b72d98 --- /dev/null +++ b/Sources/AgentsInstructions/InstructionPromptReadback.swift @@ -0,0 +1,18 @@ +import Foundation + +extension InstructionTargets { + /// Normalized bytes are used by the ledger. The byte range belongs to the original document. + package static func auditImportBlock(_ bytes: Data) throws + -> (normalized: Data, byteRange: Range)? + { + let document = try MarkdownDocument(bytes: bytes) + guard let block = try document.managedBlock() else { return nil } + let start = document.lines[.. SnapshotInstruction? + { + guard Declaration.isInstructionName(name) else { + throw CoreError.invalidSource("invalid instruction name: \(name)") + } + let root = try view.directory() + let container = + root.lastPathComponent == ".agent" ? "instructions" : InstructionSources.ownContainer + let file = root.appendingPathComponent(container).appendingPathComponent(name + ".md") + let path = try view.relativePath(file) + try InstructionSources.requireNoLinks(file, below: view.root) + guard FileManager.default.fileExists(atPath: file.path) else { return nil } + return try read(view, name: name, path: path) + } + + package static func read(_ view: SourceSnapshot, own: Bool = false) throws + -> [SnapshotInstruction] + { + let root = try view.directory() + let containers = + own + ? [root.lastPathComponent == ".agent" ? "instructions" : InstructionSources.ownContainer] + : InstructionSources.containers + var names = Set() + var result: [SnapshotInstruction] = [] + for container in containers { + let directory = root.appendingPathComponent(container) + for (name, file) in try InstructionSources.files(in: directory, tree: view.root) { + try Task.checkCancellation() + guard names.insert(name).inserted else { + throw CoreError.invalidSource("duplicate instruction name: \(name)") + } + let path = try view.relativePath(file) + result.append(try read(view, name: name, path: path)) + } + } + return result.sorted { $0.name < $1.name } + } + + package static func searchRoots(of path: String, name: String) -> [String] { + InstructionSources.containers.compactMap { container in + let unit = container + "/" + name + ".md" + if path == unit { return "." } + if path.hasSuffix("/" + unit) { return String(path.dropLast(unit.count + 1)) } + return nil + } + } + + package static func requireNoLinks(_ file: URL, in view: SourceSnapshot) throws { + try InstructionSources.requireNoLinks(file, below: view.root) + } + + private static func read(_ view: SourceSnapshot, name: String, path: String) throws + -> SnapshotInstruction + { + let bytes = try FileSystem.read(at: view.resource(path)) + let section = try Instructions.validateSource( + bytes, id: view.snapshot.source + ":" + name, allowRestrictions: true) + return SnapshotInstruction(name: name, path: path, bytes: bytes, section: section) + } +} diff --git a/Sources/AgentsInstructions/InstructionSourceDiagnostics.swift b/Sources/AgentsInstructions/InstructionSourceDiagnostics.swift index 63813c6..8c23f8d 100644 --- a/Sources/AgentsInstructions/InstructionSourceDiagnostics.swift +++ b/Sources/AgentsInstructions/InstructionSourceDiagnostics.swift @@ -2,15 +2,18 @@ import AgentsCore import Foundation enum InstructionSourceDiagnostics { - static func inspect(store: StateStore, declaration: Declaration, lock: ResolvedState) + static func inspect( + store: StateStore, declaration: Declaration, lock: ResolvedState, + sourcePolicy: EffectiveSourcePolicy, bundledSources: Set + ) -> [InstructionDiagnostic] { var diagnostics: [InstructionDiagnostic] = [] - let cache = SourceCache(store: store) + 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 else { continue } + guard !pins.isEmpty, !bundledSources.contains(id) else { continue } let root = source.kind == .local ? URL(fileURLWithPath: String(id.dropFirst("local:".count))) : nil do { diff --git a/Sources/AgentsInstructions/InstructionSources.swift b/Sources/AgentsInstructions/InstructionSources.swift index 66fbcc6..f3ec837 100644 --- a/Sources/AgentsInstructions/InstructionSources.swift +++ b/Sources/AgentsInstructions/InstructionSources.swift @@ -21,12 +21,6 @@ final class InstructionSources { cache = SourceCache(store: store) } - func lockedSource(_ source: SourceDeclaration) -> LockedSource { - LockedSource( - kind: source.kind, url: source.kind == .git ? source.gitURL : nil, - requirement: source.requirement, path: source.path) - } - func discover(_ source: SourceDeclaration, cacheSource: Bool = true) throws -> [InstructionUnit] { let id = try source.identity(environment: store.environment) if let units = discovered[id] { return units } @@ -49,7 +43,8 @@ final class InstructionSources { for container in Self.containers { let directory = root.appendingPathComponent(container) for (name, file) in try Self.files(in: directory, tree: tree) { - let section = try Instructions.validateSource(Data(contentsOf: file), id: id + ":" + name) + let section = try Instructions.validateSource( + FileSystem.read(at: file), id: id + ":" + name) units.append( InstructionUnit( record: LockedSection( @@ -77,7 +72,7 @@ final class InstructionSources { let directory = project.appendingPathComponent(Self.ownContainer) let units = try Self.unique( Self.files(in: directory, tree: project).map { name, file in - let section = try Instructions.validateSource(Data(contentsOf: file), id: name) + let section = try Instructions.validateSource(FileSystem.read(at: file), id: name) return InstructionUnit( record: LockedSection( name: name, source: Self.own, @@ -100,87 +95,52 @@ final class InstructionSources { guard Declaration.isInstructionName(name), FileManager.default.fileExists(atPath: file.path) else { throw CoreError.notFound("own instructions file: \(name)") } try Self.requireNoLinks(file, below: project) - let section = try Instructions.validateSource(Data(contentsOf: file), id: name) + let section = try Instructions.validateSource(FileSystem.read(at: file), id: name) return InstructionUnit( record: LockedSection(name: name, source: Self.own, path: path, hash: section.hash), section: section) } - func resolve( - references: [String], declaration: Declaration, lock: inout ResolvedState - ) throws -> [InstructionUnit] { - try references.map { reference in - guard let (alias, name) = Self.split(reference) else { - return try own(named: reference) - } - guard let source = declaration.sources[alias] else { - throw CoreError.invalidState("invalid instruction reference: \(reference)") - } - guard let unit = try discover(source).first(where: { $0.record.name == name }) else { - throw CoreError.notFound("instruction section: \(reference)") - } - lock.sources[unit.record.source] = lockedSource(source) - return unit - } - } - - func restore( - _ records: [LockedSection], sources: [String: LockedSource], cachedOnly: Bool = false - ) throws - -> [InstructionUnit] - { - try records.map { record in - if record.source == Self.own { - guard let unit = try? own(named: record.name), unit.record.path == record.path, - unit.record.hash == record.hash - else { throw InstructionError.ownChanged(name: record.name) } - return unit - } - guard let source = sources[record.source], let revision = record.revision, - source.kind != .wellKnown - else { throw CoreError.invalidState("instruction section requires a locked Git revision") } - let key = record.source + "\n" + revision + "\n" + record.path - let section: InstructionSection - if let existing = restored[key] { - section = existing - } else { - let materialized = cache.materializedURL(sourceID: record.source, revision: revision) - try cache.validatePath(materialized) - func read(_ root: URL) throws -> InstructionSection { - let file = try PathSafety.resolvedChild(base: root, subpath: record.path) - try Self.contained(file, in: root) - return try Instructions.validateSource(Data(contentsOf: file), id: Self.identity(record)) + /// 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") } - if FileManager.default.fileExists(atPath: materialized.path) { - section = try read(materialized) - } else { - guard !cachedOnly else { - throw CoreError.notFound("locked instruction cache: \(record.name)") - } - section = try cache.withSnapshot( - sourceID: record.source, source: source, revision: revision, read) - } - restored[key] = section - } - guard section.hash == record.hash else { - throw CoreError.invalidState("locked instruction digest mismatch: \(record.name)") - } - return InstructionUnit(record: record, section: section) - } - } - - func retain(_ lock: ResolvedState) throws { - let records = lock.instructions.sections + lock.instructions.chatgpt.values.flatMap(\.sections) - for record in records where record.source != Self.own { - guard let source = lock.sources[record.source], let revision = record.revision else { - throw CoreError.invalidState("missing instruction pin") - } - let root = try cache.materialize(sourceID: record.source, source: source, revision: revision) - let file = try PathSafety.resolvedChild(base: root, subpath: record.path) - try Self.contained(file, in: root) - guard Instructions.hash(try Data(contentsOf: file)) == record.hash else { - throw CoreError.invalidState("cached instruction digest mismatch: \(record.name)") + 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 } } @@ -200,7 +160,7 @@ final class InstructionSources { } /// Rejects a symbolic link at `url` or at any directory between `tree` and it. - private static func requireNoLinks(_ url: URL, below tree: URL) throws { + static func requireNoLinks(_ url: URL, below tree: URL) throws { var cursor = tree for component in PathSafety.relativePath(url.path, to: tree.path).split(separator: "/") { cursor.appendPathComponent(String(component)) @@ -214,7 +174,7 @@ final class InstructionSources { /// The `.md` files below a container, by name, except the target names `AGENTS.md` and /// `GEMINI.md`, which a project may generate there. Symbolic links and invalid names are errors. - private static func files(in directory: URL, tree: URL) throws -> [(String, URL)] { + static func files(in directory: URL, tree: URL) throws -> [(String, URL)] { guard FileManager.default.fileExists(atPath: directory.path) else { return [] } try contained(directory, in: tree) try requireNoLinks(directory, below: tree) diff --git a/Sources/AgentsInstructions/InstructionTargets.swift b/Sources/AgentsInstructions/InstructionTargets.swift index 12a5971..5c73e92 100644 --- a/Sources/AgentsInstructions/InstructionTargets.swift +++ b/Sources/AgentsInstructions/InstructionTargets.swift @@ -1,16 +1,21 @@ import AgentsCore import Foundation -struct InstructionTargets { +package struct InstructionTargets { + package init(store: StateStore) { self.store = store } let store: StateStore /// Plans every generated target from `sections` in declared order, the Claude import, and the /// removal of targets that no longer receive sections. `restoring` keeps the locked targets, /// recipients and Claude imports, and requires each rendering to match its locked hash. - func plan( + package func plan( sections: [InstructionSection], agents: [AgentID], previous: LockedInstructions, restoring: Bool = false - ) throws -> (targets: [String: LockedTarget], changes: [InstructionTargetChange]) { + ) throws -> ( + targets: [String: LockedTarget], changes: [InstructionTargetChange], + expectations: [String: TargetPrecondition] + ) { + var expectations: [String: TargetPrecondition] = [:] var targets: [String: LockedTarget] = [:] var rendered: [String: String] = [:] if !sections.isEmpty { @@ -43,16 +48,26 @@ struct InstructionTargets { } } if !restoring, store.scope == .project, recipients.contains(.claudeCode), - targets["AGENTS.md"] != nil, let path = try forwardingPath() + targets["AGENTS.md"] != nil { - let file = store.environment.projectDirectory.appendingPathComponent(path.rawValue) - let key = InstructionLocations.key(for: InstructionLocations.physical(file), store: store) - guard targets[key] == nil else { - throw CoreError.invalidState("forwarding overlaps an instruction target") + for path in ClaudeInstructionPath.allCases { + let file = store.environment.projectDirectory.appendingPathComponent(path.rawValue) + expectations[file.path] = try TargetPrecondition(file) + let physical = file.resolvingSymlinksInPath() + if physical.path != file.path { + expectations[physical.path] = try TargetPrecondition(physical) + } + } + if let path = try forwardingPath() { + let file = store.environment.projectDirectory.appendingPathComponent(path.rawValue) + let key = InstructionLocations.key(for: InstructionLocations.physical(file), store: store) + guard targets[key] == nil else { + throw CoreError.invalidState("forwarding overlaps an instruction target") + } + targets[key] = LockedTarget( + agents: [.claudeCode], import: String(path.importLine.dropFirst()), blockHash: "", + created: false) } - targets[key] = LockedTarget( - agents: [.claudeCode], import: String(path.importLine.dropFirst()), blockHash: "", - created: false) } } if restoring { @@ -65,7 +80,16 @@ struct InstructionTargets { var problems: [InstructionLinkProblem] = [] for key in Set(previous.targets.keys).union(targets.keys).sorted() { let file = try InstructionLocations.file(for: key, store: store) - let before = try Self.read(file) + let input = try TargetPrecondition.readingFile(file) + let before = input.bytes + if let earlier = expectations[file.path] { + guard earlier.sameGeneration(as: input.evidence) else { + throw CoreError.invalidState( + "instruction target changed during preparation: \(file.path)") + } + } else { + expectations[file.path] = input.evidence + } let old = previous.targets[key] var after: Data? var foreign = false @@ -116,7 +140,8 @@ struct InstructionTargets { afterAgents: targets[key]?.agents ?? [], drift: drift, foreign: foreign)) } guard problems.isEmpty else { throw InstructionError.invalidLinks(problems) } - return (targets, changes) + for evidence in expectations.values { try evidence.validate() } + return (targets, changes, expectations) } /// The file an agent reads for sections placed in `directory`, or nil when the agent has no file. @@ -174,6 +199,16 @@ struct InstructionTargets { } } + /// Checks frozen rendered output against its receiving checkout, not mutable authoring input. + package func validateRenderedLinks(_ bytes: Data, at file: URL) throws { + guard let text = String(data: bytes, encoding: .utf8) else { + throw InstructionError.invalidLockedBlock + } + let problems = linkProblems( + in: text, file: file, key: InstructionLocations.key(for: file, store: store)) + guard problems.isEmpty else { throw InstructionError.invalidLinks(problems) } + } + /// Links in a rendered target that do not resolve, from the target file, to a regular file in /// the checkout being written. User targets belong to no checkout, so every local link fails. func linkProblems(in text: String, file: URL, key: String) -> [InstructionLinkProblem] { @@ -260,7 +295,7 @@ struct InstructionTargets { } /// Rejects targets inside an instructions container of a local source. - static func validateSourceDirectories( + package static func validateSourceDirectories( _ changes: [InstructionTargetChange], sources: [String: LockedSource] ) throws { for source in sources where source.value.kind == .local { @@ -288,10 +323,16 @@ struct InstructionTargets { guard try file.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile == true else { throw CoreError.unsafePath("instruction target is not a regular file: \(file.path)") } - return try Data(contentsOf: file) + return try FileSystem.read(at: file) + } + + package static func ownedImportBytes(_ bytes: Data?) throws -> Data? { + guard let bytes else { return nil } + let document = try MarkdownDocument(bytes: bytes) + return try document.managedBlock().map { Data(document.normalized($0).utf8) } } - private static func importBlock(in bytes: Data, at path: ClaudeInstructionPath) throws + package static func importBlock(in bytes: Data, at path: ClaudeInstructionPath) throws -> (bytes: Data, blockHash: String) { let document = try MarkdownDocument(bytes: bytes) diff --git a/Sources/AgentsInstructions/InstructionUpdatePlan.swift b/Sources/AgentsInstructions/InstructionUpdatePlan.swift deleted file mode 100644 index 327e62b..0000000 --- a/Sources/AgentsInstructions/InstructionUpdatePlan.swift +++ /dev/null @@ -1,72 +0,0 @@ -import AgentsCore -import Foundation - -/// Assembly and retention inputs for one scope generation; the caller owns commit and pruning. -package final class InstructionUpdatePlan { - package let next: ResolvedState - package let report: InstructionUpdateReport - private let sources: InstructionSources - private let identities: [PathIdentity] - private let forwardingInputs: [(URL, Data?)] - private let replace: Bool - - init( - next: ResolvedState, report: InstructionUpdateReport, sources: InstructionSources, - replace: Bool - ) throws { - self.next = next - self.report = report - self.sources = sources - self.replace = replace - let store = sources.store - var paths = report.targets.map(\.url) - for agent in Set(report.targets.flatMap { ($0.beforeAgents ?? []) + $0.afterAgents }) { - if let logical = InstructionLocations.file( - for: agent, scope: store.scope, environment: store.environment) - { - paths.append(logical) - } - } - if store.scope == .project, - next.instructions.targets.values.contains(where: { $0.agents.contains(.claudeCode) }) - { - let candidates = ClaudeInstructionPath.allCases.map { - store.environment.projectDirectory.appendingPathComponent($0.rawValue) - } - paths.append(contentsOf: candidates) - forwardingInputs = try candidates.map { url in - let resolved = url.resolvingSymlinksInPath() - paths.append(resolved) - return (resolved, try InstructionTargets.read(resolved)) - } - } else { - forwardingInputs = [] - } - identities = try paths.map { try PathIdentity($0) } - } - - package func validate() throws { - if !replace { try InstructionOperations.requireOwnership(report) } - for identity in identities { try identity.validate() } - for (url, bytes) in forwardingInputs { - guard try InstructionTargets.read(url) == bytes else { - throw CoreError.invalidState("Claude forwarding changed during preparation: \(url.path)") - } - } - for change in report.targets { - guard try InstructionTargets.read(change.url) == change.before else { - throw CoreError.invalidState( - "instruction target changed during preparation: \(change.target)") - } - } - try InstructionTargets.validateSourceDirectories(report.targets, sources: next.sources) - } - - package func retain() throws { try sources.retain(next) } - - package func stage(transaction: FileTransaction) throws { - for change in report.targets.sorted(by: { $0.url.path < $1.url.path }) where change.changed { - try transaction.replace(change.url, content: nil, data: change.after) - } - } -} diff --git a/Sources/AgentsInstructions/Instructions.swift b/Sources/AgentsInstructions/Instructions.swift index 4206959..71d1cf2 100644 --- a/Sources/AgentsInstructions/Instructions.swift +++ b/Sources/AgentsInstructions/Instructions.swift @@ -11,6 +11,12 @@ public enum Instructions { /// Validates an instructions file: front matter, a body that starts with an ATX heading whose /// level every other heading exceeds, and an end outside code and HTML blocks. public static func validateSource(_ bytes: Data, id: String) throws -> InstructionSection { + try validateSource(bytes, id: id, allowRestrictions: false) + } + + package static func validateSource(_ bytes: Data, id: String, allowRestrictions: Bool) throws + -> InstructionSection + { guard String(data: bytes, encoding: .utf8) != nil else { throw InstructionError.invalidUTF8 } func invalid(_ reason: String) -> InstructionError { .invalidSource(id: id, reason: reason) } var text = String(decoding: bytes, as: UTF8.self) @@ -21,7 +27,8 @@ public enum Instructions { } let front: InstructionFrontMatter do { - front = try InstructionFrontMatter.parse(Array(lines[1.. String { "sha256:" + FileHash.sha256Hex(data: bytes) } + package static func hash(_ bytes: Data) -> String { "sha256:" + FileHash.sha256Hex(data: bytes) } static func patternProblem(_ pattern: String) -> String? { guard !pattern.isEmpty, !pattern.hasPrefix("/") else { return "must be project-relative." } diff --git a/Sources/AgentsManifest/DeclarationDocument.swift b/Sources/AgentsManifest/DeclarationDocument.swift new file mode 100644 index 0000000..7e970c8 --- /dev/null +++ b/Sources/AgentsManifest/DeclarationDocument.swift @@ -0,0 +1,85 @@ +import AgentsCore +import Foundation + +/// A fully admitted, schema-checked and domain-valid immutable YAML declaration snapshot. +public struct DeclarationDocument: Sendable { + public let declaration: DeclarationIR + public let diagnostics: [ManifestDiagnostic] + public let sourceMap: DeclarationSourceMap + public let digest: String + public var bytes: [UInt8] { source.bytes } + package let metrics: FrontEndMetrics + let source: SourceText + let root: YAMLNode + let locations: [String: YAMLNode] + let defaulted: Set + let comments: [Range] + + public init(bytes: [UInt8], identity: DocumentIdentity) throws { + try self.init(bytes: bytes, identity: identity, validateDomain: true) + } + + /// Private drafts remain parser/schema/budget checked; only the edit composer can construct + /// them, and it validates the complete final domain before any bytes leave preparation. + init( + bytes: [UInt8], identity: DocumentIdentity, validateDomain: Bool, + observe: ((FrontEndStage, FrontEndMetrics) -> Void)? = nil + ) throws { + source = SourceText(Array(bytes.prefix(ManifestLimits.Input.bytes + 1)), identity: identity) + let parsed = try YAMLParser.parse(source, observe: observe) + let validation = YAMLValidation(source: source) + do { try validation.validate(parsed.root) } catch let failure as ManifestFailure { + throw ManifestFailure(failure.diagnostics, metrics: parsed.metrics, stage: .decoding) + } + observe?(.lowering, parsed.metrics) + let projection = YAMLProjection(source: source) + declaration = try projection.declaration(parsed.root) + try validateIRBudget(IRTree.root(declaration), source: source) + observe?(.domain, parsed.metrics) + var diagnostics: [ManifestDiagnostic] = [] + if validateDomain { + do { + diagnostics = try YAMLDomainValidation( + declaration: declaration, source: source, locations: projection.locations + ).validate() + } catch let failure as ManifestFailure { + throw ManifestFailure(failure.diagnostics[0], metrics: parsed.metrics, stage: .domain) + } + } + defaulted = Set(projection.entries.filter(\.defaulted).map(\.pointer)) + comments = parsed.comments + root = parsed.root + locations = projection.locations + sourceMap = DeclarationSourceMap(entries: projection.entries) + digest = "sha256:" + FileHash.sha256Hex(data: Data(bytes)) + self.diagnostics = diagnostics + var metrics = parsed.metrics + metrics.parserCalls = 1 + metrics.syntaxNodes = parsed.nodes + metrics.syntaxDepth = parsed.depth + metrics.evaluationSteps = validation.work + metrics.expandedNodes = IRTree.count(IRTree.root(declaration)) + metrics.decodedBytes = validation.strings + observe?(.sourceMap, metrics) + self.metrics = metrics + } + + /// JSON Pointers address complete semantic IR, including indexed sources, groups and prompts. + public func node(at pointer: String) -> NodeID? { + locations[pointer].map { NodeID(digest: digest, pointer: pointer, syntax: $0.range.lowerBound) } + } + + public func editability(of node: NodeID) -> Editability { + guard node.digest == digest, locations[node.pointer]?.range.lowerBound == node.syntax else { + return .readOnly(reason: "stale snapshot handle") + } + if node.pointer.hasSuffix("/kind") { + return .readOnly(reason: "record kind; replace its containing value") + } + return .direct + } + + public func preparing(_ edits: [ManifestEdit]) throws -> DocumentChange { + try DocumentEditor(document: self).prepare(edits) + } +} diff --git a/Sources/AgentsManifest/DeclarationEditPlan.swift b/Sources/AgentsManifest/DeclarationEditPlan.swift new file mode 100644 index 0000000..e9eb5d9 --- /dev/null +++ b/Sources/AgentsManifest/DeclarationEditPlan.swift @@ -0,0 +1,88 @@ +import AgentsCore + +package enum DeclarationEditPlan { + package static func bytes( + replacing previous: Declaration, with next: Declaration, in bytes: [UInt8]?, + identity: DocumentIdentity, environment: RuntimeEnvironment + ) throws -> [UInt8]? { + try next.validate(environment: environment) + guard let bytes else { + if ManifestProjection.equivalent(previous, next, environment: environment) { return nil } + let ir = YAMLConstruction.root(next) + try validateIRBudget(IRTree.root(ir), source: SourceText([], identity: identity)) + let output = YAMLWriter.manifest(ir) + let document = try DeclarationDocument(bytes: output, identity: identity) + guard + ManifestProjection.equivalent( + try ManifestProjection.declaration(of: document, environment: environment), next, + environment: environment) + else { + throw document.source.failure( + "manifest.edit.mismatch", "constructed declaration differs from intended domain", 0) + } + return output + } + let original = try DeclarationDocument(bytes: bytes, identity: identity) + let current = try ManifestProjection.declaration(of: original, environment: environment) + guard ManifestProjection.equivalent(current, previous, environment: environment) else { + throw original.source.failure( + "manifest.edit.baseline", "declaration changed during preparation", 0) + } + if ManifestProjection.equivalent(current, next, environment: environment) { return nil } + var target = next + // Retained sources preserve their spelling and comments when identity, requirement and + // subpath agree in their declaring environments. Their authored order still participates. + for index in target.sourceDeclarations.indices { + if let old = current.sourceDeclarations.first(where: { + $0.name == target.sourceDeclarations[index].name + }), + ManifestProjection.equivalent( + old.source, target.sourceDeclarations[index].source, environment: environment) + { + target.sourceDeclarations[index].source = old.source + } + } + let intended = IRTree.root(YAMLConstruction.root(target)) + let initial = IRTree.root(original.declaration) + var diff = IRDiff() + try diff.compare(initial, intended) + return try compose( + diff.edits, original: original, intended: intended, next: next, environment: environment) + } + + static func compose( + _ edits: [IREdit], original: DeclarationDocument, intended: DeclarationValue, next: Declaration, + environment: RuntimeEnvironment + ) throws -> [UInt8] { + let initial = IRTree.root(original.declaration) + // The direct script fixes target positions/fields once. Its length is bounded by the two + // admitted IR structures, independently of how batches are sized or sources transition. + let peakNodes = IRTree.count(initial) + IRTree.count(intended) + let maximum = 2 * peakNodes + guard edits.count <= maximum else { + throw original.source.failure("manifest.limit", "edit composition bound", 0) + } + var currentDocument = original + var offset = 0 + while offset < edits.count { + let cost = 2 * peakNodes + 2 * ManifestLimits.Syntax.nodes + let count = min( + ManifestLimits.Editing.requests, max(1, ManifestLimits.Editing.steps / max(1, cost))) + let end = min(edits.count, offset + count) + currentDocument = try DocumentEditor.draft(Array(edits[offset.. DocumentChange { + guard edits.count <= ManifestLimits.Editing.requests else { + throw failure("manifest.limit", "edit request limit") + } + var current = document + var pointers: [String] = [] + var work = 0 + var comparisons = 0 + var handles = Dictionary(uniqueKeysWithValues: document.locations.keys.map { ($0, $0) }) + for edit in edits { + let requested = try operations(edit, in: current, handles: handles) + var operations: [IREdit] = [] + for request in requested { + if case .set(let pointer, let replacement?) = request, + let old = IRTree.value(IRTree.root(current.declaration), at: pointer) + { + var diff = IRDiff(comparisons: comparisons) + try diff.compare(old, replacement, at: pointer) + comparisons = diff.comparisons + operations += diff.edits + } else { + operations.append(request) + } + } + var offset = 0 + while offset < operations.count { + let end = min(operations.count, offset + ManifestLimits.Editing.requests) + let batch = try Self.draft(Array(operations[offset.. DraftBatch { + guard edits.count <= ManifestLimits.Editing.requests else { + throw document.source.failure("manifest.limit", "edit request limit", 0) + } + var work = 0 + return try draft(edits, in: document, work: &work) + } + + private static func draft(_ edits: [IREdit], in document: DeclarationDocument, work: inout Int) + throws -> DraftBatch + { + var current = document + var changed: [String] = [] + for edit in edits { + let old = IRTree.root(current.declaration) + let expected = edit.applying(to: old) + work += + IRTree.count(old) + IRTree.count(expected) + current.metrics.syntaxNodes + + current.comments.count + try validateIRBudget(expected, source: document.source) + guard work <= ManifestLimits.Editing.steps else { + throw document.source.failure("manifest.limit", "edit batch work steps", 0) + } + if IRTree.equivalent(expected, old) { continue } + let patches = try YAMLPatches(document: current).patches(for: edit, expected: expected) + var bytes = current.bytes + let sorted = patches.sorted { $0.range.lowerBound > $1.range.lowerBound } + var boundary = bytes.count + for patch in sorted { + guard patch.range.lowerBound >= 0, patch.range.upperBound <= boundary else { + throw document.source.failure("manifest.edit.mismatch", "overlapping edit patches", 0) + } + bytes.replaceSubrange(patch.range, with: patch.replacement) + boundary = patch.range.lowerBound + } + let next = try DeclarationDocument( + bytes: bytes, identity: document.source.identity, validateDomain: false) + guard IRTree.equivalent(IRTree.root(next.declaration), expected) else { + throw document.source.failure( + "manifest.edit.mismatch", "edit differs from full expected declaration", 0) + } + guard next.bytes != current.bytes else { + throw document.source.failure("manifest.edit.mismatch", "an edit batch made no progress", 0) + } + current = next + switch edit { + case .set(let pointer, _), .insert(let pointer, _, _), .remove(let pointer, _), + .move(let pointer, _, _): + changed.append(pointer) + case .relocate(let origin, _, let destination, _): changed += [origin, destination] + } + } + return DraftBatch(document: current, changedPointers: changed) + } + + static func change( + from original: DeclarationDocument, to final: DeclarationDocument, pointers: [String] + ) -> DocumentChange { + let a = original.bytes + let b = final.bytes + var first = 0 + while first < min(a.count, b.count) && a[first] == b[first] { first += 1 } + var tail = 0 + while tail < min(a.count, b.count) - first && a[a.count - tail - 1] == b[b.count - tail - 1] { + tail += 1 + } + let patches = + a == b + ? [] + : [ + SourcePatch( + range: first..<(a.count - tail), replacement: Array(b[first..<(b.count - tail)])) + ] + return DocumentChange( + originalDigest: original.digest, patches: patches, bytes: b, digest: final.digest, + expectedDeclaration: final.declaration, diagnostics: final.diagnostics, + delta: SemanticDelta(changedPointers: Array(Set(pointers)).sorted(by: utf8Less))) + } + + private func operations( + _ edit: ManifestEdit, in current: DeclarationDocument, handles: [String: String] + ) throws -> [IREdit] { + let root = IRTree.root(current.declaration) + func pointer(_ id: NodeID) throws -> String { + guard id.digest == document.digest, document.node(at: id.pointer) == id, + let mapped = handles[id.pointer], IRTree.value(root, at: mapped) != nil + else { throw failure("manifest.edit.stale", "stale snapshot handle") } + return mapped + } + func container(_ id: ContainerID, _ field: String) throws -> String { + switch id { + case .root: return "/" + field + case .group(let id): + let path = try pointer(id) + guard IRTree.value(root, at: path)?.record?.kind == "group" else { + throw failure("manifest.edit.readOnly", "expected a group occurrence") + } + return path + "/" + field + } + } + func index(_ position: InsertionPosition, in path: String) throws -> Int { + guard let values = IRTree.value(root, at: path)?.elements else { + throw failure("manifest.edit.readOnly", "expected an ordered collection") + } + switch position { + case .first: return 0 + case .last: return values.count + case .before(let id), .after(let id): + let target = try pointer(id) + guard target.hasPrefix(path + "/"), let i = Int(target.dropFirst(path.count + 1)), + i < values.count + else { throw failure("manifest.edit.stale", "position is outside collection") } + if case .after = position { return i + 1 } + return i + } + } + func upsert(_ path: String, _ value: DeclarationRecord) throws -> [IREdit] { + guard let values = IRTree.value(root, at: path)?.elements else { + throw failure("manifest.edit.readOnly", "expected a named collection") + } + if let index = values.firstIndex(where: { $0.record?["name"] == value["name"] }) { + return [.set(path + "/\(index)", .record(value))] + } + return [.insert(path, values.count, .record(value))] + } + func removeNamed(_ path: String, _ name: String) throws -> [IREdit] { + guard let values = IRTree.value(root, at: path)?.elements else { + throw failure("manifest.edit.readOnly", "expected a named collection") + } + return values.firstIndex(where: { $0.record?["name"]?.string == name }).map { + [.remove(path, $0)] + } ?? [] + } + func remove(_ id: NodeID) throws -> [IREdit] { + let path = try pointer(id) + let slash = path.lastIndex(of: "/")! + guard let index = Int(path[path.index(after: slash)...]) else { + throw failure("manifest.edit.readOnly", "expected an occurrence") + } + let parent = String(path[.. [IREdit] { + let old = try pointer(id) + let slash = old.lastIndex(of: "/")! + let parent = String(old[.. from ? target - 1 : target)] } + return [.relocate(parent, from, path, target)] + } + switch edit { + case .setDefaultAgents(let agents): + return [.set("/defaultAgents", YAMLConstruction.agents(agents))] + case .upsertSource(let source): return try upsert("/sources", YAMLConstruction.source(source)) + case .replaceSource(let id, let replacement): + let path = try pointer(id) + let segments = IRTree.segments(path) + guard segments.count == 2, segments[0] == "sources", let index = Int(segments[1]), + current.declaration.sources.indices.contains(index) + else { throw failure("manifest.edit.readOnly", "expected a source occurrence") } + guard + !current.declaration.sources.enumerated().contains(where: { + $0.offset != index && $0.element["name"]?.string == replacement.name + }) + else { throw failure("manifest.domain", "duplicate source alias") } + let alias = current.declaration.sources[index]["name"]!.string! + return [.set(path, .record(YAMLConstruction.source(replacement)))] + + (alias == replacement.name + ? [] : SourceReferenceEdits.replacing(alias, with: replacement.name, in: root)) + case .removeSource(let alias): return try removeNamed("/sources", alias) + case .insertComponent(let value, let owner, let position): + let path = try container(owner, "components") + return try [ + .insert(path, index(position, in: path), .record(YAMLConstruction.component(value))) + ] + case .replaceComponent(let id, let value): + return try [.set(pointer(id), .record(YAMLConstruction.component(value)))] + case .removeComponent(let id), .removeSection(let id), .removeGroupReference(let id): + return try remove(id) + case .moveComponent(let id, let owner, let position): + return try move(id, into: container(owner, "components"), at: position) + case .setSkillSelection(let id, let value): + let owner = try pointer(id) + guard IRTree.value(root, at: owner)?.record?.kind == "skills" else { + throw failure("manifest.edit.readOnly", "expected a skills occurrence") + } + let path = owner + "/select" + switch value { + case .all: return [.set(path, .string("all"))] + case .names(let names): return [.set(path, YAMLConstruction.strings(names))] + } + case .upsertSkillOverride(let id, let value): + return try upsert(pointer(id) + "/overrides", YAMLConstruction.override(value)) + case .removeSkillOverride(let id, let name): + return try removeNamed(pointer(id) + "/overrides", name) + case .insertSection(let value, let id, let position): + let path = try pointer(id) + "/sections" + return try [ + .insert(path, index(position, in: path), .record(YAMLConstruction.section(value))) + ] + case .moveSection(let id, let position): + let path = try pointer(id) + let slash = path.lastIndex(of: "/")! + return try move(id, into: String(path[.. [String: String] { + var result: [String: String] = [:] + if case .relocate(let origin, let from, let destination, let to) = edit { + let prefix = origin + "/" + String(from) + let carried = handles.filter { $0.value == prefix || $0.value.hasPrefix(prefix + "/") } + let shifted = remap( + remap(handles, after: .remove(origin, from)), after: .insert(destination, to, .null)) + return shifted.merging( + carried.mapValues { destination + "/" + String(to) + $0.dropFirst(prefix.count) } + ) { _, value in value } + } + for (original, path) in handles { + switch edit { + case .set(let pointer, _): + if !path.hasPrefix(pointer + "/") { result[original] = path } + case .insert(let pointer, let index, _), .remove(let pointer, let index), + .move(let pointer, let index, _): + guard path.hasPrefix(pointer + "/") else { + result[original] = path + continue + } + let suffix = path.dropFirst(pointer.count + 1) + let segments = suffix.split(separator: "/", maxSplits: 1) + guard let current = Int(segments[0]) else { + result[original] = path + continue + } + let next: Int + switch edit { + case .insert: next = current >= index ? current + 1 : current + case .remove: + if current == index { continue } + next = current > index ? current - 1 : current + case .move(_, _, let to): + if current == index { + next = to + } else if index < to && current > index && current <= to { + next = current - 1 + } else if index > to && current >= to && current < index { + next = current + 1 + } else { + next = current + } + default: next = current + } + result[original] = + pointer + "/" + String(next) + (segments.count == 2 ? "/" + segments[1] : "") + case .relocate: break + } + } + return result + } + private func failure(_ code: String, _ message: String) -> ManifestFailure { + document.source.failure(code, message, 0) + } +} diff --git a/Sources/AgentsManifest/DocumentModels.swift b/Sources/AgentsManifest/DocumentModels.swift new file mode 100644 index 0000000..bcd8892 --- /dev/null +++ b/Sources/AgentsManifest/DocumentModels.swift @@ -0,0 +1,63 @@ +import AgentsCore + +/// An occurrence in one immutable document snapshot, never a persistent component identity. +public struct NodeID: Sendable, Hashable { + package let digest: String + package let pointer: String + package let syntax: Int +} + +public enum ContainerID: Sendable { + case root + case group(NodeID) +} +public enum InsertionPosition: Sendable { + case first, last + case before(NodeID) + case after(NodeID) +} +public enum Editability: Sendable, Equatable { + case direct + case readOnly(reason: String) +} + +/// Edits carry complete domain intent. They never contain parser nodes or source programs. +public enum ManifestEdit: Sendable { + case setDefaultAgents([AgentID]?) + case upsertSource(NamedSourceDeclaration) + /// Replaces one source in place and retargets its typed alias references. + case replaceSource(NodeID, with: NamedSourceDeclaration) + case removeSource(alias: String) + case insertComponent(ComponentDeclaration, into: ContainerID, at: InsertionPosition) + case replaceComponent(NodeID, with: ComponentDeclaration) + case removeComponent(NodeID) + case moveComponent(NodeID, into: ContainerID, at: InsertionPosition) + case setSkillSelection(NodeID, SkillSelection) + case upsertSkillOverride(NodeID, NamedSkillOverrideDeclaration) + case removeSkillOverride(NodeID, name: String) + case insertSection(SectionDeclaration, into: NodeID, at: InsertionPosition) + case removeSection(NodeID) + case moveSection(NodeID, at: InsertionPosition) + case upsertPrompt(NodeID, NamedPromptDeclaration) + case removePrompt(NodeID, name: String) + case upsertGroup(ComponentGroupDeclaration) + case removeGroup(name: String) + case insertGroupReference(GroupUseDeclaration, into: ContainerID, at: InsertionPosition) + case removeGroupReference(NodeID) + case setExports([String]) + case setWatch([String]) + case setLifecycle(DeclarationValue?) + case setDictionaryEntry(NodeID, key: String, value: NativeValue) + case removeDictionaryEntry(NodeID, key: String) +} + +public struct SemanticDelta: Sendable, Equatable { public let changedPointers: [String] } +public struct DocumentChange: Sendable { + public let originalDigest: String + public let patches: [SourcePatch] + public let bytes: [UInt8] + public let digest: String + public let expectedDeclaration: DeclarationIR + public let diagnostics: [ManifestDiagnostic] + public let delta: SemanticDelta +} diff --git a/Sources/AgentsManifest/IRTree.swift b/Sources/AgentsManifest/IRTree.swift new file mode 100644 index 0000000..e93ae17 --- /dev/null +++ b/Sources/AgentsManifest/IRTree.swift @@ -0,0 +1,269 @@ +import AgentsCore + +/// A single complete IR tree is used for edit intent and comparison; no mutable domain mirror +/// is retained alongside it. +enum IRTree { + static func root(_ ir: DeclarationIR) -> DeclarationValue { + var fields: [String: DeclarationValue] = [ + "defaultAgents": ir.defaultAgents.map(YAMLConstruction.strings) ?? .null, + "sources": .array(ir.sources.map(DeclarationValue.record)), + "packages": .array(ir.packages.map(DeclarationValue.record)), + "components": .array(ir.components.map(DeclarationValue.record)), + "groups": .array(ir.groups.map(DeclarationValue.record)), + "uses": .array(ir.uses.map(DeclarationValue.record)), + "exports": YAMLConstruction.strings(ir.exports), + "watch": YAMLConstruction.strings(ir.watch), + ] + fields["lifecycle"] = ir.lifecycle + return .record(DeclarationRecord(kind: "declaration", fields: fields)) + } + + static func equivalent(_ lhs: DeclarationValue, _ rhs: DeclarationValue) -> Bool { + lhs == rhs + && LifecycleDeclaration.equivalent(lhs.record?["lifecycle"], rhs.record?["lifecycle"]) + } + + static func declaration(_ root: DeclarationValue) -> DeclarationIR { + let f = root.record!.fields + func records(_ key: String) -> [DeclarationRecord] { f[key]!.elements!.map { $0.record! } } + func strings(_ key: String) -> [String] { f[key]!.elements!.map { $0.string! } } + return DeclarationIR( + defaultAgents: f["defaultAgents"]?.elements.map { $0.map { $0.string! } }, + exports: strings("exports"), sources: records("sources"), components: records("components"), + groups: records("groups"), uses: records("uses"), watch: strings("watch"), + packages: records("packages"), lifecycle: f["lifecycle"]) + } + static func segments(_ pointer: String) -> [String] { + guard !pointer.isEmpty else { return [] } + return pointer.dropFirst().split(separator: "/", omittingEmptySubsequences: false).map { + pointerUnescape(String($0)) + } + } + static func value(_ root: DeclarationValue, at pointer: String) -> DeclarationValue? { + var value = root + for key in segments(pointer) { + switch value { + case .record(let record): + guard let next = record[key] else { return nil } + value = next + case .dictionary(let fields): + guard let next = fields[key] else { return nil } + value = next + case .array(let items): + guard let index = Int(key), items.indices.contains(index) else { return nil } + value = items[index] + default: return nil + } + } + return value + } + static func replacing( + _ root: DeclarationValue, at pointer: String, with replacement: DeclarationValue? + ) -> DeclarationValue { + let keys = segments(pointer) + func update(_ value: DeclarationValue, _ depth: Int) -> DeclarationValue { + if depth == keys.count { return replacement ?? .null } + let key = keys[depth] + switch value { + case .record(let record): + var fields = record.fields + if depth + 1 == keys.count && replacement == nil { + fields.removeValue(forKey: key) + } else { + fields[key] = update(fields[key] ?? .null, depth + 1) + } + return .record(DeclarationRecord(kind: record.kind, fields: fields)) + case .dictionary(var fields): + if depth + 1 == keys.count && replacement == nil { + fields.removeValue(forKey: key) + } else { + fields[key] = update(fields[key] ?? .null, depth + 1) + } + return .dictionary(fields) + case .array(var values): + let index = Int(key)! + if depth + 1 == keys.count && replacement == nil { + values.remove(at: index) + } else { + values[index] = update(values[index], depth + 1) + } + return .array(values) + default: preconditionFailure("checked IR pointer") + } + } + return update(root, 0) + } + static func count(_ value: DeclarationValue) -> Int { + switch value { + case .record(let record): return 1 + record.fields.values.reduce(0) { $0 + count($1) } + case .dictionary(let fields): return 1 + fields.values.reduce(0) { $0 + count($1) } + case .array(let values): return 1 + values.reduce(0) { $0 + count($1) } + default: return 1 + } + } +} + +enum IREdit { + case set(String, DeclarationValue?) + case insert(String, Int, DeclarationValue) + case remove(String, Int) + case move(String, Int, Int) + case relocate(String, Int, String, Int) + + func applying(to root: DeclarationValue) -> DeclarationValue { + switch self { + case .set(let pointer, let value): return IRTree.replacing(root, at: pointer, with: value) + case .insert(let pointer, let index, let value): + var values = IRTree.value(root, at: pointer)!.elements! + values.insert(value, at: index) + return IRTree.replacing(root, at: pointer, with: .array(values)) + case .remove(let pointer, let index): + var values = IRTree.value(root, at: pointer)!.elements! + values.remove(at: index) + return IRTree.replacing(root, at: pointer, with: .array(values)) + case .relocate(let source, let from, let destination, let to): + let value = IRTree.value(root, at: source)!.elements![from] + let removed = IREdit.remove(source, from).applying(to: root) + return IREdit.insert(destination, to, value).applying(to: removed) + case .move(let pointer, let from, let to): + var values = IRTree.value(root, at: pointer)!.elements! + let value = values.remove(at: from) + values.insert(value, at: to) + return IRTree.replacing(root, at: pointer, with: .array(values)) + } + } +} + +/// Computes one direct script in comparable operation units. The script is finite: each array +/// step fixes the next target position or removes a surplus occurrence; each field is visited once. +struct IRDiff { + private(set) var comparisons = 0 + + init(comparisons: Int = 0) { self.comparisons = comparisons } + private(set) var edits: [IREdit] = [] + + mutating func compare(_ old: DeclarationValue, _ new: DeclarationValue, at pointer: String = "") + throws + { + if pointer == "/lifecycle" { + if !LifecycleDeclaration.equivalent(old, new) { edits.append(.set(pointer, new)) } + return + } + if try equal(old, new) { return } + switch (old, new) { + case (.record(let a), .record(let b)) + where a.kind == "package" && b.kind == "package" + && (a["version"] == nil) != (b["version"] == nil): + edits.append(.set(pointer, new)) + case (.record(let a), .record(let b)) where a.kind == b.kind: + try fields(a.fields, b.fields, at: pointer) + case (.dictionary(let a), .dictionary(let b)): try fields(a, b, at: pointer) + case (.array(var a), .array(let b)): + for index in b.indices { + if index >= a.count { + edits.append(.insert(pointer, index, b[index])) + a.insert(b[index], at: index) + continue + } + if try equal(a[index], b[index]) { continue } + var exact: Int? + var matches: [Int] = [] + for candidate in a.indices.dropFirst(index + 1) { + if try equal(a[candidate], b[index]) { + exact = candidate + break + } + if identity(a[candidate]) != nil && identity(a[candidate]) == identity(b[index]) { + matches.append(candidate) + } + } + let sameIdentity = identity(a[index]) != nil && identity(a[index]) == identity(b[index]) + if exact == nil && !sameIdentity && matches.count > 1 { + throw ManifestFailure( + ManifestDiagnostic( + code: "manifest.ambiguous", message: "ambiguous matching occurrences", + span: SourceSpan( + document: DocumentIdentity("manifest"), start: 0, end: 0, line: 1, column: 1))) + } + if let match = exact ?? (sameIdentity ? nil : matches.first) { + edits.append(.move(pointer, match, index)) + a.insert(a.remove(at: match), at: index) + } else if !sameIdentity { + var retained = false + for later in b.indices.dropFirst(index + 1) { + if try equal(a[index], b[later]) { + retained = true + break + } + if identity(a[index]) != nil && identity(a[index]) == identity(b[later]) { + retained = true + break + } + } + if retained { + edits.append(.insert(pointer, index, b[index])) + a.insert(b[index], at: index) + continue + } + } + try compare(a[index], b[index], at: pointer + "/\(index)") + a[index] = b[index] + } + while a.count > b.count { + edits.append(.remove(pointer, a.count - 1)) + a.removeLast() + } + default: edits.append(.set(pointer, new)) + } + } + private mutating func fields( + _ old: [String: DeclarationValue], _ new: [String: DeclarationValue], at pointer: String + ) throws { + for key in Set(old.keys).union(new.keys).sorted(by: utf8Less) { + let path = pointer + "/" + pointerEscape(key) + if let a = old[key], let b = new[key] { + try compare(a, b, at: path) + } else { + edits.append(.set(path, new[key])) + } + } + } + private mutating func equal(_ lhs: DeclarationValue, _ rhs: DeclarationValue) throws -> Bool { + var pending = [(lhs, rhs)] + while let (a, b) = pending.popLast() { + comparisons += 1 + guard comparisons <= ManifestLimits.Editing.comparisonPairs else { throw limit() } + switch (a, b) { + case (.record(let x), .record(let y)): + guard x.kind == y.kind, x.fields.keys == y.fields.keys else { return false } + if x.kind == "declaration", !LifecycleDeclaration.equivalent(x["lifecycle"], y["lifecycle"]) + { + return false + } + for key in x.fields.keys.sorted(by: utf8Less) { + pending.append((x.fields[key]!, y.fields[key]!)) + } + case (.dictionary(let x), .dictionary(let y)): + guard x.keys == y.keys else { return false } + for key in x.keys.sorted(by: utf8Less) { pending.append((x[key]!, y[key]!)) } + case (.array(let x), .array(let y)): + guard x.count == y.count else { return false } + pending += zip(x, y) + default: if a != b { return false } + } + } + return true + } + private func identity(_ value: DeclarationValue) -> String? { + guard let record = value.record else { return nil } + return record["name"]?.string.map { record.kind + ":" + $0 } + ?? (record.kind == "skills" ? record["source"]?.string.map { "skills:" + $0 } : nil) + } + private func limit() -> ManifestFailure { + ManifestFailure( + ManifestDiagnostic( + code: "manifest.limit", message: "edit comparison limit", + span: SourceSpan( + document: DocumentIdentity("manifest"), start: 0, end: 0, line: 1, column: 1))) + } +} diff --git a/Sources/AgentsManifest/JSONPointer.swift b/Sources/AgentsManifest/JSONPointer.swift new file mode 100644 index 0000000..53e8d03 --- /dev/null +++ b/Sources/AgentsManifest/JSONPointer.swift @@ -0,0 +1,17 @@ +import Foundation + +/// JSON Pointer segments escape tilde before slash; decoding reverses that order. +func pointerEscape(_ text: String) -> String { + text.replacingOccurrences(of: "~", with: "~0").replacingOccurrences(of: "/", with: "~1") +} + +func pointerUnescape(_ text: String) -> String { + text.replacingOccurrences(of: "~1", with: "/").replacingOccurrences(of: "~0", with: "~") +} + +func pointerSegments(_ pointer: String) -> [String] { + guard !pointer.isEmpty else { return [] } + return pointer.split(separator: "/", omittingEmptySubsequences: false).dropFirst().map { + pointerUnescape(String($0)) + } +} diff --git a/Sources/AgentsManifest/ManifestDiagnostic.swift b/Sources/AgentsManifest/ManifestDiagnostic.swift new file mode 100644 index 0000000..5bee25c --- /dev/null +++ b/Sources/AgentsManifest/ManifestDiagnostic.swift @@ -0,0 +1,74 @@ +import AgentsCore + +public struct ManifestDiagnostic: Sendable, Equatable { + public enum Severity: String, Sendable { case warning, error } + public let code: String + public let severity: Severity + public let message: String + public let span: SourceSpan + public let related: [SourceSpan] + public let fixIt: SourcePatch? + package var lifecycleIssue: LifecycleDeclarationIssue? + + public init( + code: String, severity: Severity = .error, message: String, span: SourceSpan, + related: [SourceSpan] = [], fixIt: SourcePatch? = nil + ) { + self.code = code + self.severity = severity + self.message = message + self.span = span + self.related = related + self.fixIt = fixIt + } +} + +public struct ManifestFailure: Error, Sendable { + public let diagnostics: [ManifestDiagnostic] + package let metrics: FrontEndMetrics + package let stage: FrontEndStage + package init( + _ diagnostic: ManifestDiagnostic, metrics: FrontEndMetrics = FrontEndMetrics(), + stage: FrontEndStage = .admission + ) { + self.init([diagnostic], metrics: metrics, stage: stage) + } + + package init( + _ diagnostics: [ManifestDiagnostic], metrics: FrontEndMetrics = FrontEndMetrics(), + stage: FrontEndStage = .admission + ) { + self.diagnostics = diagnostics + self.metrics = metrics + self.stage = stage + } +} + +public struct SourcePatch: Sendable, Equatable { + public let range: Range + public let replacement: [UInt8] + package init(range: Range, replacement: [UInt8]) { + self.range = range + self.replacement = replacement + } +} + +package struct FrontEndMetrics: Sendable, Codable { + package var parserCalls = 0 + package var parserCallbacks = 0 + package var syntaxNodes = 0 + package var syntaxDepth = 0 + package var evaluationSteps = 0 + package var expandedNodes = 0 + package var decodedBytes = 0 + package var admissionSeconds = 0.0 + package var parsingSeconds = 0.0 + package var guardSeconds = 0.0 + package var inspectionSeconds = 0.0 + package var evaluationSeconds = 0.0 + package var domainSeconds = 0.0 + package var loweringSeconds = 0.0 + package var sourceMapSeconds = 0.0 + package var teardownSeconds = 0.0 + package init() {} +} diff --git a/Sources/AgentsManifest/ManifestDump.swift b/Sources/AgentsManifest/ManifestDump.swift new file mode 100644 index 0000000..fcb647f --- /dev/null +++ b/Sources/AgentsManifest/ManifestDump.swift @@ -0,0 +1,120 @@ +import AgentsCore + +/// Complete local intent and semantic source coordinates. No source resolution occurs. +public struct ManifestDump: Sendable { + public struct Location: Sendable { + public let pointer: String + public let span: SourceSpan + public let origins: [SourceSpan] + public let defaulted: Bool + public let editability: ManifestJSONValue + } + public let schemaVersion = 2 + public let kind = "manifest" + public let format = "yaml" + public let manifestVersion = 1 + public let sourceDigest: String + public let declaration: ManifestJSONValue + public let locations: [Location] + public let diagnostics: [ManifestDiagnostic] + + public init(bytes: [UInt8]) throws { + try self.init( + document: DeclarationDocument(bytes: bytes, identity: DocumentIdentity("manifest"))) + } + public init(document: DeclarationDocument) throws { + sourceDigest = document.digest + let ir = document.declaration + var fields: [String: ManifestJSONValue] = [ + "defaultAgents": ir.defaultAgents.map { .array($0.map(ManifestJSONValue.string)) } ?? .null, + "sources": .array(ir.sources.map { Self.value(.record($0)) }), + "components": .array(ir.components.map { Self.value(.record($0)) }), + "groups": .array(ir.groups.map { Self.value(.record($0)) }), + "uses": .array(ir.uses.map { Self.value(.record($0)) }), + "exports": .array(ir.exports.map(ManifestJSONValue.string)), + "watch": .array(ir.watch.map(ManifestJSONValue.string)), + ] + if let lifecycle = ir.lifecycle { fields["lifecycle"] = Self.value(lifecycle) } + if !ir.packages.isEmpty { + fields["packages"] = .array(ir.packages.map { Self.value(.record($0)) }) + } + declaration = .object(fields) + locations = document.sourceMap.entries.map { + let editability: ManifestJSONValue + if $0.pointer.hasSuffix("/kind") { + editability = .object([ + "kind": .string("readOnly"), + "reason": .string("record kind; replace its containing value"), + ]) + } else { + editability = .object(["kind": .string("direct")]) + } + return Location( + pointer: $0.pointer, span: Self.span($0.span), origins: $0.origins.map(Self.span), + defaulted: $0.defaulted, editability: editability) + }.sorted { utf8Less($0.pointer, $1.pointer) } + diagnostics = document.diagnostics.map { + ManifestDiagnostic( + code: $0.code, severity: $0.severity, message: $0.message, span: Self.span($0.span), + related: $0.related.map(Self.span)) + } + _ = try json.encodedCount(limit: ManifestLimits.Output.encodedBytes - 1) + } + public func encodedJSON() throws -> [UInt8] { try json.encodedJSON() } + + private var json: ManifestJSONValue { + .object([ + "schemaVersion": .integer(schemaVersion), "kind": .string(kind), "format": .string(format), + "manifestVersion": .integer(manifestVersion), "sourceDigest": .string(sourceDigest), + "declaration": declaration, + "locations": .array( + locations.map { + .object([ + "pointer": .string($0.pointer), "span": Self.spanJSON($0.span), + "origins": .array($0.origins.map(Self.spanJSON)), "defaulted": .boolean($0.defaulted), + "editability": $0.editability, + ]) + }), + "diagnostics": .array( + diagnostics.map { + .object([ + "code": .string($0.code), "severity": .string($0.severity.rawValue), + "message": .string($0.message), "span": Self.spanJSON($0.span), + "related": .array($0.related.map(Self.spanJSON)), + ]) + }), + ]) + } + private static func span(_ value: SourceSpan) -> SourceSpan { + SourceSpan( + document: DocumentIdentity("manifest"), start: value.start, end: value.end, line: value.line, + column: value.column) + } + private static func spanJSON(_ value: SourceSpan) -> ManifestJSONValue { + .object([ + "document": .string("manifest"), "start": .integer(value.start), "end": .integer(value.end), + "line": .integer(value.line), "column": .integer(value.column), + ]) + } + private static func value(_ value: DeclarationValue) -> ManifestJSONValue { + switch value { + case .string(let value): return .string(value) + case .integer(let value): return .integer(value) + case .boolean(let value): return .boolean(value) + case .null: return .null + case .array(let values): return .array(values.map(Self.value)) + case .dictionary(let values): return .object(values.mapValues(Self.value)) + case .record(let record): + return .object( + record.fields.mapValues(Self.value).merging(["kind": .string(record.kind)]) { _, value in + value + }) + case .requirement(let requirement): + var fields = [ + "kind": ManifestJSONValue.string(requirement.kind), "value": .string(requirement.value), + ] + if let upper = requirement.upperBound { fields["to"] = .string(upper) } + return .object(fields) + } + } +} diff --git a/Sources/AgentsManifest/ManifestExpansionBudget.swift b/Sources/AgentsManifest/ManifestExpansionBudget.swift new file mode 100644 index 0000000..a596dd3 --- /dev/null +++ b/Sources/AgentsManifest/ManifestExpansionBudget.swift @@ -0,0 +1,78 @@ +import AgentsCore + +/// One expanded declaration sequence, counting repeated references by occurrence. +/// The caller retains spent traversal work across rejected source selections. +package struct ManifestExpansionBudget { + package enum Failure: Error { case limit } + + private var total = ValueCost() + private var sourceMap = SourceMapBudget() + + package init() {} + + package mutating func consume( + _ record: DeclarationRecord, origins: [SourceSpan], locations: [SourceMapEntry], + spending: (Int) throws -> Void + ) throws { + var cost = try cost(.record(record), depth: 1, spending: spending) + guard origins.count <= ManifestLimits.SourceMap.origins else { throw Failure.limit } + // Reference origins are inherited by every descendant value location. + cost.origins = ValueCost.add(cost.origins, cost.nodes * origins.count) + total.append(cost) + guard total.fits, total.nodes <= ManifestLimits.SourceMap.locations else { + throw Failure.limit + } + for location in locations { + try spending(1 + location.origins.count + origins.count) + guard + sourceMap.consume( + pointer: location.pointer, span: location.span, + origins: location.origins + origins) + else { throw Failure.limit } + } + } + + private func cost( + _ value: DeclarationValue, depth: Int, spending: (Int) throws -> Void + ) throws -> ValueCost { + try spending(1) + guard depth < ManifestLimits.Values.depth else { throw Failure.limit } + let result: ValueCost + switch value { + case .string(let text): result = .scalar(text) + case .integer, .boolean, .null: result = ValueCost() + case .array(let values): + guard values.count <= ManifestLimits.Values.entries else { throw Failure.limit } + result = try .container(values.map { try cost($0, depth: depth + 1, spending: spending) }) + case .dictionary(let fields): + result = try fieldsCost(fields, depth: depth, spending: spending) + case .record(let record): + result = try fieldsCost( + record.fields, kind: record.kind, depth: depth, spending: spending) + case .requirement(let requirement): + var fields = [requirement.kind: DeclarationValue.string(requirement.value)] + if let upper = requirement.upperBound { fields["to"] = .string(upper) } + result = try fieldsCost(fields, depth: depth, spending: spending) + } + guard result.fits else { throw Failure.limit } + return result + } + + private func fieldsCost( + _ fields: [String: DeclarationValue], kind: String? = nil, depth: Int, + spending: (Int) throws -> Void + ) throws -> ValueCost { + guard fields.count <= ManifestLimits.Values.entries else { throw Failure.limit } + var children: [ValueCost] = [] + var keys = fields.keys.sorted() + if let kind { + try spending(1) + children.append(.scalar(kind)) + keys.append("kind") + } + for key in fields.keys.sorted() { + children.append(try cost(fields[key]!, depth: depth + 1, spending: spending)) + } + return .container(children, keys: keys) + } +} diff --git a/Sources/AgentsManifest/ManifestFrontEnd.swift b/Sources/AgentsManifest/ManifestFrontEnd.swift new file mode 100644 index 0000000..6cbc937 --- /dev/null +++ b/Sources/AgentsManifest/ManifestFrontEnd.swift @@ -0,0 +1,18 @@ +import AgentsCore + +package enum FrontEndStage: String, Sendable, Codable { + case admission, parser, decoding, domain, lowering, sourceMap, teardown +} +package enum FrontEndCheck: Sendable, Equatable { case syntax, declaration } +package enum ManifestFrontEnd { + package static func inspect( + bytes: [UInt8], identity: DocumentIdentity, checking: FrontEndCheck, + observe: ((FrontEndStage, FrontEndMetrics) -> Void)? = nil + ) throws -> FrontEndMetrics { + observe?(.admission, FrontEndMetrics()) + let document = try DeclarationDocument( + bytes: bytes, identity: identity, validateDomain: checking == .declaration, observe: observe) + observe?(.teardown, document.metrics) + return document.metrics + } +} diff --git a/Sources/AgentsManifest/ManifestJSONValue.swift b/Sources/AgentsManifest/ManifestJSONValue.swift new file mode 100644 index 0000000..7a03e36 --- /dev/null +++ b/Sources/AgentsManifest/ManifestJSONValue.swift @@ -0,0 +1,90 @@ +import AgentsCore + +/// JSON data for the evaluated manifest schema. Decimal configuration payloads remain strings. +public indirect enum ManifestJSONValue: Sendable, Equatable { + case string(String) + case integer(Int) + case boolean(Bool) + case null + case array([ManifestJSONValue]) + case object([String: ManifestJSONValue]) + + func encodedCount(limit: Int, budget: String = "encoded JSON output bytes") throws -> Int { + var count = 0 + try write(indentation: "") { text in + guard text.utf8.count <= limit - count else { + throw ManifestFailure( + ManifestDiagnostic( + code: "manifest.limit", message: budget, + span: SourceSpan( + document: DocumentIdentity("manifest"), start: 0, end: 0, line: 1, column: 1))) + } + count += text.utf8.count + } + return count + } + + func encodedJSON(limit: Int = ManifestLimits.Output.encodedBytes) throws -> [UInt8] { + let count = try encodedCount(limit: limit - 1) + var result = "" + result.reserveCapacity(count + 1) + try write(indentation: "") { result += $0 } + result += "\n" + return Array(result.utf8) + } + + private func write(indentation: String, emit: (String) throws -> Void) throws { + func string(_ text: String) throws { + try emit("\"") + for scalar in text.unicodeScalars { + switch scalar { + case "\"": try emit("\\\"") + case "\\": try emit("\\\\") + case "\n": try emit("\\n") + case "\r": try emit("\\r") + case "\t": try emit("\\t") + case "\u{8}": try emit("\\b") + case "\u{C}": try emit("\\f") + case "\0"..<" ": + let hex = String(scalar.value, radix: 16) + try emit("\\u" + String(repeating: "0", count: 4 - hex.count) + hex) + default: try emit(String(scalar)) + } + } + try emit("\"") + } + switch self { + case .null: try emit("null") + case .integer(let value): try emit(String(value)) + case .boolean(let value): try emit(value ? "true" : "false") + case .string(let value): try string(value) + case .array(let values): + if values.isEmpty { + try emit("[]") + return + } + try emit("[\n") + for (index, value) in values.enumerated() { + try emit(indentation + " ") + try value.write(indentation: indentation + " ", emit: emit) + try emit((index < values.count - 1 ? "," : "") + "\n") + } + try emit(indentation + "]") + case .object(let fields): + if fields.isEmpty { + try emit("{}") + return + } + try emit("{\n") + let keys = fields.keys.sorted(by: utf8Less) + for (index, key) in keys.enumerated() { + try emit(indentation + " ") + try string(key) + try emit(": ") + try fields[key]!.write(indentation: indentation + " ", emit: emit) + try emit((index < keys.count - 1 ? "," : "") + "\n") + } + try emit(indentation + "}") + } + } +} diff --git a/Sources/AgentsManifest/ManifestLimits.swift b/Sources/AgentsManifest/ManifestLimits.swift new file mode 100644 index 0000000..0c8060a --- /dev/null +++ b/Sources/AgentsManifest/ManifestLimits.swift @@ -0,0 +1,43 @@ +/// YAML declaration bounds, grouped by their owner in the manifest contract. +/// Counts are charged by occurrence, including unused definitions and repeated origins. +package enum ManifestLimits { + package enum Input { + package static let bytes = 2_097_152 + } + enum Syntax { + static let depth = 128 + static let nodes = 100_000 + } + enum Evaluation { + static let frames = 64 + static let steps = 100_000 + } + enum Values { + static let nodes = 100_000 + static let stringBytes = 16_777_216 + static let entries = 10_000 + static let depth = 64 + } + enum Domain { + static let steps = 100_000 + } + enum Groups { + static let activeReferences = 64 + } + enum SourceMap { + static let locations = 100_000 + static let origins = 1_000_000 + static let encodedBytes = 16_777_216 + } + enum Output { + static let encodedBytes = 33_554_432 + } + enum Editing { + static let comparisonPairs = 200_000 + static let steps = 1_000_000 + static let requests = 100 + } + enum Diagnostics { + static let warnings = 100 + } +} diff --git a/Sources/AgentsManifest/ManifestProjection.swift b/Sources/AgentsManifest/ManifestProjection.swift new file mode 100644 index 0000000..0580230 --- /dev/null +++ b/Sources/AgentsManifest/ManifestProjection.swift @@ -0,0 +1,411 @@ +import AgentsCore + +/// Static projection of the complete declaration. References and runtime bindings remain data; +/// this layer does not resolve sources, read resources or execute declared programs. +package enum ManifestProjection { + package static func declaration(of document: DeclarationDocument, environment: RuntimeEnvironment) + throws -> Declaration + { + let result = try draftDeclaration(of: document, environment: environment) + try result.validate(environment: environment) + return result + } + + /// Converts statically typed values without domain validation for private edit composition. + static func draftDeclaration(of document: DeclarationDocument, environment: RuntimeEnvironment) + throws -> Declaration + { + let projection = Projection(document: document) + let ir = document.declaration + let sources = ir.sources.map { record in + let kind: SourceKind = + record.kind == "git" ? .git : record.kind == "local" ? .local : .wellKnown + let location = record[kind == .git ? "url" : kind == .local ? "path" : "index"]!.string! + var requirement: SourceRequirement? + if case .requirement(let value) = record["requirement"] { requirement = value } + return NamedSourceDeclaration( + name: record["name"]!.string!, + source: SourceDeclaration( + kind: kind, location: location, requirement: requirement, path: record["subpath"]?.string, + environment: SourceEnvironment( + projectDirectory: environment.projectDirectory, homeDirectory: environment.homeDirectory + ))) + } + let exact = ir.packages.filter { $0["version"] != nil } + let requirements = ir.packages.filter { $0["requirement"] != nil } + let result = Declaration( + agents: ir.defaultAgents?.map { AgentID(rawValue: $0)! }, + sourceDeclarations: sources, + components: try ir.components.map(projection.component), + groups: try ir.groups.map { record in + ComponentGroupDeclaration( + name: record["name"]!.string!, + components: try projection.records(record["components"]).map(projection.component), + uses: projection.records(record["uses"]).map(projection.use), + condition: projection.condition(record["condition"])) + }, uses: ir.uses.map(projection.use), exports: ir.exports, + watch: ir.watch.isEmpty ? nil : ir.watch, packages: try exact.map(packageDependency), + marketplaceRoots: try requirements.map(marketplaceRoot), lifecycle: ir.lifecycle) + return result + } + + static func packageDependency(_ record: DeclarationRecord) throws -> MarketplaceDependency { + try MarketplaceDependency( + name: record["name"]!.string!, catalog: marketplaceOrigin(record["catalog"]), + coordinate: MarketplaceCoordinate( + package: record["package"]!.string!, version: record["version"]!.string!)) + } + + static func marketplaceRoot(_ record: DeclarationRecord) throws -> MarketplaceRoot { + guard case .requirement(let requirement) = record["requirement"] else { + throw MarketplaceError.invalidPackage("missing requirement") + } + return try MarketplaceRoot( + name: record["name"]!.string!, catalog: marketplaceOrigin(record["catalog"]), + package: record["package"]!.string!, requirement: requirement, + selections: (record["selections"]?.elements ?? []).map { value in + guard case .dictionary(let selection) = value, + case .dictionary(let member) = selection["member"] + else { throw MarketplaceError.invalidPackage("invalid selection") } + return try MarketplaceMemberSelection( + package: selection["package"]!.string!, + catalog: selection["catalog"].map(marketplaceOrigin), + member: MarketplaceMemberKey( + kind: DeclaredComponentKind(rawValue: member["kind"]!.string!)!, + name: member["name"]!.string!), + targets: selection["targets"]!.elements!.map { AgentID(rawValue: $0.string!)! }) + }) + } + + private static func marketplaceOrigin(_ value: DeclarationValue?) throws -> MarketplaceOrigin { + guard case .dictionary(let fields) = value else { + throw MarketplaceError.invalidOrigin("missing catalog") + } + return try MarketplaceOrigin( + kind: MarketplaceOrigin.Kind(rawValue: fields["kind"]!.string!)!, + location: fields["location"]!.string!, ref: fields["ref"]?.string, + subpath: fields["subpath"]?.string) + } + + /// Canonical intent of the imported sources and their selected producer groups. + package static func marketplaceContributionBytes( + _ declaration: Declaration, aliases: Set + ) -> [UInt8] { + YAMLWriter.manifest( + YAMLConstruction.root( + Declaration( + sourceDeclarations: declaration.sourceDeclarations.filter { aliases.contains($0.name) }, + uses: declaration.uses.filter { $0.source.map(aliases.contains) ?? false }))) + } + + /// Source spelling is compared using its declaring directories. All ordered structures and + /// every component field participate; absent recipients remain distinct from explicit empty. + package static func equivalent( + _ lhs: Declaration, _ rhs: Declaration, environment: RuntimeEnvironment + ) -> Bool { + guard lhs.packages == rhs.packages, lhs.marketplaceRoots == rhs.marketplaceRoots, + LifecycleDeclaration.equivalent(lhs.lifecycle, rhs.lifecycle), + sameRecipients(lhs.agents, rhs.agents), + lhs.exports == rhs.exports, + lhs.groups == rhs.groups, lhs.uses == rhs.uses, Set(lhs.watch ?? []) == Set(rhs.watch ?? []), + lhs.sourceDeclarations.map(\.name) == rhs.sourceDeclarations.map(\.name), + zip(lhs.sourceDeclarations, rhs.sourceDeclarations).allSatisfy({ + equivalent($0.source, $1.source, environment: environment) + }), + lhs.components.count == rhs.components.count + else { return false } + return zip(lhs.components, rhs.components).allSatisfy { left, right in + switch (left, right) { + case (.skills(let a, let x), .skills(let b, let y)): return a == b && equivalent(x, y) + case (.instructions(let x), .instructions(let y)): return equivalent(x, y) + default: return left == right + } + } + } + + static func equivalent( + _ lhs: SourceDeclaration, _ rhs: SourceDeclaration, environment: RuntimeEnvironment + ) -> Bool { + func identity(_ source: SourceDeclaration) -> String { + (try? source.identity(environment: environment)) ?? source.location + } + func subpath(_ source: SourceDeclaration) -> String { + source.path.map { (try? PathSafety.sanitizeSubpath($0)) ?? $0 } ?? "." + } + let requirements: Bool + switch (lhs.requirement, rhs.requirement) { + case (nil, nil): requirements = true + case (let left?, let right?): requirements = left.declarationEquivalent(to: right) + default: requirements = false + } + return lhs.kind == rhs.kind && requirements && identity(lhs) == identity(rhs) + && subpath(lhs) == subpath(rhs) + } + + static func equivalent(_ lhs: SkillDeclaration, _ rhs: SkillDeclaration) -> Bool { + let selections: Bool + switch (lhs.select, rhs.select) { + case (.all, .all): selections = true + case (.names(let left), .names(let right)): selections = Set(left) == Set(right) + default: selections = false + } + let leftNames = lhs.overrideDeclarations.map(\.name) + let rightNames = rhs.overrideDeclarations.map(\.name) + guard Set(leftNames).count == leftNames.count, Set(rightNames).count == rightNames.count else { + return false + } + let left = Dictionary( + uniqueKeysWithValues: lhs.overrideDeclarations.map { ($0.name, $0.override) }) + let right = Dictionary( + uniqueKeysWithValues: rhs.overrideDeclarations.map { ($0.name, $0.override) }) + return lhs.path == rhs.path && selections && Set(lhs.exclude ?? []) == Set(rhs.exclude ?? []) + && lhs.mode == rhs.mode + && sameRecipients(lhs.agents, rhs.agents) && left.keys == right.keys + && left.allSatisfy { equivalent($1, right[$0]!) } + && lhs.condition == rhs.condition && lhs.native == rhs.native + } + + static func equivalent(_ lhs: SkillOverride, _ rhs: SkillOverride) -> Bool { + lhs.mode == rhs.mode && sameRecipients(lhs.agents, rhs.agents) + } + + static func equivalent(_ lhs: InstructionsDeclaration, _ rhs: InstructionsDeclaration) -> Bool { + sameRecipients(lhs.agents, rhs.agents) && lhs.sectionReferences == rhs.sectionReferences + && lhs.prompts == rhs.prompts && lhs.condition == rhs.condition && lhs.native == rhs.native + } + + static func sameRecipients(_ lhs: [AgentID]?, _ rhs: [AgentID]?) -> Bool { + lhs.map(Set.init) == rhs.map(Set.init) + } +} + +/// Schema validation checks field types before conversion, including private drafts. +private struct Projection { + let document: DeclarationDocument + + func records(_ value: DeclarationValue?) -> [DeclarationRecord] { + (value?.elements ?? []).map { $0.record! } + } + func strings(_ value: DeclarationValue?) -> [String] { + (value?.elements ?? []).map { $0.string! } + } + func recipients(_ value: DeclarationValue?) -> [AgentID]? { + value?.elements.map { $0.map { AgentID(rawValue: $0.string!)! } } + } + func dictionary(_ value: DeclarationValue?) -> [String: DeclarationValue] { + if case .dictionary(let values) = value { return values } + return [:] + } + func condition(_ value: DeclarationValue?) -> DeclarationCondition? { + guard let r = value?.record else { return nil } + return DeclarationCondition( + agents: recipients(r["agents"]), + scopes: r["scopes"]?.elements.map { $0.map { InstallScope(rawValue: $0.string!)! } }, + platforms: r["platforms"]?.elements.map { + $0.map { DeclarationPlatform(rawValue: $0.string!)! } + }) + } + func use(_ r: DeclarationRecord) -> GroupUseDeclaration { + GroupUseDeclaration( + name: r["name"]!.string!, source: r["source"]?.string, condition: condition(r["condition"])) + } + func section(_ r: DeclarationRecord) -> SectionDeclaration { + SectionDeclaration( + name: r["name"]!.string!, source: r["source"]?.string, condition: condition(r["condition"]), + recipients: r["recipients"]?.elements.map { + $0.map { InstructionRecipient(rawValue: $0.string!)! } + }) + } + func resource(_ r: DeclarationRecord) -> ResourceDeclaration { + ResourceDeclaration(path: r["path"]!.string!, source: r["source"]?.string) + } + func binding(_ value: DeclarationValue) -> RuntimeBinding { + let r = value.record! + let text = r["value"]!.string! + switch r.kind { + case "environment": return .environment(text) + case "secret": return .secret(text) + default: return .literal(text) + } + } + func executable(_ r: DeclarationRecord) -> ExecutableDeclaration { + ExecutableDeclaration( + executable: r["executable"]!.string!, executableSource: r["executableSource"]?.string, + arguments: strings(r["arguments"]), + environment: dictionary(r["environment"]).mapValues(binding), + workingDirectory: r["workingDirectory"]?.record.map(resource)) + } + func prompt(_ r: DeclarationRecord) -> PromptBody { + r.kind == "literal" ? .literal(r["value"]!.string!) : .file(resource(r)) + } + func nativeValue(_ value: DeclarationValue) -> NativeValue { + let r = value.record! + switch r.kind { + case "string": return .string(r["value"]!.string!) + case "integer": if case .integer(let v) = r["value"] { return .integer(v) } + case "decimal": return .decimal(r["value"]!.string!) + case "boolean": if case .boolean(let v) = r["value"] { return .boolean(v) } + case "null": return .null + case "array": return .array((r["value"]?.elements ?? []).map(nativeValue)) + case "object": return .object(dictionary(r["value"]).mapValues(nativeValue)) + default: break + } + preconditionFailure("statically typed configuration value") + } + func native(_ value: DeclarationValue?) -> AgentsCore.NativeConfiguration { + dictionary(value).mapValues { dictionary($0).mapValues(nativeValue) } + } + func event(_ r: DeclarationRecord) -> HookEventDeclaration { + switch r.kind { + case "beforeTool": return .beforeTool + case "afterTool": return .afterTool + case "sessionStart": return .sessionStart + case "sessionEnd": return .sessionEnd + default: return .native(r["value"]!.string!) + } + } + func operation(_ r: DeclarationRecord) -> PermissionOperationDeclaration { + switch r.kind { + case "read": return .read + case "write": return .write + case "execute": return .execute + default: return .tool(r["value"]!.string!) + } + } + func rule(_ r: DeclarationRecord) -> PermissionRuleDeclaration { + let op = operation(r["operation"]!.record!) + let pattern = r["pattern"]!.string! + switch r.kind { + case "allow": return .allow(op, pattern) + case "ask": return .ask(op, pattern) + default: return .deny(op, pattern) + } + } + func reference(_ r: DeclarationRecord) -> ComponentReferenceDeclaration { + let name = r["name"]!.string! + switch r.kind { + case "skill": return .skill(name: name) + case "instruction": return .instruction(name: name) + case "mcpServer": return .mcpServer(name: name) + case "hook": return .hook(name: name) + case "subagent": return .subagent(name: name) + case "command": return .command(name: name) + case "lspServer": return .lspServer(name: name) + case "permissions": return .permissions(name: name) + case "ignore": return .ignore(name: name) + default: return .plugin(name: name) + } + } + func component(_ r: DeclarationRecord) throws -> ComponentDeclaration { + let agents = recipients(r["agents"]) + let condition = condition(r["condition"]) + let native = native(r["native"]) + let name = r["name"]?.string ?? "" + switch r.kind { + case "skills": + let overrides = records(r["overrides"]).map { record in + ( + record["name"]!.string!, + SkillOverride( + agents: recipients(record["agents"]), + mode: record["mode"]?.string.flatMap(InstallMode.init(rawValue:))) + ) + } + var result = SkillDeclaration( + select: r["select"]?.elements.map { .names($0.map { $0.string! }) } ?? .all, + path: r["path"]?.string, + exclude: strings(r["exclude"]).isEmpty ? nil : strings(r["exclude"]), agents: agents, + mode: r["mode"]?.string.flatMap(InstallMode.init(rawValue:)), + overrides: nil, condition: condition, native: native) + result.overrideDeclarations = overrides.map { + NamedSkillOverrideDeclaration(name: $0.0, override: $0.1) + } + return .skills(source: r["source"]!.string!, result) + case "instructions": + var result = InstructionsDeclaration(agents: agents, condition: condition, native: native) + result.sectionReferences = records(r["sections"]).map(section) + result.prompts = records(r["chatGPT"]).map { record in + var prompt = PromptDeclaration( + sections: [], append: record["append"]?.string, + condition: self.condition(record["condition"])) + prompt.sectionReferences = records(record["sections"]).map(section) + return NamedPromptDeclaration(name: record["name"]!.string!, prompt: prompt) + } + return .instructions(result) + case "mcpServer": + let record = r["transport"]!.record! + let transport: MCPTransportDeclaration + switch record.kind { + case "stdio": transport = .stdio(executable(record)) + case "streamableHTTP": + transport = .streamableHTTP( + url: record["url"]!.string!, headers: dictionary(record["headers"]).mapValues(binding)) + default: + transport = .sse( + url: record["url"]!.string!, headers: dictionary(record["headers"]).mapValues(binding)) + } + let registry = r["registry"]?.record.map { fields in + MCPRegistryEvidence( + registry: fields["registry"]!.string!, server: fields["server"]!.string!, + version: fields["version"]!.string!, origin: fields["origin"]!.string!, + package: fields["package"]?.string, invocationDigest: fields["invocationDigest"]?.string, + portableBindings: fields["portableBindings"].map { + dictionary($0).mapValues { $0.string! } + } + ) + } + return .mcpServer( + name: name, transport: transport, agents: agents, condition: condition, native: native, + registry: registry) + case "hook": + var timeout: Int? + if case .integer(let v) = r["timeoutSeconds"] { timeout = v } + return .hook( + name: name, event: event(r["event"]!.record!), run: executable(r["run"]!.record!), + matcher: r["matcher"]?.string, timeoutSeconds: timeout, agents: agents, + condition: condition, native: native) + case "subagent": + return .subagent( + name: name, description: r["description"]!.string!, prompt: prompt(r["prompt"]!.record!), + model: r["model"]?.string, + tools: r["tools"]?.elements.map { $0.map { $0.string! } }, agents: agents, + condition: condition, native: native) + case "command": + return .command( + name: name, description: r["description"]!.string!, prompt: prompt(r["prompt"]!.record!), + parameters: records(r["parameters"]).map { + PromptParameterDeclaration( + name: $0["name"]!.string!, description: $0["description"]!.string!, + defaultValue: $0["defaultValue"]?.string) + }, agents: agents, condition: condition, native: native) + case "lspServer": + return .lspServer( + name: name, run: executable(r["run"]!.record!), + languages: dictionary(r["languages"]).mapValues { $0.string! }, + initializationOptions: dictionary(r["initializationOptions"]).mapValues(nativeValue), + agents: agents, condition: condition, native: native) + case "permissions": + return .permissions( + name: name, rules: records(r["rules"]).map(rule), agents: agents, condition: condition, + native: native) + case "ignore": + return .ignore( + name: name, patterns: strings(r["patterns"]), + purpose: IgnorePurposeDeclaration(rawValue: r["purpose"]!.string!)!, agents: agents, + condition: condition, native: native) + case "plugin": + return .plugin( + name: name, path: r["path"]!.string!, source: r["source"]!.string!, + mode: PluginModeDeclaration(rawValue: r["mode"]!.string!)!, + select: r["select"]?.elements.map { + $0.map { DeclaredComponentKind(rawValue: $0.string!)! } + }, exclude: records(r["exclude"]).map(reference), agents: agents, condition: condition, + native: native) + default: + throw ManifestFailure( + ManifestDiagnostic( + code: "manifest.unsupported", message: "unknown component family: \(r.kind)", + span: document.source.span(0..<0))) + } + } +} diff --git a/Sources/AgentsManifest/ManifestSchema.swift b/Sources/AgentsManifest/ManifestSchema.swift new file mode 100644 index 0000000..ab2d9c9 --- /dev/null +++ b/Sources/AgentsManifest/ManifestSchema.swift @@ -0,0 +1,278 @@ +// Generated by Scripts/generate-manifest-schema.py. + +enum ManifestSchema { + static let root: YAMLRule = .object( + [ + "version": .integerConstant(1), "defaultAgents": .array(.named("agent"), maximum: 10000), + "sources": .dictionary(.named("source"), maximum: 10000), + "packages": .dictionary(.named("marketplacePackage"), maximum: 10000), + "components": .array(.named("component"), maximum: 10000), + "groups": .dictionary(.named("group"), maximum: 10000), + "uses": .array(.named("use"), maximum: 10000), "exports": .array(.string, maximum: 10000), + "lifecycle": .named("lifecycle"), "watch": .array(.string, maximum: 10000), + ], required: ["version"], maximum: nil) + static let definitions: [String: YAMLRule] = [ + "lifecycle": .object( + [ + "pre-install": .array(.named("lifecycleAction"), maximum: 128), + "post-install": .array(.named("lifecycleAction"), maximum: 128), + "pre-update": .array(.named("lifecycleAction"), maximum: 128), + "post-update": .array(.named("lifecycleAction"), maximum: 128), + "pre-uninstall": .array(.named("lifecycleAction"), maximum: 128), + "post-uninstall": .array(.named("lifecycleAction"), maximum: 128), + "pre-compile": .array(.named("lifecycleAction"), maximum: 128), + ], required: [], maximum: nil), + "lifecycleAction": .oneOf([ + .object( + [ + "type": .constant("command"), "bash": .string, "env": .dictionary(.string, maximum: 128), + "timeout": .integer(minimum: 1, maximum: 300), + ], required: ["type", "bash"], maximum: nil), + .object( + [ + "type": .constant("command"), "command": .string, + "env": .dictionary(.string, maximum: 128), "timeout": .integer(minimum: 1, maximum: 300), + ], required: ["type", "command"], maximum: nil), + .object( + [ + "type": .constant("command"), "run": .string, "env": .dictionary(.string, maximum: 128), + "timeout": .integer(minimum: 1, maximum: 300), + ], required: ["type", "run"], maximum: nil), + .object( + [ + "type": .constant("http"), "url": .string, "headers": .dictionary(.string, maximum: 128), + "allowedEnvVars": .array(.string, maximum: 128), + "timeout": .integer(minimum: 1, maximum: 300), + ], required: ["type", "url"], maximum: nil), + ]), + "marketplacePackage": .oneOf([ + .object( + ["package": .string, "version": .string, "catalog": .named("marketplaceCatalog")], + required: ["package", "version", "catalog"], maximum: nil), + .object( + [ + "package": .string, "requirement": .named("marketplaceRequirement"), + "catalog": .named("marketplaceCatalog"), + "selections": .array(.named("marketplaceSelection"), maximum: 1024), + ], required: ["package", "requirement", "catalog"], maximum: nil), + ]), + "marketplaceRequirement": .oneOf([ + .object(["exact": .string], required: ["exact"], maximum: nil), + .object(["from": .string], required: ["from"], maximum: nil), + .object(["upToNextMinor": .string], required: ["upToNextMinor"], maximum: nil), + .object(["from": .string, "to": .string], required: ["from", "to"], maximum: nil), + ]), + "marketplaceSelection": .object( + [ + "package": .string, "catalog": .named("marketplaceCatalog"), + "member": .object( + ["kind": .enumeration(["skills", "instructions", "mcpServer"]), "name": .string], + required: ["kind", "name"], maximum: nil), "targets": .array(.named("agent"), maximum: 6), + ], required: ["package", "member", "targets"], maximum: nil), + "marketplaceCatalog": .object( + [ + "kind": .enumeration(["directory", "git", "hosted"]), "location": .string, "ref": .string, + "subpath": .string, + ], required: ["kind", "location"], maximum: nil), + "agent": .enumeration([ + "codex", "claude-code", "cursor", "gemini-cli", "opencode", "antigravity", + ]), + "condition": .object( + [ + "agents": .array(.named("agent"), maximum: 10000), + "scopes": .array(.enumeration(["project", "user"]), maximum: 10000), + "platforms": .array(.enumeration(["macos", "linux"]), maximum: 10000), + ], required: [], maximum: nil), + "resource": .object(["path": .string, "source": .string], required: ["path"], maximum: nil), + "section": .object( + [ + "name": .string, "source": .string, "condition": .named("condition"), + "recipients": .array( + .enumeration([ + "codex", "claude-code", "cursor", "gemini-cli", "opencode", "antigravity", + "chatgpt-app", "gemini-app", + ]), maximum: 8), + ], required: ["name"], maximum: nil), + "binding": .oneOf([ + .string, .object(["env": .string], required: ["env"], maximum: nil), + .object(["secret": .string], required: ["secret"], maximum: nil), + ]), + "prompt": .oneOf([ + .string, .object(["file": .named("resource")], required: ["file"], maximum: nil), + ]), + "run": .object( + [ + "executable": .string, "arguments": .array(.string, maximum: 10000), + "environment": .dictionary(.named("binding"), maximum: 10000), + "workingDirectory": .named("resource"), "executableSource": .string, + ], required: ["executable"], maximum: nil), + "transport": .oneOf([ + .object( + [ + "kind": .constant("stdio"), "executable": .string, + "arguments": .array(.string, maximum: 10000), + "environment": .dictionary(.named("binding"), maximum: 10000), + "workingDirectory": .named("resource"), "executableSource": .string, + ], required: ["kind", "executable"], maximum: nil), + .object( + [ + "kind": .enumeration(["streamableHTTP", "sse"]), "url": .string, + "headers": .dictionary(.named("binding"), maximum: 10000), + ], required: ["kind", "url"], maximum: nil), + ]), + "event": .oneOf([ + .enumeration(["beforeTool", "afterTool", "sessionStart", "sessionEnd"]), + .object(["native": .string], required: ["native"], maximum: nil), + ]), + "operation": .oneOf([ + .enumeration(["read", "write", "execute"]), + .object(["tool": .string], required: ["tool"], maximum: nil), + ]), + "rule": .object( + [ + "effect": .enumeration(["allow", "ask", "deny"]), "operation": .named("operation"), + "pattern": .string, + ], required: ["effect", "operation", "pattern"], maximum: nil), + "parameter": .object( + ["name": .string, "description": .string, "defaultValue": .string], + required: ["name", "description"], maximum: nil), + "promptDeclaration": .object( + [ + "sections": .array(.named("section"), maximum: 10000), "append": .string, + "condition": .named("condition"), + ], required: [], maximum: nil), + "override": .object( + [ + "agents": .array(.named("agent"), maximum: 10000), + "mode": .enumeration(["link", "copy", "edit"]), + ], required: [], maximum: nil), + "requirement": .oneOf([ + .object(["branch": .string], required: ["branch"], maximum: nil), + .object(["revision": .string], required: ["revision"], maximum: nil), + .object(["exact": .string], required: ["exact"], maximum: nil), + .object(["from": .string], required: ["from"], maximum: nil), + .object(["upToNextMinor": .string], required: ["upToNextMinor"], maximum: nil), + .object(["from": .string, "to": .string], required: ["from", "to"], maximum: nil), + ]), + "source": .oneOf([ + .object( + ["url": .string, "subpath": .string, "requirement": .named("requirement")], + required: ["url"], maximum: nil), + .object( + ["path": .string, "subpath": .string, "requirement": .named("requirement")], + required: ["path"], maximum: nil), + .object(["index": .string, "subpath": .string], required: ["index"], maximum: nil), + ]), + "componentReference": .object( + [ + "kind": .enumeration([ + "skill", "instruction", "mcpServer", "hook", "subagent", "command", "lspServer", + "permissions", "ignore", "plugin", + ]), "name": .string, + ], required: ["kind", "name"], maximum: nil), + "component_skills": .object( + [ + "kind": .constant("skills"), "agents": .array(.named("agent"), maximum: 10000), + "condition": .named("condition"), + "native": .dictionary(.dictionary(.native, maximum: 10000), maximum: 10000), + "source": .string, "select": .oneOf([.constant("all"), .array(.string, maximum: 10000)]), + "exclude": .array(.string, maximum: 10000), "mode": .enumeration(["link", "copy", "edit"]), + "overrides": .dictionary(.named("override"), maximum: 10000), "path": .string, + ], required: ["kind", "source"], maximum: nil), + "component_instructions": .object( + [ + "kind": .constant("instructions"), "agents": .array(.named("agent"), maximum: 10000), + "condition": .named("condition"), + "native": .dictionary(.dictionary(.native, maximum: 10000), maximum: 10000), + "sections": .array(.named("section"), maximum: 10000), + "chatgpt": .dictionary(.named("promptDeclaration"), maximum: 10000), + ], required: ["kind"], maximum: nil), + "mcpRegistry": .object( + [ + "registry": .string, "server": .string, "version": .string, "origin": .string, + "package": .string, "invocationDigest": .string, + "portableBindings": .dictionary(.string, maximum: 10000), + ], required: ["registry", "server", "version", "origin"], maximum: nil), + "component_mcpServer": .object( + [ + "kind": .constant("mcpServer"), "agents": .array(.named("agent"), maximum: 10000), + "condition": .named("condition"), + "native": .dictionary(.dictionary(.native, maximum: 10000), maximum: 10000), + "name": .string, "registry": .named("mcpRegistry"), "transport": .named("transport"), + ], required: ["kind", "name", "transport"], maximum: nil), + "component_hook": .object( + [ + "kind": .constant("hook"), "agents": .array(.named("agent"), maximum: 10000), + "condition": .named("condition"), + "native": .dictionary(.dictionary(.native, maximum: 10000), maximum: 10000), + "name": .string, "event": .named("event"), "run": .named("run"), "matcher": .string, + "timeoutSeconds": .integer(minimum: 1), + ], required: ["kind", "name", "event", "run"], maximum: nil), + "component_subagent": .object( + [ + "kind": .constant("subagent"), "agents": .array(.named("agent"), maximum: 10000), + "condition": .named("condition"), + "native": .dictionary(.dictionary(.native, maximum: 10000), maximum: 10000), + "name": .string, "description": .string, "prompt": .named("prompt"), "model": .string, + "tools": .array(.string, maximum: 10000), + ], required: ["kind", "name", "description", "prompt"], maximum: nil), + "component_command": .object( + [ + "kind": .constant("command"), "agents": .array(.named("agent"), maximum: 10000), + "condition": .named("condition"), + "native": .dictionary(.dictionary(.native, maximum: 10000), maximum: 10000), + "name": .string, "description": .string, "prompt": .named("prompt"), + "parameters": .array(.named("parameter"), maximum: 10000), + ], required: ["kind", "name", "description", "prompt"], maximum: nil), + "component_lspServer": .object( + [ + "kind": .constant("lspServer"), "agents": .array(.named("agent"), maximum: 10000), + "condition": .named("condition"), + "native": .dictionary(.dictionary(.native, maximum: 10000), maximum: 10000), + "name": .string, "run": .named("run"), "languages": .dictionary(.string, maximum: 10000), + "initializationOptions": .dictionary(.native, maximum: 10000), + ], required: ["kind", "name", "run", "languages"], maximum: nil), + "component_permissions": .object( + [ + "kind": .constant("permissions"), "agents": .array(.named("agent"), maximum: 10000), + "condition": .named("condition"), + "native": .dictionary(.dictionary(.native, maximum: 10000), maximum: 10000), + "name": .string, "rules": .array(.named("rule"), maximum: 10000), + ], required: ["kind", "name", "rules"], maximum: nil), + "component_ignore": .object( + [ + "kind": .constant("ignore"), "agents": .array(.named("agent"), maximum: 10000), + "condition": .named("condition"), + "native": .dictionary(.dictionary(.native, maximum: 10000), maximum: 10000), + "name": .string, "patterns": .array(.string, maximum: 10000), + "purpose": .enumeration(["context", "indexing"]), + ], required: ["kind", "name", "patterns"], maximum: nil), + "component_plugin": .object( + [ + "kind": .constant("plugin"), "agents": .array(.named("agent"), maximum: 10000), + "condition": .named("condition"), + "native": .dictionary(.dictionary(.native, maximum: 10000), maximum: 10000), + "name": .string, "source": .string, "path": .string, + "mode": .enumeration(["native", "components"]), + "select": .array( + .enumeration([ + "skills", "instructions", "mcpServer", "hook", "subagent", "command", "lspServer", + "permissions", "ignore", "plugin", + ]), maximum: 10000), "exclude": .array(.named("componentReference"), maximum: 10000), + ], required: ["kind", "name", "source", "path"], maximum: nil), + "component": .oneOf([ + .named("component_skills"), .named("component_instructions"), .named("component_mcpServer"), + .named("component_hook"), .named("component_subagent"), .named("component_command"), + .named("component_lspServer"), .named("component_permissions"), .named("component_ignore"), + .named("component_plugin"), + ]), + "use": .object( + ["group": .string, "source": .string, "condition": .named("condition")], required: ["group"], + maximum: nil), + "group": .object( + [ + "components": .array(.named("component"), maximum: 10000), + "uses": .array(.named("use"), maximum: 10000), "condition": .named("condition"), + ], required: [], maximum: nil), + ] +} diff --git a/Sources/AgentsManifest/ManifestState.swift b/Sources/AgentsManifest/ManifestState.swift new file mode 100644 index 0000000..cc04690 --- /dev/null +++ b/Sources/AgentsManifest/ManifestState.swift @@ -0,0 +1,74 @@ +import AgentsCore +import Foundation + +/// Declaration access for scope state. Core owns the file, its captured bytes, the missing +/// declaration rule and publication; this module parses, projects and plans edits. Parse, projection +/// and edit failures are `ManifestFailure` diagnostics identified by the declaration path. +extension StateStore { + /// The complete declaration, or an empty one when the scope has no state. + package func readDeclaration(prepared: StatePrecondition? = nil) throws -> Declaration { + guard let document = try declarationDocument(prepared: prepared) else { return Declaration() } + return try ManifestProjection.declaration(of: document, environment: environment) + } + + /// Plans `next` as an edit of the prepared document that `previous` was read from. Nil means + /// no semantic change. A document that no longer projects to `previous` is a stale + /// preparation. + package func planDeclaration( + _ next: Declaration, replacing previous: Declaration, prepared: StatePrecondition + ) throws -> DeclarationChange? { + let bytes = try declarationBytes(prepared: prepared) + var next = next + if bytes == nil { next.watch = next.watch?.sorted(by: utf8Less) } + let output: [UInt8]? + do { + output = try DeclarationEditPlan.bytes( + replacing: previous, with: next, in: bytes.map(Array.init), identity: declarationIdentity, + environment: environment) + } catch let failure as ManifestFailure + where failure.diagnostics.contains(where: { $0.code == "manifest.edit.baseline" }) + { + throw CoreError.invalidState("declaration changed during preparation: \(declarationURL.path)") + } + return output.map { DeclarationChange(bytes: Data($0)) } + } + + /// Reads the complete declaration under a shared lock, without recovery or creating files. + public func loadDeclaration() throws -> Declaration { + try withReadLock { try readDeclaration() } + } + + /// Reads the complete declaration document under a shared lock, without recovery, creating + /// files or resolving its sources. Nil means the scope has no state. + public func loadManifest() throws -> DeclarationDocument? { + try withReadLock { try declarationDocument(prepared: nil) } + } + + private var declarationIdentity: DocumentIdentity { DocumentIdentity(declarationURL.path) } + + package func declarationDocument(prepared: StatePrecondition?) throws -> DeclarationDocument? { + try declarationBytes(prepared: prepared).map { + try DeclarationDocument(bytes: Array($0), identity: declarationIdentity) + } + } +} + +extension DeclarationAccess { + package static var manifest: Self { + Self( + read: { store, prepared in try store.readDeclaration(prepared: prepared) }, + plan: { store, previous, next, prepared in + try store.planDeclaration(next, replacing: previous, prepared: prepared) + }) + } +} + +extension WatchOperations { + public init( + discoverSkills: @escaping @Sendable (URL) throws -> [WatchSkill], + fetchArtifacts: @escaping @Sendable (String) throws -> [WatchArtifact] + ) { + self.init( + discoverSkills: discoverSkills, fetchArtifacts: fetchArtifacts, declarations: .manifest) + } +} diff --git a/Sources/AgentsManifest/OrganizationPolicyDocument.swift b/Sources/AgentsManifest/OrganizationPolicyDocument.swift new file mode 100644 index 0000000..ddda025 --- /dev/null +++ b/Sources/AgentsManifest/OrganizationPolicyDocument.swift @@ -0,0 +1,260 @@ +import AgentsCore +import Foundation + +package enum OrganizationPolicyDocument { + package static func parse(_ bytes: Data, url: URL) throws -> OrganizationRules { + let reader = try YAMLReader(bytes: Array(bytes), identity: .init(url.absoluteString)) + let root = try Fields(reader.root, reader: reader) + var rules = OrganizationRules() + rules.name = try root.text("name") + rules.version = try root.text("version") + rules.parent = try root.text("extends") + rules.enforcement = try root.choice("enforcement", [.off, .warn, .block]) ?? .warn + rules.fetchFailure = try root.choice("fetch_failure", [.warn, .block]) ?? .warn + if let cache = try root.object("cache") { + try cache.requireKeys(["ttl"]) + rules.ttl = min(86_400, try cache.positive("ttl") ?? 3600) + } + if let sources = try root.object("sources") { + try sources.requireKeys(["allow", "deny"]) + rules.sourceAllow = try sources.list("allow") + rules.sourceDeny = try sources.list("deny") ?? [] + } + if let deps = try root.object("dependencies") { + try deps.requireKeys([ + "allow", "deny", "require", "require_resolution", "max_depth", "require_pinned_constraint", + ]) + rules.dependencyAllow = try deps.list("allow") + rules.dependencyDeny = try deps.list("deny") ?? [] + rules.dependencyRequire = try deps.packages() + rules.resolution = try deps.choice( + "require_resolution", OrganizationRules.Resolution.allCases) + rules.maximumDepth = try deps.positive("max_depth") + rules.pinnedConstraint = try deps.flag("require_pinned_constraint") ?? false + } + if let marketplace = try root.object("marketplace") { + try marketplace.requireKeys(["allow"]) + rules.marketplaceAllow = try marketplace.list("allow") + } + if let mcp = try root.object("mcp") { + try mcp.requireKeys([ + "allow", "deny", "require", "transport", "self_defined", "trust_transitive", + ]) + rules.mcpAllow = try mcp.list("allow") + rules.mcpDeny = try mcp.list("deny") ?? [] + rules.mcpRequire = try mcp.exactList("require") + rules.mcpSelfDefined = try mcp.choice("self_defined", OrganizationRules.SelfDefined.allCases) + rules.mcpTrustTransitive = try mcp.flag("trust_transitive") + if let transport = try mcp.object("transport") { + try transport.requireKeys(["allow"]) + rules.mcpTransportAllow = try transport.list("allow")?.map { value in + switch value { + case "stdio", "sse", "streamable-http": return value + case "http": return "streamable-http" + default: throw transport.failure(transport.node, "Unknown MCP transport.") + } + } + } + } + if let executable = try root.object("executables") { + try executable.requireKeys(["deny_all", "deny", "require", "recommend", "enforce"]) + rules.executableDenyAll = try executable.flag("deny_all") ?? false + rules.executableDeny = try executable.list("deny") ?? [] + rules.executableRequire = try executable.exactList("require") + for key in ["recommend", "enforce"] where try executable.exactList(key).isEmpty == false { + rules.warnings.append("executables.\(key) does not grant execution or installation trust.") + } + } + if let manifest = try root.object("manifest") { + try manifest.requireKeys([ + "required_fields", "require_explicit_includes", "content_types", "scripts", + ]) + rules.requiredFields = try manifest.exactList("required_fields") + rules.explicitIncludes = try manifest.flag("require_explicit_includes") ?? false + rules.scriptsDenied = try manifest.enumeration("scripts", ["allow", "deny"]) == "deny" + if let types = try manifest.object("content_types") { + try types.requireKeys(["allow"]) + rules.contentTypes = try types.list("allow") + } + } + if let security = try root.object("security") { + try security.requireKeys(["integrity", "audit"]) + if let integrity = try security.object("integrity") { + try integrity.requireKeys(["require_hashes"]) + rules.requireHashes = try integrity.flag("require_hashes") ?? false + } + if let audit = try security.object("audit") { + try audit.requireKeys(["fail_on_drift"]) + rules.failOnDrift = try audit.flag("fail_on_drift") ?? false + } + } + if let unmanaged = try root.object("unmanaged_files") { + try unmanaged.requireKeys(["action", "directories", "exclude"]) + rules.unmanagedAction = + try unmanaged.choice("action", OrganizationRules.Action.allCases) ?? .ignore + rules.unmanagedDirectories = try unmanaged.exactList("directories") + for path in rules.unmanagedDirectories where path == "." || (try? ledgerPath(path)) == nil { + throw unmanaged.failure( + unmanaged.node, "Unmanaged directories must be relative workspace paths.") + } + rules.unmanagedExclude = try unmanaged.list("exclude") ?? [] + } + let accepted: Set = [ + "name", "version", "extends", "enforcement", "fetch_failure", "cache", "sources", + "dependencies", "marketplace", "mcp", "executables", "manifest", "security", + "unmanaged_files", + ] + rules.warnings += root.fields.keys.sorted().filter { !accepted.contains($0) }.map { + "Unsupported organization policy field: \($0)." + } + return rules + } + + private struct Fields { + let node: YAMLNode + let reader: YAMLReader + let fields: [String: YAMLNode] + + init(_ node: YAMLNode, reader: YAMLReader) throws { + self.node = node + self.reader = reader + guard let pairs = node.pairs else { + throw ManifestFailure( + .init( + code: "org-policy.field", message: "Expected a mapping.", span: reader.span(of: node))) + } + var values: [String: YAMLNode] = [:] + for (key, value) in pairs { + guard let name = Self.string(key), values[name] == nil, + name.utf8.count <= 128, !name.isEmpty + else { + throw ManifestFailure( + .init( + code: "org-policy.field", message: "Invalid field name.", span: reader.span(of: key))) + } + values[name] = value + } + fields = values + } + + func failure(_ value: YAMLNode, _ message: String) -> ManifestFailure { + ManifestFailure( + .init(code: "org-policy.field", message: message, span: reader.span(of: value))) + } + + func requireKeys(_ keys: Set) throws { + if let key = fields.keys.sorted().first(where: { !keys.contains($0) }) { + throw failure(fields[key]!, "Unsupported organization policy rule.") + } + } + + private static func kind(_ node: YAMLNode) -> YAMLScalar? { + guard let scalar = node.scalar, !scalar.decimalTag else { return nil } + return scalar.quoted ? .string : YAMLScalar.classify(scalar.text) + } + + private static func string(_ node: YAMLNode) -> String? { + kind(node) == .string ? node.text : nil + } + + private func value(_ key: String) -> YAMLNode? { + fields[key].flatMap { Self.kind($0) == .null ? nil : $0 } + } + + func object(_ key: String) throws -> Self? { + try value(key).map { try Self($0, reader: reader) } + } + + private func text(_ value: YAMLNode) throws -> String { + guard let string = Self.string(value), !string.isEmpty, string.utf8.count <= 4096, + string.utf8.allSatisfy({ $0 >= 32 && $0 != 127 }) + else { throw failure(value, "Expected a nonempty string.") } + return string + } + + func text(_ key: String) throws -> String? { try value(key).map(text) } + + func flag(_ key: String) throws -> Bool? { + guard let value = fields[key] else { return nil } + guard Self.kind(value) == .boolean else { throw failure(value, "Expected a boolean.") } + return value.text?.lowercased() == "true" + } + + func positive(_ key: String) throws -> Int? { + guard let value = fields[key] else { return nil } + guard Self.kind(value) == .integer, let number = value.text.flatMap(YAMLScalar.integer), + number > 0 + else { throw failure(value, "Expected a positive integer.") } + return number + } + + func enumeration(_ key: String, _ choices: [String]) throws -> String? { + guard let value = fields[key] else { return nil } + let raw = try text(value) + guard choices.contains(raw) else { throw failure(value, "Unsupported rule value.") } + return raw + } + + func choice(_ key: String, _ choices: [T]) throws -> T? + where T.RawValue == String { + try enumeration(key, choices.map(\.rawValue)).flatMap(T.init(rawValue:)) + } + + func list(_ key: String) throws -> [String]? { + guard let value = value(key) else { return nil } + guard let items = value.items, items.count <= 256 else { + throw failure(value, "Expected a list of at most 256 entries.") + } + return try items.map(text) + } + + func exactList(_ key: String) throws -> [String] { + let values = try list(key) ?? [] + if values.contains(where: { $0.contains(where: { "*?[]".contains($0) }) }) { + throw failure(fields[key]!, "Expected exact identities or field names.") + } + return values + } + + func packages() throws -> [OrganizationRules.RequiredPackage] { + guard let value = value("require") else { return [] } + guard let items = value.items, items.count <= 256 else { + throw failure(value, "Expected a list of at most 256 requirements.") + } + return try items.map { item in + let identity: String + let requirement: SourceRequirement? + if item.pairs != nil { + let entry = try Self(item, reader: reader) + try entry.requireKeys(["identity", "exact", "from", "upToNextMinor", "to"]) + guard let raw = try entry.text("identity") else { + throw failure(item, "A package requirement needs an identity.") + } + identity = raw + let exact = try entry.text("exact") + let from = try entry.text("from") + let minor = try entry.text("upToNextMinor") + let to = try entry.text("to") + guard [exact, from, minor].compactMap({ $0 }).count <= 1, to == nil || from != nil else { + throw failure(item, "Conflicting version constraints.") + } + if let exact { + requirement = .exact(exact) + } else if let from { + requirement = to.map { .range(from: from, to: $0) } ?? .upToNextMajor(from: from) + } else { + requirement = minor.map(SourceRequirement.upToNextMinor) + } + } else { + identity = try text(item) + requirement = nil + } + guard identity.contains("/"), + !identity.contains(where: { "*?[]".contains($0) }), + requirement == nil || (try? requirement?.canonicalized()) != nil + else { throw failure(item, "Invalid exact package identity or version constraint.") } + return .init(identity: identity, version: try requirement?.canonicalized()) + } + } + } +} diff --git a/Sources/AgentsManifest/Resources/agents.schema.json b/Sources/AgentsManifest/Resources/agents.schema.json new file mode 100644 index 0000000..fec6bf0 --- /dev/null +++ b/Sources/AgentsManifest/Resources/agents.schema.json @@ -0,0 +1,1848 @@ +{ + "type": "object", + "properties": { + "version": { + "const": 1, + "type": "integer", + "x-agents-scalar-kind": "integer", + "description": "Required manifest version, written as the plain integer 1. Core rejects decimal spelling such as 1.0 even when a JSON Schema validator treats it as an integer." + }, + "defaultAgents": { + "type": "array", + "items": { + "$ref": "#/$defs/agent" + }, + "maxItems": 10000, + "description": "Default recipients for components that omit agents. Omission defaults to codex and claude-code; an empty list selects no recipients. Component overrides and conditions further determine effective targets.", + "examples": [ + [ + "codex", + "claude-code" + ], + [] + ] + }, + "sources": { + "type": "object", + "additionalProperties": { + "$ref": "#/$defs/source" + }, + "maxProperties": 10000, + "description": "Source aliases local to this declaration, retained in declaration order. References use these keys; aliases must be nonempty, must not be . or contain a colon, and must identify distinct normalized sources. Omission or an empty mapping declares none." + }, + "packages": { + "type": "object", + "additionalProperties": { + "$ref": "#/$defs/marketplacePackage" + }, + "maxProperties": 10000, + "description": "Marketplace roots keyed by consumer alias. Each root specifies a catalog, package and version requirement. Member selections record the recipients requested by that root." + }, + "components": { + "type": "array", + "items": { + "$ref": "#/$defs/component" + }, + "maxItems": 10000, + "description": "Direct component declarations, retained in order and checked even when their conditions select no targets. Omission or an empty sequence declares none." + }, + "groups": { + "type": "object", + "additionalProperties": { + "$ref": "#/$defs/group" + }, + "maxProperties": 10000, + "description": "Named reusable groups, retained in declaration order. Defining a group does not activate it; uses selects it and exports makes it available to importers. Unused groups are still validated." + }, + "uses": { + "type": "array", + "items": { + "$ref": "#/$defs/use" + }, + "maxItems": 10000, + "description": "Group references expanded in declaration order. Omission or an empty sequence activates no groups. Local reference cycles are errors, including in inactive groups." + }, + "exports": { + "type": "array", + "items": { + "type": "string" + }, + "maxItems": 10000, + "description": "Names of local groups available to importing declarations, retained in order. Every name must name a declared group and occur once. Omission or an empty sequence exports none." + }, + "lifecycle": { + "$ref": "#/$defs/lifecycle", + "description": "Ordered package-manager lifecycle actions. Project execution requires explicit local trust." + }, + "watch": { + "type": "array", + "items": { + "type": "string" + }, + "maxItems": 10000, + "description": "Source aliases subscribed independently of installations. Names must be unique and refer to declared source aliases. Omission and an empty sequence are equivalent; watch order has set-like semantics." + } + }, + "required": [ + "version" + ], + "additionalProperties": false, + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://agents.tools/schemas/agents-1.json", + "title": "Agents declaration", + "description": "Version 1 declaration of symbolic sources, components and groups. Parsing validates supplied YAML without resolving sources, reading referenced resources or running programs. Unknown fixed fields and null optional fields are errors; omitted collections are empty unless a field says otherwise. Core diagnostics also enforce YAML scalar kinds, numeric identity and domain relationships that general JSON Schema cannot express.", + "$defs": { + "lifecycle": { + "type": "object", + "properties": { + "pre-install": { + "type": "array", + "items": { + "$ref": "#/$defs/lifecycleAction" + }, + "maxItems": 128 + }, + "post-install": { + "type": "array", + "items": { + "$ref": "#/$defs/lifecycleAction" + }, + "maxItems": 128 + }, + "pre-update": { + "type": "array", + "items": { + "$ref": "#/$defs/lifecycleAction" + }, + "maxItems": 128 + }, + "post-update": { + "type": "array", + "items": { + "$ref": "#/$defs/lifecycleAction" + }, + "maxItems": 128 + }, + "pre-uninstall": { + "type": "array", + "items": { + "$ref": "#/$defs/lifecycleAction" + }, + "maxItems": 128 + }, + "post-uninstall": { + "type": "array", + "items": { + "$ref": "#/$defs/lifecycleAction" + }, + "maxItems": 128 + }, + "pre-compile": { + "type": "array", + "items": { + "$ref": "#/$defs/lifecycleAction" + }, + "maxItems": 128 + } + }, + "required": [], + "additionalProperties": false + }, + "lifecycleAction": { + "oneOf": [ + { + "type": "object", + "properties": { + "type": { + "const": "command" + }, + "bash": { + "type": "string" + }, + "env": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "maxProperties": 128 + }, + "timeout": { + "type": "integer", + "minimum": 1, + "maximum": 300 + } + }, + "required": [ + "type", + "bash" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "type": { + "const": "command" + }, + "command": { + "type": "string" + }, + "env": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "maxProperties": 128 + }, + "timeout": { + "type": "integer", + "minimum": 1, + "maximum": 300 + } + }, + "required": [ + "type", + "command" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "type": { + "const": "command" + }, + "run": { + "type": "string" + }, + "env": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "maxProperties": 128 + }, + "timeout": { + "type": "integer", + "minimum": 1, + "maximum": 300 + } + }, + "required": [ + "type", + "run" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "type": { + "const": "http" + }, + "url": { + "type": "string" + }, + "headers": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "maxProperties": 128 + }, + "allowedEnvVars": { + "type": "array", + "items": { + "type": "string" + }, + "maxItems": 128 + }, + "timeout": { + "type": "integer", + "minimum": 1, + "maximum": 300 + } + }, + "required": [ + "type", + "url" + ], + "additionalProperties": false + } + ] + }, + "marketplacePackage": { + "oneOf": [ + { + "type": "object", + "properties": { + "package": {"type": "string"}, + "version": {"type": "string"}, + "catalog": {"$ref": "#/$defs/marketplaceCatalog"} + }, + "required": ["package", "version", "catalog"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "package": {"type": "string"}, + "requirement": {"$ref": "#/$defs/marketplaceRequirement"}, + "catalog": {"$ref": "#/$defs/marketplaceCatalog"}, + "selections": { + "type": "array", + "items": {"$ref": "#/$defs/marketplaceSelection"}, + "maxItems": 1024 + } + }, + "required": ["package", "requirement", "catalog"], + "additionalProperties": false + } + ] + }, + "marketplaceRequirement": { + "oneOf": [ + {"type": "object", "properties": {"exact": {"type": "string"}}, "required": ["exact"], "additionalProperties": false}, + {"type": "object", "properties": {"from": {"type": "string"}}, "required": ["from"], "additionalProperties": false}, + {"type": "object", "properties": {"upToNextMinor": {"type": "string"}}, "required": ["upToNextMinor"], "additionalProperties": false}, + {"type": "object", "properties": {"from": {"type": "string"}, "to": {"type": "string"}}, "required": ["from", "to"], "additionalProperties": false} + ] + }, + "marketplaceSelection": { + "type": "object", + "properties": { + "package": {"type": "string"}, + "catalog": {"$ref": "#/$defs/marketplaceCatalog"}, + "member": { + "type": "object", + "properties": { + "kind": {"enum": ["skills", "instructions", "mcpServer"]}, + "name": {"type": "string"} + }, + "required": ["kind", "name"], + "additionalProperties": false + }, + "targets": {"type": "array", "items": {"$ref": "#/$defs/agent"}, "maxItems": 6} + }, + "required": ["package", "member", "targets"], + "additionalProperties": false + }, + "marketplaceCatalog": { + "type": "object", + "properties": { + "kind": { + "type": "string", + "enum": [ + "directory", + "git", + "hosted" + ], + "description": "A local catalog directory, Git catalog or hosted HTTPS index." + }, + "location": { + "type": "string", + "description": "A project-relative or absolute path for a directory, a Git repository locator, or a hosted HTTPS index URL." + }, + "ref": { + "type": "string", + "description": "Git commit, branch or tag for release discovery. Omission uses the default branch." + }, + "subpath": { + "type": "string", + "description": "Relative directory inside the Git catalog tree." + } + }, + "required": [ + "kind", + "location" + ], + "additionalProperties": false + }, + "agent": { + "type": "string", + "enum": [ + "codex", + "claude-code", + "cursor", + "gemini-cli", + "opencode", + "antigravity" + ], + "description": "Recipient identifier. Support for deploying an individual component is checked by its consuming operation; accepting the identifier does not imply every component is supported by that client." + }, + "condition": { + "type": "object", + "properties": { + "agents": { + "type": "array", + "items": { + "$ref": "#/$defs/agent" + }, + "maxItems": 10000, + "description": "Only these recipients remain eligible. Omission leaves recipients unrestricted; an empty list matches none. Duplicate recipients are errors." + }, + "scopes": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "project", + "user" + ] + }, + "maxItems": 10000, + "description": "Only these installation scopes match. Omission allows either scope; an empty list matches neither. Duplicate scopes are errors." + }, + "platforms": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "macos", + "linux" + ] + }, + "maxItems": 10000, + "description": "Only these operating systems match. Omission allows either platform; an empty list matches neither. Duplicate platforms are errors." + } + }, + "required": [], + "additionalProperties": false, + "description": "Intersecting restrictions on recipients, scope and platform. Omitted dimensions impose no restriction; an explicit empty dimension matches nothing. Nested group, use, component and section conditions combine by intersection, without removing inactive intent from the declaration." + }, + "resource": { + "type": "object", + "properties": { + "path": { + "type": "string", + "description": "Required relative resource path within the selected source. Absolute paths, home expansion and parent traversal are not allowed." + }, + "source": { + "type": "string", + "description": "Alias declared in this document. Omission or . uses the current declaring source; imported declarations retain their own source context." + } + }, + "required": [ + "path" + ], + "additionalProperties": false, + "description": "A resource path with an optional source alias. It remains symbolic during declaration reads; linking resolves and confines it to the selected source root.", + "examples": [ + { + "path": "prompts/review.md", + "source": "team" + } + ] + }, + "section": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "Instruction name relative to its instruction container, without .md. Nested names use / separators." + }, + "source": { + "type": "string", + "description": "Source alias for this section. Omission or . selects the declaring source's own instructions; root user instructions require a named source when linking." + }, + "condition": { + "$ref": "#/$defs/condition", + "description": "Additional restrictions for this section, intersected with enclosing conditions. Omission imposes no additional restriction." + }, + "recipients": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "codex", + "claude-code", + "cursor", + "gemini-cli", + "opencode", + "antigravity", + "chatgpt-app", + "gemini-app" + ] + }, + "maxItems": 8, + "description": "Exhaustive section recipients. Omission inherits the component's local recipients. An empty list selects none. ChatGPT App and Gemini App produce copyable text. Available on the component's sections. Named prompt sections inherit their prompt destination." + } + }, + "required": [ + "name" + ], + "additionalProperties": false, + "description": "One instruction section reference. Section sequences retain their declared order and occurrences; the referenced content is read only by the consuming operation." + }, + "binding": { + "oneOf": [ + { + "type": "string", + "description": "Literal text, used exactly as supplied. Strings resembling binding syntax are not interpolated." + }, + { + "type": "object", + "properties": { + "env": { + "type": "string", + "description": "Name of an environment variable resolved locally by the consuming operation." + } + }, + "required": [ + "env" + ], + "additionalProperties": false, + "description": "Symbolic local environment binding; no value is captured in the declaration." + }, + { + "type": "object", + "properties": { + "secret": { + "type": "string", + "description": "Name of a secret resolved locally by the consuming operation's binding provider." + } + }, + "required": [ + "secret" + ], + "additionalProperties": false, + "description": "Symbolic local secret binding; no value is captured in the declaration." + } + ], + "description": "A literal string or a symbolic local environment/secret binding. Declaration reads preserve the binding without looking up values. Only the consuming operation resolves bindings; they are not source-provided literals.", + "examples": [ + "literal text", + { + "env": "SERVICE_TOKEN" + }, + { + "secret": "service-token" + } + ] + }, + "prompt": { + "oneOf": [ + { + "type": "string", + "description": "Inline prompt body, including any literal newlines." + }, + { + "type": "object", + "properties": { + "file": { + "$ref": "#/$defs/resource", + "description": "Resource containing the prompt body, resolved in its declaring source context." + } + }, + "required": [ + "file" + ], + "additionalProperties": false, + "description": "Prompt body read from a resource by the consuming operation." + } + ], + "description": "Inline prompt text or a reference to a prompt file. Declaration reads do not read the file. Command input tokens use ${input:name}; $${input:name} escapes a literal token." + }, + "run": { + "type": "object", + "properties": { + "executable": { + "type": "string", + "description": "Required program name or relative executable path. A bare name is resolved by the consuming operation; paths containing / are source resources. Reading the declaration never starts the program." + }, + "arguments": { + "type": "array", + "items": { + "type": "string" + }, + "maxItems": 10000, + "description": "Arguments in invocation order, passed as individual strings. Omission or an empty sequence supplies no arguments." + }, + "environment": { + "type": "object", + "additionalProperties": { + "$ref": "#/$defs/binding" + }, + "maxProperties": 10000, + "description": "Environment variable names mapped to literals or local bindings. Omission or an empty mapping supplies no declared entries; reading the declaration does not resolve bindings." + }, + "workingDirectory": { + "$ref": "#/$defs/resource", + "description": "Working directory resource, resolved by the consuming operation. Omission leaves the directory unspecified in the declaration." + }, + "executableSource": { + "type": "string", + "description": "Source alias for a resource executable path. Omission uses the declaring source; a bare PATH command cannot specify a source." + } + }, + "required": [ + "executable" + ], + "additionalProperties": false, + "description": "A declared invocation, preserved as data until a consuming operation explicitly uses it. It does not contain a shell command line." + }, + "transport": { + "oneOf": [ + { + "type": "object", + "properties": { + "kind": { + "const": "stdio", + "description": "Selects the local stdio transport." + }, + "executable": { + "type": "string", + "description": "Required program name or relative executable path. A bare name is resolved by the consuming operation; paths containing / are source resources. Reading the declaration never starts the program." + }, + "arguments": { + "type": "array", + "items": { + "type": "string" + }, + "maxItems": 10000, + "description": "Arguments in invocation order, passed as individual strings. Omission or an empty sequence supplies no arguments." + }, + "environment": { + "type": "object", + "additionalProperties": { + "$ref": "#/$defs/binding" + }, + "maxProperties": 10000, + "description": "Environment variable names mapped to literals or local bindings. Omission or an empty mapping supplies no declared entries; reading the declaration does not resolve bindings." + }, + "workingDirectory": { + "$ref": "#/$defs/resource", + "description": "Working directory resource, resolved by the consuming operation. Omission leaves the directory unspecified in the declaration." + }, + "executableSource": { + "type": "string", + "description": "Source alias for a resource executable path. Omission uses the declaring source; a bare PATH command cannot specify a source." + } + }, + "required": [ + "kind", + "executable" + ], + "additionalProperties": false, + "description": "Local MCP server invocation over standard input/output." + }, + { + "type": "object", + "properties": { + "kind": { + "type": "string", + "enum": [ + "streamableHTTP", + "sse" + ], + "description": "Selects Streamable HTTP or SSE transport." + }, + "url": { + "type": "string", + "description": "Required HTTP or HTTPS endpoint with a host and no embedded credentials or fragment." + }, + "headers": { + "type": "object", + "additionalProperties": { + "$ref": "#/$defs/binding" + }, + "maxProperties": 10000, + "description": "HTTP header names mapped to literals or local bindings. Omission or an empty mapping supplies no declared headers. Values remain unresolved during declaration reads." + } + }, + "required": [ + "kind", + "url" + ], + "additionalProperties": false, + "description": "Remote MCP endpoint with optional literal or locally bound headers." + } + ], + "description": "MCP connection declaration: a local stdio invocation, Streamable HTTP or SSE. Parsing neither starts a server nor opens a connection." + }, + "event": { + "oneOf": [ + { + "type": "string", + "enum": [ + "beforeTool", + "afterTool", + "sessionStart", + "sessionEnd" + ], + "description": "Portable event mapped by the target client adapter." + }, + { + "type": "object", + "properties": { + "native": { + "type": "string", + "description": "Event name in the selected client's vocabulary; the component must explicitly target exactly one agent." + } + }, + "required": [ + "native" + ], + "additionalProperties": false, + "description": "Client-specific hook event; support is checked by the consuming adapter." + } + ], + "description": "Portable hook event or a client-native event name. A native event requires exactly one explicit component recipient." + }, + "operation": { + "oneOf": [ + { + "type": "string", + "enum": [ + "read", + "write", + "execute" + ], + "description": "Portable file-read, file-write or program-execution operation." + }, + { + "type": "object", + "properties": { + "tool": { + "type": "string", + "description": "Tool identifier to which the rule applies." + } + }, + "required": [ + "tool" + ], + "additionalProperties": false, + "description": "Named tool operation interpreted by the target client." + } + ], + "description": "Portable permission operation or a named client tool operation. Interpretation belongs to the target client adapter." + }, + "rule": { + "type": "object", + "properties": { + "effect": { + "type": "string", + "enum": [ + "allow", + "ask", + "deny" + ], + "description": "Allow, ask for confirmation, or deny the matching operation in the target client." + }, + "operation": { + "$ref": "#/$defs/operation", + "description": "Portable operation or named client tool to match." + }, + "pattern": { + "type": "string", + "description": "Match pattern interpreted for the operation by the target adapter. Read and write patterns must be safe relative resource paths." + } + }, + "required": [ + "effect", + "operation", + "pattern" + ], + "additionalProperties": false, + "description": "One permission rule. Rules retain declaration order; the target client determines enforcement semantics." + }, + "parameter": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "Input token name used in ${input:name}. It must be nonempty and contain no }, colon or NUL." + }, + "description": { + "type": "string", + "description": "User-facing explanation of the input requested by the command." + }, + "defaultValue": { + "type": "string", + "description": "Optional literal default input text. Omission leaves the default unspecified; an empty string is an explicit empty default." + } + }, + "required": [ + "name", + "description" + ], + "additionalProperties": false, + "description": "A named command input. Parameter names must be unique within the command; inline prompt tokens must refer to declared parameters." + }, + "promptDeclaration": { + "type": "object", + "properties": { + "sections": { + "type": "array", + "items": { + "$ref": "#/$defs/section" + }, + "maxItems": 10000, + "description": "Instruction sections in rendering order, including repeated references. Omission or an empty sequence supplies none." + }, + "append": { + "type": "string", + "description": "Relative file appended to the prompt by the consuming operation. In project scope it uses the declaring source; in user scope it is relative to the user home directory. Omission appends no file." + }, + "condition": { + "$ref": "#/$defs/condition", + "description": "Additional scope/platform restrictions for this named prompt. Omission imposes no additional restriction." + } + }, + "required": [], + "additionalProperties": false, + "description": "A named ChatGPT prompt composed from ordered instruction sections and an optional append file. Names are the keys in chatgpt; omission of sections means an empty sequence." + }, + "override": { + "type": "object", + "properties": { + "agents": { + "type": "array", + "items": { + "$ref": "#/$defs/agent" + }, + "maxItems": 10000, + "description": "Recipients for this skill instead of component/default recipients. Omission inherits; an empty list selects no recipients. Enclosing conditions still restrict the result." + }, + "mode": { + "type": "string", + "enum": [ + "link", + "copy", + "edit" + ], + "description": "Installation mode for this skill instead of the component mode. Omission inherits. edit requires a live local source without a requirement." + } + }, + "required": [], + "additionalProperties": false, + "description": "Per-skill recipient and installation-mode overrides. The mapping key is the skill name and must belong to an explicit selection when one is supplied." + }, + "requirement": { + "oneOf": [ + { + "type": "object", + "properties": { + "branch": { + "type": "string", + "description": "Track the named Git branch." + } + }, + "required": [ + "branch" + ], + "additionalProperties": false, + "description": "Track the named Git branch." + }, + { + "type": "object", + "properties": { + "revision": { + "type": "string", + "description": "Select the specified Git revision." + } + }, + "required": [ + "revision" + ], + "additionalProperties": false, + "description": "Select the specified Git revision." + }, + { + "type": "object", + "properties": { + "exact": { + "type": "string", + "description": "Select exactly this semantic version tag." + } + }, + "required": [ + "exact" + ], + "additionalProperties": false, + "description": "Select exactly this semantic version tag." + }, + { + "type": "object", + "properties": { + "from": { + "type": "string", + "description": "Inclusive semantic-version lower bound, below the next major version." + } + }, + "required": [ + "from" + ], + "additionalProperties": false, + "description": "Inclusive semantic-version lower bound, below the next major version." + }, + { + "type": "object", + "properties": { + "upToNextMinor": { + "type": "string", + "description": "Inclusive semantic-version lower bound, below the next minor version." + } + }, + "required": [ + "upToNextMinor" + ], + "additionalProperties": false, + "description": "Inclusive semantic-version lower bound, below the next minor version." + }, + { + "type": "object", + "properties": { + "from": { + "type": "string", + "description": "Inclusive semantic-version lower bound." + }, + "to": { + "type": "string", + "description": "Exclusive semantic-version upper bound, greater than from." + } + }, + "required": [ + "from", + "to" + ], + "additionalProperties": false, + "description": "Semantic-version interval with an inclusive lower bound and exclusive upper bound. The lower bound must be less than the upper bound." + } + ], + "description": "One Git selection policy, also applicable to local Git repositories. Version requirements select semantic-version tags; a resolved lock records the exact revision. Reading the declaration never performs resolution.", + "examples": [ + { + "from": "1.2.0" + }, + { + "from": "1.2.0", + "to": "2.0.0" + }, + { + "branch": "main" + } + ] + }, + "source": { + "oneOf": [ + { + "type": "object", + "properties": { + "url": { + "type": "string", + "description": "Git transport URL. Complete URLs avoid canonicalization warnings; normalized repository identities must be distinct across aliases." + }, + "subpath": { + "type": "string", + "description": "Safe relative discovery path inside the source. Omission uses the source root; it cannot escape that root." + }, + "requirement": { + "$ref": "#/$defs/requirement", + "description": "Git selection policy. Omission leaves the source without an explicit requirement; resolution and exact locking belong to the consuming operation." + } + }, + "required": [ + "url" + ], + "additionalProperties": false, + "description": "Git repository selected by a transport URL and optional requirement." + }, + { + "type": "object", + "properties": { + "path": { + "type": "string", + "description": "Local path, relative to the declaring project directory unless absolute or home-relative. A requirement selects committed content from a local Git repository; edit mode requires no requirement." + }, + "subpath": { + "type": "string", + "description": "Safe relative discovery path inside the source. Omission uses the source root; it cannot escape that root." + }, + "requirement": { + "$ref": "#/$defs/requirement", + "description": "Git selection policy. Omission leaves the source without an explicit requirement; resolution and exact locking belong to the consuming operation." + } + }, + "required": [ + "path" + ], + "additionalProperties": false, + "description": "Local source interpreted using the directories of its declaring environment." + }, + { + "type": "object", + "properties": { + "index": { + "type": "string", + "description": "HTTP or HTTPS well-known skill index URL, without embedded credentials or fragment. Git requirements do not apply to this source kind." + }, + "subpath": { + "type": "string", + "description": "Safe relative discovery path inside the source. Omission uses the source root; it cannot escape that root." + } + }, + "required": [ + "index" + ], + "additionalProperties": false, + "description": "Well-known skill index accessed only during source-consuming operations." + } + ], + "description": "Exactly one Git URL, local path or well-known skill index per alias. subpath narrows the discovery root. No source is accessed while reading the declaration." + }, + "componentReference": { + "type": "object", + "properties": { + "kind": { + "type": "string", + "enum": [ + "skill", + "instruction", + "mcpServer", + "hook", + "subagent", + "command", + "lspServer", + "permissions", + "ignore", + "plugin" + ], + "description": "Kind of the individual plugin member to exclude." + }, + "name": { + "type": "string", + "description": "Relative member name within the plugin, paired with kind to identify the exclusion. Duplicate kind/name exclusions are errors." + } + }, + "required": [ + "kind", + "name" + ], + "additionalProperties": false, + "description": "A typed member reference used to exclude one component from a plugin expansion. The singular skill and instruction kinds identify individual members." + }, + "component_skills": { + "type": "object", + "properties": { + "kind": { + "const": "skills", + "description": "Selects the skills component shape." + }, + "agents": { + "type": "array", + "items": { + "$ref": "#/$defs/agent" + }, + "maxItems": 10000, + "description": "Explicit component recipients. Omission inherits the declaring document's defaultAgents; an empty list selects none. Conditions further restrict effective recipients." + }, + "condition": { + "$ref": "#/$defs/condition", + "description": "Additional restrictions intersected with enclosing group/use conditions. Omission imposes no additional restriction; inactive components remain validated and preserved." + }, + "native": { + "type": "object", + "additionalProperties": { + "type": "object", + "additionalProperties": { + "x-agents-native-value": true, + "description": "Arbitrary native data. Core preserves numeric kind and decimal lexical identity, including explicit !!float scalar payloads; general JSON Schema does not express these YAML-specific checks." + }, + "maxProperties": 10000, + "description": "Native fields for one client schema identifier. Keys and values remain client data; portable field ownership and deployment support are checked by the consuming operation." + }, + "maxProperties": 10000, + "description": "Client-schema identifiers mapped to native field mappings. Omission or an empty mapping supplies no native fields. Values are data, never environment/secret bindings: strings, representable integers, finite decimals, booleans, null, arrays and objects. Core preserves integer/decimal kind and exact decimal text; !!float \"1.00\" explicitly retains decimal identity, which general JSON Schema cannot validate. Objects have unordered domain semantics and << is an ordinary key." + }, + "source": { + "type": "string", + "description": "Required source alias, or . for the current declaring source. Source resolution occurs only in the consuming operation." + }, + "select": { + "oneOf": [ + { + "const": "all", + "description": "Select all discovered skills, subject to exclusions." + }, + { + "type": "array", + "items": { + "type": "string" + }, + "maxItems": 10000, + "description": "Select only these skill names; an empty sequence selects none." + } + ], + "description": "all or omission selects all discovered skills; a name sequence selects those skills. An empty sequence selects none. Selection is combined with exclude and per-skill overrides." + }, + "exclude": { + "type": "array", + "items": { + "type": "string" + }, + "maxItems": 10000, + "description": "Skill names removed from the selection. Omission or an empty sequence excludes none." + }, + "mode": { + "type": "string", + "enum": [ + "link", + "copy", + "edit" + ], + "description": "link shares cached content, copy creates an installed directory, and edit links live local content. Omission defaults to link. edit requires a local source without a requirement or pin." + }, + "overrides": { + "type": "object", + "additionalProperties": { + "$ref": "#/$defs/override" + }, + "maxProperties": 10000, + "description": "Skill names mapped to recipient/mode overrides. Omission or an empty mapping supplies none; omitted override fields inherit the component settings." + }, + "path": { + "type": "string", + "description": "Optional discovery path relative to the selected filesystem source view. Narrows discovery without changing containment. Not supported for index sources." + } + }, + "required": [ + "kind", + "source" + ], + "additionalProperties": false, + "description": "Select skills from a source and declare their recipients and installation modes.", + "examples": [ + { + "kind": "skills", + "source": "team", + "select": [ + "review" + ], + "agents": [ + "codex" + ] + } + ] + }, + "component_instructions": { + "type": "object", + "properties": { + "kind": { + "const": "instructions", + "description": "Selects the instructions component shape." + }, + "agents": { + "type": "array", + "items": { + "$ref": "#/$defs/agent" + }, + "maxItems": 10000, + "description": "Explicit component recipients. Omission inherits the declaring document's defaultAgents; an empty list selects none. Conditions further restrict effective recipients." + }, + "condition": { + "$ref": "#/$defs/condition", + "description": "Additional restrictions intersected with enclosing group/use conditions. Omission imposes no additional restriction; inactive components remain validated and preserved." + }, + "native": { + "type": "object", + "additionalProperties": { + "type": "object", + "additionalProperties": { + "x-agents-native-value": true, + "description": "Arbitrary native data. Core preserves numeric kind and decimal lexical identity, including explicit !!float scalar payloads; general JSON Schema does not express these YAML-specific checks." + }, + "maxProperties": 10000, + "description": "Native fields for one client schema identifier. Keys and values remain client data; portable field ownership and deployment support are checked by the consuming operation." + }, + "maxProperties": 10000, + "description": "Client-schema identifiers mapped to native field mappings. Omission or an empty mapping supplies no native fields. Values are data, never environment/secret bindings: strings, representable integers, finite decimals, booleans, null, arrays and objects. Core preserves integer/decimal kind and exact decimal text; !!float \"1.00\" explicitly retains decimal identity, which general JSON Schema cannot validate. Objects have unordered domain semantics and << is an ordinary key." + }, + "sections": { + "type": "array", + "items": { + "$ref": "#/$defs/section" + }, + "maxItems": 10000, + "description": "Instruction sections in rendering order. Omission or an empty sequence supplies none; repeated references retain their occurrences." + }, + "chatgpt": { + "type": "object", + "additionalProperties": { + "$ref": "#/$defs/promptDeclaration" + }, + "maxProperties": 10000, + "description": "Named ChatGPT prompts retained in declaration order, separate from agent-targeted sections. Omission or an empty mapping declares none." + } + }, + "required": [ + "kind" + ], + "additionalProperties": false, + "description": "Compose instruction targets and named ChatGPT prompts from ordered section references." + }, + "mcpRegistry": { + "type": "object", + "description": "The captured registry server version and selected executable package or endpoint.", + "properties": { + "registry": { + "type": "string", + "description": "Registry base URL as observed at selection." + }, + "server": { + "type": "string", + "description": "Full server name in the registry." + }, + "version": { + "type": "string", + "description": "Exact version of the server definition." + }, + "origin": { + "type": "string", + "description": "Canonical HTTP origin of the selected endpoint or artifact registry." + }, + "package": { + "type": "string", + "description": "Exact package or image coordinate for a stdio selection." + }, + "invocationDigest": { + "type": "string", + "description": "Digest binding the captured registry selection to its typed invocation." + }, + "portableBindings": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "maxProperties": 10000, + "description": "Digests of non-secret registry literals eligible for portable export." + } + }, + "required": ["registry", "server", "version", "origin"], + "additionalProperties": false + }, + "component_mcpServer": { + "type": "object", + "properties": { + "kind": { + "const": "mcpServer", + "description": "Selects the mcpServer component shape." + }, + "agents": { + "type": "array", + "items": { + "$ref": "#/$defs/agent" + }, + "maxItems": 10000, + "description": "Explicit component recipients. Omission inherits the declaring document's defaultAgents; an empty list selects none. Conditions further restrict effective recipients." + }, + "condition": { + "$ref": "#/$defs/condition", + "description": "Additional restrictions intersected with enclosing group/use conditions. Omission imposes no additional restriction; inactive components remain validated and preserved." + }, + "native": { + "type": "object", + "additionalProperties": { + "type": "object", + "additionalProperties": { + "x-agents-native-value": true, + "description": "Arbitrary native data. Core preserves numeric kind and decimal lexical identity, including explicit !!float scalar payloads; general JSON Schema does not express these YAML-specific checks." + }, + "maxProperties": 10000, + "description": "Native fields for one client schema identifier. Keys and values remain client data; portable field ownership and deployment support are checked by the consuming operation." + }, + "maxProperties": 10000, + "description": "Client-schema identifiers mapped to native field mappings. Omission or an empty mapping supplies no native fields. Values are data, never environment/secret bindings: strings, representable integers, finite decimals, booleans, null, arrays and objects. Core preserves integer/decimal kind and exact decimal text; !!float \"1.00\" explicitly retains decimal identity, which general JSON Schema cannot validate. Objects have unordered domain semantics and << is an ordinary key." + }, + "name": { + "type": "string", + "description": "Required relative component name, retained as its symbolic identity. Nested names use / separators; empty, . and .. segments are not allowed." + }, + "registry": { + "$ref": "#/$defs/mcpRegistry", + "description": "Origin and version of a registry-selected MCP definition." + }, + "transport": { + "$ref": "#/$defs/transport", + "description": "Required MCP transport and its unresolved connection settings." + } + }, + "required": [ + "kind", + "name", + "transport" + ], + "additionalProperties": false, + "description": "Declare a named MCP server connection without starting or contacting it." + }, + "component_hook": { + "type": "object", + "properties": { + "kind": { + "const": "hook", + "description": "Selects the hook component shape." + }, + "agents": { + "type": "array", + "items": { + "$ref": "#/$defs/agent" + }, + "maxItems": 10000, + "description": "Explicit component recipients. Omission inherits the declaring document's defaultAgents; an empty list selects none. Conditions further restrict effective recipients." + }, + "condition": { + "$ref": "#/$defs/condition", + "description": "Additional restrictions intersected with enclosing group/use conditions. Omission imposes no additional restriction; inactive components remain validated and preserved." + }, + "native": { + "type": "object", + "additionalProperties": { + "type": "object", + "additionalProperties": { + "x-agents-native-value": true, + "description": "Arbitrary native data. Core preserves numeric kind and decimal lexical identity, including explicit !!float scalar payloads; general JSON Schema does not express these YAML-specific checks." + }, + "maxProperties": 10000, + "description": "Native fields for one client schema identifier. Keys and values remain client data; portable field ownership and deployment support are checked by the consuming operation." + }, + "maxProperties": 10000, + "description": "Client-schema identifiers mapped to native field mappings. Omission or an empty mapping supplies no native fields. Values are data, never environment/secret bindings: strings, representable integers, finite decimals, booleans, null, arrays and objects. Core preserves integer/decimal kind and exact decimal text; !!float \"1.00\" explicitly retains decimal identity, which general JSON Schema cannot validate. Objects have unordered domain semantics and << is an ordinary key." + }, + "name": { + "type": "string", + "description": "Required relative component name, retained as its symbolic identity. Nested names use / separators; empty, . and .. segments are not allowed." + }, + "event": { + "$ref": "#/$defs/event", + "description": "Required portable or native hook event. Native events require exactly one explicit component recipient." + }, + "run": { + "$ref": "#/$defs/run", + "description": "Required invocation performed when the target client triggers this hook. Declaration reads never execute it." + }, + "matcher": { + "type": "string", + "description": "Optional target-client matcher text. Omission leaves matching unspecified; support and interpretation belong to the adapter." + }, + "timeoutSeconds": { + "type": "integer", + "minimum": 1, + "x-agents-scalar-kind": "integer", + "description": "Positive plain integer timeout in seconds. Omission leaves the timeout unspecified. Core rejects decimal spellings such as 1.0 and out-of-range integers." + } + }, + "required": [ + "kind", + "name", + "event", + "run" + ], + "additionalProperties": false, + "description": "Declare a named event-triggered invocation without executing it." + }, + "component_subagent": { + "type": "object", + "properties": { + "kind": { + "const": "subagent", + "description": "Selects the subagent component shape." + }, + "agents": { + "type": "array", + "items": { + "$ref": "#/$defs/agent" + }, + "maxItems": 10000, + "description": "Explicit component recipients. Omission inherits the declaring document's defaultAgents; an empty list selects none. Conditions further restrict effective recipients." + }, + "condition": { + "$ref": "#/$defs/condition", + "description": "Additional restrictions intersected with enclosing group/use conditions. Omission imposes no additional restriction; inactive components remain validated and preserved." + }, + "native": { + "type": "object", + "additionalProperties": { + "type": "object", + "additionalProperties": { + "x-agents-native-value": true, + "description": "Arbitrary native data. Core preserves numeric kind and decimal lexical identity, including explicit !!float scalar payloads; general JSON Schema does not express these YAML-specific checks." + }, + "maxProperties": 10000, + "description": "Native fields for one client schema identifier. Keys and values remain client data; portable field ownership and deployment support are checked by the consuming operation." + }, + "maxProperties": 10000, + "description": "Client-schema identifiers mapped to native field mappings. Omission or an empty mapping supplies no native fields. Values are data, never environment/secret bindings: strings, representable integers, finite decimals, booleans, null, arrays and objects. Core preserves integer/decimal kind and exact decimal text; !!float \"1.00\" explicitly retains decimal identity, which general JSON Schema cannot validate. Objects have unordered domain semantics and << is an ordinary key." + }, + "name": { + "type": "string", + "description": "Required relative component name, retained as its symbolic identity. Nested names use / separators; empty, . and .. segments are not allowed." + }, + "description": { + "type": "string", + "description": "User-facing explanation of when to use this subagent." + }, + "prompt": { + "$ref": "#/$defs/prompt", + "description": "Required inline prompt or prompt-file reference. File contents are not read during declaration parsing." + }, + "model": { + "type": "string", + "description": "Optional target-client model identifier. Omission leaves model selection unspecified." + }, + "tools": { + "type": "array", + "items": { + "type": "string" + }, + "maxItems": 10000, + "description": "Optional target-client tool names. Omission leaves the tool list unspecified; an empty sequence is an explicit empty list." + } + }, + "required": [ + "kind", + "name", + "description", + "prompt" + ], + "additionalProperties": false, + "description": "Declare a named subagent with a description and prompt body." + }, + "component_command": { + "type": "object", + "properties": { + "kind": { + "const": "command", + "description": "Selects the command component shape." + }, + "agents": { + "type": "array", + "items": { + "$ref": "#/$defs/agent" + }, + "maxItems": 10000, + "description": "Explicit component recipients. Omission inherits the declaring document's defaultAgents; an empty list selects none. Conditions further restrict effective recipients." + }, + "condition": { + "$ref": "#/$defs/condition", + "description": "Additional restrictions intersected with enclosing group/use conditions. Omission imposes no additional restriction; inactive components remain validated and preserved." + }, + "native": { + "type": "object", + "additionalProperties": { + "type": "object", + "additionalProperties": { + "x-agents-native-value": true, + "description": "Arbitrary native data. Core preserves numeric kind and decimal lexical identity, including explicit !!float scalar payloads; general JSON Schema does not express these YAML-specific checks." + }, + "maxProperties": 10000, + "description": "Native fields for one client schema identifier. Keys and values remain client data; portable field ownership and deployment support are checked by the consuming operation." + }, + "maxProperties": 10000, + "description": "Client-schema identifiers mapped to native field mappings. Omission or an empty mapping supplies no native fields. Values are data, never environment/secret bindings: strings, representable integers, finite decimals, booleans, null, arrays and objects. Core preserves integer/decimal kind and exact decimal text; !!float \"1.00\" explicitly retains decimal identity, which general JSON Schema cannot validate. Objects have unordered domain semantics and << is an ordinary key." + }, + "name": { + "type": "string", + "description": "Required relative component name, retained as its symbolic identity. Nested names use / separators; empty, . and .. segments are not allowed." + }, + "description": { + "type": "string", + "description": "User-facing explanation of this prompt command." + }, + "prompt": { + "$ref": "#/$defs/prompt", + "description": "Required inline prompt or prompt-file reference. ${input:name} refers to a declared parameter; $${input:name} is literal text." + }, + "parameters": { + "type": "array", + "items": { + "$ref": "#/$defs/parameter" + }, + "maxItems": 10000, + "description": "Inputs in declaration order. Omission or an empty sequence declares none. Names must be unique and inline prompt tokens must refer to these names." + } + }, + "required": [ + "kind", + "name", + "description", + "prompt" + ], + "additionalProperties": false, + "description": "Declare a named prompt command and its input parameters." + }, + "component_lspServer": { + "type": "object", + "properties": { + "kind": { + "const": "lspServer", + "description": "Selects the lspServer component shape." + }, + "agents": { + "type": "array", + "items": { + "$ref": "#/$defs/agent" + }, + "maxItems": 10000, + "description": "Explicit component recipients. Omission inherits the declaring document's defaultAgents; an empty list selects none. Conditions further restrict effective recipients." + }, + "condition": { + "$ref": "#/$defs/condition", + "description": "Additional restrictions intersected with enclosing group/use conditions. Omission imposes no additional restriction; inactive components remain validated and preserved." + }, + "native": { + "type": "object", + "additionalProperties": { + "type": "object", + "additionalProperties": { + "x-agents-native-value": true, + "description": "Arbitrary native data. Core preserves numeric kind and decimal lexical identity, including explicit !!float scalar payloads; general JSON Schema does not express these YAML-specific checks." + }, + "maxProperties": 10000, + "description": "Native fields for one client schema identifier. Keys and values remain client data; portable field ownership and deployment support are checked by the consuming operation." + }, + "maxProperties": 10000, + "description": "Client-schema identifiers mapped to native field mappings. Omission or an empty mapping supplies no native fields. Values are data, never environment/secret bindings: strings, representable integers, finite decimals, booleans, null, arrays and objects. Core preserves integer/decimal kind and exact decimal text; !!float \"1.00\" explicitly retains decimal identity, which general JSON Schema cannot validate. Objects have unordered domain semantics and << is an ordinary key." + }, + "name": { + "type": "string", + "description": "Required relative component name, retained as its symbolic identity. Nested names use / separators; empty, . and .. segments are not allowed." + }, + "run": { + "$ref": "#/$defs/run", + "description": "Required language server invocation, retained as data until used by the consuming operation." + }, + "languages": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "maxProperties": 10000, + "description": "File extensions, including a leading dot, mapped to nonempty language identifiers. An empty mapping declares no extension associations.", + "examples": [ + { + ".swift": "swift" + } + ] + }, + "initializationOptions": { + "type": "object", + "additionalProperties": { + "x-agents-native-value": true, + "description": "Arbitrary native data, including null, nested arrays/objects and decimals with exact lexical identity. Bindings are not evaluated here." + }, + "maxProperties": 10000, + "description": "Native values passed as language server initialization options. Omission or an empty mapping supplies none. Values retain Core integer/decimal kind and exact decimal text; !!float \"1.00\" explicitly marks a decimal. Null and nested arrays/objects are data, not runtime bindings." + } + }, + "required": [ + "kind", + "name", + "run", + "languages" + ], + "additionalProperties": false, + "description": "Declare a named language server invocation and extension-to-language mapping." + }, + "component_permissions": { + "type": "object", + "properties": { + "kind": { + "const": "permissions", + "description": "Selects the permissions component shape." + }, + "agents": { + "type": "array", + "items": { + "$ref": "#/$defs/agent" + }, + "maxItems": 10000, + "description": "Explicit component recipients. Omission inherits the declaring document's defaultAgents; an empty list selects none. Conditions further restrict effective recipients." + }, + "condition": { + "$ref": "#/$defs/condition", + "description": "Additional restrictions intersected with enclosing group/use conditions. Omission imposes no additional restriction; inactive components remain validated and preserved." + }, + "native": { + "type": "object", + "additionalProperties": { + "type": "object", + "additionalProperties": { + "x-agents-native-value": true, + "description": "Arbitrary native data. Core preserves numeric kind and decimal lexical identity, including explicit !!float scalar payloads; general JSON Schema does not express these YAML-specific checks." + }, + "maxProperties": 10000, + "description": "Native fields for one client schema identifier. Keys and values remain client data; portable field ownership and deployment support are checked by the consuming operation." + }, + "maxProperties": 10000, + "description": "Client-schema identifiers mapped to native field mappings. Omission or an empty mapping supplies no native fields. Values are data, never environment/secret bindings: strings, representable integers, finite decimals, booleans, null, arrays and objects. Core preserves integer/decimal kind and exact decimal text; !!float \"1.00\" explicitly retains decimal identity, which general JSON Schema cannot validate. Objects have unordered domain semantics and << is an ordinary key." + }, + "name": { + "type": "string", + "description": "Required relative component name, retained as its symbolic identity. Nested names use / separators; empty, . and .. segments are not allowed." + }, + "rules": { + "type": "array", + "items": { + "$ref": "#/$defs/rule" + }, + "maxItems": 10000, + "description": "Permission rules in declaration order. An empty sequence declares no rules. Enforcement belongs to the target client." + } + }, + "required": [ + "kind", + "name", + "rules" + ], + "additionalProperties": false, + "description": "Declare a named ordered collection of client permission rules." + }, + "component_ignore": { + "type": "object", + "properties": { + "kind": { + "const": "ignore", + "description": "Selects the ignore component shape." + }, + "agents": { + "type": "array", + "items": { + "$ref": "#/$defs/agent" + }, + "maxItems": 10000, + "description": "Explicit component recipients. Omission inherits the declaring document's defaultAgents; an empty list selects none. Conditions further restrict effective recipients." + }, + "condition": { + "$ref": "#/$defs/condition", + "description": "Additional restrictions intersected with enclosing group/use conditions. Omission imposes no additional restriction; inactive components remain validated and preserved." + }, + "native": { + "type": "object", + "additionalProperties": { + "type": "object", + "additionalProperties": { + "x-agents-native-value": true, + "description": "Arbitrary native data. Core preserves numeric kind and decimal lexical identity, including explicit !!float scalar payloads; general JSON Schema does not express these YAML-specific checks." + }, + "maxProperties": 10000, + "description": "Native fields for one client schema identifier. Keys and values remain client data; portable field ownership and deployment support are checked by the consuming operation." + }, + "maxProperties": 10000, + "description": "Client-schema identifiers mapped to native field mappings. Omission or an empty mapping supplies no native fields. Values are data, never environment/secret bindings: strings, representable integers, finite decimals, booleans, null, arrays and objects. Core preserves integer/decimal kind and exact decimal text; !!float \"1.00\" explicitly retains decimal identity, which general JSON Schema cannot validate. Objects have unordered domain semantics and << is an ordinary key." + }, + "name": { + "type": "string", + "description": "Required relative component name, retained as its symbolic identity. Nested names use / separators; empty, . and .. segments are not allowed." + }, + "patterns": { + "type": "array", + "items": { + "type": "string" + }, + "maxItems": 10000, + "description": "Ignore patterns in declaration order, interpreted by the target client for the selected purpose. An empty sequence declares none." + }, + "purpose": { + "type": "string", + "enum": [ + "context", + "indexing" + ], + "description": "context excludes content from model context; indexing excludes it from indexing. Omission defaults to context; support is checked by the consuming adapter." + } + }, + "required": [ + "kind", + "name", + "patterns" + ], + "additionalProperties": false, + "description": "Declare a named collection of context or indexing ignore patterns." + }, + "component_plugin": { + "type": "object", + "properties": { + "kind": { + "const": "plugin", + "description": "Selects the plugin component shape." + }, + "agents": { + "type": "array", + "items": { + "$ref": "#/$defs/agent" + }, + "maxItems": 10000, + "description": "Explicit component recipients. Omission inherits the declaring document's defaultAgents; an empty list selects none. Conditions further restrict effective recipients." + }, + "condition": { + "$ref": "#/$defs/condition", + "description": "Additional restrictions intersected with enclosing group/use conditions. Omission imposes no additional restriction; inactive components remain validated and preserved." + }, + "native": { + "type": "object", + "additionalProperties": { + "type": "object", + "additionalProperties": { + "x-agents-native-value": true, + "description": "Arbitrary native data. Core preserves numeric kind and decimal lexical identity, including explicit !!float scalar payloads; general JSON Schema does not express these YAML-specific checks." + }, + "maxProperties": 10000, + "description": "Native fields for one client schema identifier. Keys and values remain client data; portable field ownership and deployment support are checked by the consuming operation." + }, + "maxProperties": 10000, + "description": "Client-schema identifiers mapped to native field mappings. Omission or an empty mapping supplies no native fields. Values are data, never environment/secret bindings: strings, representable integers, finite decimals, booleans, null, arrays and objects. Core preserves integer/decimal kind and exact decimal text; !!float \"1.00\" explicitly retains decimal identity, which general JSON Schema cannot validate. Objects have unordered domain semantics and << is an ordinary key." + }, + "name": { + "type": "string", + "description": "Required relative component name, retained as its symbolic identity. Nested names use / separators; empty, . and .. segments are not allowed." + }, + "source": { + "type": "string", + "description": "Required source alias, or . for the declaring source, containing the plugin resource." + }, + "path": { + "type": "string", + "description": "Required safe relative plugin resource path within the selected source." + }, + "mode": { + "type": "string", + "enum": [ + "native", + "components" + ], + "description": "components (the default) expands plugin members. native installs the vendor plugin for exactly one explicit recipient and forbids select and nonempty exclude." + }, + "select": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "skills", + "instructions", + "mcpServer", + "hook", + "subagent", + "command", + "lspServer", + "permissions", + "ignore", + "plugin" + ] + }, + "maxItems": 10000, + "description": "Component kinds to include during components-mode expansion. Omission leaves kinds unrestricted; an empty sequence selects none. Duplicate kinds are errors." + }, + "exclude": { + "type": "array", + "items": { + "$ref": "#/$defs/componentReference" + }, + "maxItems": 10000, + "description": "Typed individual members removed from components-mode expansion. Omission or an empty sequence excludes none. Each kind/name pair must be unique." + } + }, + "required": [ + "kind", + "name", + "source", + "path" + ], + "additionalProperties": false, + "description": "Declare a plugin resource for native installation or component expansion." + }, + "component": { + "oneOf": [ + { + "$ref": "#/$defs/component_skills" + }, + { + "$ref": "#/$defs/component_instructions" + }, + { + "$ref": "#/$defs/component_mcpServer" + }, + { + "$ref": "#/$defs/component_hook" + }, + { + "$ref": "#/$defs/component_subagent" + }, + { + "$ref": "#/$defs/component_command" + }, + { + "$ref": "#/$defs/component_lspServer" + }, + { + "$ref": "#/$defs/component_permissions" + }, + { + "$ref": "#/$defs/component_ignore" + }, + { + "$ref": "#/$defs/component_plugin" + } + ], + "description": "One component declaration, selected by its required kind. All fields are checked even when the component is inactive; target-client support is evaluated by the consuming operation." + }, + "use": { + "type": "object", + "properties": { + "group": { + "type": "string", + "description": "Required group name. Without source it must name a local group; a named source must export the group before linking can use it." + }, + "source": { + "type": "string", + "description": "Alias of the producer exporting this group. Omission selects a local group; . addresses the current source. Remote source aliases are not rebound in the importing document." + }, + "condition": { + "$ref": "#/$defs/condition", + "description": "Additional restrictions for this expansion, intersected with group and enclosing conditions. Omission imposes no additional restriction." + } + }, + "required": [ + "group" + ], + "additionalProperties": false, + "description": "Activate a local group or an exported group from a source. Uses retain order and occurrences; nested conditions intersect and source aliases remain local to their declaring document.", + "examples": [ + { + "group": "checks" + }, + { + "group": "checks", + "source": "team" + } + ] + }, + "group": { + "type": "object", + "properties": { + "components": { + "type": "array", + "items": { + "$ref": "#/$defs/component" + }, + "maxItems": 10000, + "description": "Direct components retained in declaration order. Omission or an empty sequence contributes none." + }, + "uses": { + "type": "array", + "items": { + "$ref": "#/$defs/use" + }, + "maxItems": 10000, + "description": "Nested group uses expanded in declaration order. Omission or an empty sequence references none." + }, + "condition": { + "$ref": "#/$defs/condition", + "description": "Restrictions intersected with each importing use and nested component/section condition. Omission imposes no additional restriction." + } + }, + "required": [], + "additionalProperties": false, + "description": "A reusable group of direct components and nested uses. Definition alone does not activate it. Local use cycles are rejected, and unused or inactive contents are still validated." + } + } +} diff --git a/Sources/AgentsManifest/SourcePolicyDocument.swift b/Sources/AgentsManifest/SourcePolicyDocument.swift new file mode 100644 index 0000000..cd12e27 --- /dev/null +++ b/Sources/AgentsManifest/SourcePolicyDocument.swift @@ -0,0 +1,167 @@ +import AgentsCore +import Foundation + +/// The standalone version 1 install policy. Parsing performs no filesystem or network reads. +public enum SourcePolicyDocument { + public static func parse(_ bytes: Data, identity: DocumentIdentity) throws -> SourcePolicyRules { + let reader: YAMLReader + do { + reader = try YAMLReader(bytes: Array(bytes), identity: identity) + } catch let error as YAMLReadFailure { + throw ManifestFailure( + .init(code: "source-policy.yaml", message: "Invalid policy YAML.", span: error.span)) + } + func failure(_ node: YAMLNode, _ message: String) -> ManifestFailure { + ManifestFailure( + .init(code: "source-policy.field", message: message, span: reader.span(of: node))) + } + func string(_ node: YAMLNode) -> String? { + guard let scalar = node.scalar, !scalar.decimalTag, + scalar.quoted || YAMLScalar.classify(scalar.text) == .string + else { return nil } + return scalar.text + } + func rules(_ node: YAMLNode) throws -> [SourceOrigin] { + guard let items = node.items else { throw failure(node, "Expected a sequence of origins.") } + return try items.map { item in + if let name = string(item) { + switch name { + case "local": return .local + case "inline": return .inline + case "missing": return .missing + default: throw failure(item, "Unknown source origin.") + } + } + guard let pairs = item.pairs, pairs.count == 1, + let kind = string(pairs[0].key), let value = string(pairs[0].value) + else { throw failure(item, "Expected one Git, HTTP or local origin.") } + switch kind { + case "git": + guard let origin = try? SourceOrigin.git(value) else { + throw failure(pairs[0].value, "Invalid Git repository origin.") + } + return origin + case "http": + guard let origin = try? SourceOrigin.http(value) else { + throw failure(pairs[0].value, "Invalid HTTP origin.") + } + return origin + case "local": + guard value.hasPrefix("/"), !value.contains("\0") else { + throw failure(pairs[0].value, "Expected an absolute local path.") + } + return .local(path: value) + default: throw failure(pairs[0].key, "Unknown source origin kind.") + } + } + } + guard let pairs = reader.root.pairs else { + throw failure(reader.root, "Expected a policy mapping.") + } + var allow: [SourceOrigin]? + var deny: [SourceOrigin] = [] + var hasVersion = false + for (key, value) in pairs { + switch string(key) { + case "version": + guard let scalar = value.scalar, !scalar.quoted, !scalar.decimalTag, + YAMLScalar.integer(scalar.text) == 1 + else { throw failure(value, "Expected policy version 1.") } + hasVersion = true + case "allow": allow = try rules(value) + case "deny": deny = try rules(value) + default: throw failure(key, "Unknown source policy field.") + } + } + guard hasVersion else { throw failure(reader.root, "Missing policy version.") } + return SourcePolicyRules(allow: allow, deny: deny) + } + + /// Produces a complete policy document for a caller-owned save operation. + public static func bytes(for rules: SourcePolicyRules) throws -> Data { + let encoder = JSONEncoder() + encoder.outputFormatting = [.withoutEscapingSlashes] + func list(_ label: String, _ origins: [SourceOrigin]) throws -> String { + guard !origins.isEmpty else { return label + ": []\n" } + return try label + ":\n" + + origins.map { origin in + if let locator = origin.policyLocator { + let quoted = String(decoding: try encoder.encode(locator), as: UTF8.self) + return " - \(origin.kind.rawValue): \(quoted)\n" + } + return " - \(origin.kind.rawValue)\n" + }.joined() + } + var document = "version: 1\n" + if let allow = rules.allow { document += try list("allow", allow) } + if !rules.deny.isEmpty { document += try list("deny", rules.deny) } + return Data(document.utf8) + } +} + +/// Captures the same bytes used for admission and publication, including absent scope policies. +package struct SourcePolicySnapshot: PreparedEvidence { + package let effective: EffectiveSourcePolicy + package let readDependencies: [ReadDependency] + package let fingerprint: String + private let inputs: [TargetPrecondition] + private let sourceAccess: SourceAccessConfiguration + + package var isConfigured: Bool { + effective.isConfigured || sourceAccess.settingsFingerprint != nil + } + + package static func policyURL(in store: StateStore) -> URL { + store.directory.appendingPathComponent(StateStore.sourcePolicyFileName) + } + + package static func locations(in store: StateStore) -> [(SourcePolicyLayer.Scope, URL)] { + let user = StateStore(scope: .user, environment: store.environment) + var paths: [(SourcePolicyLayer.Scope, URL)] = [(.user, policyURL(in: user))] + if store.scope == .project { paths.append((.project, policyURL(in: store))) } + if let organization = store.environment.organizationSourcePolicyURL { + paths.append((.organization, organization)) + } + return paths + } + + package init(store: StateStore) throws { + sourceAccess = try store.environment.resolvedSourceAccess() + var layers: [SourcePolicyLayer] = [] + var evidence: [TargetPrecondition] = [] + var records: [String: String] = [:] + for (scope, url) in Self.locations(in: store) { + guard url.isFileURL else { throw CoreError.invalidState("source policy requires a file URL") } + let url = url.standardizedFileURL + let captured = try TargetPrecondition.readingFile(url) + evidence.append(captured.evidence) + if let bytes = captured.bytes { + let rules = try SourcePolicyDocument.parse(bytes, identity: DocumentIdentity(url.path)) + layers.append(.init(scope: scope, url: url, rules: rules)) + records[scope.rawValue + "\0" + url.path] = FileHash.sha256Hex(data: bytes) + } else if scope == .organization { + throw CoreError.notFound("organization source policy at " + url.path) + } + } + inputs = evidence + effective = EffectiveSourcePolicy(layers: layers) + readDependencies = + evidence.map { .entry($0.url) } + + (sourceAccess.settingsURL.map { [.entry($0)] } ?? []) + records["user-source-access"] = sourceAccess.settingsFingerprint + fingerprint = try ResolvedLedgerCodec.digest(records) + try validate() + } + + package func validate(excludingTargets targets: Set = []) throws { + try sourceAccess.requireCurrentSettings() + // Source policy is an input even if a caller includes its path in a publication footprint. + for input in inputs { + if targets.isEmpty { + try input.validate() + } else { + try input.validateDuringPublication() + } + } + } +} diff --git a/Sources/AgentsManifest/SourceReferenceEdits.swift b/Sources/AgentsManifest/SourceReferenceEdits.swift new file mode 100644 index 0000000..1eb3114 --- /dev/null +++ b/Sources/AgentsManifest/SourceReferenceEdits.swift @@ -0,0 +1,53 @@ +import AgentsCore + +/// Source references are roles in admitted declaration IR, not matching strings in YAML/native data. +enum SourceReferenceEdits { + static func replacing(_ alias: String, with replacement: String, in root: DeclarationValue) + -> [IREdit] + { + var edits: [IREdit] = [] + func visit(_ value: DeclarationValue, at pointer: String) { + guard let record = value.record else { return } + func reference(_ field: String) { + if record[field]?.string == alias { + edits.append(.set(pointer + "/" + field, .string(replacement))) + } + } + func child(_ field: String) { + if let value = record[field] { visit(value, at: pointer + "/" + field) } + } + func children(_ field: String) { + for (index, value) in (record[field]?.elements ?? []).enumerated() { + visit(value, at: pointer + "/" + field + "/" + String(index)) + } + } + switch record.kind { + case "declaration": + children("components") + children("groups") + children("uses") + for (index, value) in (record["watch"]?.elements ?? []).enumerated() + where value.string == alias { + edits.append(.set("/watch/" + String(index), .string(replacement))) + } + case "group": + children("components") + children("uses") + case "instructions": + children("sections") + children("chatGPT") + case "prompt": children("sections") + case "mcpServer": child("transport") + case "hook", "lspServer": child("run") + case "command", "subagent": child("prompt") + case "skills", "plugin", "section", "exported", "path", "file": reference("source") + case "executable", "stdio": + reference("executableSource") + child("workingDirectory") + default: break + } + } + visit(root, at: "") + return edits + } +} diff --git a/Sources/AgentsManifest/SourceText.swift b/Sources/AgentsManifest/SourceText.swift new file mode 100644 index 0000000..7462d68 --- /dev/null +++ b/Sources/AgentsManifest/SourceText.swift @@ -0,0 +1,68 @@ +import AgentsCore + +struct SourceText: Sendable { + let bytes: [UInt8] + let identity: DocumentIdentity + private let lines: [Int] + + init(_ bytes: [UInt8], identity: DocumentIdentity) { + self.bytes = bytes + self.identity = identity + var starts = [0] + var i = 0 + while i < min(bytes.count, ManifestLimits.Input.bytes + 1) { + if bytes[i] == UInt8(ascii: "\r") { + if i + 1 < bytes.count && bytes[i + 1] == UInt8(ascii: "\n") { i += 1 } + starts.append(i + 1) + } else if bytes[i] == UInt8(ascii: "\n") { + starts.append(i + 1) + } + i += 1 + } + lines = starts + } + + func span(_ range: Range) -> SourceSpan { + let start = min(max(0, range.lowerBound), bytes.count) + var lo = 0 + var hi = lines.count + while lo + 1 < hi { + let mid = (lo + hi) / 2 + if lines[mid] <= start { lo = mid } else { hi = mid } + } + return SourceSpan( + document: identity, start: start, end: min(max(start, range.upperBound), bytes.count), + line: lo + 1, column: start - lines[lo] + 1) + } + + func failure(_ code: String, _ message: String, _ offset: Int, end: Int? = nil) + -> ManifestFailure + { + ManifestFailure( + ManifestDiagnostic(code: code, message: message, span: span(offset..<(end ?? offset)))) + } + + /// Decoder columns count Unicode scalars, excluding a stream-initial UTF-8 BOM. + /// Source spans retain the original bytes and count CRLF as one line break. + func decoderOffset(line: Int, scalarColumn: Int) -> Int { + guard line > 0, scalarColumn > 0 else { return 0 } + guard line <= lines.count else { return bytes.count } + var offset = lines[line - 1] + if line == 1, bytes.starts(with: [0xEF, 0xBB, 0xBF]) { offset = 3 } + var column = 1 + while offset < bytes.count, bytes[offset] != 10, bytes[offset] != 13, + column < scalarColumn + { + offset += 1 + while offset < bytes.count, bytes[offset] & 0xC0 == 0x80 { offset += 1 } + column += 1 + } + return offset + } + + func spelling(_ range: Range) -> String { + String(decoding: bytes[range], as: UTF8.self) + } +} + +func utf8Less(_ lhs: String, _ rhs: String) -> Bool { lhs.utf8.lexicographicallyPrecedes(rhs.utf8) } diff --git a/Sources/AgentsManifest/ValueBudget.swift b/Sources/AgentsManifest/ValueBudget.swift new file mode 100644 index 0000000..2ab01e4 --- /dev/null +++ b/Sources/AgentsManifest/ValueBudget.swift @@ -0,0 +1,108 @@ +import AgentsCore + +struct ValueCost: Sendable { + var nodes = 1 + var strings = 0 + var encoded = 16 + var depth = 1 + var origins = 1 + + static func scalar(_ text: String = "") -> Self { + var encoded = 2 + for byte in text.utf8 { + encoded += + byte < UInt8(ascii: " ") + ? 6 : (byte == UInt8(ascii: "\"") || byte == UInt8(ascii: "\\") ? 2 : 1) + } + return Self(strings: text.utf8.count, encoded: encoded) + } + + static func container(_ children: [ValueCost], keys: [String] = []) -> Self { + var result = Self() + for child in children { + result.append(child) + } + for key in keys { + let cost = scalar(key) + result.strings = add(result.strings, cost.strings) + result.encoded = add(result.encoded, cost.encoded + 4) + } + return result + } + + mutating func append(_ child: Self) { + nodes = Self.add(nodes, child.nodes) + strings = Self.add(strings, child.strings) + encoded = Self.add(encoded, Self.add(child.encoded, 4 + child.nodes * 2)) + origins = Self.add(origins, child.origins) + depth = max(depth, child.depth + 1) + } + + var fits: Bool { + nodes <= ManifestLimits.Values.nodes && strings <= ManifestLimits.Values.stringBytes + && encoded <= ManifestLimits.Output.encodedBytes + && depth <= ManifestLimits.Values.depth && origins <= ManifestLimits.SourceMap.origins + } + + static func add(_ lhs: Int, _ rhs: Int) -> Int { + let (result, overflow) = lhs.addingReportingOverflow(rhs) + return overflow + ? (ManifestLimits.Output.encodedBytes + 1) + : min(result, (ManifestLimits.Output.encodedBytes + 1)) + } +} + +struct SourceMapBudget { + private var locations = 0 + private var origins = 0 + private var encoded = 0 + + var remainingLocations: Int { ManifestLimits.SourceMap.locations - locations } + var remainingOrigins: Int { ManifestLimits.SourceMap.origins - origins } + + mutating func consume(pointer: String, span: SourceSpan, origins: [SourceSpan]) -> Bool { + guard remainingLocations > 0, origins.count <= remainingOrigins else { return false } + let estimate = + origins.reduce(pointer.utf8.count + span.document.rawValue.utf8.count + 160 + 80) { + ValueCost.add($0, $1.document.rawValue.utf8.count + 160) + } + guard estimate <= ManifestLimits.SourceMap.encodedBytes - encoded else { return false } + locations += 1 + self.origins += origins.count + encoded += estimate + return true + } +} + +func validateIRBudget(_ value: DeclarationValue, source: SourceText) throws { + var work = 0 + func cost(_ value: DeclarationValue, depth: Int) throws -> ValueCost { + work += 1 + guard depth <= ManifestLimits.Values.depth, work <= ManifestLimits.Values.nodes else { + throw source.failure("manifest.limit", "domain value depth/node limit", 0) + } + let result: ValueCost + switch value { + case .string(let value): result = .scalar(value) + case .array(let values): + guard values.count <= ManifestLimits.Values.entries else { + throw source.failure("manifest.limit", "container entry limit", 0) + } + result = try .container(values.map { try cost($0, depth: depth + 1) }) + case .dictionary(let fields): + guard fields.count <= ManifestLimits.Values.entries else { + throw source.failure("manifest.limit", "container entry limit", 0) + } + result = try .container( + fields.values.map { try cost($0, depth: depth + 1) }, keys: Array(fields.keys)) + case .record(let record): + result = try cost(.dictionary(record.fields), depth: depth) + case .requirement(let value): + result = .container([.scalar(value.value)] + (value.upperBound.map { [.scalar($0)] } ?? [])) + default: result = ValueCost() + } + guard result.fits else { throw source.failure("manifest.limit", "domain value budget", 0) } + return result + } + _ = try cost(value, depth: 1) +} diff --git a/Sources/AgentsManifest/YAMLConstruction.swift b/Sources/AgentsManifest/YAMLConstruction.swift new file mode 100644 index 0000000..8a90327 --- /dev/null +++ b/Sources/AgentsManifest/YAMLConstruction.swift @@ -0,0 +1,408 @@ +import AgentsCore + +/// Complete domain-to-IR construction. Optional recipients and condition dimensions retain +/// their presence; only dictionary-backed convenience inputs use canonical key ordering. +enum YAMLConstruction { + static func root(_ value: Declaration) -> DeclarationIR { + DeclarationIR( + defaultAgents: value.agents.map { $0.map(\.rawValue) }, exports: value.exports, + sources: value.sourceDeclarations.map(source), components: value.components.map(component), + groups: value.groups.map(group), uses: value.uses.map(use), watch: value.watch ?? [], + packages: value.packages.map(packageRecord) + value.marketplaceRoots.map(packageRecord), + lifecycle: value.lifecycle) + } + static func record(_ kind: String, _ fields: [String: DeclarationValue]) -> DeclarationRecord { + DeclarationRecord(kind: kind, fields: fields) + } + static func text(_ value: String?) -> DeclarationValue { + value.map(DeclarationValue.string) ?? .null + } + static func strings(_ values: [String]) -> DeclarationValue { + .array(values.map(DeclarationValue.string)) + } + static func agents(_ values: [AgentID]?) -> DeclarationValue { + values.map { strings($0.map(\.rawValue)) } ?? .null + } + static func condition(_ value: DeclarationCondition?) -> DeclarationValue { + value.map { + .record( + record( + "when", + [ + "agents": agents($0.agents), + "scopes": $0.scopes.map { strings($0.map(\.rawValue)) } ?? .null, + "platforms": $0.platforms.map { strings($0.map(\.rawValue)) } ?? .null, + ])) + } ?? .null + } + static func source(_ value: NamedSourceDeclaration) -> DeclarationRecord { + let source = value.source + return record( + source.kind == .git ? "git" : source.kind == .local ? "local" : "index", + [ + "name": .string(value.name), + source.kind == .git ? "url" : source.kind == .local ? "path" : "index": .string( + source.kind == .git ? source.gitURL : source.location), + "subpath": text(source.path), + "requirement": source.requirement.map(DeclarationValue.requirement) ?? .null, + ]) + } + static func packageRecord(_ value: MarketplaceDependency) -> DeclarationRecord { + record( + "package", + [ + "name": .string(value.name), "package": .string(value.coordinate.package), + "version": .string(value.coordinate.version), "catalog": catalog(value.catalog), + ]) + } + static func packageRecord(_ value: MarketplaceRoot) -> DeclarationRecord { + var fields: [String: DeclarationValue] = [ + "name": .string(value.name), "package": .string(value.package), + "requirement": .requirement(value.requirement), "catalog": catalog(value.catalog), + ] + if !value.selections.isEmpty { + fields["selections"] = .array( + value.selections.map { selection in + var fields: [String: DeclarationValue] = [ + "package": .string(selection.package), + "member": .dictionary([ + "kind": .string(selection.member.kind.rawValue), + "name": .string(selection.member.name), + ]), + "targets": strings(selection.targets.map(\.rawValue)), + ] + fields["catalog"] = selection.catalog.map(catalog) + return .dictionary(fields) + }) + } + return record("package", fields) + } + private static func catalog(_ origin: MarketplaceOrigin) -> DeclarationValue { + var fields: [String: DeclarationValue] = [ + "kind": .string(origin.kind.rawValue), "location": .string(origin.location), + ] + fields["ref"] = origin.ref.map(DeclarationValue.string) + fields["subpath"] = origin.subpath.map(DeclarationValue.string) + return .dictionary(fields) + } + static func use(_ value: GroupUseDeclaration) -> DeclarationRecord { + record( + value.source == nil ? "local" : "exported", + [ + "name": .string(value.name), "source": text(value.source), + "condition": condition(value.condition), + ]) + } + static func group(_ value: ComponentGroupDeclaration) -> DeclarationRecord { + record( + "group", + [ + "name": .string(value.name), + "components": .array(value.components.map { .record(component($0)) }), + "uses": .array(value.uses.map { .record(use($0)) }), + "condition": condition(value.condition), + ]) + } + static func section(_ value: SectionDeclaration) -> DeclarationRecord { + record( + "section", + [ + "name": .string(value.name), "source": text(value.source), + "condition": condition(value.condition), + "recipients": value.recipients.map { .array($0.map { .string($0.rawValue) }) } ?? .null, + ]) + } + static func promptDeclaration(_ value: NamedPromptDeclaration) -> DeclarationRecord { + record( + "prompt", + [ + "name": .string(value.name), + "sections": .array(value.prompt.sectionReferences.map { .record(section($0)) }), + "append": text(value.prompt.append), "condition": condition(value.prompt.condition), + ]) + } + static func override(_ value: NamedSkillOverrideDeclaration) -> DeclarationRecord { + record( + "skill", + [ + "name": .string(value.name), "agents": agents(value.override.agents), + "mode": text(value.override.mode?.rawValue), + ]) + } + static func nativeValue(_ value: NativeValue) -> DeclarationValue { + let kind: String + let payload: DeclarationValue? + switch value { + case .string(let value): + kind = "string" + payload = .string(value) + case .integer(let value): + kind = "integer" + payload = .integer(value) + case .decimal(let value): + kind = "decimal" + payload = .string(value) + case .boolean(let value): + kind = "boolean" + payload = .boolean(value) + case .null: + kind = "null" + payload = nil + case .array(let value): + kind = "array" + payload = .array(value.map(nativeValue)) + case .object(let value): + kind = "object" + payload = .dictionary(value.mapValues(nativeValue)) + } + return .record(record(kind, payload.map { ["value": $0] } ?? [:])) + } + static func native(_ value: NativeConfiguration) -> DeclarationValue { + .dictionary(value.mapValues { .dictionary($0.mapValues(nativeValue)) }) + } + static func binding(_ value: RuntimeBinding) -> DeclarationValue { + let kind: String + let text: String + switch value { + case .literal(let value): + kind = "literal" + text = value + case .environment(let value): + kind = "environment" + text = value + case .secret(let value): + kind = "secret" + text = value + } + return .record(record(kind, ["value": .string(text)])) + } + static func resource(_ value: ResourceDeclaration) -> DeclarationRecord { + record("path", ["path": .string(value.path), "source": text(value.source)]) + } + static func prompt(_ value: PromptBody) -> DeclarationValue { + switch value { + case .literal(let value): return .record(record("literal", ["value": .string(value)])) + case .file(let value): return .record(record("file", resource(value).fields)) + } + } + static func run(_ value: ExecutableDeclaration, kind: String = "executable") -> DeclarationRecord + { + record( + kind, + [ + "executable": .string(value.executable), "executableSource": text(value.executableSource), + "arguments": strings(value.arguments), + "environment": .dictionary(value.environment.mapValues(binding)), + "workingDirectory": value.workingDirectory.map { .record(resource($0)) } ?? .null, + ]) + } + static func transport(_ value: MCPTransportDeclaration) -> DeclarationValue { + switch value { + case .stdio(let value): return .record(run(value, kind: "stdio")) + case .streamableHTTP(let url, let headers): + return .record( + record( + "streamableHTTP", + ["url": .string(url), "headers": .dictionary(headers.mapValues(binding))])) + case .sse(let url, let headers): + return .record( + record("sse", ["url": .string(url), "headers": .dictionary(headers.mapValues(binding))])) + } + } + static func event(_ value: HookEventDeclaration) -> DeclarationValue { + let kind: String + switch value { + case .beforeTool: kind = "beforeTool" + case .afterTool: kind = "afterTool" + case .sessionStart: kind = "sessionStart" + case .sessionEnd: kind = "sessionEnd" + case .native(let value): return .record(record("native", ["value": .string(value)])) + } + return .record(record(kind, [:])) + } + static func operation(_ value: PermissionOperationDeclaration) -> DeclarationValue { + let kind: String + switch value { + case .read: kind = "read" + case .write: kind = "write" + case .execute: kind = "execute" + case .tool(let value): return .record(record("tool", ["value": .string(value)])) + } + return .record(record(kind, [:])) + } + static func rule(_ value: PermissionRuleDeclaration) -> DeclarationValue { + switch value { + case .allow(let op, let pattern): + return .record(record("allow", ["operation": operation(op), "pattern": .string(pattern)])) + case .ask(let op, let pattern): + return .record(record("ask", ["operation": operation(op), "pattern": .string(pattern)])) + case .deny(let op, let pattern): + return .record(record("deny", ["operation": operation(op), "pattern": .string(pattern)])) + } + } + static func reference(_ value: ComponentReferenceDeclaration) -> DeclarationValue { + let kind: String + let name: String + switch value { + case .skill(let value): + kind = "skill" + name = value + case .instruction(let value): + kind = "instruction" + name = value + case .mcpServer(let value): + kind = "mcpServer" + name = value + case .hook(let value): + kind = "hook" + name = value + case .subagent(let value): + kind = "subagent" + name = value + case .command(let value): + kind = "command" + name = value + case .lspServer(let value): + kind = "lspServer" + name = value + case .permissions(let value): + kind = "permissions" + name = value + case .ignore(let value): + kind = "ignore" + name = value + case .plugin(let value): + kind = "plugin" + name = value + } + return .record(record(kind, ["name": .string(name)])) + } + static func component(_ value: ComponentDeclaration) -> DeclarationRecord { + let kind: String + var fields: [String: DeclarationValue] + let recipients: [AgentID]? + let when: DeclarationCondition? + let config: NativeConfiguration + switch value { + case .skills(let source, let value): + kind = "skills" + recipients = value.agents + when = value.condition + config = value.native + let selection: DeclarationValue + switch value.select { + case .all: selection = .string("all") + case .names(let values): selection = strings(values) + } + fields = [ + "source": .string(source), "path": text(value.path), "select": selection, + "exclude": strings(value.exclude ?? []), + "mode": text(value.mode?.rawValue), + "overrides": .array(value.overrideDeclarations.map { .record(override($0)) }), + ] + case .instructions(let value): + kind = "instructions" + recipients = value.agents + when = value.condition + config = value.native + fields = [ + "sections": .array(value.sectionReferences.map { .record(section($0)) }), + "chatGPT": .array(value.prompts.map { .record(promptDeclaration($0)) }), + ] + case .mcpServer(let name, let value, let a, let c, let n, let registry): + kind = "mcpServer" + recipients = a + when = c + config = n + fields = ["name": .string(name), "transport": transport(value)] + if let registry { + var evidence: [String: DeclarationValue] = [ + "registry": .string(registry.registry), "server": .string(registry.server), + "version": .string(registry.version), "origin": .string(registry.origin), + ] + evidence["package"] = registry.package.map(DeclarationValue.string) + evidence["invocationDigest"] = registry.invocationDigest.map(DeclarationValue.string) + evidence["portableBindings"] = registry.portableBindings.map { + .dictionary($0.mapValues(DeclarationValue.string)) + } + fields["registry"] = .record(record("mcpRegistry", evidence)) + } + case .hook(let name, let e, let r, let matcher, let timeout, let a, let c, let n): + kind = "hook" + recipients = a + when = c + config = n + fields = [ + "name": .string(name), "event": event(e), "run": .record(run(r)), "matcher": text(matcher), + "timeoutSeconds": timeout.map(DeclarationValue.integer) ?? .null, + ] + case .subagent(let name, let description, let p, let model, let tools, let a, let c, let n): + kind = "subagent" + recipients = a + when = c + config = n + fields = [ + "name": .string(name), "description": .string(description), "prompt": prompt(p), + "model": text(model), "tools": tools.map(strings) ?? .null, + ] + case .command(let name, let description, let p, let parameters, let a, let c, let n): + kind = "command" + recipients = a + when = c + config = n + fields = [ + "name": .string(name), "description": .string(description), "prompt": prompt(p), + "parameters": .array( + parameters.map { + .record( + record( + "parameter", + [ + "name": .string($0.name), "description": .string($0.description), + "defaultValue": text($0.defaultValue), + ])) + }), + ] + case .lspServer(let name, let r, let languages, let options, let a, let c, let n): + kind = "lspServer" + recipients = a + when = c + config = n + fields = [ + "name": .string(name), "run": .record(run(r)), + "languages": .dictionary(languages.mapValues(DeclarationValue.string)), + "initializationOptions": .dictionary(options.mapValues(nativeValue)), + ] + case .permissions(let name, let rules, let a, let c, let n): + kind = "permissions" + recipients = a + when = c + config = n + fields = ["name": .string(name), "rules": .array(rules.map(rule))] + case .ignore(let name, let patterns, let purpose, let a, let c, let n): + kind = "ignore" + recipients = a + when = c + config = n + fields = [ + "name": .string(name), "patterns": strings(patterns), "purpose": .string(purpose.rawValue), + ] + case .plugin( + let name, let path, let source, let mode, let select, let exclude, let a, let c, let n): + kind = "plugin" + recipients = a + when = c + config = n + fields = [ + "name": .string(name), "path": .string(path), "source": .string(source), + "mode": .string(mode.rawValue), + "select": select.map { strings($0.map(\.rawValue)) } ?? .null, + "exclude": .array(exclude.map(reference)), + ] + } + fields["agents"] = agents(recipients) + fields["condition"] = condition(when) + fields["native"] = native(config) + return record(kind, fields) + } +} diff --git a/Sources/AgentsManifest/YAMLDomainValidation.swift b/Sources/AgentsManifest/YAMLDomainValidation.swift new file mode 100644 index 0000000..e1de657 --- /dev/null +++ b/Sources/AgentsManifest/YAMLDomainValidation.swift @@ -0,0 +1,334 @@ +import AgentsCore +import Foundation + +struct YAMLDomainValidation { + let declaration: DeclarationIR + let source: SourceText + let locations: [String: YAMLNode] + private let sources: [String: DeclarationRecord] + private let groups: [String: DeclarationRecord] + + init(declaration: DeclarationIR, source: SourceText, locations: [String: YAMLNode]) { + self.declaration = declaration + self.source = source + self.locations = locations + sources = Dictionary( + uniqueKeysWithValues: declaration.sources.map { ($0["name"]!.string!, $0) }) + groups = Dictionary(uniqueKeysWithValues: declaration.groups.map { ($0["name"]!.string!, $0) }) + } + + func validate() throws -> [ManifestDiagnostic] { + var diagnostics: [ManifestDiagnostic] = [] + var sourceRoots = Set<[String]>() + for (index, record) in declaration.sources.enumerated() { + let path = "/sources/\(index)" + let alias = record["name"]!.string! + guard !alias.isEmpty, alias != ".", !alias.contains(":") else { + throw fail(path, "invalid source alias") + } + let location = record[ + record.kind == "git" ? "url" : record.kind == "local" ? "path" : "index"]!.string! + let identity: String + if record.kind == "local" { + guard !location.isEmpty, !location.contains("\0") else { + throw fail(path, "invalid local source") + } + identity = + URL(fileURLWithPath: location, relativeTo: URL(fileURLWithPath: "/")).standardizedFileURL + .path + } else { + do { + identity = try SourceDeclaration( + kind: record.kind == "git" ? .git : .wellKnown, location: location + ).transportIdentity() + } catch { throw fail(path, "invalid source URL") } + } + if record.kind == "git", let node = locations[path + "/url"], let raw = node.text { + let canonical = SourceDeclaration(kind: .git, location: raw).gitURL + if raw != canonical, diagnostics.count < ManifestLimits.Diagnostics.warnings { + diagnostics.append( + ManifestDiagnostic( + code: "manifest.domain", severity: .warning, + message: "use the complete Git transport URL", span: source.span(node.range), + fixIt: SourcePatch( + range: node.range, replacement: Array(YAMLWriter.quote(canonical).utf8)))) + } else if raw != canonical, diagnostics.count == ManifestLimits.Diagnostics.warnings { + diagnostics.append( + ManifestDiagnostic( + code: "manifest.diagnostics.truncated", severity: .warning, + message: "further diagnostics omitted", span: source.span(node.range))) + } + } + let subpath = record["subpath"]?.string ?? "." + try resource(subpath, path) + let root = try PathSafety.sanitizeSubpath(subpath) + guard sourceRoots.insert([identity, record.kind == "index" ? "." : root]).inserted else { + throw fail(path, "two aliases normalize to the same source and discovery root") + } + if case .requirement(let requirement) = record["requirement"] { + do { try requirement.validate() } catch { + throw fail(path + "/requirement", "invalid source requirement") + } + } + } + for (index, package) in declaration.packages.enumerated() { + do { + if package["version"] != nil { + _ = try ManifestProjection.packageDependency(package) + } else { + _ = try ManifestProjection.marketplaceRoot(package) + } + } catch { + throw fail("/packages/\(index)", "invalid marketplace package: \(error)") + } + } + try unique(declaration.defaultAgents ?? [], "/defaultAgents") + try unique(declaration.exports, "/exports") + try unique(declaration.watch, "/watch") + for name in declaration.exports where groups[name] == nil { + throw fail("/exports", "unknown exported group: \(name)", code: "manifest.group.missing") + } + for name in declaration.watch { try alias(name, "/watch") } + for (index, record) in declaration.components.enumerated() { + try component(record, "/components/\(index)") + } + for (index, record) in declaration.groups.enumerated() { + let path = "/groups/\(index)" + try name(record["name"]!.string!, path) + try condition(record["condition"], path + "/condition") + for (i, value) in (record["components"]?.elements ?? []).enumerated() { + try component(value.record!, path + "/components/\(i)") + } + for (i, value) in (record["uses"]?.elements ?? []).enumerated() { + try use(value.record!, path + "/uses/\(i)") + } + } + for (index, record) in declaration.uses.enumerated() { try use(record, "/uses/\(index)") } + var completed = Set() + func cycle(_ name: String, stack: [String]) throws { + guard stack.count < ManifestLimits.Groups.activeReferences else { + throw fail("/groups", "group reference depth limit", code: "manifest.limit") + } + if stack.contains(name) { + throw fail("/groups", "group reference cycle", code: "manifest.group.cycle") + } + if completed.contains(name) { return } + for value in groups[name]?["uses"]?.elements ?? [] { + let record = value.record! + if record["source"]?.string == nil { + try cycle(record["name"]!.string!, stack: stack + [name]) + } + } + completed.insert(name) + } + for group in declaration.groups { try cycle(group["name"]!.string!, stack: []) } + return diagnostics + } + + private func fail(_ pointer: String, _ message: String, code: String = "manifest.domain") + -> ManifestFailure + { + source.failure(code, message, locations[pointer]?.range.lowerBound ?? 0) + } + private func strings(_ value: DeclarationValue?) -> [String] { + (value?.elements ?? []).map { $0.string! } + } + private func unique(_ values: [String], _ pointer: String) throws { + guard Set(values).count == values.count else { throw fail(pointer, "duplicate value") } + } + private func name(_ text: String, _ pointer: String) throws { + let parts = text.split(separator: "/", omittingEmptySubsequences: false) + guard !parts.isEmpty, !parts.contains(where: { $0.isEmpty || $0 == "." || $0 == ".." }), + !text.contains(":"), !text.contains("\\"), + !text.unicodeScalars.contains(where: { $0.value < 0x20 || $0.value == 0x7F }) + else { throw fail(pointer, "invalid relative name") } + } + private func resource(_ text: String, _ pointer: String) throws { + if text == "~" || text.hasPrefix("~/") { throw fail(pointer, "unsafe resource path") } + do { _ = try PathSafety.sanitizeSubpath(text) } catch { + throw fail(pointer, "unsafe resource path") + } + } + private func alias(_ text: String, _ pointer: String) throws { + guard text == "." || sources[text] != nil else { + throw fail(pointer, "unknown source alias: \(text)") + } + } + private func condition(_ value: DeclarationValue?, _ pointer: String) throws { + guard let record = value?.record else { return } + for field in ["agents", "scopes", "platforms"] { + try unique(strings(record[field]), pointer + "/" + field) + } + } + private func use(_ record: DeclarationRecord, _ pointer: String) throws { + let group = record["name"]!.string! + try name(group, pointer) + if let source = record["source"]?.string { + try alias(source, pointer) + } else if groups[group] == nil { + throw fail(pointer, "unknown local group: \(group)", code: "manifest.group.missing") + } + try condition(record["condition"], pointer + "/condition") + } + private func section(_ record: DeclarationRecord, _ pointer: String) throws { + guard Declaration.isInstructionName(record["name"]!.string!) else { + throw fail(pointer, "invalid section name") + } + if let source = record["source"]?.string { try alias(source, pointer) } + try condition(record["condition"], pointer + "/condition") + try unique(strings(record["recipients"]), pointer + "/recipients") + } + private func resource(_ record: DeclarationRecord, _ pointer: String) throws { + try resource(record["path"]!.string!, pointer) + if let source = record["source"]?.string { try alias(source, pointer) } + } + private func run(_ record: DeclarationRecord, _ pointer: String) throws { + let executable = record["executable"]!.string! + guard !executable.isEmpty, !executable.contains("\0") else { + throw fail(pointer, "invalid executable") + } + if executable.contains("/") || executable.hasPrefix("~") { try resource(executable, pointer) } + if let alias = record["executableSource"]?.string { + try self.alias(alias, pointer + "/executableSource") + guard executable.contains("/") else { + throw fail(pointer + "/executableSource", "executable source requires a resource path") + } + } + if let directory = record["workingDirectory"]?.record { try resource(directory, pointer) } + } + private func component(_ record: DeclarationRecord, _ pointer: String) throws { + try unique(strings(record["agents"]), pointer + "/agents") + try condition(record["condition"], pointer + "/condition") + if let n = record["name"]?.string { try name(n, pointer + "/name") } + switch record.kind { + case "skills": + let source = record["source"]!.string! + try alias(source, pointer) + if let path = record["path"]?.string { + try resource(path, pointer + "/path") + guard sources[source]?.kind != "index" else { + throw fail(pointer + "/path", "skill paths require a filesystem source") + } + } + let selected = record["select"]?.elements.map { $0.map { $0.string! } } + let excluded = strings(record["exclude"]) + do { + try Declaration.validateNames(selected ?? []) + try Declaration.validateNames(excluded) + } catch { throw fail(pointer, "invalid skill names") } + let overrides = (record["overrides"]?.elements ?? []).map { $0.record! } + let names = overrides.map { $0["name"]!.string! } + do { try Declaration.validateNames(names) } catch { + throw fail(pointer, "invalid skill overrides") + } + for override in overrides { + if let selected, !selected.contains(override["name"]!.string!) { + throw fail(pointer, "override is outside explicit skill selection") + } + try unique(strings(override["agents"]), pointer) + } + if ([record["mode"]?.string] + overrides.map { $0["mode"]?.string }).contains("edit"), + source != ".", + sources[source]?.kind != "local" || sources[source]?["requirement"] != .null + { + throw fail(pointer, "edit mode needs a local source without a requirement") + } + case "instructions": + for (index, value) in record["sections"]!.elements!.enumerated() { + try section(value.record!, pointer + "/sections/\(index)") + } + for value in record["chatGPT"]!.elements! { + let prompt = value.record! + for sectionValue in prompt["sections"]!.elements! { + guard sectionValue.record?["recipients"] == .null else { + throw fail(pointer, "named prompt sections inherit the named prompt destination") + } + try section(sectionValue.record!, pointer) + } + if let append = prompt["append"]?.string { try resource(append, pointer) } + try condition(prompt["condition"], pointer) + } + case "mcpServer": + let transport = record["transport"]!.record! + if transport.kind == "stdio" { + try run(transport, pointer) + } else { + let url = URLComponents(string: transport["url"]!.string!) + guard ["http", "https"].contains(url?.scheme?.lowercased() ?? ""), + url?.host?.isEmpty == false, url?.user == nil, url?.password == nil, url?.fragment == nil + else { throw fail(pointer, "invalid HTTP transport URL") } + } + case "hook": + try run(record["run"]!.record!, pointer) + if record["event"]!.record!.kind == "native", record["agents"]?.elements?.count != 1 { + throw fail(pointer, "native hook event requires exactly one explicit recipient") + } + case "subagent", "command": + let prompt = record["prompt"]!.record! + if prompt.kind == "file" { try resource(prompt, pointer) } + if record.kind == "command" { + let parameters = (record["parameters"]?.elements ?? []).map { $0.record! } + let names = parameters.map { $0["name"]!.string! } + try unique(names, pointer) + guard + names.allSatisfy({ + !$0.isEmpty && !$0.contains("}") && !$0.contains(":") && !$0.contains("\0") + }) + else { throw fail(pointer, "invalid prompt parameter name") } + if prompt.kind == "literal" { + let bytes = Array(prompt["value"]!.string!.utf8) + let escaped = Array("$${input:".utf8) + let token = Array("${input:".utf8) + var i = 0 + while i < bytes.count { + if bytes[i...].starts(with: escaped) { + i += escaped.count + while i < bytes.count && bytes[i] != 125 { i += 1 } + } else if bytes[i...].starts(with: token) { + let start = i + token.count + i = start + while i < bytes.count && bytes[i] != 125 { i += 1 } + guard i < bytes.count, + names.contains(String(decoding: bytes[start.. 1, !ext.contains("/"), !ext.contains("\0"), + value.string?.isEmpty == false + else { throw fail(pointer, "invalid language extension mapping") } + } + } + case "permissions": + for value in record["rules"]!.elements! { + let rule = value.record! + if ["read", "write"].contains(rule["operation"]!.record!.kind) { + try resource(rule["pattern"]!.string!, pointer) + } + } + case "plugin": + try alias(record["source"]!.string!, pointer) + try resource(record["path"]!.string!, pointer) + try unique(strings(record["select"]), pointer) + let excluded = record["exclude"]!.elements! + guard + Set(excluded.map { $0.record!.kind + ":" + $0.record!["name"]!.string! }).count + == excluded.count + else { throw fail(pointer, "duplicate plugin exclusion") } + for value in excluded { try name(value.record!["name"]!.string!, pointer) } + if record["mode"]?.string == "native", + record["agents"]?.elements?.count != 1 || record["select"] != .null || !excluded.isEmpty + { + throw fail( + pointer, "native plugin requires one explicit recipient and no selection/exclusions") + } + default: break + } + } +} diff --git a/Sources/AgentsManifest/YAMLParser.swift b/Sources/AgentsManifest/YAMLParser.swift new file mode 100644 index 0000000..b3d858f --- /dev/null +++ b/Sources/AgentsManifest/YAMLParser.swift @@ -0,0 +1,388 @@ +import AgentsCore +import Foundation +import TreeSitter +import TreeSitterYAML +import Yams + +/// Ordered, decoded data with concrete UTF-8 ranges. Mapping order is retained independently +/// of the domain's dictionary semantics. Concrete parser and editing trees stay internal. +indirect enum YAMLData: Sendable, Equatable { + case scalar(String, quoted: Bool, decimalTag: Bool) + case sequence([YAMLNode]) + case mapping([(key: YAMLNode, value: YAMLNode)]) + + static func == (lhs: Self, rhs: Self) -> Bool { + switch (lhs, rhs) { + case (.scalar(let a, let q, let t), .scalar(let b, let r, let u)): + return a == b && q == r && t == u + case (.sequence(let a), .sequence(let b)): return a == b + case (.mapping(let a), .mapping(let b)): + return a.count == b.count && zip(a, b).allSatisfy { $0.key == $1.key && $0.value == $1.value } + default: return false + } + } +} + +package struct YAMLNode: Sendable, Equatable { + let data: YAMLData + package let range: Range + let entryRange: Range + let flow: Bool + + /// Scalar spelling and style are read-only; node and graph construction remain internal. + package var scalar: (text: String, quoted: Bool, decimalTag: Bool)? { + if case .scalar(let text, let quoted, let decimalTag) = data { + return (text, quoted, decimalTag) + } + return nil + } + + package var text: String? { + if case .scalar(let text, _, _) = data { return text } + return nil + } + package var pairs: [(key: YAMLNode, value: YAMLNode)]? { + if case .mapping(let pairs) = data { return pairs } + return nil + } + package var items: [YAMLNode]? { + if case .sequence(let items) = data { return items } + return nil + } +} + +private struct YAMLParseInput { + let bytes: UnsafePointer + let count: Int + var callbacks = 0 + var offset = 0 + var failed = false + var cancelled = false +} + +struct YAMLParseResult { + let root: YAMLNode + let callbacks: Int + let nodes: Int + let depth: Int + let comments: [Range] + let metrics: FrontEndMetrics +} + +enum YAMLParser { + // The pinned runtime reports periodic parse progress, including weighted tree compression. + // Scalar scanning remains input-byte bounded. This measured work policy is not an allocation bound. + static let callbackLimit = 16_000 + + static func parse( + _ source: SourceText, observe: ((FrontEndStage, FrontEndMetrics) -> Void)? = nil + ) throws -> YAMLParseResult { + try Task.checkCancellation() + let clock = ContinuousClock() + var start = clock.now + var metrics = FrontEndMetrics() + var stage = FrontEndStage.admission + observe?(stage, metrics) + do { + guard source.bytes.count <= ManifestLimits.Input.bytes else { + throw source.failure("manifest.limit", "input byte limit", ManifestLimits.Input.bytes) + } + guard let text = String(bytes: source.bytes, encoding: .utf8) else { + throw source.failure("manifest.encoding", "expected UTF-8", 0) + } + var offset = source.bytes.count - text.utf8.count + for scalar in text.unicodeScalars { + let value = scalar.value + if value == 0 || value == 0x85 || value == 0x2028 || value == 0x2029 + || value < 0x20 && ![9, 10, 13].contains(value) + || (0x7F...0x9F).contains(value) || value == 0xFFFE || value == 0xFFFF + + { + throw source.failure( + "manifest.character", "unsupported raw source character", offset, + end: offset + scalar.utf8.count) + } + offset += scalar.utf8.count + } + metrics.admissionSeconds = seconds(start.duration(to: clock.now)) + start = clock.now + stage = .parser + metrics.parserCalls = 1 + observe?(stage, metrics) + guard let parser = ts_parser_new() else { + throw source.failure("manifest.parser", "could not allocate YAML parser", 0) + } + defer { ts_parser_delete(parser) } + guard ts_parser_set_language(parser, tree_sitter_yaml()) else { + throw source.failure("manifest.parser", "YAML grammar ABI mismatch", 0) + } + var callbacks = 0 + var parserOffset = 0 + var cancelled = false + let tree = source.bytes.withUnsafeBytes { raw -> OpaquePointer? in + // A stable non-null pointer is required for empty input too. + var empty: CChar = 0 + return withUnsafePointer(to: &empty) { emptyPointer in + var state = YAMLParseInput( + bytes: raw.baseAddress?.assumingMemoryBound(to: CChar.self) ?? emptyPointer, + count: raw.count) + return withUnsafeMutablePointer(to: &state) { pointer in + let input = TSInput( + payload: UnsafeMutableRawPointer(pointer), + read: { payload, index, _, count in + let state = payload!.assumingMemoryBound(to: YAMLParseInput.self).pointee + let offset = min(Int(index), state.count) + count!.pointee = UInt32(state.count - offset) + return state.bytes.advanced(by: offset) + }, encoding: TSInputEncodingUTF8, decode: nil) + let options = TSParseOptions( + payload: UnsafeMutableRawPointer(pointer), + progress_callback: { progress in + let state = progress!.pointee.payload!.assumingMemoryBound(to: YAMLParseInput.self) + state.pointee.callbacks += 1 + state.pointee.offset = Int(progress!.pointee.current_byte_offset) + state.pointee.failed = progress!.pointee.has_error + state.pointee.cancelled = Task.isCancelled + return state.pointee.cancelled || state.pointee.failed + || state.pointee.callbacks > YAMLParser.callbackLimit + }) + let result = ts_parser_parse_with_options(parser, nil, input, options) + callbacks = pointer.pointee.callbacks + parserOffset = pointer.pointee.offset + cancelled = pointer.pointee.cancelled + return result + } + } + } + metrics.parsingSeconds = seconds(start.duration(to: clock.now)) + metrics.parserCallbacks = callbacks + guard let tree else { + if cancelled { throw CancellationError() } + throw source.failure( + callbacks > callbackLimit ? "manifest.limit" : "manifest.syntax", + callbacks > callbackLimit ? "YAML parser work limit" : "invalid YAML", parserOffset) + } + defer { ts_tree_delete(tree) } + try Task.checkCancellation() + start = clock.now + let root = ts_tree_root_node(tree) + var pending: [(TSNode, Int)] = [(root, 1)] + var count = 0 + var depth = 0 + var documents = 0 + var comments: [Range] = [] + while let (node, level) = pending.popLast() { + count += 1 + depth = max(depth, level) + metrics.syntaxNodes = count + metrics.syntaxDepth = depth + let start = Int(ts_node_start_byte(node)) + if count > ManifestLimits.Syntax.nodes || level > ManifestLimits.Syntax.depth { + throw source.failure("manifest.limit", "YAML CST node/depth limit", start) + } + let kind = String(cString: ts_node_type(node)) + if kind == "document" { documents += 1 } + if kind == "comment" { comments.append(nodeRange(node)) } + if ["anchor", "alias", "yaml_directive", "tag_directive", "reserved_directive"].contains( + kind) + { + throw source.failure("manifest.unsupported", "unsupported YAML \(kind)", start) + } + if kind == "tag", source.spelling(nodeRange(node)) != "!!float" { + throw source.failure("manifest.tag", "only NativeValue !!float is supported", start) + } + if ts_node_is_error(node) || ts_node_is_missing(node) { + throw source.failure("manifest.syntax", "invalid YAML", start) + } + for index in 0.. ManifestFailure + { + switch error { + case .scanner(_, let problem, let mark, _), .parser(_, let problem, let mark, _), + .composer(_, let problem, let mark, _): + return source.failure( + "manifest.syntax", "YAML decoding failed: \(problem)", + source.decoderOffset(line: mark.line, scalarColumn: mark.column)) + case .duplicatedKeysInMapping(let duplicates, let context): + // Yams supplies one key's mark, not the positions of every conflicting occurrence. + return source.failure( + "manifest.key.duplicate", + "duplicate decoded mapping key(s): \(duplicates.joined(separator: ", "))", + source.decoderOffset(line: context.mark.line, scalarColumn: context.mark.column)) + case .reader(let problem, let offset, _, _): + let index = offset.flatMap { offset in + offset >= 0 ? text.index(text.startIndex, offsetBy: offset, limitedBy: text.endIndex) : nil + } + // UTF-8 String decoding consumes a leading BOM; reader offsets index that decoded string. + let byteOffset = + index.map { + source.bytes.count - text.utf8.count + + text.utf8.distance(from: text.utf8.startIndex, to: $0) + } ?? 0 + return source.failure("manifest.syntax", "YAML decoding failed: \(problem)", byteOffset) + default: + return source.failure("manifest.syntax", "YAML decoding failed: \(error)", 0) + } + } + + private static func seconds(_ duration: Duration) -> Double { + let parts = duration.components + return Double(parts.seconds) + Double(parts.attoseconds) / 1e18 + } + + private static func nodeRange(_ node: TSNode) -> Range { + Int(ts_node_start_byte(node)).. [TSNode] { + (0.. YAMLNode + { + let kind = String(cString: ts_node_type(syntax)) + let children = children(syntax) + let range = nodeRange(syntax) + let tags = children.filter { String(cString: ts_node_type($0)) == "tag" } + let content = children.filter { String(cString: ts_node_type($0)) != "tag" } + if ["stream", "document", "block_node", "flow_node", "block_sequence_item"].contains(kind), + content.count == 1 + { + let node = try pair(content[0], semantic, source: source) + let tagged = !tags.isEmpty + if tagged { + guard case .scalar(let text, let quoted, _) = node.data, + semantic.tag.rawValue == "tag:yaml.org,2002:float" + else { throw source.failure("manifest.tag", "!!float requires a scalar", range.lowerBound) } + return YAMLNode( + data: .scalar(text, quoted: quoted, decimalTag: true), range: range, + entryRange: range, flow: node.flow) + } + return YAMLNode(data: node.data, range: node.range, entryRange: range, flow: node.flow) + } + if ["block_mapping", "flow_mapping", "flow_pair"].contains(kind), let mapping = semantic.mapping + { + let syntaxPairs = kind == "flow_pair" ? [syntax] : children + guard syntaxPairs.count == mapping.count else { + throw source.failure( + "manifest.parser.mismatch", "YAML parsers disagree on mapping", range.lowerBound) + } + var pairs: [(key: YAMLNode, value: YAMLNode)] = [] + var keys = Set() + for (syntaxPair, semanticPair) in zip(syntaxPairs, mapping) { + let key = field(syntaxPair, "key") + let value = field(syntaxPair, "value") + guard !ts_node_is_null(key) else { + throw source.failure( + "manifest.schema", "mapping entries require explicit keys", + Int(ts_node_start_byte(syntaxPair))) + } + let keyNode = try pair(key, semanticPair.key, source: source) + guard case .scalar(let name, let quoted, let tag) = keyNode.data, + !tag, quoted || YAMLScalar.classify(name) == .string + else { + throw source.failure( + "manifest.key", "mapping key must be a string", keyNode.range.lowerBound) + } + guard keys.insert(name).inserted else { + throw source.failure( + "manifest.key.duplicate", "duplicate decoded mapping key: \(name)", + keyNode.range.lowerBound) + } + let node: YAMLNode + if ts_node_is_null(value) { + node = try emptyScalar(syntaxPair, semanticPair.value, source: source) + } else { + node = try pair(value, semanticPair.value, source: source) + } + pairs.append( + ( + keyNode, + YAMLNode( + data: node.data, range: node.range, entryRange: nodeRange(syntaxPair), flow: node.flow + ) + )) + } + return YAMLNode( + data: .mapping(pairs), range: range, entryRange: range, flow: kind != "block_mapping") + } + if kind == "block_sequence" || kind == "flow_sequence", let sequence = semantic.sequence { + guard children.count == sequence.count else { + throw source.failure( + "manifest.parser.mismatch", "YAML parsers disagree on sequence", range.lowerBound) + } + return YAMLNode( + data: .sequence(try zip(children, sequence).map { try pair($0, $1, source: source) }), + range: range, entryRange: range, flow: kind == "flow_sequence") + } + if kind == "block_sequence_item", content.isEmpty { + return try emptyScalar(syntax, semantic, source: source) + } + if let scalar = semantic.scalar, + ["plain_scalar", "single_quote_scalar", "double_quote_scalar", "block_scalar"].contains(kind) + { + return YAMLNode( + data: .scalar(scalar.string, quoted: kind != "plain_scalar", decimalTag: false), + range: range, entryRange: range, flow: true) + } + throw source.failure( + "manifest.parser.mismatch", "YAML parsers disagree on structure", range.lowerBound) + } + + private static func emptyScalar(_ syntax: TSNode, _ semantic: Yams.Node, source: SourceText) + throws -> YAMLNode + { + guard semantic.scalar?.string == "", + let delimiter = (0.. TSNode { + name.withCString { ts_node_child_by_field_name(node, $0, UInt32(name.utf8.count)) } + } +} diff --git a/Sources/AgentsManifest/YAMLPatches.swift b/Sources/AgentsManifest/YAMLPatches.swift new file mode 100644 index 0000000..df7c4bd --- /dev/null +++ b/Sources/AgentsManifest/YAMLPatches.swift @@ -0,0 +1,540 @@ +import AgentsCore +import Foundation + +/// Concrete collection and field changes. A patch owns only the selected value/entry and its +/// attached trivia. Structural ambiguity is reported before a candidate can be published. +struct YAMLPatches { + let document: DeclarationDocument + private var source: SourceText { document.source } + private var bytes: [UInt8] { document.bytes } + + func patches(for edit: IREdit, expected: DeclarationValue) throws -> [SourcePatch] { + switch edit { + case .set(let pointer, let value): return try set(pointer, value) + case .insert(let pointer, let index, let value): return try insert(pointer, index, value) + case .remove(let pointer, let index): return try remove(pointer, index, retainComments: true) + case .relocate(let origin, let from, let destination, let to): + let nodes = try children(origin) + let originalContainer = document.locations[origin]! + let node = nodes[from] + let value = IRTree.value(IRTree.root(document.declaration), at: origin)!.elements![from] + let removal = try remove(origin, from, retainComments: false) + var insertion = try insert(destination, to, value) + let carried = document.comments.filter { + owned(node, container: originalContainer).contains($0.lowerBound) + }.map { source.spelling($0) } + let target = document.locations[destination]! + if !originalContainer.flow, !target.flow, !document.defaulted.contains(destination) { + let raw = source.spelling(owned(node, container: originalContainer)) + let oldIndent = indentation(at: node.entryRange.lowerBound) + let targetNodes = try children(destination) + let newIndent = + targetNodes.first.map { indentation(at: $0.entryRange.lowerBound) } + ?? indentation(at: target.range.lowerBound) + let shifted = raw.components(separatedBy: newline).map { line in + line.hasPrefix(oldIndent) ? newIndent + line.dropFirst(oldIndent.count) : line + }.joined(separator: newline) + insertion = insertion.map { + SourcePatch(range: $0.range, replacement: movedEntry(shifted, at: $0.range.lowerBound)) + } + } else if !carried.isEmpty { + let rendered = YAMLWriter.flow(value) + let prefix = newline + carried.map { " " + $0 + newline }.joined() + " " + insertion = insertion.map { + let text = String(decoding: $0.replacement, as: UTF8.self).replacingOccurrences( + of: rendered, with: prefix + rendered) + return SourcePatch(range: $0.range, replacement: Array(text.utf8)) + } + } + return removal + insertion + case .move(let pointer, let from, let to): + guard let container = document.locations[pointer], !document.defaulted.contains(pointer) + else { throw readOnly(pointer, "missing collection") } + if container.flow { + if document.comments.contains(where: { container.range.contains($0.lowerBound) }) { + var content = flowContent(container) + content.entries.insert(content.entries.remove(at: from), at: to) + return [ + SourcePatch( + range: container.range, + replacement: Array(renderFlow(content, container: container).utf8)) + ] + } + // Common flow collections retain the exact moved value and comments. Delimiters are + // reconstructed within the collection; nested values and their spelling remain owned. + let values = IRTree.value(IRTree.root(document.declaration), at: pointer)!.elements! + var order = Array(values.indices) + order.insert(order.remove(at: from), at: to) + let children = try children(pointer) + let named = isNamed(pointer) + let text = order.map { i -> String in + let node = children[i] + let range = named ? node.entryRange : node.range + return source.spelling(range) + }.joined(separator: ", ") + let opening = named ? "{" : "[" + let closing = named ? "}" : "]" + return [ + SourcePatch(range: container.range, replacement: Array((opening + text + closing).utf8)) + ] + } + let children = try children(pointer) + let moved = children[from] + let range = owned(moved, container: container) + let remaining = children.indices.filter { $0 != from } + let offset: Int + if to < remaining.count { + offset = owned(children[remaining[to]], container: container).lowerBound + } else { + offset = owned(children[remaining.last ?? from], container: container).upperBound + } + return [ + SourcePatch(range: range, replacement: []), + SourcePatch( + range: offset.. [SourcePatch] { + let (parent, key) = split(pointer) + let absent = document.defaulted.contains(pointer) || document.locations[pointer] == nil + if absent { + guard let value, value != .null else { return [] } + return try addField(parent, key, value) + } + let node = document.locations[pointer]! + if value == nil || value == .null { + guard let container = mapping(at: parent), + let pair = container.pairs?.first(where: { $0.key.text == yamlKey(key, parent: parent) }) + else { + throw readOnly(pointer, "value has no removable mapping entry") + } + return try removeEntry(pair.value, container: container, retainComments: true) + } + if let next = value?.record, ["git", "local", "index"].contains(next.kind), + field(pointer) == "sources", + let old = IRTree.value(IRTree.root(document.declaration), at: pointer)?.record, + old.kind != next.kind + { + let oldKey = old.kind == "git" ? "url" : old.kind == "local" ? "path" : "index" + let newKey = next.kind == "git" ? "url" : next.kind == "local" ? "path" : "index" + guard let pair = node.pairs?.first(where: { $0.key.text == oldKey }) else { + throw readOnly(pointer, "source location has no concrete field") + } + var patches = [ + SourcePatch(range: pair.key.range, replacement: Array(YAMLWriter.quote(newKey).utf8)), + SourcePatch( + range: pair.value.range, replacement: Array(YAMLWriter.flow(next[newKey]!).utf8)), + ] + for field in ["name", "requirement", "subpath"] where old[field] != next[field] { + patches += try set(pointer + "/" + field, next[field]) + } + return patches + } + if field(pointer) == "packages", let next = value?.record, + let old = IRTree.value(IRTree.root(document.declaration), at: pointer)?.record, + (old["version"] == nil) != (next["version"] == nil) + { + let oldKey = old["version"] == nil ? "requirement" : "version" + let newKey = oldKey == "version" ? "requirement" : "version" + guard let pair = node.pairs?.first(where: { $0.key.text == oldKey }) else { + throw readOnly(pointer, "package requirement has no concrete field") + } + var patches = [ + SourcePatch(range: pair.key.range, replacement: Array(YAMLWriter.quote(newKey).utf8)) + ] + patches += try set(pointer + "/" + oldKey, next[newKey]) + for field in ["name", "package", "catalog", "selections"] where old[field] != next[field] { + patches += try set(pointer + "/" + field, next[field]) + } + return patches + } + var rendered = YAMLWriter.flow(value!, field: field(pointer)) + if key == "value", + IRTree.value(IRTree.root(document.declaration), at: parent)?.record?.kind == "decimal", + let text = value?.string + { + rendered = "!!float " + YAMLWriter.quote(text) + } + // Comments inside a block scalar belong to its header, never its decoded payload. + let comments = document.comments.filter { node.range.contains($0.lowerBound) } + if !comments.isEmpty { + if pointer == "/lifecycle", rendered.hasPrefix("{") { + let indent = indentation(at: node.range.lowerBound) + " " + let preserved = comments.map { indent + source.spelling($0) + newline }.joined() + rendered = "{" + newline + preserved + indent + rendered.dropFirst() + } else if comments.count == 1, !rendered.contains("\n") { + rendered += " " + source.spelling(comments[0]) + } else if let container = document.locations[parent], container.items != nil, + let index = Int(key) + { + if container.flow { + var content = flowContent(container) + content.entries[index].text = rendered + content.entries[index].leading += comments.map { source.spelling($0) } + return [ + SourcePatch( + range: container.range, + replacement: Array(renderFlow(content, container: container).utf8)) + ] + } + let indent = indentation(at: node.entryRange.lowerBound) + let prefix = comments.map { source.spelling($0) + newline + indent }.joined() + return [ + SourcePatch(range: node.entryRange, replacement: Array((prefix + "- " + rendered).utf8)) + ] + } else { + throw readOnly(pointer, "replacement has comments without a precise entry boundary") + } + } + if node.range.upperBound > node.range.lowerBound, bytes[node.range.upperBound - 1] == 10, + !rendered.hasSuffix("\n") + { + rendered += newline + } + if node.range.isEmpty, node.range.lowerBound > 0, + [UInt8(ascii: ":"), UInt8(ascii: "-")].contains(bytes[node.range.lowerBound - 1]) + { + rendered = " " + rendered + } + return [SourcePatch(range: node.range, replacement: Array(rendered.utf8))] + } + + private func addField(_ parent: String, _ key: String, _ value: DeclarationValue) throws + -> [SourcePatch] + { + guard let container = mapping(at: parent) else { + throw readOnly(parent, "missing owning mapping") + } + if document.defaulted.contains(parent) { + let (owner, field) = split(parent) + return try addField(owner, field, .dictionary([key: value])) + } + let key = yamlKey(key, parent: parent) + let text = YAMLWriter.quote(key) + ": " + YAMLWriter.flow(value, field: key) + guard let pairs = container.pairs else { + throw readOnly(parent, "field owner is not a mapping") + } + if container.flow { + if bytes[container.range.lowerBound] != UInt8(ascii: "{") { + return [ + SourcePatch( + range: container.range, + replacement: Array(("{" + source.spelling(container.range) + ", " + text + "}").utf8)) + ] + } + return appendFlow(text, to: container) + } + // The mapping starts after a compact sequence indicator, before any explicit key indicator. + let offset = container.range.lowerBound + let start = lineStart(offset) + let bom = start == 0 && bytes.starts(with: [0xEF, 0xBB, 0xBF]) ? 3 : 0 + let indent = String(repeating: " ", count: offset - start - bom) + let end = + pairs.last.map { lineEnd($0.value.entryRange.upperBound) } ?? container.range.upperBound + return [ + SourcePatch(range: end.. [SourcePatch] + { + guard let container = document.locations[pointer] else { + throw readOnly(pointer, "missing collection") + } + let children = try children(pointer) + let named = isNamed(pointer) + let text: String + if named { + let record = value.record! + text = + YAMLWriter.quote(record["name"]!.string!) + ": " + + YAMLWriter.flow(value, field: field(pointer)) + } else { + text = YAMLWriter.flow(value) + } + if document.defaulted.contains(pointer) { + let (parent, key) = split(pointer) + return try addField(parent, key, .array([value])) + } + if container.flow { + if index == children.count { return appendFlow(text, to: container) } + if document.comments.contains(where: { container.range.contains($0.lowerBound) }) { + var content = flowContent(container) + content.entries.insert(FlowEntry(text: text), at: index) + return [ + SourcePatch( + range: container.range, + replacement: Array(renderFlow(content, container: container).utf8)) + ] + } + if index < children.count { + let offset = (named ? children[index].entryRange : children[index].range).lowerBound + return [SourcePatch(range: offset.. YAMLNode? { + guard let node = document.locations[pointer] else { return nil } + if IRTree.value(IRTree.root(document.declaration), at: pointer)?.record?.kind == "file" { + return node.pairs?.first(where: { $0.key.text == "file" })?.value + } + return node + } + + private func movedEntry(_ text: String, at offset: Int) -> [UInt8] { + let prefix = offset > 0 && bytes[offset - 1] != 10 ? newline : "" + let suffix = offset < bytes.count && !text.hasSuffix(newline) ? newline : "" + return Array((prefix + text + suffix).utf8) + } + + private func blockEntry(_ text: String, at offset: Int) -> [UInt8] { + let prefix = offset > 0 && bytes[offset - 1] != 10 ? newline : "" + let suffix = offset == bytes.count && bytes.last != 10 ? "" : newline + return Array((prefix + text + suffix).utf8) + } + + private func appendFlow(_ text: String, to container: YAMLNode) -> [SourcePatch] { + let last = container.items?.last ?? container.pairs?.last?.value + let start = last?.entryRange.upperBound ?? container.range.lowerBound + 1 + let end = container.range.upperBound - 1 + // An implicit value ends at its colon; a plain key still needs whitespace before the comma. + let separator = last?.range.isEmpty == true ? " ," : "," + if start == end { + return [ + SourcePatch( + range: end..= start && comment.lowerBound < end { + if bytes[cursor.. [SourcePatch] + { + guard let container = document.locations[pointer] else { + throw readOnly(pointer, "missing collection") + } + let children = try children(pointer) + guard children.indices.contains(index) else { throw readOnly(pointer, "missing occurrence") } + return try removeEntry(children[index], container: container, retainComments: retainComments) + } + + private func removeEntry(_ node: YAMLNode, container: YAMLNode, retainComments: Bool) throws + -> [SourcePatch] + { + if container.flow { + let all = container.items ?? container.pairs!.map(\.value) + guard let index = all.firstIndex(where: { $0.range == node.range }) else { + throw readOnly("", "entry is not in its container") + } + var range = container.pairs == nil ? node.range : node.entryRange + if index + 1 < all.count { + let end = + container.pairs == nil + ? all[index + 1].range.lowerBound : all[index + 1].entryRange.lowerBound + range = range.lowerBound.. 0 { + let start = + container.pairs == nil + ? all[index - 1].range.upperBound : all[index - 1].entryRange.upperBound + range = start.. FlowContent { + let nodes = container.items ?? container.pairs!.map(\.value) + let ranges = nodes.map { container.pairs == nil ? $0.range : $0.entryRange } + var result = FlowContent(entries: ranges.map { FlowEntry(text: source.spelling($0)) }) + var index = 0 + for comment in document.comments + where container.range.contains(comment.lowerBound) { + while index < ranges.count && ranges[index].upperBound <= comment.lowerBound { index += 1 } + if index < ranges.count && ranges[index].contains(comment.lowerBound) { continue } + let text = source.spelling(comment) + if index > 0 && lineStart(comment.lowerBound) == lineStart(ranges[index - 1].upperBound - 1) { + result.entries[index - 1].trailing.append(text) + } else if index < ranges.count { + let gap = source.spelling(comment.upperBound.. String { + let base = indentation(at: container.range.lowerBound) + let indent = base + " " + var text = (container.pairs == nil ? "[" : "{") + newline + for comment in content.header { text += indent + comment + newline } + for entry in content.entries { + for comment in entry.leading { text += indent + comment + newline } + text += indent + entry.text + "," + if let first = entry.trailing.first { text += " " + first } + text += newline + for comment in entry.trailing.dropFirst() { text += indent + comment + newline } + } + for comment in content.footer { text += indent + comment + newline } + return text + base + (container.pairs == nil ? "]" : "}") + } + + private func children(_ pointer: String) throws -> [YAMLNode] { + guard let node = document.locations[pointer] else { + throw readOnly(pointer, "missing collection") + } + if document.defaulted.contains(pointer) { return [] } + if let items = node.items { return items } + if let pairs = node.pairs { return pairs.map(\.value) } + throw readOnly(pointer, "expected a collection") + } + private func owned(_ node: YAMLNode, container: YAMLNode) -> Range { + var start = lineStart(node.entryRange.lowerBound) + while start > 0 { + let end = start - 1 + let previous = lineStart(end) + let line = source.spelling(previous.. Int { + var index = min(offset, bytes.count) + while index > 0 && bytes[index - 1] != 10 { index -= 1 } + return index + } + private func lineEnd(_ offset: Int) -> Int { + if offset > 0 && bytes[offset - 1] == 10 { return offset } + var index = offset + while index < bytes.count && bytes[index] != 10 { index += 1 } + return min(bytes.count, index + 1) + } + private func indentation(at offset: Int) -> String { + let start = lineStart(offset) + var end = start + while end < bytes.count && bytes[end] == 32 { end += 1 } + return String(decoding: bytes[start.. (String, String) { + let index = pointer.lastIndex(of: "/")! + return ( + String(pointer[.. String { + let parts = IRTree.segments(pointer) + if parts.last.flatMap(Int.init) != nil { return parts.dropLast().last ?? "" } + return parts.last ?? "" + } + private func isNamed(_ pointer: String) -> Bool { + ["sources", "packages", "groups", "overrides", "chatGPT"].contains(field(pointer)) + } + private func yamlKey(_ field: String, parent: String) -> String { + if field == "chatGPT" { return "chatgpt" } + if field == "name", parent.contains("/uses/") { return "group" } + return field + } + private func readOnly(_ pointer: String, _ message: String) -> ManifestFailure { + source.failure( + "manifest.edit.readOnly", message, document.locations[pointer]?.range.lowerBound ?? 0) + } +} diff --git a/Sources/AgentsManifest/YAMLProjection.swift b/Sources/AgentsManifest/YAMLProjection.swift new file mode 100644 index 0000000..2e229bd --- /dev/null +++ b/Sources/AgentsManifest/YAMLProjection.swift @@ -0,0 +1,371 @@ +import AgentsCore + +/// Converts validated YAML data into the syntax-independent complete declaration, recording +/// semantic indexed pointers while the concrete mapping keys are still available. +final class YAMLProjection { + let source: SourceText + private(set) var locations: [String: YAMLNode] = [:] + private(set) var entries: [SourceMapEntry] = [] + private var budget = SourceMapBudget() + private var entryIndexes: [String: Int] = [:] + + init(source: SourceText) { self.source = source } + + func declaration(_ root: YAMLNode) throws -> DeclarationIR { + try mark(root, "") + let fields = fields(root) + let sources = try named(fields["sources"], at: "/sources", owner: root, role: "source") + let packages = try named(fields["packages"], at: "/packages", owner: root, role: "package") + let components = try records( + fields["components"], at: "/components", owner: root, role: "component") + let groups = try named(fields["groups"], at: "/groups", owner: root, role: "group") + let uses = try records(fields["uses"], at: "/uses", owner: root, role: "use") + let defaults = try field( + fields["defaultAgents"], at: "/defaultAgents", owner: root, default: .null) + let exports = try field(fields["exports"], at: "/exports", owner: root, default: .array([])) + let watch = try field(fields["watch"], at: "/watch", owner: root, default: .array([])) + return DeclarationIR( + defaultAgents: defaults.elements.map { $0.map { $0.string! } }, + exports: exports.elements!.map { $0.string! }, sources: sources, components: components, + groups: groups, uses: uses, watch: watch.elements!.map { $0.string! }, packages: packages, + lifecycle: try fields["lifecycle"].map { try plain($0, at: "/lifecycle", lifecycle: true) }) + } + + private func fields(_ node: YAMLNode) -> [String: YAMLNode] { + Dictionary(uniqueKeysWithValues: (node.pairs ?? []).map { ($0.key.text!, $0.value) }) + } + + private func mark(_ node: YAMLNode, _ pointer: String, defaulted: Bool = false) throws { + let span = source.span(node.range) + if let index = entryIndexes[pointer] { + locations[pointer] = node + entries[index] = SourceMapEntry(pointer: pointer, span: span, defaulted: defaulted) + return + } + guard budget.consume(pointer: pointer, span: span, origins: []) else { + throw source.failure("manifest.limit", "source map budget", node.range.lowerBound) + } + locations[pointer] = node + entryIndexes[pointer] = entries.count + entries.append(SourceMapEntry(pointer: pointer, span: span, defaulted: defaulted)) + } + + private func field( + _ node: YAMLNode?, at pointer: String, owner: YAMLNode, default fallback: DeclarationValue + ) throws -> DeclarationValue { + guard let node else { + try mark(owner, pointer, defaulted: true) + return fallback + } + return try plain(node, at: pointer) + } + + func plain(_ node: YAMLNode, at pointer: String, lifecycle: Bool = false) throws + -> DeclarationValue + { + try mark(node, pointer) + switch node.data { + case .scalar(let text, let quoted, let tag): + if lifecycle && tag { return .null } + if quoted { return .string(text) } + switch YAMLScalar.classify(text) { + case .integer: return YAMLScalar.integer(text).map(DeclarationValue.integer) ?? .null + case .decimal where lifecycle: return .null + case .boolean: return .boolean(text.lowercased() == "true") + case .null: return .null + default: return .string(text) + } + case .sequence(let items): + return try .array( + items.enumerated().map { + try plain($0.element, at: pointer + "/\($0.offset)", lifecycle: lifecycle) + }) + case .mapping(let pairs): + var result: [String: DeclarationValue] = [:] + for pair in pairs { + result[pair.key.text!] = try plain( + pair.value, at: pointer + "/" + pointerEscape(pair.key.text!), lifecycle: lifecycle) + } + return .dictionary(result) + } + } + + private func records(_ node: YAMLNode?, at pointer: String, owner: YAMLNode, role: String) throws + -> [DeclarationRecord] + { + try mark(node ?? owner, pointer, defaulted: node == nil) + return try (node?.items ?? []).enumerated().map { + try record($0.element, at: pointer + "/\($0.offset)", role: role) + } + } + + private func named(_ node: YAMLNode?, at pointer: String, owner: YAMLNode, role: String) throws + -> [DeclarationRecord] + { + try mark(node ?? owner, pointer, defaulted: node == nil) + return try (node?.pairs ?? []).enumerated().map { index, pair in + let path = pointer + "/\(index)" + var value = try record(pair.value, at: path, role: role).fields + value["name"] = .string(pair.key.text!) + try mark(pair.key, path + "/name") + return DeclarationRecord(kind: kind(pair.value, role: role), fields: value) + } + } + + private func kind(_ node: YAMLNode, role: String) -> String { + let f = fields(node) + switch role { + case "component", "transport", "reference": return f["kind"]!.text! + case "source": return f["url"] != nil ? "git" : f["path"] != nil ? "local" : "index" + case "use": return f["source"] == nil ? "local" : "exported" + case "condition": return "when" + case "section": return "section" + case "group": return "group" + case "override": return "skill" + case "promptDeclaration": return "prompt" + case "resource": return "path" + case "run": return "executable" + case "parameter": return "parameter" + case "rule": return f["effect"]!.text! + default: return role + } + } + + private func record(_ node: YAMLNode, at pointer: String, role: String) throws + -> DeclarationRecord + { + try mark(node, pointer) + let input = fields(node) + let kind = kind(node, role: role) + if let explicit = input["kind"] { + try mark(explicit, pointer + "/kind") + } else if role == "source", + let key = node.pairs?.first(where: { ["url", "path", "index"].contains($0.key.text!) })?.key + { + try mark(key, pointer + "/kind") + } else if role == "rule", let effect = input["effect"] { + try mark(effect, pointer + "/kind") + } else { + try mark(node, pointer + "/kind", defaulted: true) + } + var output: [String: DeclarationValue] = [:] + var defaults: [String: DeclarationValue] = [:] + if role == "component" { + defaults = ["agents": .null, "condition": .null, "native": .dictionary([:])] + } + switch role == "component" ? kind : role { + case "source": defaults = ["subpath": .null, "requirement": .null] + case "condition": defaults = ["agents": .null, "scopes": .null, "platforms": .null] + case "group": defaults = ["components": .array([]), "uses": .array([]), "condition": .null] + case "use": defaults = ["source": .null, "condition": .null] + case "section": defaults = ["source": .null, "condition": .null, "recipients": .null] + case "override": defaults = ["agents": .null, "mode": .null] + case "promptDeclaration": + defaults = ["sections": .array([]), "append": .null, "condition": .null] + case "resource": defaults = ["source": .null] + case "run", "transport": + defaults = [ + "arguments": .array([]), "environment": .dictionary([:]), "workingDirectory": .null, + "executableSource": .null, + ] + case "parameter": defaults = ["defaultValue": .null] + case "skills": + defaults.merge([ + "path": .null, "select": .string("all"), "exclude": .array([]), "mode": .null, + "overrides": .array([]), + ]) { _, r in r } + case "instructions": + defaults.merge(["sections": .array([]), "chatGPT": .array([])]) { _, r in r } + case "hook": defaults.merge(["matcher": .null, "timeoutSeconds": .null]) { _, r in r } + case "subagent": defaults.merge(["model": .null, "tools": .null]) { _, r in r } + case "command": defaults["parameters"] = .array([]) + case "lspServer": defaults["initializationOptions"] = .dictionary([:]) + case "ignore": defaults["purpose"] = .string("context") + case "plugin": + defaults.merge(["mode": .string("components"), "select": .null, "exclude": .array([])]) { + _, r in r + } + default: break + } + if role == "transport", kind != "stdio" { defaults = ["headers": .dictionary([:])] } + for (name, fallback) in defaults { + let yamlName = name == "chatGPT" ? "chatgpt" : name + if input[yamlName] == nil { + try mark(node, pointer + "/" + name, defaulted: true) + output[name] = fallback + } + } + for (name, value) in input { + if name == "kind" || role == "rule" && name == "effect" { continue } + let field = name == "chatgpt" ? "chatGPT" : role == "use" && name == "group" ? "name" : name + let path = pointer + "/" + pointerEscape(field) + switch name { + case "condition": output[field] = try .record(record(value, at: path, role: "condition")) + case "components": + output[field] = try .array( + records(value, at: path, owner: node, role: "component").map(DeclarationValue.record)) + case "uses": + output[field] = try .array( + records(value, at: path, owner: node, role: "use").map(DeclarationValue.record)) + case "overrides": + output[field] = try .array( + named(value, at: path, owner: node, role: "override").map(DeclarationValue.record)) + case "chatgpt": + output[field] = try .array( + named(value, at: path, owner: node, role: "promptDeclaration").map( + DeclarationValue.record)) + case "sections", "parameters", "rules": + let childRole = name == "sections" ? "section" : name == "parameters" ? "parameter" : "rule" + output[field] = try .array( + records(value, at: path, owner: node, role: childRole).map(DeclarationValue.record)) + case "registry" where role == "component": + output[field] = try .record(record(value, at: path, role: "mcpRegistry")) + case "transport", "run", "workingDirectory": + output[field] = try .record( + record(value, at: path, role: name == "workingDirectory" ? "resource" : name)) + case "prompt": output[field] = try prompt(value, at: path) + case "event", "operation": output[field] = try symbol(value, at: path, role: name) + case "environment", "headers": + try mark(value, path) + var result: [String: DeclarationValue] = [:] + for pair in value.pairs! { + result[pair.key.text!] = try binding( + pair.value, at: path + "/" + pointerEscape(pair.key.text!)) + } + output[field] = .dictionary(result) + case "native": + try mark(value, path) + var schemas: [String: DeclarationValue] = [:] + for pair in value.pairs! { + schemas[pair.key.text!] = try nativeDictionary( + pair.value, at: path + "/" + pointerEscape(pair.key.text!)) + } + output[field] = .dictionary(schemas) + case "initializationOptions": output[field] = try nativeDictionary(value, at: path) + case "exclude" where role == "component" && kind == "plugin": + output[field] = try .array( + records(value, at: path, owner: node, role: "reference").map(DeclarationValue.record)) + case "requirement": + try mark(value, path) + let requirement = fields(value) + let text = requirement.values.first!.text! + let parsed: SourceRequirement + if let branch = requirement["branch"]?.text { + parsed = .branch(branch) + } else if let revision = requirement["revision"]?.text { + parsed = .revision(revision) + } else if let exact = requirement["exact"]?.text { + parsed = .exact(exact) + } else if let minor = requirement["upToNextMinor"]?.text { + parsed = .upToNextMinor(from: minor) + } else if let upper = requirement["to"]?.text { + parsed = .range(from: requirement["from"]!.text!, to: upper) + } else { + parsed = .upToNextMajor(from: text) + } + let canonical = parsed.canonical + output[field] = .requirement(canonical) + let lower = + requirement["from"] ?? requirement["upToNextMinor"] ?? requirement["branch"] + ?? requirement["revision"] ?? requirement["exact"]! + try mark(lower, path + "/value") + try mark(value.pairs!.first!.key, path + "/kind") + if canonical.upperBound != nil, let upper = requirement["to"] { + try mark(upper, path + "/to") + } + case "url" where role == "source": + try mark(value, path) + output[field] = .string(SourceDeclaration(kind: .git, location: value.text!).gitURL) + default: output[field] = try plain(value, at: path) + } + } + return DeclarationRecord(kind: kind, fields: output) + } + + private func prompt(_ node: YAMLNode, at pointer: String) throws -> DeclarationValue { + if let text = node.text { + try mark(node, pointer) + try mark(node, pointer + "/kind", defaulted: true) + try mark(node, pointer + "/value") + return .record(DeclarationRecord(kind: "literal", fields: ["value": .string(text)])) + } + let resource = try record(fields(node)["file"]!, at: pointer, role: "resource") + try mark(node, pointer) + try mark(node.pairs!.first!.key, pointer + "/kind") + return .record(DeclarationRecord(kind: "file", fields: resource.fields)) + } + + private func symbol(_ node: YAMLNode, at pointer: String, role: String) throws -> DeclarationValue + { + try mark(node, pointer) + try mark(node, pointer + "/kind") + if let text = node.text { return .record(DeclarationRecord(kind: text, fields: [:])) } + let pair = node.pairs!.first! + try mark(pair.value, pointer + "/value") + return .record( + DeclarationRecord(kind: pair.key.text!, fields: ["value": .string(pair.value.text!)])) + } + + private func binding(_ node: YAMLNode, at pointer: String) throws -> DeclarationValue { + try mark(node, pointer) + let kind: String + let value: YAMLNode + if node.text != nil { + kind = "literal" + value = node + } else { + let pair = node.pairs!.first! + kind = pair.key.text == "env" ? "environment" : "secret" + value = pair.value + } + try mark(value, pointer + "/value") + try mark(node, pointer + "/kind", defaulted: node.text != nil) + return .record(DeclarationRecord(kind: kind, fields: ["value": .string(value.text!)])) + } + + private func nativeDictionary(_ node: YAMLNode, at pointer: String) throws -> DeclarationValue { + try mark(node, pointer) + var values: [String: DeclarationValue] = [:] + for pair in node.pairs! { + values[pair.key.text!] = try native( + pair.value, at: pointer + "/" + pointerEscape(pair.key.text!)) + } + return .dictionary(values) + } + + private func native(_ node: YAMLNode, at pointer: String) throws -> DeclarationValue { + try mark(node, pointer) + try mark(node, pointer + "/kind") + let kind: String + let payload: DeclarationValue? + switch node.data { + case .scalar(let text, let quoted, let tag): + switch tag ? YAMLScalar.decimal : quoted ? .string : YAMLScalar.classify(text) { + case .string: + kind = "string" + payload = .string(text) + case .integer: + kind = "integer" + payload = .integer(YAMLScalar.integer(text)!) + case .boolean: + kind = "boolean" + payload = .boolean(text.lowercased() == "true") + case .null: + kind = "null" + payload = nil + case .decimal: + kind = "decimal" + payload = .string(YAMLScalar.decimal(text, explicit: tag)!) + } + case .sequence(let items): + kind = "array" + payload = try .array( + items.enumerated().map { try native($0.element, at: pointer + "/value/\($0.offset)") }) + case .mapping: + kind = "object" + payload = try nativeDictionary(node, at: pointer + "/value") + } + if payload != nil { try mark(node, pointer + "/value") } + return .record(DeclarationRecord(kind: kind, fields: payload.map { ["value": $0] } ?? [:])) + } +} diff --git a/Sources/AgentsManifest/YAMLReader.swift b/Sources/AgentsManifest/YAMLReader.swift new file mode 100644 index 0000000..3cad2b7 --- /dev/null +++ b/Sources/AgentsManifest/YAMLReader.swift @@ -0,0 +1,30 @@ +import AgentsCore + +/// Read-only access to the admitted YAML data graph, without canonical manifest validation. +/// Parser limits, duplicate admission and YAML 1.2 scalar identity remain owned by this module. +package struct YAMLReader: Sendable { + package let root: YAMLNode + private let source: SourceText + + package init(bytes: [UInt8], identity: DocumentIdentity) throws { + let source = SourceText(bytes, identity: identity) + do { + root = try YAMLParser.parse(source).root + self.source = source + } catch is CancellationError { + throw CancellationError() + } catch let failure as ManifestFailure { + // Decoder and duplicate-key messages can contain source values. Only coordinates escape. + throw YAMLReadFailure(span: failure.diagnostics.first?.span ?? source.span(0..<0)) + } catch { + throw YAMLReadFailure(span: source.span(0..<0)) + } + } + + package func span(of node: YAMLNode) -> SourceSpan { source.span(node.range) } +} + +package struct YAMLReadFailure: Error, Sendable, CustomStringConvertible { + package let span: SourceSpan + package var description: String { "YAML input is not admitted." } +} diff --git a/Sources/AgentsManifest/YAMLScalar.swift b/Sources/AgentsManifest/YAMLScalar.swift new file mode 100644 index 0000000..af38f57 --- /dev/null +++ b/Sources/AgentsManifest/YAMLScalar.swift @@ -0,0 +1,67 @@ +import AgentsCore +import Foundation + +/// YAML 1.2 Core resolution. Number conversion never passes through floating-point formatting. +package enum YAMLScalar: Equatable, Sendable { + case string, integer, decimal, boolean, null + + package static func classify(_ text: String) -> Self { + if ["", "~", "null", "Null", "NULL"].contains(text) { return .null } + if ["true", "True", "TRUE", "false", "False", "FALSE"].contains(text) { return .boolean } + if matches(text, #"^[-+]?(0o[0-7]+|0x[0-9a-fA-F]+|[0-9]+)$"#) { return .integer } + if matches(text, #"^[-+]?(([0-9]+(\.[0-9]*)?|\.[0-9]+)([eE][-+]?[0-9]+)?|\.(inf|Inf|INF))$"#) + || [".nan", ".NaN", ".NAN"].contains(text) + { + return .decimal + } + return .string + } + + package static func integer(_ text: String) -> Int? { + var digits = text + let negative = digits.hasPrefix("-") + if digits.hasPrefix("-") || digits.hasPrefix("+") { digits.removeFirst() } + let radix: Int + if digits.hasPrefix("0o") { + radix = 8 + digits.removeFirst(2) + } else if digits.hasPrefix("0x") { + radix = 16 + digits.removeFirst(2) + } else { + radix = 10 + } + return Int((negative ? "-" : "") + digits, radix: radix) + } + + static func decimal(_ text: String, explicit: Bool) -> String? { + if explicit { return validDecimal(text) ? text : nil } + var result = text + if result.hasPrefix("+") { result.removeFirst() } + let negative = result.hasPrefix("-") + if negative { result.removeFirst() } + let exponent = result.firstIndex { $0 == "e" || $0 == "E" } + let suffix = exponent.map { String(result[$0...]) } ?? "" + var mantissa = exponent.map { String(result[..<$0]) } ?? result + if mantissa.hasPrefix(".") { mantissa = "0" + mantissa } + if mantissa.hasSuffix(".") { mantissa += "0" } + if let dot = mantissa.firstIndex(of: ".") { + var whole = String(mantissa[.. 1 && whole.hasPrefix("0") { whole.removeFirst() } + mantissa = whole + mantissa[dot...] + } else { + while mantissa.count > 1 && mantissa.hasPrefix("0") { mantissa.removeFirst() } + } + result = (negative ? "-" : "") + mantissa + suffix + return validDecimal(result) ? result : nil + } + + static func validDecimal(_ text: String) -> Bool { + matches(text, #"^-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?$"#) + && Double(text)?.isFinite == true + } + + private static func matches(_ text: String, _ pattern: String) -> Bool { + text.range(of: pattern, options: .regularExpression) != nil + } +} diff --git a/Sources/AgentsManifest/YAMLValidation.swift b/Sources/AgentsManifest/YAMLValidation.swift new file mode 100644 index 0000000..abee4be --- /dev/null +++ b/Sources/AgentsManifest/YAMLValidation.swift @@ -0,0 +1,219 @@ +import AgentsCore + +/// The finite constraints compiled from the bundled declaration schema. No caller supplies rules. +indirect enum YAMLRule: Sendable { + case string, native + case integer(minimum: Int, maximum: Int? = nil) + case integerConstant(Int) + case constant(String) + case enumeration([String]) + case named(String) + case array(YAMLRule, maximum: Int?) + case dictionary(YAMLRule, maximum: Int?) + case object([String: YAMLRule], required: [String], maximum: Int?) + case oneOf([YAMLRule]) +} + +final class YAMLValidation { + let source: SourceText + private(set) var work = 0 + private(set) var strings = 0 + private var nodes = 0 + + init(source: SourceText) { self.source = source } + + func validate(_ node: YAMLNode) throws { + try inspect(node, depth: 1) + if let lifecycle = node.pairs?.first(where: { $0.key.text == "lifecycle" })?.value { + try validateLifecycle(lifecycle) + } + try check(node, ManifestSchema.root) + } + + private func validateLifecycle(_ node: YAMLNode) throws { + let projection = YAMLProjection(source: source) + let declaration = LifecycleDeclaration( + try projection.plain(node, at: "/lifecycle", lifecycle: true)) + let issues = declaration.issues.map { issue in + let action = [issue.event, issue.index.map(String.init)].compactMap { $0 } + let pointer = (["", "lifecycle"] + action.map(pointerEscape)).joined(separator: "/") + let location = projection.locations[pointer] ?? node + let label = (["lifecycle"] + action + (issue.field.isEmpty ? [] : [issue.field])) + .joined(separator: "/") + var diagnostic = ManifestDiagnostic( + code: "manifest.lifecycle", message: label + ": " + issue.message, + span: source.span(location.range)) + diagnostic.lifecycleIssue = issue + return diagnostic + } + if !issues.isEmpty { throw ManifestFailure(issues) } + } + + private func spend(_ node: YAMLNode) throws { + work += 1 + guard work <= ManifestLimits.Domain.steps else { + throw source.failure("manifest.limit", "schema work limit", node.range.lowerBound) + } + } + + private func inspect(_ node: YAMLNode, depth: Int) throws { + nodes += 1 + guard nodes <= ManifestLimits.Values.nodes, depth <= ManifestLimits.Values.depth else { + throw source.failure( + "manifest.limit", "decoded value node/depth limit", node.range.lowerBound) + } + switch node.data { + case .scalar(let text, _, _): strings += text.utf8.count + case .sequence(let items): + guard items.count <= ManifestLimits.Values.entries else { + throw source.failure("manifest.limit", "container entry limit", node.range.lowerBound) + } + for item in items { try inspect(item, depth: depth + 1) } + case .mapping(let pairs): + guard pairs.count <= ManifestLimits.Values.entries else { + throw source.failure("manifest.limit", "container entry limit", node.range.lowerBound) + } + for pair in pairs { + try inspect(pair.key, depth: depth + 1) + try inspect(pair.value, depth: depth + 1) + } + } + guard strings <= ManifestLimits.Values.stringBytes else { + throw source.failure("manifest.limit", "decoded string byte limit", node.range.lowerBound) + } + } + + func check(_ node: YAMLNode, _ rule: YAMLRule) throws { + try spend(node) + func fail(_ message: String) -> ManifestFailure { + source.failure("manifest.schema", message, node.range.lowerBound, end: node.range.upperBound) + } + func string() throws -> String { + guard case .scalar(let text, let quoted, let tag) = node.data, + !tag, quoted || YAMLScalar.classify(text) == .string + else { throw fail("expected a string") } + return text + } + switch rule { + case .named(let name): try check(node, ManifestSchema.definitions[name]!) + case .string: _ = try string() + case .constant(let expected): + guard try string() == expected else { throw fail("expected \(expected)") } + case .enumeration(let values): + guard try values.contains(string()) else { + throw fail("expected one of \(values.joined(separator: ", "))") + } + case .integer, .integerConstant: + guard case .scalar(let text, let quoted, let tag) = node.data, + !quoted, !tag, YAMLScalar.classify(text) == .integer, let integer = YAMLScalar.integer(text) + else { throw fail("expected a representable plain integer") } + switch rule { + case .integerConstant(let expected): + guard integer == expected else { throw fail("expected integer \(expected)") } + case .integer(let minimum, let maximum): + guard integer >= minimum else { throw fail("integer is below its minimum") } + if let maximum, integer > maximum { throw fail("integer exceeds its maximum") } + default: break + } + case .array(let item, let maximum): + guard let items = node.items else { throw fail("expected a sequence") } + if let maximum, items.count > maximum { throw fail("sequence exceeds maxItems: \(maximum)") } + for node in items { try check(node, item) } + case .dictionary(let value, let maximum): + guard let pairs = node.pairs else { throw fail("expected a mapping") } + if let maximum, pairs.count > maximum { + throw fail("mapping exceeds maxProperties: \(maximum)") + } + for pair in pairs { try check(pair.value, value) } + case .object(let fields, let required, let maximum): + guard let pairs = node.pairs else { throw fail("expected a mapping") } + if let maximum, pairs.count > maximum { + throw fail("mapping exceeds maxProperties: \(maximum)") + } + let present = Set(pairs.map { $0.key.text! }) + for name in required where !present.contains(name) { throw fail("missing field: \(name)") } + for pair in pairs { + let name = pair.key.text! + guard let rule = fields[name] else { + throw source.failure( + "manifest.schema", "unknown field: \(name)", pair.key.range.lowerBound) + } + try check(pair.value, rule) + } + case .oneOf(let choices): + // Disjoint literal discriminators permit one traversal of component/transport subtrees. + // Other unions must count all matching branches to enforce oneOf. + if let kind = node.pairs?.first(where: { $0.key.text == "kind" })?.value.text { + var discriminated: [String: YAMLRule] = [:] + var disjoint = true + for candidate in choices { + let resolved: YAMLRule + if case .named(let name) = candidate { + resolved = ManifestSchema.definitions[name]! + } else { + resolved = candidate + } + guard case .object(let fields, let required, _) = resolved, + required.contains("kind"), let discriminator = fields["kind"] + else { + disjoint = false + break + } + let values: [String] + switch discriminator { + case .constant(let value): values = [value] + case .enumeration(let options): values = options + default: + disjoint = false + values = [] + } + for value in values { + if discriminated.updateValue(candidate, forKey: value) != nil { disjoint = false } + } + } + if disjoint, let candidate = discriminated[kind] { + try check(node, candidate) + return + } + } + var matches = 0 + var firstFailure: ManifestFailure? + for choice in choices { + do { + try check(node, choice) + matches += 1 + } catch let failure as ManifestFailure { + if failure.diagnostics.first?.code == "manifest.limit" { throw failure } + firstFailure = firstFailure ?? failure + } + } + guard matches == 1 else { + if matches == 0, let firstFailure { throw firstFailure } + throw fail("ambiguous field shape") + } + case .native: + switch node.data { + case .scalar(let text, let quoted, let tag): + if tag { + guard YAMLScalar.decimal(text, explicit: true) != nil else { + throw fail("!!float requires exact finite JSON-number text") + } + } else if !quoted { + switch YAMLScalar.classify(text) { + case .integer: + guard YAMLScalar.integer(text) != nil else { + throw fail("integer overflow; use !!float for a decimal value") + } + case .decimal: + guard YAMLScalar.decimal(text, explicit: false) != nil else { + throw fail("expected a finite decimal") + } + default: break + } + } + case .sequence(let items): for item in items { try check(item, .native) } + case .mapping(let pairs): for pair in pairs { try check(pair.value, .native) } + } + } + } +} diff --git a/Sources/AgentsManifest/YAMLWriter.swift b/Sources/AgentsManifest/YAMLWriter.swift new file mode 100644 index 0000000..c479a71 --- /dev/null +++ b/Sources/AgentsManifest/YAMLWriter.swift @@ -0,0 +1,147 @@ +import AgentsCore + +/// Canonical output is used for new documents and owned replacement values. Existing documents +/// are changed through concrete ranges; their unrelated bytes are never reprinted. +enum YAMLWriter { + static func manifest(_ value: DeclarationIR) -> [UInt8] { + var result = "version: 1\n" + if let agents = value.defaultAgents { + result += "defaultAgents: " + flow(YAMLConstruction.strings(agents)) + "\n" + } + if !value.sources.isEmpty { result += namedBlock("sources", value.sources) } + if !value.packages.isEmpty { result += namedBlock("packages", value.packages) } + if !value.components.isEmpty { + result += "components:\n" + for component in value.components { result += " - " + flow(.record(component)) + "\n" } + } + if !value.groups.isEmpty { result += namedBlock("groups", value.groups) } + if !value.uses.isEmpty { + result += "uses: " + flow(.array(value.uses.map(DeclarationValue.record))) + "\n" + } + if !value.exports.isEmpty { + result += "exports: " + flow(YAMLConstruction.strings(value.exports)) + "\n" + } + if let lifecycle = value.lifecycle { result += "lifecycle: " + flow(lifecycle) + "\n" } + if !value.watch.isEmpty { + result += "watch: " + flow(YAMLConstruction.strings(value.watch)) + "\n" + } + return Array(result.utf8) + } + + private static func namedBlock(_ field: String, _ records: [DeclarationRecord]) -> String { + field + ":\n" + + records.map { + " " + quote($0["name"]!.string!) + ": " + flow(.record($0), field: field) + "\n" + }.joined() + } + + static func quote(_ text: String) -> String { + var result = "\"" + for scalar in text.unicodeScalars { + switch scalar { + case "\"": result += "\\\"" + case "\\": result += "\\\\" + case "\n": result += "\\n" + case "\r": result += "\\r" + case "\t": result += "\\t" + case "\0"..<" ", "\u{7F}"..."\u{9F}", "\u{2028}", "\u{2029}", "\u{FFFE}", "\u{FFFF}": + let hex = String(scalar.value, radix: 16) + result += "\\u" + String(repeating: "0", count: max(0, 4 - hex.count)) + hex + default: result += String(scalar) + } + } + return result + "\"" + } + + static func flow(_ value: DeclarationValue, field: String = "") -> String { + switch value { + case .null: return "null" + case .string(let value): return quote(value) + case .integer(let value): return String(value) + case .boolean(let value): return value ? "true" : "false" + case .dictionary(let values): + return mapping(values.keys.sorted(by: utf8Less).map { ($0, flow(values[$0]!, field: $0)) }) + case .array(let values): + if ["sources", "packages", "groups", "overrides", "chatGPT"].contains(field) { + return mapping( + values.map { value in + let record = value.record! + return (record["name"]!.string!, flow(value, field: field)) + }) + } + return "[" + values.map { flow($0) }.joined(separator: ", ") + "]" + case .requirement(let value): + let key: String + switch value { + case .branch: key = "branch" + case .revision: key = "revision" + case .exact: key = "exact" + case .upToNextMajor, .range: key = "from" + case .upToNextMinor: key = "upToNextMinor" + } + var fields = [(key, quote(value.value))] + if let upper = value.upperBound { fields.append(("to", quote(upper))) } + return mapping(fields) + case .record(let record): + let f = record.fields + if ["string", "integer", "boolean", "array", "object"].contains(record.kind), + let payload = f["value"] + { + return flow(payload) + } + if record.kind == "decimal" { return "!!float " + quote(f["value"]!.string!) } + if record.kind == "null" { return "null" } + if record.kind == "literal" { return quote(f["value"]!.string!) } + if ["environment", "secret", "native", "tool"].contains(record.kind) { + return mapping([ + (record.kind == "environment" ? "env" : record.kind, quote(f["value"]!.string!)) + ]) + } + if record.kind == "file" { + return mapping([("file", flow(.record(DeclarationRecord(kind: "path", fields: f))))]) + } + if f.isEmpty { return quote(record.kind) } + let componentKinds = [ + "skills", "instructions", "mcpServer", "hook", "subagent", "command", "lspServer", + "permissions", "ignore", "plugin", + ] + var pairs: [(String, String)] = [] + if componentKinds.contains(record.kind) + || ["stdio", "streamableHTTP", "sse"].contains(record.kind) + { + pairs.append(("kind", quote(record.kind))) + } + if ["allow", "ask", "deny"].contains(record.kind) { + pairs.append(("effect", quote(record.kind))) + } + let named = ["sources", "packages", "groups", "overrides", "chatGPT"].contains(field) + let order = [ + "name", "source", "url", "path", "index", "requirement", "subpath", "select", "exclude", + "mode", "overrides", "sections", "chatGPT", "description", "prompt", "model", "tools", + "parameters", "transport", "event", "run", "matcher", "timeoutSeconds", "executable", + "executableSource", "arguments", "environment", "workingDirectory", "headers", "languages", + "initializationOptions", "rules", "operation", "pattern", "patterns", "purpose", + "components", "uses", "append", "agents", "recipients", "scopes", "platforms", "condition", + "native", + ] + let keys = f.keys.sorted { left, right in + let a = order.firstIndex(of: left) ?? order.count + let b = order.firstIndex(of: right) ?? order.count + return a == b ? utf8Less(left, right) : a < b + } + for key in keys where f[key] != .null && !(named && key == "name") { + let yamlKey = + key == "chatGPT" + ? "chatgpt" + : ["local", "exported"].contains(record.kind) && f["path"] == nil && key == "name" + ? "group" : key + pairs.append((yamlKey, flow(f[key]!, field: key))) + } + return mapping(pairs) + } + } + + static func mapping(_ values: [(String, String)]) -> String { + "{" + values.map { quote($0.0) + ": " + $0.1 }.joined(separator: ", ") + "}" + } +} diff --git a/Sources/AgentsSkills/Discovery.swift b/Sources/AgentsSkills/Discovery.swift index 40eb5ea..e279e35 100644 --- a/Sources/AgentsSkills/Discovery.swift +++ b/Sources/AgentsSkills/Discovery.swift @@ -20,9 +20,13 @@ public struct Skill: Codable, Equatable, Sendable { } } +package typealias SkillMemberSelection = @Sendable (_ name: String?, _ directory: String) -> Bool + struct DiscoveryOptions: Sendable { var includeInternal: Bool var fullDepth: Bool + var strict = false + var selecting: SkillMemberSelection? init(includeInternal: Bool = false, fullDepth: Bool = false) { self.includeInternal = includeInternal @@ -35,19 +39,42 @@ enum Discovery { "node_modules", ".git", "dist", "build", "__pycache__", "__pypackages__", ]) - static func parseSkill(at skillFile: URL, includeInternal: Bool = false) throws -> Skill? { - let content = try String(contentsOf: skillFile, encoding: .utf8) + static func parseSkill(at skillFile: URL, includeInternal: Bool = false, strict: Bool = false) + throws -> Skill? + { + let content = try FileSystem.withAccessErrors(at: skillFile) { + try String(contentsOf: skillFile, encoding: .utf8) + } + return try parseSkill(content, at: skillFile, includeInternal: includeInternal, strict: strict) + } + + static func parseSkill( + _ content: String, at skillFile: URL, includeInternal: Bool, strict: Bool, + selecting: SkillMemberSelection? = nil, diagnosticPath: String? = nil + ) throws -> Skill? { + let directory = skillFile.deletingLastPathComponent() + let path = diagnosticPath ?? skillFile.lastPathComponent let data: [String: Any] do { data = try parseFrontmatter(content) } catch { + if strict, selecting?(nil, directory.lastPathComponent) ?? true { + throw CoreError.invalidSource("\(path): malformed front matter: \(error)") + } return nil } - guard let name = data["name"] as? String, + let name = (data["name"] as? String).flatMap { $0.isEmpty ? nil : $0 } + let validate = + strict + && (selecting?(name.map(TextSanitizer.sanitizeMetadata), directory.lastPathComponent) ?? true) + if validate { + _ = try producerCondition(data, file: skillFile, content: content, diagnosticPath: path) + } + guard let name, let description = data["description"] as? String, - !name.isEmpty, !description.isEmpty else { + if validate { throw CoreError.invalidSource("\(path) requires name and description") } return nil } @@ -58,7 +85,6 @@ enum Discovery { return nil } - let directory = skillFile.deletingLastPathComponent() return Skill( name: TextSanitizer.sanitizeMetadata(name), description: TextSanitizer.sanitizeMetadata(description), @@ -72,7 +98,7 @@ enum Discovery { ) throws -> [Skill] { let searchRoot = try subpath.map { try PathSafety.resolvedChild(base: base, subpath: $0) } ?? base - let pluginGroups = pluginGroupings(base: searchRoot) + let pluginGroups = try pluginGroupings(base: searchRoot) let projectInstalledSkillNames = projectInstalledAgentSkillNames(base: searchRoot) var skills: [Skill] = [] var seen = Set() @@ -81,8 +107,23 @@ enum Discovery { func addSkillDirectory(_ directory: URL) throws -> Bool { let skillFile = directory.appendingPathComponent("SKILL.md") guard FileManager.default.fileExists(atPath: skillFile.path) else { return false } - guard var skill = try parseSkill(at: skillFile, includeInternal: options.includeInternal) - else { return false } + let parsed: Skill? + if options.strict { + let path = PathSafety.relativePath(skillFile.path, to: base.path) + let bytes = try FileSystem.read(at: skillFile) + guard let content = String(data: bytes, encoding: .utf8) else { + if options.selecting?(nil, directory.lastPathComponent) ?? true { + throw CoreError.invalidSource("\(path) must be UTF-8") + } + return false + } + parsed = try parseSkill( + content, at: skillFile, includeInternal: options.includeInternal, strict: true, + selecting: options.selecting, diagnosticPath: path) + } else { + parsed = try parseSkill(at: skillFile, includeInternal: options.includeInternal) + } + guard var skill = parsed else { return false } let key = skill.name.lowercased() guard !seen.contains(key) else { return true } if isProjectInstalledAgentSkill(directory, base: searchRoot), @@ -112,7 +153,7 @@ enum Discovery { searchRoot.appendingPathComponent(".codex/skills"), searchRoot.appendingPathComponent(".opencode/skills"), ] - priorityDirectories.append(contentsOf: pluginSkillSearchDirectories(base: searchRoot)) + priorityDirectories.append(contentsOf: try pluginSkillSearchDirectories(base: searchRoot)) for directory in priorityDirectories { let candidates = @@ -143,7 +184,28 @@ enum Discovery { } } - private static func parseFrontmatter(_ raw: String) throws -> [String: Any] { + static func producerCondition( + _ data: [String: Any], file: URL, content: String, diagnosticPath: String? = nil + ) throws -> DeclarationCondition { + var result = DeclarationCondition() + let lines = content.components(separatedBy: "\n") + for key in ["agents", "platforms", "scopes"] { + guard let raw = data[key] else { continue } + let line = (lines.firstIndex { $0.hasPrefix(key + ":") } ?? 0) + 1 + do { + guard let values = raw as? [String] else { + throw CoreError.invalidSource("producer '\(key)' must be a string list") + } + result = result.intersecting(try .restrictions([key: values])) + } catch { + throw CoreError.invalidSource( + "\(diagnosticPath ?? file.lastPathComponent):\(line): \(error)") + } + } + return result + } + + static func parseFrontmatter(_ raw: String) throws -> [String: Any] { guard raw.hasPrefix("---") else { return [:] } let pattern = #"^---\r?\n([\s\S]*?)\r?\n---\r?\n?"# guard let regex = try? NSRegularExpression(pattern: pattern), @@ -239,12 +301,12 @@ enum Discovery { (try? url.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true } - private static func pluginSkillSearchDirectories(base: URL) -> [URL] { + private static func pluginSkillSearchDirectories(base: URL) throws -> [URL] { var directories: [URL] = [] let decoder = JSONDecoder() let marketplaceURL = base.appendingPathComponent(".claude-plugin/marketplace.json") - if let data = try? Data(contentsOf: marketplaceURL), + if let data = try FileSystem.readUnlessDenied(at: marketplaceURL), let manifest = try? decoder.decode(MarketplaceManifest.self, from: data) { let root = manifest.metadata?.pluginRoot @@ -269,7 +331,7 @@ enum Discovery { } let pluginURL = base.appendingPathComponent(".claude-plugin/plugin.json") - if let data = try? Data(contentsOf: pluginURL), + if let data = try FileSystem.readUnlessDenied(at: pluginURL), let manifest = try? decoder.decode(PluginManifest.self, from: data) { for skill in manifest.skills ?? [] where skill.hasPrefix("./") { @@ -285,12 +347,12 @@ enum Discovery { return directories } - private static func pluginGroupings(base: URL) -> [String: String] { + private static func pluginGroupings(base: URL) throws -> [String: String] { var groups: [String: String] = [:] let decoder = JSONDecoder() let marketplaceURL = base.appendingPathComponent(".claude-plugin/marketplace.json") - if let data = try? Data(contentsOf: marketplaceURL), + if let data = try FileSystem.readUnlessDenied(at: marketplaceURL), let manifest = try? decoder.decode(MarketplaceManifest.self, from: data) { let root = manifest.metadata?.pluginRoot @@ -314,7 +376,7 @@ enum Discovery { } let pluginURL = base.appendingPathComponent(".claude-plugin/plugin.json") - if let data = try? Data(contentsOf: pluginURL), + if let data = try FileSystem.readUnlessDenied(at: pluginURL), let manifest = try? decoder.decode(PluginManifest.self, from: data), let name = manifest.name { diff --git a/Sources/AgentsSkills/PolicyHTTPRead.swift b/Sources/AgentsSkills/PolicyHTTPRead.swift new file mode 100644 index 0000000..70795d7 --- /dev/null +++ b/Sources/AgentsSkills/PolicyHTTPRead.swift @@ -0,0 +1,87 @@ +import AgentsCore +import Foundation +import Synchronization + +#if canImport(FoundationNetworking) + import FoundationNetworking +#endif + +/// An index artifact records the requested origin. Keep any redirects on that origin so a +/// later offline restore can enforce the same provenance that acquisition enforced. +final class PolicyHTTPRead: NSObject, URLSessionTaskDelegate { + private let policy: EffectiveSourcePolicy + private let origin: SourceOrigin + private let requireOrigin: (@Sendable (SourceOrigin) throws -> Void)? + private let redirectFailure = Mutex<(any Error)?>(nil) + + private init( + policy: EffectiveSourcePolicy, origin: SourceOrigin, + requireOrigin: (@Sendable (SourceOrigin) throws -> Void)? + ) { + self.policy = policy + self.origin = origin + self.requireOrigin = requireOrigin + } + + static func fetch( + _ url: URL, policy: EffectiveSourcePolicy, + requireOrigin: (@Sendable (SourceOrigin) throws -> Void)? = nil + ) throws -> Data { + let origin = try SourceOrigin.http(url.absoluteString) + try policy.require(origin) + try requireOrigin?(origin) + let delegate = PolicyHTTPRead(policy: policy, origin: origin, requireOrigin: requireOrigin) + let session = URLSession(configuration: .ephemeral, delegate: delegate, delegateQueue: nil) + defer { session.finishTasksAndInvalidate() } + let finished = DispatchSemaphore(value: 0) + let result = Mutex?>(nil) + let task = session.dataTask(with: url) { bytes, response, error in + result.withLock { output in + if let failure = delegate.redirectFailure.withLock({ $0 }) { + output = .failure(failure) + } else if let error { + output = .failure( + CoreError.invalidSource("HTTP source request failed (code \((error as NSError).code))")) + } else if let status = (response as? HTTPURLResponse)?.statusCode, + (200..<300).contains(status), let bytes + { + output = .success(bytes) + } else { + output = .failure(CoreError.invalidSource("source returned no successful HTTP response")) + } + } + finished.signal() + } + task.resume() + while finished.wait(timeout: .now() + .milliseconds(100)) == .timedOut { + if Task.isCancelled { + task.cancel() + throw CancellationError() + } + } + return try result.withLock { try $0!.get() } + } + + func urlSession( + _ session: URLSession, task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, + completionHandler: @escaping @Sendable (URLRequest?) -> Void + ) { + do { + let destination = request.url.flatMap { try? SourceOrigin.http($0.absoluteString) } + try policy.require(destination ?? .missing) + try requireOrigin?(destination ?? .missing) + guard destination == origin else { throw UnrecordedSourceRedirect() } + completionHandler(request) + } catch { + redirectFailure.withLock { $0 = error } + completionHandler(nil) + } + } +} + +struct UnrecordedSourceRedirect: Error, CustomStringConvertible { + var description: String { + "Source policy requires an explicit origin for cross-origin downloads." + } +} diff --git a/Sources/AgentsSkills/SkillInitialization.swift b/Sources/AgentsSkills/SkillInitialization.swift new file mode 100644 index 0000000..c277c63 --- /dev/null +++ b/Sources/AgentsSkills/SkillInitialization.swift @@ -0,0 +1,76 @@ +import AgentsCore +import Foundation + +package struct SkillInitialization: Sendable { + package let store: StateStore + package let root: ExistingProjectRoot + package let file: URL + private let resultDirectory: URL + package let template: Data + private let name: String? + private let selectedChild: String? + + package init( + named requestedName: String?, directory: URL, environment: RuntimeEnvironment, + requiresExistingDirectory: Bool = false, validateState: Bool = true + ) throws { + let directory = directory.standardizedFileURL + let canonicalName = requestedName.map(PathSafety.sanitizeName) + resultDirectory = canonicalName.map { directory.appendingPathComponent($0) } ?? directory + var environment = environment + if requiresExistingDirectory || FileManager.default.fileExists(atPath: directory.path) { + environment.projectDirectory = directory + name = canonicalName + selectedChild = nil + } else { + environment.projectDirectory = directory.deletingLastPathComponent() + name = canonicalName + selectedChild = directory.lastPathComponent + } + store = StateStore(scope: .project, environment: environment) + root = try store.captureExistingProjectRoot() + let observedDirectory = root.directory.resolvingSymlinksInPath() + let selectedDirectory = + selectedChild.map { observedDirectory.appendingPathComponent($0) } + ?? observedDirectory + file = (name.map { selectedDirectory.appendingPathComponent($0) } ?? selectedDirectory) + .appendingPathComponent("SKILL.md") + let title = canonicalName ?? PathSafety.sanitizeName(directory.lastPathComponent) + template = Data( + "---\nname: \(title)\ndescription: Describe when to use this skill\n---\n\n# \(title)\n\nWrite the skill instructions here.\n" + .utf8) + if validateState { + try store.withReadLock { + let target = + try selectedChild.map { + try store.skillInitializationTarget(inChildDirectory: $0, named: name) + } ?? store.skillInitializationTarget(named: name) + guard target.file == file else { + throw CoreError.invalidState("skill initialization target changed") + } + _ = try store.declarationBytes() + _ = try store.readLedger() + } + } + } + + package func apply(outcome: TransactionOutcome, checkpoint: @escaping (String) throws -> Void) + throws -> URL + { + try store.withLock(checkpoint: checkpoint, outcome: outcome, existingRoot: root) { + _ = try store.declarationBytes() + _ = try store.readLedger() + let target = + try selectedChild.map { + try store.skillInitializationTarget(inChildDirectory: $0, named: name) + } ?? store.skillInitializationTarget(named: name) + guard target.file == file else { + throw CoreError.invalidState("skill initialization target changed") + } + let transaction = FileTransaction(store: store, outcome: outcome, checkpoint: checkpoint) + try transaction.initializeSkill(target, bytes: template) + try transaction.commit() + return resultDirectory + } + } +} diff --git a/Sources/AgentsSkills/SkillLifecycle.swift b/Sources/AgentsSkills/SkillLifecycle.swift index 84efc55..b49090c 100644 --- a/Sources/AgentsSkills/SkillLifecycle.swift +++ b/Sources/AgentsSkills/SkillLifecycle.swift @@ -1,34 +1,14 @@ import AgentsCore +import AgentsManifest import Foundation struct DiscoveredSource { - var source: SourceDeclaration var id: String var root: URL - var pin: SourceRevision? var skills: [Skill] - var artifacts: [String: WellKnownRemoteSkill] } -struct PreparedSkill { - var lock: LockedSkill - var directory: URL - var payloads: [String: Data] - let executableFlags: [String: Bool]? - let identity: PathIdentity - let sourceIdentity: PathIdentity - - init(lock: LockedSkill, directory: URL, payloads: [String: Data], sourcePath: URL? = nil) throws { - self.lock = lock - self.directory = directory - self.payloads = payloads - executableFlags = try lock.hash == nil ? nil : FileHash.executableFlags(directory) - identity = try PathIdentity(directory.resolvingSymlinksInPath()) - sourceIdentity = try PathIdentity(sourcePath ?? directory) - } -} - -final class SkillLifecycle { +package final class SkillLifecycle { let store: StateStore let cache: SourceCache let provider: WellKnownProvider @@ -44,24 +24,17 @@ final class SkillLifecycle { self.provider = provider workspace = FileManager.default.temporaryDirectory.appendingPathComponent( "agents-operation-" + UUID().uuidString) - try FileManager.default.createDirectory(at: workspace, withIntermediateDirectories: true) + try FileSystem.createDirectory(at: workspace) } deinit { try? FileManager.default.removeItem(at: workspace) } - func lockedSource(_ source: SourceDeclaration) -> LockedSource { - LockedSource( - kind: source.kind, url: source.kind == .git ? source.gitURL : nil, - requirement: source.requirement, path: source.path) - } - func discover( _ source: SourceDeclaration, live: Bool, fullDepth: Bool, names: [String]? = nil, exclude: [String] = [], cacheSource: Bool = true ) throws -> DiscoveredSource { let id = try source.identity(environment: store.environment) let root: URL - var pin: SourceRevision? var artifacts: [String: WellKnownRemoteSkill] = [:] if source.kind == .wellKnown { root = workspace.appendingPathComponent(UUID().uuidString) @@ -82,12 +55,18 @@ final class SkillLifecycle { root = source.localURL(environment: store.environment) } else { root = workspace.appendingPathComponent(UUID().uuidString) - func copy(_ resolved: SourceRevision, _ snapshot: URL) throws { - pin = resolved - try FileManager.default.copyItem(at: snapshot, to: root) + func copy(_: SourceRevision, _ snapshot: URL) throws { + try FileSystem.withAccessErrors(at: root) { + try FileManager.default.copyItem(at: snapshot, to: root) + } } if let resolutions { - try resolutions.withSnapshot(source, copy) + if try resolutions.isGitSource(source) { + try resolutions.withSnapshot(source, copy) + } else { + let view = try resolutions.localSnapshot(source) + try FileManager.default.copyItem(at: view.root, to: root) + } } else { try cache.withResolvedSnapshot(source, cacheSource: cacheSource, copy) } @@ -108,8 +87,7 @@ final class SkillLifecycle { throw CoreError.invalidSkill("artifact name differs from SKILL.md name") } } - return DiscoveredSource( - source: source, id: id, root: root, pin: pin, skills: skills, artifacts: artifacts) + return DiscoveredSource(id: id, root: root, skills: skills) } func select(_ skills: [Skill], names: [String]) throws -> [Skill] { @@ -125,264 +103,57 @@ final class SkillLifecycle { return selected } - func prepare( - _ skill: Skill, in source: DiscoveredSource, declaration: SkillDeclaration, - defaultAgents: [AgentID] - ) throws -> PreparedSkill { - let name = PathSafety.sanitizeName(skill.name) - let override = declaration.overrides?[name] - let agents = override?.agents ?? declaration.agents ?? defaultAgents - let mode = override?.mode ?? declaration.mode ?? .link - guard !agents.isEmpty else { throw CoreError.invalidSkill("skill has no recipients: \(name)") } - let path = PathSafety.relativePath(skill.path, to: source.root.path) - var directory = URL(fileURLWithPath: skill.path) - let artifact = source.artifacts[name] - let lock: LockedSkill - if mode == .edit { - guard source.source.kind == .local, source.source.requirement == nil else { - throw CoreError.invalidSource("edit requires a local source with no requirement") - } - directory = try PathSafety.resolvedChild( - base: source.source.localURL(environment: store.environment), subpath: path) - guard - FileManager.default.fileExists(atPath: directory.appendingPathComponent("SKILL.md").path) - else { throw CoreError.notFound("live skill directory") } - lock = LockedSkill( - source: source.id, path: path, - installs: Dictionary(uniqueKeysWithValues: Set(agents).map { ($0.rawValue, mode) })) - } else { - guard source.pin != nil || artifact != nil else { - throw CoreError.invalidSource("link and copy require committed Git content") - } - lock = LockedSkill( - source: source.id, revision: source.pin?.revision, version: source.pin?.version, - artifact: artifact?.artifact, path: artifact == nil ? path : nil, - hash: "sha256:" + (try FileHash.folderHash(directory)), - installs: Dictionary(uniqueKeysWithValues: Set(agents).map { ($0.rawValue, mode) })) - } - return try PreparedSkill( - lock: lock, directory: directory, payloads: artifact?.payloads ?? [:], - sourcePath: mode == .edit ? URL(fileURLWithPath: skill.path) : nil) - } - - func restore(name: String, skill: LockedSkill, sources: [String: LockedSource]) throws - -> PreparedSkill + package static func installationTargets(_ ledger: ResolvedLedger, store: StateStore) throws + -> [String: SkillInstallationTarget] { - guard let source = sources[skill.source] else { - throw CoreError.invalidState("unknown locked source") - } - let directory: URL - var payloads: [String: Data] = [:] - if skill.installs.values.allSatisfy({ $0 == .edit }) { - let declaration = try cache.declaration(sourceID: skill.source, source: source) - directory = try PathSafety.resolvedChild( - base: declaration.localURL(environment: store.environment), subpath: skill.path ?? ".") - } else if let artifact = skill.artifact { - let restored = try provider.restore(artifact, cache: cache) - payloads = restored.payloads - directory = workspace.appendingPathComponent(UUID().uuidString) - try write(restored.files, to: directory) - } else { - guard let revision = skill.revision, let path = skill.path else { - throw CoreError.invalidState("missing locked revision or path") - } - let cached = cache.materializedURL(sourceID: skill.source, revision: revision) - try cache.validatePath(cached) - let root: URL - if FileManager.default.fileExists(atPath: cached.path) { - root = cached - } else { - root = workspace.appendingPathComponent(UUID().uuidString) - try cache.withSnapshot(sourceID: skill.source, source: source, revision: revision) { - snapshot in - try FileManager.default.copyItem(at: snapshot, to: root) - } - } - directory = try PathSafety.resolvedChild(base: root, subpath: path) - } - guard FileManager.default.fileExists(atPath: directory.appendingPathComponent("SKILL.md").path) - else { throw CoreError.notFound("locked skill is unavailable: \(name)") } - if let hash = skill.hash, try "sha256:" + FileHash.folderHash(directory) != hash { - throw CoreError.invalidState("locked skill digest mismatch: \(name)") - } - return try PreparedSkill(lock: skill, directory: directory, payloads: payloads) - } - - func apply( - declaration: Declaration, previous: ResolvedState, next: ResolvedState, - prepared: [String: PreparedSkill], names: Set, writeState: Bool = true - ) throws -> [InstallResult] { - try declaration.validate(environment: store.environment) - try next.validate() - try validateOwnership(previous: previous, next: next, names: names) - let retained = try retain(prepared: prepared, next: next) - let transaction = FileTransaction(store: store) - try stage( - previous: previous, next: next, prepared: prepared, retained: retained, - names: names, transaction: transaction) - if writeState { - try store.stageDeclaration(declaration, in: transaction) - try transaction.replace( - store.resolvedURL, content: nil, data: StateStore.encodeState(next.normalized)) - } - try cache.prune(referencedBy: next, transaction: transaction) - try transaction.commit() - return receipts(next: next, names: names) - } - - func validateOwnership(previous: ResolvedState, next: ResolvedState, names: Set) throws { - let oldTargets = try targets(previous) - let newTargets = try targets(next) - // Only recorded targets belong to this scope. Dangling or looping links hold no content. - for (path, target) in newTargets.sorted(by: { $0.key < $1.key }) - where names.contains(target.name) && oldTargets[path] == nil && Self.holdsContent(atPath: path) - { - throw CoreError.invalidSkill( - "skill '\(target.name)' in \(store.scope.rawValue) scope cannot be installed at \(path): " - + "an entry this scope does not manage already exists there; move or remove it first") - } - } - - func retain(prepared: [String: PreparedSkill], next: ResolvedState) throws -> [String: URL] { - var retained: [String: URL] = [:] - for (name, item) in prepared.sorted(by: { $0.key < $1.key }) { - try validate(item, name: name) - let skill = item.lock - let path: URL - if let revision = skill.revision, let source = next.sources[skill.source] { - let root = try cache.materialize(sourceID: skill.source, source: source, revision: revision) - path = try PathSafety.resolvedChild(base: root, subpath: skill.path ?? ".") - } else if let artifact = skill.artifact { - for (digest, data) in item.payloads { _ = try cache.storeArtifact(data, digest: digest) } - guard let hash = skill.hash else { - throw CoreError.invalidState("missing artifact content hash") - } - path = try cache.materializeArtifact(item.directory, digest: artifact.digest, hash: hash) - } else { - path = item.directory - } - if let hash = skill.hash { - guard try "sha256:" + FileHash.folderHash(path) == hash, - try FileHash.executableFlags(path) == item.executableFlags - else { - throw CoreError.invalidState("cached skill content or executable mode mismatch: \(name)") - } - } - retained[name] = path - } - return retained - } - - func validate(_ item: PreparedSkill, name: String) throws { - try item.identity.validate() - try item.sourceIdentity.validate() - if let hash = item.lock.hash { - guard try "sha256:" + FileHash.folderHash(item.directory) == hash, - try FileHash.executableFlags(item.directory) == item.executableFlags - else { throw CoreError.invalidState("prepared skill changed: \(name)") } - } else { - guard - let skill = try Discovery.parseSkill( - at: item.directory.appendingPathComponent("SKILL.md"), includeInternal: true), - PathSafety.sanitizeName(skill.name) == name - else { throw CoreError.invalidSkill("live skill is unavailable: \(name)") } - } - } - - func stage( - previous: ResolvedState, next: ResolvedState, prepared: [String: PreparedSkill], - retained: [String: URL], names: Set, transaction: FileTransaction - ) throws { - let oldTargets = try targets(previous) - let newTargets = try targets(next) - for path in Set(oldTargets.keys).union(newTargets.keys).sorted() { - if let target = newTargets[path], names.contains(target.name), - let content = retained[target.name], let item = prepared[target.name] - { - guard - !PathSafety.isContained( - content.resolvingSymlinksInPath(), in: URL(fileURLWithPath: path).standardizedFileURL) - else { throw CoreError.unsafePath("installation would replace its own source") } - try transaction.replace( - URL(fileURLWithPath: path), content: content, link: target.mode != .copy, - expectedHash: item.lock.hash, - executableFlags: item.executableFlags) - } else if let target = oldTargets[path], names.contains(target.name), newTargets[path] == nil - { - try transaction.replace(URL(fileURLWithPath: path), content: nil) - } - } - } - - func receipts(next: ResolvedState, names: Set) -> [InstallResult] { - names.sorted().flatMap { name in - (next.skills[name]?.installs ?? [:]).sorted(by: { $0.key < $1.key }).compactMap { raw, mode in - guard let agent = AgentID(rawValue: raw) else { return nil } - return InstallResult( - skill: name, agent: agent, scope: store.scope, mode: mode, - path: Self.target(name: name, agent: agent, store: store).path) - } - } - } - - func membership(name: String, old: LockedSkill?, new: LockedSkill?) -> [SkillMembershipChange] { - Set((old?.installs ?? [:]).keys).union((new?.installs ?? [:]).keys).sorted().compactMap { raw in - guard let agent = AgentID(rawValue: raw) else { return nil } - return SkillMembershipChange( - agent: agent, - path: Self.physicalTarget(Self.target(name: name, agent: agent, store: store)).path, - before: old?.installs[raw].map { .installed(mode: $0) } ?? .absent, - after: new?.installs[raw].map { .installed(mode: $0) } ?? .absent) - } - } - - func changes(name: String, old: LockedSkill?, new: PreparedSkill?) throws -> [SkillFileChange] { - let oldTargets = try targets(ResolvedState(skills: old.map { [name: $0] } ?? [:])) - let newTargets = try targets(ResolvedState(skills: new.map { [name: $0.lock] } ?? [:])) - var result: [SkillFileChange] = [] - for path in Set(oldTargets.keys).union(newTargets.keys).sorted() { - let target = URL(fileURLWithPath: path) - let before = try entries(target) - var after: [String: SkillFileEntry] = [:] - if let planned = newTargets[path], let new { - after = try entries(new.directory) - if planned.mode != .copy { - let content: URL - if let revision = new.lock.revision { - content = try PathSafety.resolvedChild( - base: cache.materializedURL(sourceID: new.lock.source, revision: revision), - subpath: new.lock.path ?? ".") - } else if let artifact = new.lock.artifact { - content = store.cacheDirectory.appendingPathComponent( - "artifact-content/" + artifact.digest.dropFirst(7)) - } else { - content = new.directory + var targets: [String: SkillInstallationTarget] = [:] + var resolver = SkillInstallationTargetResolver(store: store) + for deployment in ledger.deployments where deployment.route == "agents/skill@1" { + guard deployment.target.kind == .registered, + let agent = deployment.recipients.first, deployment.recipients.count == 1, + deployment.target.root == "skills-" + agent.rawValue + else { throw CoreError.invalidState("invalid skill installation recipient") } + let name = deployment.target.path + targets[agent.rawValue + "/" + name] = try resolver.target(for: agent, named: name) + } + return targets + } + + private struct RequiredInstallations: Error { + let targets: [String: SkillInstallationTarget] + } + + /// Capture all managed slots before admitting physical reads; never recover during inventory. + static func withInstallationReadLock( + store: StateStore, onPendingRecovery: (() throws -> T)? = nil, + _ body: (ResolvedLedger) throws -> T + ) throws -> T { + var targets: [String: SkillInstallationTarget] = [:] + while true { + do { + return try store.withReadLock( + onPendingRecovery: onPendingRecovery, installations: Array(targets.values) + ) { + let ledger = try store.readLedger() + let required = try installationTargets(ledger, store: store) + guard Set(required.keys).isSubset(of: Set(targets.keys)) else { + throw RequiredInstallations(targets: required) } - after["."] = .symbolicLink( - FileTransaction.linkDestination( - content, parent: target.deletingLastPathComponent(), store: store)) - } else { - after["."] = .directory + return try body(ledger) } - } - for relative in Set(before.keys).union(after.keys).sorted() - where before[relative] != after[relative] { - result.append( - SkillFileChange( - path: relative == "." ? path : target.appendingPathComponent(relative).path, - before: before[relative], after: after[relative])) + } catch let required as RequiredInstallations { + targets.merge(required.targets, uniquingKeysWith: { _, next in next }) } } - return result } - static func target(name: String, agent: AgentID, store: StateStore) -> URL { + package static func target(name: String, agent: AgentID, store: StateStore) -> URL { AgentRegistry.installSkillsDirectory( for: agent, scope: store.scope, environment: store.environment ).appendingPathComponent(name).standardizedFileURL } - static func holdsContent(atPath path: String) -> Bool { + package static func holdsContent(atPath path: String) -> Bool { guard let attributes = try? FileManager.default.attributesOfItem(atPath: path) else { return false } @@ -390,40 +161,23 @@ final class SkillLifecycle { || FileManager.default.fileExists(atPath: path) } - static func physicalTarget(_ url: URL) -> URL { + package static func physicalTarget(_ url: URL) -> URL { url.deletingLastPathComponent().resolvingSymlinksInPath() .appendingPathComponent(url.lastPathComponent).standardizedFileURL } - func targets(_ lock: ResolvedState) throws -> [String: (name: String, mode: InstallMode)] { - var result: [String: (name: String, mode: InstallMode)] = [:] - for (name, skill) in lock.skills { - for (raw, mode) in skill.installs { - guard let agent = AgentID(rawValue: raw) else { - throw CoreError.invalidState("unknown locked agent") - } - let url = Self.target(name: name, agent: agent, store: store) - let physical = Self.physicalTarget(url).path - if let existing = result[physical], existing.name != name || existing.mode != mode { - throw CoreError.invalidState("agents sharing a skill directory must use the same mode") - } - result[physical] = (name, mode) - } - } - return result - } - private func write(_ files: [String: Data], to directory: URL) throws { - try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + try FileSystem.createDirectory(at: directory) for (path, data) in files { let url = try PathSafety.resolvedChild(base: directory, subpath: path) - try FileManager.default.createDirectory( - at: url.deletingLastPathComponent(), withIntermediateDirectories: true) - try data.write(to: url) + try FileSystem.createDirectory(at: url.deletingLastPathComponent()) + try FileSystem.write(data, to: url) } } - func entries(_ directory: URL, followRoot: Bool = true) throws -> [String: SkillFileEntry] { + package static func entries(_ directory: URL, followRoot: Bool = true) throws -> [String: + SkillFileEntry] + { func entry(_ url: URL) throws -> SkillFileEntry? { guard let attributes = try? FileManager.default.attributesOfItem(atPath: url.path) else { return nil @@ -434,7 +188,7 @@ final class SkillLifecycle { case .typeDirectory: return .directory case .typeRegular: let mode = (attributes[.posixPermissions] as? NSNumber)?.uint16Value ?? 0 - return .file(try Data(contentsOf: url), executable: mode & 0o111 != 0) + return .file(try FileSystem.read(at: url), executable: mode & 0o111 != 0) default: throw CoreError.unsafePath("unsupported installed entry: \(url.path)") } } diff --git a/Sources/AgentsSkills/SkillModels.swift b/Sources/AgentsSkills/SkillModels.swift index 5de52cb..0667963 100644 --- a/Sources/AgentsSkills/SkillModels.swift +++ b/Sources/AgentsSkills/SkillModels.swift @@ -43,6 +43,16 @@ public struct AddOutcome: Sendable { public var availableSkills: [Skill] /// Empty when inspection or multiple unselected skills require a CLI choice. public var installed: [InstallResult] + + package init( + source: SourceDeclaration, sourceID: String, availableSkills: [Skill], + installed: [InstallResult] + ) { + self.source = source + self.sourceID = sourceID + self.availableSkills = availableSkills + self.installed = installed + } } public struct InstallResult: Codable, Equatable, Sendable { @@ -51,10 +61,23 @@ public struct InstallResult: Codable, Equatable, Sendable { public var scope: InstallScope public var mode: InstallMode public var path: String + + package init(skill: String, agent: AgentID, scope: InstallScope, mode: InstallMode, path: String) + { + self.skill = skill + self.agent = agent + self.scope = scope + self.mode = mode + self.path = path + } } public struct ResolvedInstallReport: Sendable { public var installed: [InstallResult] + + package init(installed: [InstallResult]) { + self.installed = installed + } } public enum InstalledSkillStatus: String, Codable, Sendable { @@ -88,6 +111,12 @@ public struct SkillFileChange: Codable, Equatable, Sendable { public var path: String public var before: SkillFileEntry? public var after: SkillFileEntry? + + package init(path: String, before: SkillFileEntry?, after: SkillFileEntry?) { + self.path = path + self.before = before + self.after = after + } } /// Membership recorded by the lock, independent of filesystem presence. @@ -101,6 +130,13 @@ public struct SkillMembershipChange: Codable, Equatable, Sendable { public let path: String public let before: SkillMembership public let after: SkillMembership + + package init(agent: AgentID, path: String, before: SkillMembership, after: SkillMembership) { + self.agent = agent + self.path = path + self.before = before + self.after = after + } } public struct UpdateResult: Codable, Equatable, Sendable { @@ -117,6 +153,27 @@ public struct UpdateResult: Codable, Equatable, Sendable { public var membership: [SkillMembershipChange] public var changes: [SkillFileChange] public var installed: [InstallResult] + + package init( + skill: String, sourceIdentity: String, changed: Bool, oldRevision: String?, + newRevision: String?, oldVersion: String?, newVersion: String?, oldHash: String?, + newHash: String?, lockMissing: Bool, membership: [SkillMembershipChange], + changes: [SkillFileChange], installed: [InstallResult] + ) { + self.skill = skill + self.sourceIdentity = sourceIdentity + self.changed = changed + self.oldRevision = oldRevision + self.newRevision = newRevision + self.oldVersion = oldVersion + self.newVersion = newVersion + self.oldHash = oldHash + self.newHash = newHash + self.lockMissing = lockMissing + self.membership = membership + self.changes = changes + self.installed = installed + } } public enum DoctorCheckStatus: String, Codable, Sendable { case ok, warning, error } diff --git a/Sources/AgentsSkills/SkillOperations.swift b/Sources/AgentsSkills/SkillOperations.swift index 8523e51..82eaeb2 100644 --- a/Sources/AgentsSkills/SkillOperations.swift +++ b/Sources/AgentsSkills/SkillOperations.swift @@ -1,363 +1,8 @@ import AgentsCore +import AgentsManifest import Foundation public enum SkillOperations { - public static func add(_ options: AddOptions) throws -> AddOutcome { - try add(options, provider: WellKnownProvider()) - } - - static func add(_ options: AddOptions, provider: WellKnownProvider) throws -> AddOutcome { - var options = options - if let name = try SourceArgument(options.source).name { - guard !options.all else { - throw CoreError.invalidSource("@skill: names one skill and cannot be combined with all") - } - if !options.skillNames.contains(name) { options.skillNames.append(name) } - } - var automaticSelection: (sourceID: String, name: String)? - if options.listOnly || (options.skillNames.isEmpty && !options.all) { - let outcome = try add(options, provider: provider, apply: false) - if options.listOnly || outcome.availableSkills.count > 1 { return outcome } - automaticSelection = outcome.availableSkills.first.map { (outcome.sourceID, $0.name) } - } - return try add(options, provider: provider, apply: true, automaticSelection: automaticSelection) - } - - private static func add( - _ options: AddOptions, provider: WellKnownProvider, apply: Bool, - automaticSelection: (sourceID: String, name: String)? = nil - ) throws -> AddOutcome { - let store = StateStore(scope: options.scope, environment: options.environment) - return try operate(store, apply: apply) { declaration, lock in - let lifecycle = try SkillLifecycle(store: store, provider: provider) - var declaration = declaration - let selectionChanged = CoreError.invalidState( - "automatic skill selection changed during discovery; retry the command") - let source: SourceDeclaration - let id: String - do { - source = try sourceDeclaration(options, declaration: declaration) - id = try source.identity(environment: options.environment) - } catch { - if automaticSelection != nil { throw selectionChanged } - throw error - } - if let automaticSelection, automaticSelection.sourceID != id { throw selectionChanged } - let existing = try declaration.sources.keys.sorted().first { - try declaration.sources[$0]?.identity(environment: options.environment) == id - } - let alias = options.alias ?? existing ?? declaration.derivedAlias(for: source.location) - if let current = declaration.sources[alias], - try current.identity(environment: options.environment) != id - { - throw CoreError.invalidSource("source alias already refers to another source: \(alias)") - } - declaration.sources[alias] = source - try declaration.validate(environment: options.environment) - let available = try lifecycle.discover( - source, - live: options.mode == .edit - || (options.listOnly && source.kind == .local && source.requirement == nil), - fullDepth: options.fullDepth, cacheSource: apply) - let selected: [Skill] - if let automaticSelection { - guard let skill = available.skills.first(where: { $0.name == automaticSelection.name }) - else { throw selectionChanged } - selected = [skill] - } else { - selected = try lifecycle.select(available.skills, names: options.skillNames) - } - guard options.listOnly || !selected.isEmpty else { - throw CoreError.notFound("no skills found in \(options.source)") - } - if !apply { - return AddOutcome(source: source, sourceID: id, availableSkills: selected, installed: []) - } - var selection = declaration.skills?[alias] ?? SkillDeclaration(select: .names([])) - let names = selected.map { PathSafety.sanitizeName($0.name) } - if options.all { - selection.select = .all - } else if case .names(let previous) = selection.select { - selection.select = .names(Array(Set(previous + names)).sorted()) - } - selection.exclude = selection.exclude?.filter { !names.contains($0) } - if declaration.skills?[alias] == nil || options.all { - selection.agents = options.agents - selection.mode = options.mode - } else { - for name in names { - selection.overrides = selection.overrides ?? [:] - let recipients = options.agents ?? selection.overrides?[name]?.agents ?? selection.agents - selection.overrides?[name] = SkillOverride(agents: recipients, mode: options.mode) - } - } - declaration.skills = declaration.skills ?? [:] - declaration.skills?[alias] = selection - try declaration.validate(environment: options.environment) - var next = lock - next.sources[id] = lifecycle.lockedSource(source) - var prepared: [String: PreparedSkill] = [:] - for skill in selected { - let name = PathSafety.sanitizeName(skill.name) - if let current = lock.skills[name], current.source != id { - let ownerAlias = try declaration.sources.keys.sorted().first { - try declaration.sources[$0]?.identity(environment: options.environment) - == current.source - } - let owner = ownerAlias.map { "'\($0)' (\(current.source))" } ?? current.source - let locations = AgentID.allCases.filter { current.installs[$0.rawValue] != nil }.map { - "\($0.rawValue) at \(SkillLifecycle.target(name: name, agent: $0, store: store).path)" - }.joined(separator: ", ") - throw CoreError.invalidSkill( - "skill '\(name)' in \(options.scope.rawValue) scope already belongs to source \(owner); " - + "cannot add from source '\(alias)' (\(id)). Existing installations: \(locations)") - } - let item = try lifecycle.prepare( - skill, in: available, declaration: selection, defaultAgents: declaration.defaultAgents) - prepared[name] = item - next.skills[name] = item.lock - } - try next.validate() - let installed = try lifecycle.apply( - declaration: declaration, previous: lock, next: next, prepared: prepared, names: Set(names)) - return AddOutcome( - source: source, sourceID: id, availableSkills: selected, installed: installed) - } - } - - /// Resolves declared intent. The callback runs before any target or state replacement. - public static func updateInstalled( - scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment(), - skillNames: [String] = [], apply: Bool = false, - beforeApply: (([UpdateResult]) throws -> Void)? = nil - ) throws -> [UpdateResult] { - try update( - scope: scope, environment: environment, skillNames: skillNames, apply: apply, - beforeApply: beforeApply, provider: WellKnownProvider()) - } - - static func update( - scope: InstallScope, environment: RuntimeEnvironment, skillNames: [String], apply: Bool, - beforeApply: (([UpdateResult]) throws -> Void)? = nil, provider: WellKnownProvider - ) throws -> [UpdateResult] { - let store = StateStore(scope: scope, environment: environment) - return try operate(store, apply: apply) { declaration, previous in - let baseline = try StatePrecondition(store: store) - let resolutions = try SourceResolutionSession(store: store) - let plan = try prepareUpdate( - store: store, declaration: declaration, previous: previous, resolutions: resolutions, - skillNames: skillNames, provider: provider) - try plan.next.validate() - var results = plan.results - if apply { - try plan.validateOwnership() - try beforeApply?(results) - try baseline.validate() - try plan.validate() - let retained = try plan.retain() - try baseline.validate() - try plan.validate() - let transaction = FileTransaction(store: store) - try plan.stage(retained: retained, transaction: transaction) - try store.stageDeclaration(declaration, in: transaction) - try transaction.replace( - store.resolvedURL, content: nil, data: StateStore.encodeState(plan.next.normalized)) - try SourceCache(store: store).prune(referencedBy: plan.next, transaction: transaction) - try transaction.commit() - let installed = plan.receipts - for index in results.indices { - results[index].installed = installed.filter { $0.skill == results[index].skill } - } - } - return results - } - } - - /// Prepares skill-owned records; the caller validates the complete generation after assembly. - package static func prepareUpdate( - store: StateStore, declaration: Declaration, previous: ResolvedState, - resolutions: SourceResolutionSession, skillNames: [String] = [] - ) throws -> SkillUpdatePlan { - try prepareUpdate( - store: store, declaration: declaration, previous: previous, resolutions: resolutions, - skillNames: skillNames, provider: WellKnownProvider()) - } - - private static func prepareUpdate( - store: StateStore, declaration: Declaration, previous: ResolvedState, - resolutions: SourceResolutionSession, skillNames: [String], provider: WellKnownProvider - ) throws -> SkillUpdatePlan { - let environment = store.environment - let lifecycle = try SkillLifecycle(store: store, provider: provider, resolutions: resolutions) - let requested = Set(skillNames.map(PathSafety.sanitizeName)) - var next = previous - var prepared: [String: PreparedSkill] = [:] - for alias in (declaration.skills ?? [:]).keys.sorted() { - guard let selection = declaration.skills?[alias], let source = declaration.sources[alias] - else { continue } - let id = try source.identity(environment: environment) - let requestedHere = requested.filter { name in - if let installed = previous.skills[name] { return installed.source == id } - if case .names(let names) = selection.select { return names.contains(name) } - return !(selection.exclude ?? []).contains(name) - } - if !requested.isEmpty && requestedHere.isEmpty { continue } - if case .names(let names) = selection.select, names.isEmpty { continue } - func mode(_ name: String) -> InstallMode { - selection.overrides?[name]?.mode ?? selection.mode ?? .link - } - let explicit: [String]? - if !requested.isEmpty { - explicit = requestedHere.sorted() - } else if case .names(let names) = selection.select { - explicit = names - } else { - explicit = nil - } - let primaryLive = - explicit.map { $0.allSatisfy { mode($0) == .edit } } ?? (selection.mode == .edit) - var liveSource: DiscoveredSource? - var pinnedSource: DiscoveredSource? - func discover(live: Bool) throws -> DiscoveredSource { - if live, let liveSource { return liveSource } - if !live, let pinnedSource { return pinnedSource } - let result = try lifecycle.discover( - source, live: live, fullDepth: explicit != nil, names: explicit, - exclude: selection.exclude ?? []) - if live { liveSource = result } else { pinnedSource = result } - return result - } - let primary = try discover(live: primaryLive) - var names = explicit ?? primary.skills.map { PathSafety.sanitizeName($0.name) } - if explicit == nil { - let overrides = (selection.overrides ?? [:]).keys.filter { - (mode($0) == .edit) != primaryLive - } - for name in overrides { - let alternate = try discover(live: mode(name) == .edit) - if !Discovery.filter(alternate.skills, names: [name]).isEmpty { names.append(name) } - } - names = Array(Set(names)).filter { !(selection.exclude ?? []).contains($0) }.sorted() - } - for name in names { - let discovered = try discover(live: mode(name) == .edit) - let matches = Discovery.filter(discovered.skills, names: [name]) - if matches.isEmpty, explicit == nil { continue } - if matches.isEmpty, previous.skills[name] == nil, !requested.isEmpty, - !selection.hasNamedSelection - { - continue - } - let skill = try lifecycle.select(discovered.skills, names: [name])[0] - if let current = prepared[name], current.lock.source != id { - throw CoreError.invalidSkill("duplicate skill name: \(name)") - } - if let current = previous.skills[name], current.source != id { - throw CoreError.invalidSkill("skill '\(name)' already belongs to \(current.source)") - } - let item = try lifecycle.prepare( - skill, in: discovered, declaration: selection, defaultAgents: declaration.defaultAgents) - prepared[name] = item - next.skills[name] = item.lock - } - next.sources[id] = lifecycle.lockedSource(source) - } - guard requested.isSubset(of: Set(prepared.keys)) else { - throw CoreError.notFound("requested skill is not declared or is missing upstream") - } - if requested.isEmpty { next.skills = prepared.mapValues(\.lock) } - let affected = requested.isEmpty ? Set(previous.skills.keys).union(prepared.keys) : requested - let results = try affected.sorted().map { name in - let old = previous.skills[name] - let new = next.skills[name] - let changes = try lifecycle.changes(name: name, old: old, new: prepared[name]) - return UpdateResult( - skill: name, sourceIdentity: new?.source ?? old?.source ?? "", - changed: old != new || !changes.isEmpty, oldRevision: old?.revision, - newRevision: new?.revision, oldVersion: old?.version, newVersion: new?.version, - oldHash: old?.hash, newHash: new?.hash, - lockMissing: !FileManager.default.fileExists(atPath: store.resolvedURL.path), - membership: lifecycle.membership(name: name, old: old, new: new), changes: changes, - installed: []) - } - return try SkillUpdatePlan( - lifecycle: lifecycle, previous: previous, next: next, prepared: prepared, - names: affected, results: results) - } - - /// Restores each locked pin and recipient. Never resolves requirements or consults an index. - public static func installResolvedReport( - scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment() - ) throws -> ResolvedInstallReport { - try install(scope: scope, environment: environment, provider: WellKnownProvider()) - } - - static func install( - scope: InstallScope, environment: RuntimeEnvironment, provider: WellKnownProvider - ) throws -> ResolvedInstallReport { - let store = StateStore(scope: scope, environment: environment) - return try operate(store, apply: true) { declaration, lock in - let lifecycle = try SkillLifecycle(store: store, provider: provider) - var prepared: [String: PreparedSkill] = [:] - for (name, skill) in lock.skills { - prepared[name] = try lifecycle.restore(name: name, skill: skill, sources: lock.sources) - } - return ResolvedInstallReport( - installed: try lifecycle.apply( - declaration: declaration, previous: lock, next: lock, prepared: prepared, - names: Set(lock.skills.keys), writeState: false)) - } - } - - @discardableResult - public static func remove( - skillNames: [String], scope: InstallScope = .project, agents: [AgentID]? = nil, - environment: RuntimeEnvironment = RuntimeEnvironment() - ) throws -> [String] { - let store = StateStore(scope: scope, environment: environment) - return try operate(store, apply: true) { declaration, lock in - var declaration = declaration - var next = lock - let names = Set(skillNames.map(PathSafety.sanitizeName)) - guard names.isSubset(of: Set(lock.skills.keys)) else { - throw CoreError.notFound("skill is not installed") - } - for name in names { - guard var skill = next.skills[name] else { continue } - if let agents { - for agent in agents { skill.installs.removeValue(forKey: agent.rawValue) } - } else { - skill.installs = [:] - } - next.skills[name] = skill.installs.isEmpty ? nil : skill - for alias in (declaration.skills ?? [:]).keys { - guard let source = declaration.sources[alias], - try source.identity(environment: environment) == skill.source, - var selection = declaration.skills?[alias] - else { continue } - if skill.installs.isEmpty { - if case .all = selection.select { - selection.exclude = Array(Set((selection.exclude ?? []) + [name])).sorted() - } else if case .names(let members) = selection.select { - selection.select = .names(members.filter { $0 != name }) - } - selection.overrides?.removeValue(forKey: name) - } else { - selection.overrides = selection.overrides ?? [:] - let mode = selection.overrides?[name]?.mode - selection.overrides?[name] = SkillOverride( - agents: skill.installs.keys.compactMap(AgentID.init(rawValue:)), mode: mode) - } - declaration.skills?[alias] = selection - } - } - let lifecycle = try SkillLifecycle(store: store, provider: WellKnownProvider()) - _ = try lifecycle.apply( - declaration: declaration, previous: lock, next: next, prepared: [:], names: names) - return names.sorted() - } - } - public static func removableSkillNames( scope: InstallScope = .project, agents: [AgentID]? = nil, environment: RuntimeEnvironment = RuntimeEnvironment() @@ -371,41 +16,61 @@ public enum SkillOperations { environment: RuntimeEnvironment = RuntimeEnvironment() ) throws -> [InstalledSkill] { let store = StateStore(scope: scope, environment: environment) - return try operate(store, apply: false) { _, lock in - try managedInventory(store: store, lock: lock, agents: agents) + return try SkillLifecycle.withInstallationReadLock(store: store) { ledger in + _ = try store.readDeclaration() + let roots = store.ledgerRoots(recordedIn: ledger) + return try managedInventory(store: store, ledger: ledger, roots: roots, agents: agents) } } - private static func managedInventory(store: StateStore, lock: ResolvedState, agents: [AgentID]?) - throws -> [InstalledSkill] - { - try lock.skills.keys.sorted().flatMap { name in - guard let skill = lock.skills[name] else { return [InstalledSkill]() } - return try skill.installs.keys.sorted().compactMap { raw in - guard let agent = AgentID(rawValue: raw), let mode = skill.installs[raw], - agents?.contains(agent) ?? true - else { return nil } - let target = SkillLifecycle.target(name: name, agent: agent, store: store) - let present = FileManager.default.fileExists( - atPath: target.appendingPathComponent("SKILL.md").path) - var status: InstalledSkillStatus = - present ? (mode == .edit ? .editLinked : .installed) : .missing - if present, mode != .edit, let hash = skill.hash, - try "sha256:" + FileHash.folderHash(target) != hash + private static func managedInventory( + store: StateStore, ledger: ResolvedLedger, roots: [String: URL], agents: [AgentID]? + ) throws -> [InstalledSkill] { + var result: [InstalledSkill] = [] + for deployment in ledger.deployments where deployment.route == "agents/skill@1" { + guard + let lowering = ledger.lowerings.first(where: { $0.deployments.contains(deployment.id) }), + let component = deployment.owners.first.flatMap({ ledger.components[$0] }), + let resource = component.resources.first.flatMap({ ledger.resources[$0] }) + else { continue } + let mode = lowering.layout.object?["mode"]?.text.flatMap(InstallMode.init(rawValue:)) ?? .copy + let target = try deployment.target.resolve(roots: roots) + let present = FileManager.default.fileExists( + atPath: target.appendingPathComponent("SKILL.md").path) + var status: InstalledSkillStatus = + present ? (mode == .edit ? .editLinked : .installed) : .missing + if present, mode != .edit { + let flags = Dictionary( + uniqueKeysWithValues: resource.entries.filter { $0.kind == .file }.map { + ($0.path, $0.executable) + }) + if try "sha256:" + FileHash.folderHash(target) != resource.hash + || FileHash.executableFlags(target) != flags { status = .copyDrift } - if !present, - (try? FileManager.default.destinationOfSymbolicLink(atPath: target.path)) != nil - { - status = .brokenLink + } + if !present, (try? FileManager.default.destinationOfSymbolicLink(atPath: target.path)) != nil + { + status = .brokenLink + } + for agent in deployment.recipients where agents?.contains(agent) ?? true { + if !result.contains(where: { + $0.name == PathSafety.sanitizeName(component.name) && $0.agent == agent + && $0.path == target.path + }) { + result.append( + InstalledSkill( + name: PathSafety.sanitizeName(component.name), agent: agent, scope: store.scope, + path: target.path, + sourceIdentity: try ledger.sourceIdentity(component.source, roots: roots), + isInstalled: present, status: status, mode: mode)) } - return InstalledSkill( - name: name, agent: agent, scope: store.scope, path: target.path, - sourceIdentity: skill.source, - isInstalled: present, status: status, mode: mode) } } + return result.sorted { + ($0.name, $0.agent.rawValue, $0.path) < ($1.name, $1.agent.rawValue, $1.path) + } } public static func listInstalled( @@ -413,14 +78,17 @@ public enum SkillOperations { environment: RuntimeEnvironment = RuntimeEnvironment() ) throws -> [InstalledSkill] { let store = StateStore(scope: scope, environment: environment) - return try operate(store, apply: false) { _, lock in - var result = try managedInventory(store: store, lock: lock, agents: agents).filter { - $0.isInstalled - && (try? Discovery.parseSkill( - at: URL(fileURLWithPath: $0.path).appendingPathComponent("SKILL.md"), - includeInternal: true)) != nil - } - for agent in agents ?? AgentID.allCases { + return try SkillLifecycle.withInstallationReadLock(store: store) { ledger in + _ = try store.readDeclaration() + let roots = store.ledgerRoots(recordedIn: ledger) + var result = try managedInventory(store: store, ledger: ledger, roots: roots, agents: agents) + .filter { + $0.isInstalled + && (try? Discovery.parseSkill( + at: URL(fileURLWithPath: $0.path).appendingPathComponent("SKILL.md"), + includeInternal: true)) != nil + } + for agent in agents ?? AgentRegistry.skillAgents { let roots = scope == .project ? AgentRegistry.projectScanDirectories(for: agent, environment: environment) @@ -459,33 +127,43 @@ public enum SkillOperations { environment: RuntimeEnvironment = RuntimeEnvironment() ) throws -> DoctorReport { let store = StateStore(scope: scope, environment: environment) - return try store.withReadLock( + return try SkillLifecycle.withInstallationReadLock( + store: store, onPendingRecovery: { - DoctorReport(checks: [ + let recovery = FileTransaction.recoveryDiagnostic(store: store) + return DoctorReport(checks: [ DoctorCheck( - id: "pending-recovery", status: .warning, - message: - "Transaction recovery is pending; the next command that changes this scope will recover it.", + id: recovery.requiresOwner ? "unresolved-transaction" : "pending-recovery", + status: .warning, + message: recovery.message, path: store.directory.path) ]) }, - { + { ledger in let declaration = try store.readDeclaration() - let lock = try store.readResolved() - var checks = try managedInventory(store: store, lock: lock, agents: agents).filter { + let roots = store.ledgerRoots(recordedIn: ledger) + var checks = try managedInventory( + store: store, ledger: ledger, roots: roots, agents: agents + ).filter { $0.status != .installed && $0.status != .editLinked }.map { DoctorCheck( id: $0.status.rawValue, status: .warning, message: "\($0.name): \($0.status.rawValue)", path: $0.path) } - let cache = SourceCache(store: store) + let cache = try SourceCache( + store: store, sourcePolicy: SourcePolicySnapshot(store: store).effective) + let bundledSources = try ledger.bundledSourceIdentities(in: store, roots: roots) for (alias, source) in declaration.sources.sorted(by: { $0.key < $1.key }) { let id = try source.identity(environment: environment) - let skills = lock.skills.values.filter { $0.source == id } + guard !bundledSources.contains(id) else { continue } + let skills = try ledger.components.values.filter { + guard $0.kind == "skills", !$0.recipients.isEmpty else { return false } + return try ledger.sourceIdentity($0.source, roots: roots) == id + } guard !skills.isEmpty else { continue } if source.kind == .local { - let paths = skills.compactMap(\.path) + let paths = skills.flatMap { $0.resources.compactMap { ledger.resources[$0]?.path } } let output = try? ProcessRunner.git( [ "--no-optional-locks", "-C", source.localURL(environment: environment).path, @@ -526,52 +204,75 @@ public enum SkillOperations { } public static func initializeSkill(named name: String?, directory: URL) throws -> URL { - let store = StateStore( - scope: .project, environment: RuntimeEnvironment(projectDirectory: directory)) - return try store.withLock(createIfMissing: false) { - _ = try store.readDeclaration() - _ = try store.readResolved() - let name = name.map(PathSafety.sanitizeName) - let root = name.map { directory.appendingPathComponent($0) } ?? directory - let file = root.appendingPathComponent("SKILL.md") - guard !FileManager.default.fileExists(atPath: file.path) else { - throw CoreError.invalidSkill("SKILL.md already exists at \(file.path)") - } - try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) - let title = name ?? PathSafety.sanitizeName(root.lastPathComponent) - try - "---\nname: \(title)\ndescription: Describe when to use this skill\n---\n\n# \(title)\n\nWrite the skill instructions here.\n" - .write(to: file, atomically: true, encoding: .utf8) - return root - } + try SkillInitialization( + named: name, directory: directory, environment: RuntimeEnvironment(), validateState: false + ) + .apply(outcome: TransactionOutcome(), checkpoint: { _ in }) } - private static func operate( - _ store: StateStore, apply: Bool, _ body: (Declaration, ResolvedState) throws -> T - ) throws -> T { - if apply { - return try store.withLock { try body(store.readDeclaration(), store.readResolved()) } +} + +extension SkillOperations { + package static func lockedMetadata(at directory: URL, installedName: String) throws -> Skill { + let metadata = try Discovery.parseSkill( + at: directory.appendingPathComponent("SKILL.md"), includeInternal: true) + guard let metadata, PathSafety.sanitizeName(metadata.name) == installedName else { + throw CoreError.invalidSkill( + "SKILL.md no longer identifies the locked skill \(installedName)") } - return try store.withReadLock { try body(store.readDeclaration(), store.readResolved()) } + return metadata } - private static func sourceDeclaration(_ options: AddOptions, declaration: Declaration) throws - -> SourceDeclaration - { - let selection = try SourceArgument(options.source).selection( + package static func inspect( + _ options: AddOptions, declaration: Declaration + ) throws -> (SourceDeclaration, String, [Skill]) { + let argument = try SourceArgument(options.source).selection( in: declaration, requirement: options.sourceRequirement, path: options.path, environment: options.environment) - let source = selection.applied(to: selection.source) + let source = argument.applied(to: argument.source) if options.mode == .edit, source.kind != .local || source.requirement != nil { throw CoreError.invalidSource("edit requires a local source with no requirement") } - return source + let store = StateStore(scope: options.scope, environment: options.environment) + let policy = try SourcePolicySnapshot(store: store) + try policy.effective.require(source, environment: store.environment) + return try SourceResolutionSession.withTemporaryRead( + store: store, sourcePolicy: policy.effective + ) { session in + let lifecycle = try SkillLifecycle( + store: store, + provider: WellKnownProvider( + sourcePolicy: policy.effective, sourceAccess: store.environment.sourceAccess), + resolutions: session) + let found = try lifecycle.discover( + source, + live: options.mode == .edit + || (options.listOnly && source.kind == .local && source.requirement == nil), + fullDepth: options.fullDepth, + names: policy.effective.isConfigured && !options.skillNames.isEmpty + ? options.skillNames.map { $0.lowercased() } : nil, + cacheSource: false) + let selected = try lifecycle.select(found.skills, names: options.skillNames) + let available = selected.map { skill in + var skill = skill + if PathSafety.isContained(URL(fileURLWithPath: skill.path), in: found.root) { + skill.path = PathSafety.relativePath(skill.path, to: found.root.path) + skill.skillFile = PathSafety.relativePath(skill.skillFile, to: found.root.path) + } + return skill + } + try policy.validate() + return (source, found.id, available) + } } } -extension SkillDeclaration { - fileprivate var hasNamedSelection: Bool { - if case .names = select { return true } - return false +extension SkillOperations { + package static func validateLiveMetadata(at directory: URL, name: String) throws { + let metadata = try Discovery.parseSkill( + at: directory.appendingPathComponent("SKILL.md"), includeInternal: true) + guard metadata?.name == name else { + throw CoreError.invalidSkill("live skill metadata changed during preparation") + } } } diff --git a/Sources/AgentsSkills/SkillSnapshotReader.swift b/Sources/AgentsSkills/SkillSnapshotReader.swift new file mode 100644 index 0000000..83d19d2 --- /dev/null +++ b/Sources/AgentsSkills/SkillSnapshotReader.swift @@ -0,0 +1,103 @@ +import AgentsCore +import Foundation + +/// Relative skill evidence read from an already selected snapshot. This reader never resolves +/// a source or retains content. Live paths belong only to an actual local edit selection. +package struct SnapshotSkill: Equatable, Sendable { + package let name: String + package let description: String + package let path: String + package let condition: DeclarationCondition + package let hash: String + package let executableFlags: [String: Bool] + package let livePath: String? +} + +package enum SkillSnapshotReader { + package static func manifestName(_ bytes: Data, path: String) throws -> String { + guard let content = String(data: bytes, encoding: .utf8), + let skill = try Discovery.parseSkill( + content, at: URL(fileURLWithPath: "/" + path), includeInternal: true, strict: true, + diagnosticPath: path) + else { throw CoreError.invalidSource("invalid packaged SKILL.md: " + path) } + return skill.name + } + + package static func read( + _ view: SourceSnapshot, live: Bool = false, selecting: SkillMemberSelection? = nil + ) throws -> [SnapshotSkill] { + let base: URL + if live { + guard let root = view.liveRoot else { + throw CoreError.invalidSource("skill source is immutable") + } + base = root + } else { + base = view.root + } + let selected = try SourceSnapshot( + snapshot: view.snapshot, pin: view.pin, root: base, + discoveryPath: view.discoveryPath, localEnvironment: view.localEnvironment, + liveRoot: view.liveRoot, + packageIdentity: view.packageIdentity) + var options = DiscoveryOptions(fullDepth: true) + options.strict = true + options.selecting = selecting + let skills = try Discovery.discover(in: base, subpath: selected.discoveryPath, options: options) + return try skills.filter { + selecting?($0.name, URL(fileURLWithPath: $0.path).lastPathComponent) ?? true + }.map { + skill in + try Task.checkCancellation() + let path = try selected.relativePath(URL(fileURLWithPath: skill.path)) + let directory = try selected.resource(path) + try selected.validateResourceTree(directory) + let file = try selected.resource(path + "/SKILL.md") + let bytes = try FileSystem.read(at: file) + let fields = try Discovery.parseFrontmatter(String(decoding: bytes, as: UTF8.self)) + return try SnapshotSkill( + name: skill.name, description: skill.description, path: path, + condition: Discovery.producerCondition( + fields, file: file, content: String(decoding: bytes, as: UTF8.self), + diagnosticPath: path + "/SKILL.md"), + hash: "sha256:" + FileHash.folderHash(directory), + executableFlags: FileHash.executableFlags(directory), + livePath: live ? directory.path : nil) + } + } +} + +/// Existing skill index formats remain skill-only. Artifact coordinates, not the mutable index, +/// identify the selected content for later retention and locked reconstruction. +package struct SnapshotIndexSkill: Sendable { + package let name: String + package let artifact: LockedArtifact + package let files: [String: Data] + package let executableFlags: [String: Bool] +} + +extension SkillSnapshotReader { + package static func index( + _ source: SourceDeclaration, names: [String]? = nil, exclude: [String] = [], + sourcePolicy: EffectiveSourcePolicy = .init(), + sourceAccess: SourceAccessConfiguration = .init(), + requireOrigin: (@Sendable (SourceOrigin) throws -> Void)? = nil + ) throws -> [SnapshotIndexSkill] { + try Task.checkCancellation() + if sourcePolicy.isConfigured { try sourcePolicy.require(.http(source.location)) } + let provider = + requireOrigin.map { + WellKnownProvider.guarded( + sourcePolicy: sourcePolicy, sourceAccess: sourceAccess, requireOrigin: $0) + } ?? WellKnownProvider(sourcePolicy: sourcePolicy, sourceAccess: sourceAccess) + let result = try provider.fetchAllSkills( + from: source.location, names: names, exclude: exclude + ).map { + SnapshotIndexSkill( + name: $0.installName, artifact: $0.artifact, files: $0.files, + executableFlags: $0.executableFlags) + } + try Task.checkCancellation() + return result + } +} diff --git a/Sources/AgentsSkills/SkillUpdatePlan.swift b/Sources/AgentsSkills/SkillUpdatePlan.swift deleted file mode 100644 index a6f8ce6..0000000 --- a/Sources/AgentsSkills/SkillUpdatePlan.swift +++ /dev/null @@ -1,78 +0,0 @@ -import AgentsCore -import Foundation - -/// A domain plan borrows the scope lock and never commits or prunes independently. -package final class SkillUpdatePlan { - package let next: ResolvedState - package let results: [UpdateResult] - package let targetPaths: [URL] - private let lifecycle: SkillLifecycle - private let previous: ResolvedState - private let prepared: [String: PreparedSkill] - private let names: Set - private let before: [(URL, PathIdentity, Bool, [String: SkillFileEntry])] - private let recipientPaths: [PathIdentity] - - init( - lifecycle: SkillLifecycle, previous: ResolvedState, next: ResolvedState, - prepared: [String: PreparedSkill], names: Set, results: [UpdateResult] - ) throws { - self.lifecycle = lifecycle - self.previous = previous - self.next = next - self.prepared = prepared - self.names = names - self.results = results - let oldTargets = try lifecycle.targets(previous).filter { names.contains($0.value.name) } - let newTargets = try lifecycle.targets(next).filter { names.contains($0.value.name) } - targetPaths = Set(oldTargets.keys).union(newTargets.keys).sorted().map { - URL(fileURLWithPath: $0) - } - before = try targetPaths.map { url in - let follow = oldTargets[url.path]?.mode != .edit - return (url, try PathIdentity(url), follow, try lifecycle.entries(url, followRoot: follow)) - } - recipientPaths = try names.sorted().flatMap { name in - Set((previous.skills[name]?.installs ?? [:]).keys) - .union((next.skills[name]?.installs ?? [:]).keys).compactMap { raw in - AgentID(rawValue: raw).map { - SkillLifecycle.target(name: name, agent: $0, store: lifecycle.store) - } - } - }.map { try PathIdentity($0) } - } - - package func validateOwnership() throws { - try lifecycle.validateOwnership(previous: previous, next: next, names: names) - for (path, target) in try lifecycle.targets(next) { - if let item = prepared[target.name], item.lock.hash == nil, - PathSafety.isContained(item.directory, in: URL(fileURLWithPath: path)) - { - throw CoreError.unsafePath("installation would replace its own source") - } - } - } - - package func validate() throws { - for identity in recipientPaths { try identity.validate() } - for (url, identity, follow, entries) in before { - try identity.validate() - guard try lifecycle.entries(url, followRoot: follow) == entries else { - throw CoreError.invalidState("skill target changed during preparation: \(url.path)") - } - } - for (name, item) in prepared { try lifecycle.validate(item, name: name) } - } - - package func retain() throws -> [String: URL] { - try lifecycle.retain(prepared: prepared, next: next) - } - - package func stage(retained: [String: URL], transaction: FileTransaction) throws { - try lifecycle.stage( - previous: previous, next: next, prepared: prepared, retained: retained, - names: names, transaction: transaction) - } - - package var receipts: [InstallResult] { lifecycle.receipts(next: next, names: names) } -} diff --git a/Sources/AgentsSkills/WatchSupport.swift b/Sources/AgentsSkills/WatchSupport.swift index 2dadf7f..774ce61 100644 --- a/Sources/AgentsSkills/WatchSupport.swift +++ b/Sources/AgentsSkills/WatchSupport.swift @@ -1,4 +1,5 @@ import AgentsCore +import AgentsManifest import Foundation extension SkillOperations { @@ -23,6 +24,14 @@ extension SkillOperations { WatchArtifact( name: $0.installName, artifact: $0.artifact, files: $0.files, payloads: $0.payloads) } + }, + declarations: .manifest, + sourcePolicy: { try SourcePolicySnapshot(store: $0).effective }, + fetchGuardedArtifacts: { location, policy in + try WellKnownProvider(sourcePolicy: policy).fetchAllSkills(from: location).map { + WatchArtifact( + name: $0.installName, artifact: $0.artifact, files: $0.files, payloads: $0.payloads) + } }) } } diff --git a/Sources/AgentsSkills/WellKnownProvider.swift b/Sources/AgentsSkills/WellKnownProvider.swift index 7f9fe95..c87e194 100644 --- a/Sources/AgentsSkills/WellKnownProvider.swift +++ b/Sources/AgentsSkills/WellKnownProvider.swift @@ -2,24 +2,31 @@ import AgentsCore import Foundation import Yams +#if canImport(FoundationNetworking) + import FoundationNetworking +#endif + struct WellKnownRemoteSkill: Equatable, Sendable { var installName: String var description: String var sourceURL: URL var digest: String? var files: [String: Data] + var executableFlags: [String: Bool] var artifact: LockedArtifact var payloads: [String: Data] init( installName: String, description: String, sourceURL: URL, digest: String? = nil, - files: [String: Data], artifact: LockedArtifact? = nil, payloads: [String: Data] = [:] + files: [String: Data], artifact: LockedArtifact? = nil, payloads: [String: Data] = [:], + executableFlags: [String: Bool] = [:] ) { self.installName = installName self.description = description self.sourceURL = sourceURL self.digest = digest self.files = files + self.executableFlags = executableFlags self.artifact = artifact ?? LockedArtifact(type: .skillMD, url: sourceURL.absoluteString, digest: digest ?? "") @@ -33,11 +40,45 @@ struct WellKnownProvider: Sendable { private static let maxArchiveUnpackedBytes = 50 * 1024 * 1024 var fetch: @Sendable (URL) throws -> Data + private let sourceAccess: SourceAccessConfiguration + private let sourcePolicy: EffectiveSourcePolicy + private let requireOrigin: (@Sendable (SourceOrigin) throws -> Void)? init( + sourcePolicy: EffectiveSourcePolicy = .init(), + sourceAccess: SourceAccessConfiguration = .init(), fetch: @escaping @Sendable (URL) throws -> Data = { url in try Data(contentsOf: url) } ) { self.fetch = fetch + self.sourcePolicy = sourcePolicy + self.sourceAccess = sourceAccess + requireOrigin = nil + } + + static func guarded( + sourcePolicy: EffectiveSourcePolicy, sourceAccess: SourceAccessConfiguration, + requireOrigin: @escaping @Sendable (SourceOrigin) throws -> Void + ) -> Self { + Self( + guardedSourcePolicy: sourcePolicy, sourceAccess: sourceAccess, requireOrigin: requireOrigin) + } + + private init( + guardedSourcePolicy: EffectiveSourcePolicy, sourceAccess: SourceAccessConfiguration, + requireOrigin: @escaping @Sendable (SourceOrigin) throws -> Void + ) { + fetch = { url in try Data(contentsOf: url) } + sourcePolicy = guardedSourcePolicy + self.sourceAccess = sourceAccess + self.requireOrigin = requireOrigin + } + + private func read(_ url: URL) throws -> Data { + try sourceAccess.requireDirectHTTP(url, policy: sourcePolicy) + if sourcePolicy.isConfigured || requireOrigin != nil { + return try PolicyHTTPRead.fetch(url, policy: sourcePolicy, requireOrigin: requireOrigin) + } + return try fetch(url) } func indexURLCandidates(for rawURL: String) throws -> [( @@ -80,7 +121,15 @@ struct WellKnownProvider: Sendable { for candidate in try indexURLCandidates(for: rawURL) { let index: WellKnownIndex do { - index = try JSONDecoder().decode(WellKnownIndex.self, from: fetch(candidate.index)) + index = try JSONDecoder().decode(WellKnownIndex.self, from: read(candidate.index)) + } catch let error as OrganizationPolicyFailure { + throw error + } catch let error as SourcePolicyFailure { + throw error + } catch is UnrecordedSourceRedirect { + throw UnrecordedSourceRedirect() + } catch is CancellationError { + throw CancellationError() } catch { lastError = error continue @@ -99,7 +148,7 @@ struct WellKnownProvider: Sendable { guard let url = URL(string: rawURL), url.path.lowercased().hasSuffix("skill.md") else { return nil } - let data = try fetch(url) + let data = try read(url) let text = String(data: data, encoding: .utf8) ?? "" let metadata = try parseFrontmatter(text) let fallbackName = url.deletingLastPathComponent().lastPathComponent @@ -134,7 +183,7 @@ struct WellKnownProvider: Sendable { .appendingPathComponent(wellKnownPath) .appendingPathComponent(entry.name) .appendingPathComponent(safe) - let data = try fetch(fileURL) + let data = try read(fileURL) files[safe] = data let digest = "sha256:" + FileHash.sha256Hex(data: data) records.append(ArtifactFile(url: fileURL.absoluteString, path: safe, digest: digest)) @@ -159,14 +208,18 @@ struct WellKnownProvider: Sendable { guard let artifactURL = URL(string: entry.url, relativeTo: indexURL)?.absoluteURL else { throw CoreError.invalidSource("invalid artifact URL: \(entry.url)") } - let data = try fetch(artifactURL) + let data = try read(artifactURL) try verifyDigest(data: data, expected: entry.digest) let files: [String: Data] + let executableFlags: [String: Bool] switch entry.type { case "skill-md": files = ["SKILL.md": data] + executableFlags = [:] case "archive": - files = try unpackArchive(data, artifactURL: artifactURL) + let unpacked = try unpackArchive(data, artifactURL: artifactURL) + files = unpacked.files + executableFlags = unpacked.executableFlags default: throw CoreError.invalidSource("unsupported well-known artifact type: \(entry.type)") } @@ -179,7 +232,7 @@ struct WellKnownProvider: Sendable { artifact: LockedArtifact( type: entry.type == "archive" ? .archive : .skillMD, url: artifactURL.absoluteString, digest: entry.digest), - payloads: [entry.digest: data] + payloads: [entry.digest: data], executableFlags: executableFlags ) } } @@ -191,10 +244,13 @@ struct WellKnownProvider: Sendable { try artifact.validate() var payloads: [String: Data] = [:] func download(_ url: String, digest: String) throws -> Data { + guard let destination = URL(string: url) else { throw SourceAccessError.invalidRepository } + try sourceAccess.requireDirectHTTP(destination, policy: sourcePolicy) + try cache.store.environment.sourceAccess.requireDirectHTTP(destination) let cached = try cache.artifactURL(digest: digest) let data = FileManager.default.fileExists(atPath: cached.path) - ? try Data(contentsOf: cached) : try fetch(URL(string: url)!) + ? try FileSystem.read(at: cached) : try read(destination) try verifyDigest(data: data, expected: digest) payloads[digest] = data return data @@ -205,7 +261,7 @@ struct WellKnownProvider: Sendable { return (["SKILL.md": data], payloads) case .archive: let data = try download(artifact.url, digest: artifact.digest) - return (try unpackArchive(data, artifactURL: URL(string: artifact.url)!), payloads) + return (try unpackArchive(data, artifactURL: URL(string: artifact.url)!).files, payloads) case .files: let records = artifact.files ?? [] guard try LockedArtifact.filesDigest(records) == artifact.digest else { @@ -246,7 +302,9 @@ struct WellKnownProvider: Sendable { ) } - private func unpackArchive(_ data: Data, artifactURL: URL) throws -> [String: Data] { + private func unpackArchive(_ data: Data, artifactURL: URL) throws -> ( + files: [String: Data], executableFlags: [String: Bool] + ) { let lowerPath = artifactURL.path.lowercased() if lowerPath.hasSuffix(".zip") || data.starts(with: [0x50, 0x4b]) { return try unpackZip(data) @@ -254,13 +312,15 @@ struct WellKnownProvider: Sendable { return try unpackTarGz(data) } - private func unpackTarGz(_ data: Data) throws -> [String: Data] { + private func unpackTarGz(_ data: Data) throws -> ( + files: [String: Data], executableFlags: [String: Bool] + ) { let tempRoot = FileManager.default.temporaryDirectory .appendingPathComponent("agents-artifact-" + UUID().uuidString) let archive = tempRoot.appendingPathComponent("artifact.tar.gz") let extract = tempRoot.appendingPathComponent("extract") - try FileManager.default.createDirectory(at: extract, withIntermediateDirectories: true) - try data.write(to: archive) + try FileSystem.createDirectory(at: extract) + try FileSystem.write(data, to: archive) defer { try? FileManager.default.removeItem(at: tempRoot) } @@ -294,13 +354,15 @@ struct WellKnownProvider: Sendable { return try collectExtractedFiles(from: extract) } - private func unpackZip(_ data: Data) throws -> [String: Data] { + private func unpackZip(_ data: Data) throws -> ( + files: [String: Data], executableFlags: [String: Bool] + ) { let tempRoot = FileManager.default.temporaryDirectory .appendingPathComponent("agents-artifact-" + UUID().uuidString) let archive = tempRoot.appendingPathComponent("artifact.zip") let extract = tempRoot.appendingPathComponent("extract") - try FileManager.default.createDirectory(at: extract, withIntermediateDirectories: true) - try data.write(to: archive) + try FileSystem.createDirectory(at: extract) + try FileSystem.write(data, to: archive) defer { try? FileManager.default.removeItem(at: tempRoot) } @@ -334,7 +396,9 @@ struct WellKnownProvider: Sendable { return try collectExtractedFiles(from: extract) } - private func collectExtractedFiles(from extract: URL) throws -> [String: Data] { + private func collectExtractedFiles(from extract: URL) throws -> ( + files: [String: Data], executableFlags: [String: Bool] + ) { guard let enumerator = FileManager.default.enumerator( at: extract, @@ -342,7 +406,7 @@ struct WellKnownProvider: Sendable { options: [.skipsPackageDescendants] ) else { - return [:] + return ([:], [:]) } var totalBytes = 0 @@ -364,7 +428,7 @@ struct WellKnownProvider: Sendable { guard files.keys.contains(where: { $0.lowercased() == "skill.md" }) else { throw CoreError.invalidSource("well-known archive has no SKILL.md") } - return files + return (files, try FileHash.executableFlags(extract)) } } diff --git a/Sources/AgentsUpdates/AgentClientInspection.swift b/Sources/AgentsUpdates/AgentClientInspection.swift new file mode 100644 index 0000000..5663771 --- /dev/null +++ b/Sources/AgentsUpdates/AgentClientInspection.swift @@ -0,0 +1,208 @@ +import AgentsCore +import Components +import Foundation + +public enum AgentClientObservationStatus: String, Sendable { + case present, notFound, inaccessible, invalid, unavailable +} + +public enum AgentClientVersionUnknown: String, Sendable { + case artifactNotFound, unrecognizedLayout, missingMetadata, unreadableMetadata + case malformedMetadata, oversizedMetadata, nonRegularMetadata, missingVersion, unavailable +} + +/// Raw artifact metadata, independent of historical schema evidence and configuration admission. +public struct AgentClientVersion: Sendable { + public let rawVersion: String? + public let build: String? + public let metadataURL: URL? + public let metadataKey: String? + public let unknownReason: AgentClientVersionUnknown? + + fileprivate init(_ value: ClientVersionObservation) { + rawVersion = value.version + build = value.build + metadataURL = value.metadata + metadataKey = value.key + unknownReason = value.unknown.flatMap { AgentClientVersionUnknown(rawValue: $0.rawValue) } + } +} + +public struct AgentClientLookupIssue: Sendable { + public let path: String + public let status: AgentClientObservationStatus + public let reason: String +} + +public struct AgentClientPATHCoverage: Sendable { + public let pathWasSupplied: Bool + public let absoluteDirectories: [URL] + /// Empty and relative entries are excluded rather than resolved against an implicit directory. + public let excludedEntries: [String] +} + +public struct AgentClientCommand: Sendable { + public enum Role: String, Sendable { case agentCLI, editorLauncher } + public let name: String + public let role: Role + public let location: URL? + public let resolvedLocation: URL? + public let status: AgentClientObservationStatus + /// Earlier lookup errors mean a later selection is not guaranteed shell resolution. + public let lookupIssues: [AgentClientLookupIssue] + public let version: AgentClientVersion +} + +public struct AgentClientApplication: Sendable { + public let bundleIdentifier: String? + public let location: URL? + public let status: AgentClientObservationStatus + public let version: AgentClientVersion +} + +public struct AgentClientConfigurationLocation: Sendable { + public enum Purpose: String, Sendable { + case skillInstallation, skillScan, instructions, nativeConfiguration + } + public enum ObjectRole: String, Sendable { case file, container } + public let identity: String + public let scope: String + public let purpose: Purpose + public let objectRole: ObjectRole + public let location: URL? + public let status: AgentClientObservationStatus + public let diagnostic: String? +} + +public struct AgentClientSurface: Sendable { + public let identifier: String + public let displayName: String +} + +public struct AgentClientSchemaEvidence: Sendable { + public enum Status: String, Sendable { case recorded, unsupportedUnderEvidence, unverified } + public enum Placement: String, Sendable { case standalone, pluginMember } + public let surface: AgentClientSurface + public let kind: DeclaredComponentKind + public let scope: String + public let placement: Placement + public let status: Status + public let revision: String? + public let sources: [String] + public let limitation: String? +} + +public struct AgentClientRecord: Sendable { + public let agent: AgentID + public let commands: [AgentClientCommand] + public let applications: [AgentClientApplication] + public let configurationLocations: [AgentClientConfigurationLocation] + public let schemaEvidence: [AgentClientSchemaEvidence] +} + +/// An interval of passive observations, not an atomic snapshot or a configuration admission result. +public struct AgentClientInspection: Sendable { + public let startedAt: Date + public let finishedAt: Date + public let scope: InstallScope + public let projectDirectory: URL + public let homeDirectory: URL + public let pathCoverage: AgentClientPATHCoverage + public let clients: [AgentClientRecord] +} + +public enum AgentClientOperations { + /// Returns the documented component formats and scopes without probing the local system. + public static func schemaEvidence(for agent: AgentID) -> [AgentClientSchemaEvidence] { + ClientCapabilityInspection.entries(for: agent).map { + .init( + surface: .init(identifier: $0.surface.rawValue, displayName: $0.displayName), + kind: $0.kind, scope: $0.scope, placement: .init(rawValue: $0.placement)!, + status: .init(rawValue: $0.status)!, revision: $0.evidence?.revision, + sources: $0.evidence?.sources ?? [], limitation: $0.reason) + } + } + + /// Never invokes clients, reads configuration contents, recovers state or writes destinations. + /// Returned URLs are provenance; consumers should keep explicit re-detection independent of editing. + public static func inspect( + scope: InstallScope = .user, environment: RuntimeEnvironment + ) throws -> AgentClientInspection { + let started = Date() + let coverage = ClientPathCoverage(environment: environment) + let nativeLocations = NativeTargetRoute.clientLocations(scope: scope, environment: environment) + let clients = AgentID.allCases.map { agent in + let commands = AgentRegistry.clientCommands(for: agent).map { candidate in + let value = AgentClientObservation.command(candidate, coverage: coverage) + return AgentClientCommand( + name: value.command, role: .init(rawValue: value.role)!, + location: value.location, resolvedLocation: value.resolvedLocation, + status: status(value.state), + lookupIssues: value.issues.map { + .init(path: $0.path, status: status($0.state), reason: $0.reason) + }, version: .init(value.version)) + } + let application = AgentClientApplications.inspect(agent: agent) + var locations = AgentRegistry.clientSkillLocations( + for: agent, scope: scope, environment: environment + ) + .map { identity, url in + location( + identity, scope: scope.rawValue, + purpose: identity == "skills.install" ? .skillInstallation : .skillScan, + container: true, result: .success(url)) + } + locations += InstructionLocations.clientFiles( + for: agent, scope: scope, environment: environment + ).map { + location( + $0.0, scope: scope.rawValue, purpose: .instructions, + container: $0.0 == "instructions.rules", + result: .success($0.1)) + } + locations += nativeLocations.filter { $0.agents.contains(agent) }.map { + location( + $0.identity, scope: $0.evidenceScope, purpose: .nativeConfiguration, + container: $0.container, result: $0.location) + } + return AgentClientRecord( + agent: agent, commands: commands, + applications: [ + .init( + bundleIdentifier: application.bundleIdentifier, + location: application.location, status: status(application.state), + version: .init(application.version)) + ], + configurationLocations: locations, + schemaEvidence: schemaEvidence(for: agent)) + } + return .init( + startedAt: started, finishedAt: Date(), scope: scope, + projectDirectory: environment.projectDirectory, homeDirectory: environment.homeDirectory, + pathCoverage: .init( + pathWasSupplied: coverage.supplied, absoluteDirectories: coverage.directories, + excludedEntries: coverage.excluded), clients: clients) + } + + private static func status(_ value: ClientObservationState) -> AgentClientObservationStatus { + .init(rawValue: value.rawValue)! + } + + private static func location( + _ identity: String, scope: String, purpose: AgentClientConfigurationLocation.Purpose, + container: Bool, result: Result + ) -> AgentClientConfigurationLocation { + switch result { + case .success(let url): + .init( + identity: identity, scope: scope, purpose: purpose, + objectRole: container ? .container : .file, location: url, + status: status(AgentClientObservation.presence(url, directory: container)), diagnostic: nil) + case .failure(let error): + .init( + identity: identity, scope: scope, purpose: purpose, + objectRole: container ? .container : .file, location: nil, status: .invalid, + diagnostic: String(describing: error)) + } + } +} diff --git a/Sources/AgentsUpdates/Bundles/AuthorLockedMembers.swift b/Sources/AgentsUpdates/Bundles/AuthorLockedMembers.swift new file mode 100644 index 0000000..c2f9204 --- /dev/null +++ b/Sources/AgentsUpdates/Bundles/AuthorLockedMembers.swift @@ -0,0 +1,93 @@ +import AgentsCore +import AgentsManifest +import Components +import Foundation + +extension AuthorCapture { + mutating func addLocked( + _ selection: [MarketplaceMemberKey], store: StateStore, policy: AuthorPackagePolicy + ) throws { + guard let bytes = try store.configurationInputBytes(StateStore.resolvedFileName) else { + throw CoreError.notFound("agents.resolved for selected package dependencies") + } + let ledger = try ResolvedLedgerCodec.decode(bytes, limits: .standard) + let roots = store.ledgerRoots(recordedIn: ledger) + let bundleRecords = ledger.components.keys.filter { record in + let component = ledger.components[record]! + return !component.chatGPT && component.payload.object?["prompt"] == nil + } + let available = Dictionary(grouping: bundleRecords) { record in + let component = ledger.components[record]! + return MarketplaceMemberKey( + kind: DeclaredComponentKind(rawValue: component.kind) ?? .plugin, + name: component.name) + } + var requested = Set() + for member in selection { + try member.validate() + guard let matches = available[member], matches.count == 1, let record = matches.first, + requested.insert(record).inserted + else { + throw CoreError.invalidSource( + "expected one selected locked " + member.kind.rawValue + ": " + member.name) + } + } + let selected = requested + let ordered = ledger.occurrences.compactMap { occurrence in + requested.remove(occurrence.component) + } + guard requested.isEmpty else { + throw CoreError.invalidState("selected dependency has no locked occurrence") + } + let packageSources = try BundlePackageProvenance.locked( + for: selected, ledger: ledger, store: store, policy: policy.source.effective, + organization: policy.organization) + var resourceIDs = Set() + var evidence: [String: [BundleSourceEvidence]] = [:] + for record in ordered { + let component = ledger.components[record]! + let resources = component.resources.map { ledger.resources[$0]! } + for resource in resources { + guard resource.kind != .liveEdit else { + throw CoreError.invalidState("cannot pack live dependency: " + component.name) + } + try AuthorContentAudit.requirePublishable(resource.path) + for entry in resource.entries + resource.support { + try AuthorContentAudit.requirePublishable(entry.path) + } + } + resourceIDs.formUnion(component.resources) + let sources = try BundleOperations.portableSources( + for: record, captured: resources, ledger: ledger, roots: roots, store: store, + lockedOnly: true) + try policy.admit(sources, member: component.name) + let portable = try Set(sources + (packageSources[record] ?? [])).map { source in + if source.policyOrigin.kind == .local, source.policyOrigin.identity != nil { + return try BundleSourceEvidence( + origin: source.packageName == nil ? .missing : .local, revision: source.revision, + version: source.version, + packageName: source.packageName, root: source.root) + } + return source + } + let sorted = try BundleOperations.sortedSources(portable) + try policy.admit(sorted, member: component.name) + evidence[record] = sorted + } + let captured = try LedgerReplay.captureBundleResources( + resourceIDs, ledger: ledger, store: store, roots: roots, offline: true) + try absorb(captured.objects) + for record in ordered { + let component = ledger.components[record]! + let directory = try ledger.sources[component.declaringSource]?.location?.resolve(roots: roots) + let alreadyPortable = + directory.flatMap { BundleSourceLocation.container(of: $0, in: store) } != nil + let item = try BundleItem( + component: component, resources: component.resources.map { captured.resources[$0]! }, + sources: evidence[record]!, alreadyPortable: alreadyPortable) + let shared = try item.forSharing(registrySchemas: policy.registrySchemas) + noteOmissions(shared.omissions, name: component.name) + try append(shared.item) + } + } +} diff --git a/Sources/AgentsUpdates/Bundles/AuthorMCP.swift b/Sources/AgentsUpdates/Bundles/AuthorMCP.swift new file mode 100644 index 0000000..0f80651 --- /dev/null +++ b/Sources/AgentsUpdates/Bundles/AuthorMCP.swift @@ -0,0 +1,215 @@ +import AgentsCore +import Components +import Foundation + +enum AuthorMCP { + struct Sanitized { + let transport: MCPTransportDeclaration + let native: NativeConfiguration + let omissions: Int + } + + static func sanitize( + _ transport: MCPTransportDeclaration, native: NativeConfiguration, named member: String, + registry: MCPRegistryEvidence? = nil, registrySchemas: [MCPRegistryServer] = [] + ) throws -> Sanitized { + var omitted = 0 + func validateBindings(_ fields: [String: RuntimeBinding]) throws { + var portableNames: Set? + for name in fields.keys.sorted() { + let value = fields[name]! + guard !name.isEmpty, !name.utf8.contains(0) else { + throw CoreError.invalidSource("invalid MCP binding name") + } + switch value { + case .literal(let text): + if portableNames == nil, let registry { + if registrySchemas.isEmpty { + portableNames = try registry.portableLiteralBindings(in: transport) + } else { + try registry.validate(matching: transport) + portableNames = + MCPRegistryServer.attestsBindings( + in: transport, for: registry, schemas: registrySchemas) ? Set(fields.keys) : [] + } + } + guard portableNames?.contains(name) == true, !RegistryInput.isCredentialName(name), + !looksSecret(text), !personalPath(text) + else { + let label = looksSecret(name) ? "binding" : "binding " + name + throw CoreError.invalidSource( + "MCP \(member) \(label) has an unattested literal; use an environment or secret " + + "reference, or supply the exact registry schema for a public value") + } + case .environment(let key), .secret(let key): + guard !key.isEmpty, !key.utf8.contains(0), !looksSecret(key), !personalPath(key) else { + throw CoreError.invalidSource("invalid symbolic MCP binding key") + } + } + } + } + func clean(_ value: NativeValue) throws -> NativeValue? { + switch value { + case .string(let text): + if looksSecret(text) { + omitted += 1 + return nil + } + guard !personalPath(text) else { + throw CoreError.invalidSource("MCP native overrides cannot contain local paths") + } + return value + case .object(let object): + return try .object( + object.reduce(into: [:]) { result, pair in + if credentialKey(pair.key) || looksSecret(pair.key) { + omitted += 1 + } else { + result[pair.key] = try clean(pair.value) + } + }) + case .array(let items): return try .array(items.compactMap(clean)) + default: return value + } + } + let cleaned: MCPTransportDeclaration + switch transport { + case .stdio(var run): + guard !looksSecret(run.executable), + !run.executable.isEmpty, !run.executable.utf8.contains(0) + else { throw CoreError.invalidSource("nonportable MCP executable") } + if run.executable.contains("/") { + _ = try resourcePath(run.executable) + } else { + guard + run.executable.range(of: #"^[A-Za-z0-9][A-Za-z0-9._+-]*$"#, options: .regularExpression) + != nil + else { throw CoreError.invalidSource("nonportable MCP executable") } + } + if let workingDirectory = run.workingDirectory { + _ = try resourcePath(workingDirectory.path) + } + try validateBindings(run.environment) + var args: [String] = [] + var pending = run.arguments[...] + while let argument = pending.popFirst() { + if argument.hasPrefix("-"), + credentialKey(String(argument.prefix { $0 != "=" && !$0.isWhitespace })) + { + omitted += 1 + if !argument.contains("="), !argument.contains(where: \.isWhitespace), + pending.first.map({ !$0.hasPrefix("-") }) == true + { + _ = pending.popFirst() + omitted += 1 + } + } else if looksSecret(argument) { + omitted += 1 + } else { + guard !argument.utf8.contains(0), !personalPath(argument) else { + throw CoreError.invalidSource("MCP arguments cannot contain local absolute paths") + } + args.append(argument) + } + } + run.arguments = args + cleaned = .stdio(run) + case .streamableHTTP(let url, let headers): + try endpoint(url) + try validateBindings(headers) + cleaned = transport + case .sse(let url, let headers): + try endpoint(url) + try validateBindings(headers) + cleaned = transport + } + var nativeOutput: NativeConfiguration = [:] + for (client, fields) in native { + guard !looksSecret(client) else { + throw CoreError.invalidSource("invalid MCP native client name") + } + var unverified = fields + let bearerKey = "bearer_token_env_var" + let bearer = + client == AgentID.codex.rawValue ? unverified.removeValue(forKey: bearerKey) : nil + guard case .object(var result) = try clean(.object(unverified)) else { continue } + if let bearer { + guard case .string(let variable) = bearer, !looksSecret(variable) else { + throw CoreError.invalidSource( + "Codex bearer authentication needs an environment variable name") + } + try DeploymentConstruction.validateMCP( + cleaned, named: member, agent: .codex, scope: .project, + native: [client: [bearerKey: bearer]], requiresSymbolicBindings: false) + result[bearerKey] = bearer + } + if !result.isEmpty { nativeOutput[client] = result } + } + return Sanitized(transport: cleaned, native: nativeOutput, omissions: omitted) + } + + static func configuration( + name: String, transport: MCPTransportDeclaration, native: NativeConfiguration + ) throws -> LedgerValue { + let value = try LedgerPayload.component( + .mcpServer( + name: name, transport: transport, agents: nil, condition: nil, native: native, registry: nil + )) + return .init(object: [ + "transport": value.object!["transport"]!, "native": value.object!["native"]!, + ]) + } + + static func resourcePath(_ path: String) throws -> String { + let relative = path.hasPrefix("./") ? String(path.dropFirst(2)) : path + try BundleItem.validatePath(relative) + try AuthorContentAudit.requirePublishable(relative) + return relative + } + + private static func endpoint(_ url: String) throws { + _ = try SourceOrigin.http(url) + guard !looksSecret(url), let components = URLComponents(string: url), + !(components.queryItems ?? []).contains(where: { + credentialKey($0.name) || $0.value.map(looksSecret) == true + }) + else { throw CoreError.invalidSource("MCP endpoint cannot contain credential literals") } + } + + private static func credentialKey(_ key: String) -> Bool { + let normalized = key.lowercased().filter { $0.isLetter || $0.isNumber } + return ["env", "environment", "headers", "authorization", "auth", "cookie"].contains(normalized) + || normalized.hasSuffix("headers") + || ["token", "secret", "password", "credential", "key"].contains(where: normalized.contains) + } + + private static func personalPath(_ value: String) -> Bool { + value.range( + of: #"(?i)(?:^|[\s=])(?:/|~(?:/|[[:alnum:]]+/)|[a-z]:[/\\]|file:)"#, + options: .regularExpression) != nil + } + + private static func looksSecret(_ text: String) -> Bool { + text.range( + of: + #"(?i)(?:\b(?:bearer|basic)\s+\S+|\b[a-z][a-z0-9+.-]*://[^/\s@]+@|(?:^|\s)(?:--)?[\w-]*(?:token|secret|password|credential|api[-_]?key)[\w-]*[=\s]+\S+|^[A-Z][A-Z0-9_]*=\S+|(?:gh[pousr]_|github_pat_|sk-(?:proj-)?|xox[baprs]-|AKIA|ASIA|AIza|glpat-|npm_|pypi-|hf_|(?:sk|rk)_(?:test|live)_|SG\.|dapi)[a-z0-9_-]{12,})"#, + options: .regularExpression) != nil + } +} + +extension BundleItem { + func forSharing(registrySchemas: [MCPRegistryServer]) throws -> (item: Self, omissions: Int) { + guard kind == .mcpServer else { return (self, 0) } + let result = try AuthorMCP.sanitize( + transport(), native: native(), named: name, registry: mcpRegistry, + registrySchemas: registrySchemas) + guard result.omissions != 0 else { return (self, 0) } + return try ( + .init( + kind: kind, name: name, sources: sources, entries: entries, discovery: discovery, + configuration: AuthorMCP.configuration( + name: name, transport: result.transport, native: result.native), + mcpRegistry: mcpRegistry), result.omissions + ) + } +} diff --git a/Sources/AgentsUpdates/Bundles/AuthorPackageAdmission.swift b/Sources/AgentsUpdates/Bundles/AuthorPackageAdmission.swift new file mode 100644 index 0000000..4a864c3 --- /dev/null +++ b/Sources/AgentsUpdates/Bundles/AuthorPackageAdmission.swift @@ -0,0 +1,264 @@ +import AgentsCore +import AgentsInstructions +import AgentsManifest +import Foundation + +struct AuthorPackagePolicy { + let source: SourcePolicySnapshot + let organization: OrganizationPolicySnapshot + let registrySchemas: [MCPRegistryServer] + + init( + _ environment: RuntimeEnvironment, scope: InstallScope = .project, + registrySchemas: [MCPRegistryServer] = [] + ) throws { + let store = StateStore(scope: scope, environment: environment) + source = try SourcePolicySnapshot(store: store) + organization = try OrganizationPolicySnapshot(store: store) + self.registrySchemas = registrySchemas + try organization.admit() + } + + @discardableResult + func admit(_ package: BundlePackage) throws -> [OrganizationPolicyFinding] { + try package.validate() + let evaluator = organization.evaluator + var findings = evaluator.packageIdentity(.localBundle(package.name), requireAllow: false) + for dependency in package.dependencies ?? [] { + if let catalog = dependency.catalog { + let origin = try catalog.policyOrigin(environment: RuntimeEnvironment(environment: [:])) + try source.effective.require(origin, reference: dependency.package) + findings += evaluator.packageIdentity( + .init(origin, suffix: dependency.package, root: catalog.policyPath), + catalog: .init(origin, root: catalog.policyPath)) + } else { + findings += evaluator.packageIdentity(.localBundle(dependency.package), requireAllow: false) + } + } + try organization.admit(findings) + return findings + } + + func admitCatalog(_ url: URL, package: BundlePackage) throws { + try AuthorPackageOperations.requireLocalFileURL(url) + let origin = SourceOrigin.local(at: url) + try source.effective.require(origin, reference: package.name) + let evaluator = organization.evaluator + let identity = OrganizationPolicyIdentity(origin, suffix: package.name) + var findings = evaluator.packageIdentity( + identity, catalog: .init(origin), requireAllow: false) + for requirement in package.dependencies ?? [] where requirement.catalog == nil { + findings += evaluator.packageIdentity( + .init(origin, suffix: requirement.package), catalog: .init(origin)) + } + try organization.admit(findings) + } + + @discardableResult + func admit( + _ evidence: [BundleSourceEvidence], member: String + ) throws -> [OrganizationPolicyFinding] { + let evaluator = organization.evaluator + var results: [OrganizationPolicyFinding] = [] + for source in evidence { + let origin = source.policyOrigin + try self.source.effective.require(origin, reference: member) + results += evaluator.source(origin, root: source.root, path: [member]) + if source.packageName != nil { + results += evaluator.recordedBundlePackage(source, path: [member]) + } else if origin.kind != .inline { + results += evaluator.packageIdentity( + .init(origin, root: source.root), path: [member], requireAllow: false) + } + } + try organization.admit(results) + return results + } + + func admit(_ archive: BundleArchive) throws -> [OrganizationPolicyFinding] { + var findings = try admit(archive.manifest.package) + for item in archive.manifest.components { + try Task.checkCancellation() + try AuthorContentAudit.validatePaths(item.entries) + try AuthorContentAudit.validateReferences(item, objects: archive.contentObjects) + let sources = try item.installationSources() + findings += try admit(sources, member: item.name) + if item.kind == .mcpServer { + let transport = try item.transport() + guard try item.forSharing(registrySchemas: registrySchemas).omissions == 0 else { + throw CoreError.invalidSource("archive includes MCP credential literals: " + item.name) + } + for origin in item.mcpRegistry?.origins ?? [] { + try source.effective.require(origin, reference: item.name) + findings += organization.evaluator.source(origin, path: [item.name]) + } + let inline = sources.contains { $0.policyOrigin == .inline } + let identity = + item.mcpRegistry?.organizationPolicyIdentity + ?? .init(inline ? .inline : sources[0].policyOrigin, suffix: item.name) + findings += organization.evaluator.mcp( + identity, transport: transport.organizationPolicyName, selfDefined: inline, + transitive: !inline, path: [item.name], + legacyRegistry: item.mcpRegistry.map { $0.invocationDigest == nil } ?? false) + } + if item.entries.contains(where: \.executable) { + for origin in Set(sources.map(\.policyOrigin)).sorted(by: { + $0.description < $1.description + }) { + findings += organization.evaluator.executable(.init(origin), name: item.name) + } + } + } + try organization.admit(findings) + return organization.report(findings).findings + } + + func validate() throws { + try source.validate() + try organization.validate() + } +} + +struct AuthorContentAudit { + private(set) var findings: [ContentAuditFinding] = [] + + static func requirePublishable(_ path: String) throws { + for component in path.split(separator: "/") { + let name = component.lowercased() + if name == ".env" || name.hasPrefix(".env.") || name.hasSuffix(".pem") + || name.hasSuffix(".key") || ["id_rsa", "id_ed25519", ".netrc", ".npmrc"].contains(name) + { + throw CoreError.invalidSource("credential file refused: " + path) + } + if [".git", ".svn", ".hg", ".aws", ".ssh", ".gnupg", ".codex", ".claude"].contains(name) { + throw CoreError.invalidSource("private state path refused: " + path) + } + } + } + + static func validatePaths(_ entries: [LedgerEntry]) throws { + var names: Set = [] + for entry in entries { + try Task.checkCancellation() + try requirePublishable(entry.path) + let path = entry.path.folding( + options: .caseInsensitive, locale: Locale(identifier: "en_US_POSIX") + ).precomposedStringWithCanonicalMapping + guard names.insert(path).inserted else { + throw CoreError.invalidSource("colliding portable output paths") + } + } + } + + static func references(in text: String, at path: String, confinedTo root: String) throws + -> [String] + { + let depth = root.split(separator: "/").count + let directory = path.split(separator: "/").dropLast().map(String.init) + return try Instructions.localLinks(in: text).map { link in + guard let target = link.path, !target.isEmpty, !target.hasPrefix("/"), + !link.destination.lowercased().hasPrefix("file:"), + !target.contains("\\"), !target.utf8.contains(0) + else { throw CoreError.unsafePath("nonportable reference in " + path) } + var parts = directory + var descended = false + for part in target.split(separator: "/") { + if part == ".." { + guard !descended, parts.count > depth else { + throw CoreError.unsafePath("reference escapes packaged content: " + path) + } + parts.removeLast() + } else if part != "." { + descended = true + parts.append(String(part)) + } + } + return parts.joined(separator: "/") + } + } + + static func validateReferences(_ item: BundleItem, objects: [String: Data]) throws { + guard let discovery = item.discovery else { return } + let tree = Dictionary(uniqueKeysWithValues: item.entries.map { ($0.path, $0) }) + let candidates: [String] + switch item.kind { + case .skills: candidates = [discovery + "/SKILL.md"] + case .instructions: + candidates = ["instructions", ".agents/instructions"].map { + discovery + "/" + $0 + "/" + item.name + ".md" + } + case .mcpServer: return + } + for path in candidates { + guard let digest = tree[path]?.object, let bytes = objects[digest] else { continue } + let text: String + if item.kind == .instructions { + text = try Instructions.validateSource(bytes, id: item.name, allowRestrictions: true) + .content + } else { + guard let content = String(data: bytes, encoding: .utf8) else { + throw CoreError.invalidSource("invalid UTF-8 in packaged skill: " + item.name) + } + text = content + } + for reference in try references(in: text, at: path, confinedTo: discovery) { + guard tree[reference]?.path.utf8.elementsEqual(reference.utf8) == true else { + throw CoreError.invalidSource("missing packaged resource referenced in " + path) + } + } + } + } + + mutating func scan(_ bytes: Data, path: String) throws { + if let text = String(data: bytes, encoding: .utf8), !text.utf8.contains(0) { + try scan(text, path: path, allowLeadingBOM: true) + } + } + + mutating func scan(_ text: String, path: String, allowLeadingBOM: Bool = false) throws { + let matches = try ContentAuditUnicode.scan(text, leadingBOM: allowLeadingBOM) + for match in matches { + guard findings.count < ContentAuditUnicode.maximumFindings else { + throw CoreError.invalidSource("package integrity finding limit exceeded") + } + findings.append( + .init( + severity: match.severity, reason: match.reason, + location: .init( + path: path, field: nil, line: match.line, column: match.column, + promptLine: nil, promptColumn: nil), + ownership: .untracked, codePoint: match.codePoint)) + } + } + + mutating func scan(archive: BundleArchive) throws { + let package = archive.manifest.package + if let description = package.description { + try scan(description, path: "package.description") + } + if let author = package.author { try scan(author, path: "package.author") } + for member in archive.manifest.components { + let prefix = member.kind.rawValue + "/" + member.name + try scan(member.name, path: prefix) + for entry in member.entries { + try Task.checkCancellation() + if let digest = entry.object, let data = archive.contentObjects[digest] { + try scan(data, path: prefix + "/" + entry.path) + } + if let link = entry.link { try scan(link, path: prefix + "/" + entry.path) } + } + if let configuration = member.configuration { + try scan(configuration, path: prefix + "/configuration") + } + } + } + + private mutating func scan(_ value: LedgerValue, path: String) throws { + if let text = value.text { try scan(text, path: path) } + for child in value.array ?? [] { try scan(child, path: path) } + for key in (value.object ?? [:]).keys.sorted() { + try scan(key, path: path) + try scan(value.object![key]!, path: path) + } + } +} diff --git a/Sources/AgentsUpdates/Bundles/AuthorPackageCapture.swift b/Sources/AgentsUpdates/Bundles/AuthorPackageCapture.swift new file mode 100644 index 0000000..94dcbe1 --- /dev/null +++ b/Sources/AgentsUpdates/Bundles/AuthorPackageCapture.swift @@ -0,0 +1,204 @@ +import AgentsCore +import AgentsInstructions +import AgentsManifest +import AgentsSkills +import Components +import Foundation + +struct AuthorCapture { + let root: DirectoryHandle + private(set) var items: [BundleItem] = [] + private(set) var objects: [String: Data] = [:] + private(set) var warnings: [AuthorPackageWarning] = [] + private var members = Set() + private var limits = LedgerLimits.standard + + init(root: DirectoryHandle) { self.root = root } + + mutating func addFirstParty( + _ specification: AuthorPackageSpecification, store: StateStore, policy: AuthorPackagePolicy + ) throws { + if !specification.instructions.isEmpty || !specification.skills.isEmpty { + try policy.source.effective.require(.local(at: store.environment.projectDirectory)) + try policy.source.effective.require(.local) + } + for name in specification.instructions { + try addInstruction(name) + } + for path in specification.skills { + let resource = try capture(path, as: "skill") + guard resource.entries.first?.kind == .directory, + let manifest = resource.entries.first(where: { $0.path == "SKILL.md" }), + let digest = manifest.object, let bytes = objects[digest] + else { throw CoreError.invalidSource("expected complete skill directory: " + path) } + let name = try SkillSnapshotReader.manifestName(bytes, path: path + "/SKILL.md") + var tree = BundleTree() + let discovery = try tree.add(resource, under: "payload") + try add(.skills, name: name, tree: tree, discovery: discovery) + } + if !specification.mcpServers.isEmpty { + try policy.source.effective.require(.inline) + let declaration = try store.readDeclaration() + for name in specification.mcpServers { + let matches = declaration.components.filter { + if case .mcpServer(let declared, _, _, _, _, _) = $0 { return declared == name } + return false + } + guard matches.count == 1, let component = matches.first, + case .mcpServer(_, let transport, _, let condition, let native, let registry) = component, + condition == nil, registry == nil + else { + throw CoreError.invalidSource("expected one unconditional authored MCP: " + name) + } + try addMCP(name: name, transport: transport, native: native, policy: policy) + } + } + } + + private mutating func addInstruction(_ name: String) throws { + guard Declaration.isInstructionName(name) else { + throw CoreError.invalidSource("invalid authored instruction name: " + name) + } + let path = "instructions/" + name + ".md" + let resource = try capture(".agent/" + path, as: path, fileOnly: true) + guard let entry = resource.entries.first, entry.kind == .file, + let digest = entry.object, let bytes = objects[digest] + else { throw CoreError.invalidSource("expected authored instruction file: " + name) } + let section = try Instructions.validateSource(bytes, id: name, allowRestrictions: true) + var tree = BundleTree() + _ = try tree.add(resource, under: "payload") + for relative in try AuthorContentAudit.references( + in: section.content, at: path, confinedTo: "instructions" + ) { + let output = "payload/" + relative + if tree.entries[output]?.kind == .file { continue } + let reference = try capture(".agent/" + relative, as: relative, fileOnly: true) + _ = try tree.add(reference, under: "payload") + } + try add(.instructions, name: name, tree: tree, discovery: "payload") + } + + private mutating func addMCP( + name: String, transport: MCPTransportDeclaration, + native: NativeConfiguration, policy: AuthorPackagePolicy + ) throws { + let sanitized = try AuthorMCP.sanitize(transport, native: native, named: name) + var transport = sanitized.transport + var tree = BundleTree() + if case .stdio(var run) = transport { + guard run.executableSource == nil, run.workingDirectory?.source == nil else { + throw CoreError.invalidSource("authored MCP cannot read an unlocked source: " + name) + } + if run.executable.contains("/") { + let path = try AuthorMCP.resourcePath(run.executable) + let program = try capture(path, as: path, fileOnly: true) + guard program.entries[0].executable else { + throw CoreError.invalidSource("authored MCP resource is not executable: " + name) + } + run.executable = try tree.add(program, under: "payload") + } + if var working = run.workingDirectory { + let path = try AuthorMCP.resourcePath(working.path) + let directory = try capture(path, as: path) + guard directory.entries[0].kind == .directory else { + throw CoreError.invalidSource("authored MCP working directory is not a directory") + } + working.path = try tree.add(directory, under: "payload") + run.workingDirectory = working + } + transport = .stdio(run) + } + noteOmissions(sanitized.omissions, name: name) + let configuration = try AuthorMCP.configuration( + name: name, transport: transport, native: sanitized.native) + if let url = configuration.object?["transport"]?.object?["url"]?.text { + try policy.source.effective.require(.http(url), reference: name) + } + try add( + .mcpServer, name: name, tree: tree, discovery: nil, configuration: configuration, + origin: .inline) + } + + private mutating func add( + _ kind: BundleItem.Kind, name: String, tree: BundleTree, discovery: String?, + configuration: LedgerValue? = nil, origin: SourceOrigin = .local + ) throws { + let entries = tree.sortedEntries + let revision = try ResolvedLedgerCodec.digest( + [ResolvedLedgerCodec.digest(entries), ResolvedLedgerCodec.digest(configuration)]) + try append( + .init( + kind: kind, name: name, sources: [.init(origin: origin, revision: revision)], + entries: entries, discovery: discovery, configuration: configuration, mcpRegistry: nil)) + } + + mutating func append(_ item: BundleItem) throws { + let key = MarketplaceMemberKey( + kind: DeclaredComponentKind(rawValue: item.kind.rawValue)!, name: item.name) + guard members.insert(key).inserted else { + throw CoreError.invalidSource("duplicate authored package member: " + item.name) + } + try item.validate() + items.append(item) + } + + mutating func absorb(_ captured: [String: Data]) throws { + for (digest, bytes) in captured where objects[digest] == nil { + guard bytes.count <= limits.objectBytes else { + throw CoreError.invalidSource("package exceeds content object budget") + } + objects[digest] = bytes + limits.objectBytes -= bytes.count + } + } + + mutating func noteOmissions(_ count: Int, name: String) { + if count > 0 { + warnings.append( + .init( + member: .init(kind: .mcpServer, name: name), reason: .credentialOmitted, count: count)) + } + } + + private mutating func capture( + _ source: String, as path: String, fileOnly: Bool = false + ) throws -> LedgerResource { + try BundleItem.validatePath(source) + try AuthorContentAudit.requirePublishable(source) + let components = source.split(separator: "/").map(String.init) + guard components.first != ".agent" || source.hasPrefix(".agent/instructions/") else { + throw CoreError.unsafePath("private project state is not an authored resource") + } + var parent = root + for name in components.dropLast() { + guard let child = try parent.directory(name) else { throw CoreError.notFound(source) } + parent = child + } + let leaf = components.last! + if fileOnly, try ContentAuditFiles.kind(leaf, in: parent) != .regular { + throw CoreError.invalidSource("expected an authored regular file: " + source) + } + if path == "skill" { + guard let skill = try parent.directory(leaf), + try ContentAuditFiles.kind("SKILL.md", in: skill) == .regular + else { throw CoreError.invalidSource("expected complete skill directory: " + source) } + } + var remaining = limits + remaining.objectBytes = remaining.resourceBytes + if fileOnly { remaining.entries = min(remaining.entries, 1) } + let captured = try parent.capturePortableTree(leaf, limits: remaining) { relative in + if !relative.isEmpty { + try BundleItem.validatePath(relative) + try AuthorContentAudit.requirePublishable(source + "/" + relative) + } + } + if fileOnly, captured.entries.first?.kind != .file { + throw CoreError.invalidSource("expected an authored regular file: " + source) + } + try absorb(captured.objects) + limits.entries -= captured.entries.count + limits.resourceBytes -= captured.entries.reduce(0) { $0 + ($1.byteCount ?? 0) } + return .init( + kind: .embedded, source: "", path: path, hash: "", entries: captured.entries) + } +} diff --git a/Sources/AgentsUpdates/Bundles/AuthorPackageOperations.swift b/Sources/AgentsUpdates/Bundles/AuthorPackageOperations.swift new file mode 100644 index 0000000..413e008 --- /dev/null +++ b/Sources/AgentsUpdates/Bundles/AuthorPackageOperations.swift @@ -0,0 +1,285 @@ +import AgentsCore +import AgentsManifest +import Foundation + +/// Explicit author inputs. This file is independent of installation intent and recipients. +public struct AuthorPackageSpecification: Codable, Equatable, Sendable { + public let package: BundlePackage + public let instructions: [String] + public let skills: [String] + public let mcpServers: [String] + public let lockedMembers: [MarketplaceMemberKey] + + public init( + package: BundlePackage, instructions: [String] = [], skills: [String] = [], + mcpServers: [String] = [], lockedMembers: [MarketplaceMemberKey] = [] + ) { + self.package = package + self.instructions = instructions + self.skills = skills + self.mcpServers = mcpServers + self.lockedMembers = lockedMembers + } +} + +public struct AuthorPackagePath: Encodable, Equatable, Sendable { + public let member: MarketplaceMemberKey + public let entry: LedgerEntry +} + +/// An immutable archive and the inventory a caller can present before writing or publishing it. +public struct AuthorPackageArtifact: Sendable { + public let archive: Data + public let inspection: BundleInspection + public var digest: String { inspection.archiveDigest } + public let includedPaths: [AuthorPackagePath] + public let contentFindings: [ContentAuditFinding] + public let policyFindings: [OrganizationPolicyFinding] + public let warnings: [AuthorPackageWarning] + let registrySchemas: [MCPRegistryServer] +} + +public struct AuthorPackageWarning: Encodable, Equatable, Sendable { + public enum Reason: String, Encodable, Sendable { case credentialOmitted } + + public let member: MarketplaceMemberKey + public let reason: Reason + public let count: Int +} + +public enum AuthorPackageOperations { + public static let specificationFilename = "author-package.json" + + /// Creates a complete new author directory under an existing parent. Never edits a project + /// in place or creates installation state. An identical scaffold is a no-op. + @discardableResult + public static func scaffold( + _ package: BundlePackage, at destination: URL, + environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> AuthorPackageSpecification { + let policy = try AuthorPackagePolicy(environment) + try policy.admit(package) + let specification = AuthorPackageSpecification( + package: package, skills: ["skills/getting-started"]) + var tree = AuthorOutputTree() + try tree.add(specificationFilename, bytes: ResolvedLedgerCodec.bytes(specification)) + try tree.add(".agent/agents.yaml", bytes: Data("version: 1\n".utf8)) + try tree.add( + "skills/getting-started/SKILL.md", + bytes: Data( + """ + --- + name: getting-started + description: Describe when to use this skill. + --- + + # Getting started + + Describe the workflow here. + + """.utf8)) + try policy.validate() + try tree.write(to: destination, beforeCommit: policy.validate) + return specification + } + + /// Reads the explicit author specification and captures its selected closure without writes. + public static func preview( + environment: RuntimeEnvironment = RuntimeEnvironment(), + registrySchemas: [MCPRegistryServer] = [] + ) throws -> AuthorPackageArtifact { + let root = try projectRoot(environment) + let bytes = try root.readRegularFile( + specificationFilename, maximumBytes: LedgerLimits.standard.encodedBytes) + try LedgerAdmission.check(bytes, limits: .standard) + let specification = try JSONDecoder().decode(AuthorPackageSpecification.self, from: bytes) + return try capture( + specification, root: root, environment: environment, registrySchemas: registrySchemas) + } + + /// Captures explicitly supplied selections instead of reading a specification file. + public static func preview( + _ specification: AuthorPackageSpecification, + environment: RuntimeEnvironment = RuntimeEnvironment(), + registrySchemas: [MCPRegistryServer] = [] + ) throws -> AuthorPackageArtifact { + let root = try projectRoot(environment) + return try capture( + specification, root: root, environment: environment, registrySchemas: registrySchemas) + } + + /// A later process must supply the digest from its review when rebuilding for publication. + public static func rebuild( + expectedDigest: String, environment: RuntimeEnvironment = RuntimeEnvironment(), + registrySchemas: [MCPRegistryServer] = [] + ) throws -> AuthorPackageArtifact { + try checking( + preview(environment: environment, registrySchemas: registrySchemas), + expectedDigest: expectedDigest) + } + + public static func rebuild( + _ specification: AuthorPackageSpecification, expectedDigest: String, + environment: RuntimeEnvironment = RuntimeEnvironment(), + registrySchemas: [MCPRegistryServer] = [] + ) throws -> AuthorPackageArtifact { + try checking( + preview(specification, environment: environment, registrySchemas: registrySchemas), + expectedDigest: expectedDigest) + } + + /// Opens an explicitly chosen archive once. Publication retains these bytes even if the file + /// is subsequently edited or deleted. Supply an expected digest for a separate earlier review. + public static func readArchive( + at source: URL, expectedDigest: String? = nil, + environment: RuntimeEnvironment = RuntimeEnvironment(), + registrySchemas: [MCPRegistryServer] = [] + ) throws -> AuthorPackageArtifact { + let (parent, name) = try outputLocation(source) + let bytes = try parent.readRegularFile(name, maximumBytes: LedgerLimits.standard.encodedBytes) + let policy = try AuthorPackagePolicy(environment, registrySchemas: registrySchemas) + let artifact = try report(bytes, warnings: [], policy: policy) + if let expectedDigest { return try checking(artifact, expectedDigest: expectedDigest) } + return artifact + } + + /// Writes the exact captured archive to a new file beneath an existing parent. + public static func write( + _ artifact: AuthorPackageArtifact, to destination: URL, + environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws { + let policy = try outputPolicy(artifact, environment: environment) + let (parent, name) = try outputLocation(destination) + if try parent.publishRegularFile( + named: name, bytes: artifact.archive, beforeCommit: policy.validate) + { + return + } + guard + let existing = try? parent.readRegularFile(name, maximumBytes: artifact.archive.count), + existing == artifact.archive + else { throw CoreError.invalidState("artifact publication conflict: " + name) } + } + + /// Publishes the captured archive and its authored summary to an existing local team catalog. + @discardableResult + public static func publish( + _ artifact: AuthorPackageArtifact, to catalog: URL, + environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> MarketplaceRelease { + try MarketplaceOperations.publishAdmitted( + artifact.archive, inspection: artifact.inspection, to: catalog, + summary: artifact.inspection.package.description, scope: .project, environment: environment, + registrySchemas: artifact.registrySchemas) + } + + private static func checking( + _ artifact: AuthorPackageArtifact, expectedDigest: String + ) throws -> AuthorPackageArtifact { + guard artifact.digest == expectedDigest else { + throw CoreError.invalidState("package digest differs from the reviewed archive") + } + return artifact + } + + static func outputLocation(_ url: URL) throws -> (DirectoryHandle, String) { + try requireLocalFileURL(url) + let name = url.lastPathComponent + guard !name.isEmpty, name != ".", name != "..", !name.contains("/"), + !name.utf8.contains(0) + else { throw CoreError.unsafePath("expected a local artifact path") } + return (try .readDirectory(at: url.deletingLastPathComponent()), name) + } + + private static func projectRoot(_ environment: RuntimeEnvironment) throws -> DirectoryHandle { + let url = environment.projectDirectory + try requireLocalFileURL(url) + return try .readDirectory(at: url) + } + + static func requireLocalFileURL(_ url: URL) throws { + guard url.isFileURL, url.host.map({ $0.isEmpty || $0 == "localhost" }) ?? true, + url.path.hasPrefix("/"), !url.path.utf8.contains(0) + else { throw CoreError.unsafePath("expected a local file URL") } + } + + static func outputPolicy( + _ artifact: AuthorPackageArtifact, environment: RuntimeEnvironment + ) throws -> AuthorPackagePolicy { + let policy = try AuthorPackagePolicy(environment, registrySchemas: artifact.registrySchemas) + _ = try policy.admit(artifact.inspection.archive) + try policy.validate() + return policy + } + + private static func capture( + _ specification: AuthorPackageSpecification, root: DirectoryHandle, + environment: RuntimeEnvironment, registrySchemas: [MCPRegistryServer] + ) throws -> AuthorPackageArtifact { + let policy = try AuthorPackagePolicy(environment, registrySchemas: registrySchemas) + try policy.admit(specification.package) + let store = StateStore(scope: .project, environment: environment) + return try store.withReadLock { + var capture = AuthorCapture(root: root) + try capture.addFirstParty(specification, store: store, policy: policy) + if !specification.lockedMembers.isEmpty { + try capture.addLocked(specification.lockedMembers, store: store, policy: policy) + } + let archive = try BundleArchive( + package: specification.package, components: capture.items, objects: capture.objects) + return try report( + ResolvedLedgerCodec.bytes(archive), warnings: capture.warnings, policy: policy) + } + } + + private static func report( + _ bytes: Data, warnings: [AuthorPackageWarning], policy: AuthorPackagePolicy + ) throws -> AuthorPackageArtifact { + let inspection = try BundleOperations.inspect(bytes) + let findings = try policy.admit(inspection.archive) + var audit = AuthorContentAudit() + try audit.scan(archive: inspection.archive) + try policy.validate() + return .init( + archive: bytes, inspection: inspection, + includedPaths: inspection.components.flatMap { member in + member.entries.filter { $0.path != "." }.map { + AuthorPackagePath(member: member.marketplaceKey, entry: $0) + } + }, contentFindings: audit.findings, policyFindings: findings, warnings: warnings, + registrySchemas: policy.registrySchemas) + } +} + +struct AuthorOutputTree: Sendable { + var tree = BundleTree() + var objects: [String: Data] = [:] + + mutating func add(_ path: String, bytes: Data) throws { + let digest = BundleArchive.digest(bytes) + try tree.insert( + .init(path: path, kind: .file, object: digest, executable: false, byteCount: bytes.count)) + objects[digest] = bytes + } + + func validatedEntries() throws -> [LedgerEntry] { + let entries = tree.sortedEntries + try AuthorContentAudit.validatePaths(entries) + _ = try LedgerResources.validatedEntries( + .init(kind: .embedded, source: "", path: ".", hash: "", entries: entries)) + return entries + } + + func write(to destination: URL, beforeCommit: () throws -> Void) throws { + let entries = try validatedEntries() + let (parent, name) = try AuthorPackageOperations.outputLocation(destination) + if try parent.publishPortableTree( + named: name, entries: entries, objects: objects, beforeCommit: beforeCommit) + { + return + } + guard let existing = try? parent.capturePortableTree(name, admitting: { _ in }), + existing.entries == entries, existing.objects == objects + else { throw CoreError.invalidState("artifact publication conflict: " + name) } + } +} diff --git a/Sources/AgentsUpdates/Bundles/BundleArchive.swift b/Sources/AgentsUpdates/Bundles/BundleArchive.swift new file mode 100644 index 0000000..bfe5439 --- /dev/null +++ b/Sources/AgentsUpdates/Bundles/BundleArchive.swift @@ -0,0 +1,339 @@ +import AgentsCore +import Components +import Foundation + +/// Marketplace coordinates, independent of the archive format version. +public struct BundlePackage: Codable, Equatable, Sendable { + public let name: String + public let version: String + public let description: String? + public let author: String? + /// Requirements resolved by a catalog consumer. Omission preserves the canonical leaf format. + public let dependencies: [MarketplacePackageRequirement]? + + public init( + name: String, version: String, dependencies: [MarketplacePackageRequirement] = [] + ) { + self.init(name: name, version: version, dependencies: dependencies, description: nil) + } + + public init( + name: String, version: String, dependencies: [MarketplacePackageRequirement] = [], + description: String?, author: String? = nil + ) { + self.name = name + self.version = version + self.dependencies = dependencies.isEmpty ? nil : dependencies + self.description = description + self.author = author + } + + func validate() throws { + for value in [description, author].compactMap({ $0 }) { + guard !value.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, + value.utf8.count <= 1024, !value.utf8.contains(0) + else { throw CoreError.invalidSource("invalid bundle package metadata") } + } + if let dependencies { + guard !dependencies.isEmpty else { + throw CoreError.invalidSource("omit empty bundle package requirements") + } + _ = try MarketplaceCoordinate(package: name, version: version) + try MarketplacePackageRequirement.validate(dependencies) + } + let allowed = CharacterSet( + charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-_+") + for coordinate in [name, version] { + guard !coordinate.isEmpty, coordinate.utf8.count <= 128, + coordinate.utf8.first.map({ + (48...57).contains($0) || (65...90).contains($0) || (97...122).contains($0) + }) == true, + coordinate.unicodeScalars.allSatisfy(allowed.contains) + else { throw CoreError.invalidSource("invalid bundle package name or version") } + } + } +} + +public typealias BundleSourceEvidence = PortableSourceEvidence + +public struct BundleComponent: Sendable { + /// Content and provenance identity, scoped to this inspection. + public let id: String + public let kind: DeclaredComponentKind + public let name: String + public let sources: [BundleSourceEvidence] + /// Portable paths, file digests, link spellings and executable flags in this member. + public let entries: [LedgerEntry] + /// Present for MCP. Environment and secret references retain their symbolic keys. + public let configuration: NativeValue? + public let mcpRegistry: MCPRegistryEvidence? + let transport: MCPTransportDeclaration? + let native: NativeConfiguration +} + +extension BundleComponent { + public var marketplaceKey: MarketplaceMemberKey { .init(kind: kind, name: name) } + + public func supportedTargets(in scope: InstallScope) -> [AgentID] { + AgentID.allCases.filter { agent in + switch kind { + case .skills: return agent.supportsSkills + case .instructions: return agent.supportsInstructions(in: scope) + case .mcpServer: + guard let transport else { return false } + return + (try? DeploymentConstruction.validateMCP( + transport, named: name, agent: agent, scope: scope, native: native, + requiresSymbolicBindings: mcpRegistry != nil)) != nil + default: return false + } + } + } +} + +public struct BundleInspection: Sendable { + public let package: BundlePackage + public let formatVersion: Int + /// SHA-256 of the exact canonical archive bytes, including its content objects. + public let archiveDigest: String + public let components: [BundleComponent] + let archive: BundleArchive +} + +struct BundleArchive: Codable, Sendable { + static let currentFormat = "agents.bundle" + static let currentVersion = 1 + + struct Manifest: Codable, Sendable { + let package: BundlePackage + let components: [BundleItem] + } + + let format: String + let version: Int + let manifest: Manifest + let manifestDigest: String + let contentObjects: [String: Data] + + init(package: BundlePackage, components: [BundleItem], objects: [String: Data]) throws { + format = Self.currentFormat + version = Self.currentVersion + manifest = Manifest(package: package, components: components) + manifestDigest = try ResolvedLedgerCodec.digest(manifest) + contentObjects = objects + try validate() + } + + static func read(_ input: Data) throws -> Self { + let bytes = input.startIndex == 0 ? input : Data(input) + try LedgerAdmission.check(bytes, limits: .standard) + let archive = try JSONDecoder().decode(Self.self, from: bytes) + try archive.validate() + guard try ResolvedLedgerCodec.bytes(archive) == bytes else { + throw CoreError.invalidSource("bundle JSON must use the canonical version 1 encoding") + } + return archive + } + + func validate() throws { + guard format == Self.currentFormat, version == Self.currentVersion, + manifestDigest == (try ResolvedLedgerCodec.digest(manifest)), !manifest.components.isEmpty + else { throw CoreError.invalidSource("invalid bundle format, version or manifest digest") } + try manifest.package.validate() + let limits = LedgerLimits.standard + var remainingObjects = limits.objectBytes + for (digest, bytes) in contentObjects { + guard bytes.count <= remainingObjects, digest == Self.digest(bytes) else { + throw CoreError.invalidSource("invalid bundle content digest or byte budget") + } + remainingObjects -= bytes.count + } + var remainingEntries = limits.entries + var remainingBytes = limits.resourceBytes + var referenced = Set() + var items = Set() + for item in manifest.components { + try Task.checkCancellation() + guard items.insert(try item.id).inserted, item.entries.count <= remainingEntries else { + throw CoreError.invalidSource("duplicate bundle component or entry budget") + } + remainingEntries -= item.entries.count + try item.validate() + for entry in item.entries where entry.kind == .file { + guard let digest = entry.object, let bytes = contentObjects[digest], + let count = entry.byteCount, bytes.count == count, count <= remainingBytes + else { throw CoreError.invalidSource("bundle file is missing or exceeds the byte budget") } + remainingBytes -= count + referenced.insert(digest) + } + } + guard referenced == Set(contentObjects.keys) else { + throw CoreError.invalidSource("bundle contains unreferenced content") + } + } + + static func digest(_ bytes: Data) -> String { + "sha256:" + FileHash.sha256Hex(data: bytes) + } +} + +struct BundleItem: Codable, Sendable { + enum Kind: String, Codable, Sendable { + case instructions, skills, mcpServer + } + + let kind: Kind + let name: String + let sources: [BundleSourceEvidence] + let entries: [LedgerEntry] + /// Discovery root relative to the generated producer for instructions and skills. + let discovery: String? + let configuration: LedgerValue? + let mcpRegistry: MCPRegistryEvidence? + + var id: String { get throws { try ResolvedLedgerCodec.digest(self) } } + var resource: LedgerResource { + .init(kind: .embedded, source: "", path: ".", hash: "", entries: entries) + } + + /// Endpoints are inputs even in archives whose producer list predates endpoint evidence. + func installationSources() throws -> [BundleSourceEvidence] { + guard let url = configuration?.object?["transport"]?.object?["url"]?.text else { + return sources + } + let origin = try SourceOrigin.http(url) + guard !sources.contains(where: { $0.policyOrigin == origin }) else { return sources } + return try sources + [.init(origin: origin, revision: ResolvedLedgerCodec.digest(origin))] + } + + func validate() throws { + guard !name.isEmpty, name.utf8.count <= 1024, !name.utf8.contains(0), !sources.isEmpty, + Set(sources).count == sources.count + else { throw CoreError.invalidSource("invalid bundle component metadata") } + for source in sources { try source.validate() } + var paths = Set() + for entry in entries { + if entry.path != "." { + try Self.validatePath(entry.path) + guard entry.path == "payload" || entry.path.utf8.starts(with: "payload/".utf8) else { + throw CoreError.unsafePath("bundle members must stay in the payload tree") + } + } + let folded = entry.path.folding( + options: .caseInsensitive, locale: Locale(identifier: "en_US_POSIX") + ) + .precomposedStringWithCanonicalMapping + guard paths.insert(folded).inserted else { + throw CoreError.invalidSource("colliding bundle paths") + } + switch entry.kind { + case .directory: + guard !entry.executable, entry.object == nil, entry.byteCount == nil, entry.link == nil + else { throw CoreError.invalidSource("invalid bundle directory") } + case .file: + guard entry.object != nil, entry.byteCount != nil, entry.link == nil + else { throw CoreError.invalidSource("invalid bundle file") } + case .symlink: + guard !entry.executable, entry.object == nil, entry.byteCount == nil, let link = entry.link + else { throw CoreError.invalidSource("invalid bundle symlink") } + try Self.validatePath(link, link: true) + } + } + let tree = try LedgerResources.validatedEntries(resource) + guard tree["."]?.kind == .directory else { + throw CoreError.invalidSource("missing bundle tree root") + } + if let payload = tree["payload"] { + guard payload.kind == .directory else { + throw CoreError.invalidSource("invalid bundle payload root") + } + var contents = resource + contents.entries = entries.filter { $0.path != "." }.map { entry in + var member = entry + member.path = entry.path == "payload" ? "." : String(entry.path.dropFirst("payload/".count)) + return member + } + _ = try LedgerResources.validatedEntries(contents) + } + if kind == .mcpServer { + guard discovery == nil, let configuration else { + throw CoreError.invalidSource("invalid bundle MCP component") + } + try configuration.validate() + let transport = try transport() + try mcpRegistry?.validate(matching: transport) + _ = try native() + if case .stdio(let run) = transport { + guard run.executableSource == nil, run.workingDirectory?.source == nil else { + throw CoreError.invalidSource("bundle MCP resources must be self-contained") + } + if run.executable.contains("/") { + try Self.validatePath(run.executable) + guard let entry = tree[run.executable], + (entry.kind == .file && entry.executable) || entry.kind == .symlink + else { throw CoreError.invalidSource("missing executable in bundle MCP component") } + } + if let workingDirectory = run.workingDirectory { + try Self.validatePath(workingDirectory.path) + guard let entry = tree[workingDirectory.path], entry.kind != .file else { + throw CoreError.invalidSource("missing working directory in bundle MCP component") + } + } + } + } else { + guard configuration == nil, mcpRegistry == nil, let discovery else { + throw CoreError.invalidSource("invalid bundle discovery metadata") + } + try Self.validatePath(discovery) + guard tree[discovery]?.kind == .directory else { + throw CoreError.invalidSource("missing bundle discovery root") + } + switch kind { + case .instructions: + guard Declaration.isInstructionName(name), + ["instructions", ".agents/instructions"].contains(where: { + tree[discovery + "/" + $0 + "/" + name + ".md"]?.kind == .file + }) + else { throw CoreError.invalidSource("missing bundle instruction file") } + case .skills: + guard tree[discovery + "/SKILL.md"]?.kind == .file else { + throw CoreError.invalidSource("missing bundle skill manifest") + } + case .mcpServer: break + } + } + } + + func transport() throws -> MCPTransportDeclaration { + guard let configuration, let object = configuration.object, + Set(object.keys) == ["transport", "native"], let native = object["native"]?.object, + native.values.allSatisfy({ $0.kind == .object }) + else { throw CoreError.invalidSource("invalid bundle MCP fields") } + return try MCPConnectionOperations.managedTransport(configuration) + } + + func native() throws -> NativeConfiguration { + func convert(_ value: LedgerValue) throws -> NativeValue { + switch value.kind { + case .environment, .secret, .literal: + throw CoreError.invalidSource("unexpected binding in bundle native configuration") + case .array: return try .array(value.array!.map(convert)) + case .object: return try .object(value.object!.mapValues(convert)) + default: return UpdateOperations.symbolicValue(value) + } + } + return try (configuration?.object?["native"]?.object ?? [:]).mapValues { + try $0.object!.mapValues(convert) + } + } + + static func validatePath(_ path: String, link: Bool = false) throws { + let parts = path.utf8.split(separator: 47, omittingEmptySubsequences: false) + guard path.utf8.count <= 3072, parts.count <= 64, + parts.count == path.split(separator: "/", omittingEmptySubsequences: false).count, + !path.utf8.contains(0), !path.utf8.contains(92), !path.utf8.contains(58), + parts.allSatisfy({ !$0.isEmpty && $0.count <= 255 }), + link || !parts.contains(where: { $0.elementsEqual([46]) || $0.elementsEqual([46, 46]) }) + else { throw CoreError.unsafePath("nonportable bundle member path") } + } +} diff --git a/Sources/AgentsUpdates/Bundles/BundleExport.swift b/Sources/AgentsUpdates/Bundles/BundleExport.swift new file mode 100644 index 0000000..61697ef --- /dev/null +++ b/Sources/AgentsUpdates/Bundles/BundleExport.swift @@ -0,0 +1,347 @@ +import AgentsCore +import AgentsInstructions +import AgentsManifest +import Components +import Foundation + +public enum BundleOperations { + /// Exports selections from one committed inspection. Locked inputs are read without rendering, + /// executing programs or calling a binding provider. + public static func export( + _ package: BundlePackage, selections: [ComponentSelection], scope: InstallScope, + environment: RuntimeEnvironment, registrySchemas: [MCPRegistryServer] = [] + ) throws -> Data { + try package.validate() + let store = StateStore(scope: scope, environment: environment) + return try store.withReadLock { + let baseline = try StatePrecondition(store: store) + let policy = try SourcePolicySnapshot(store: store) + let organization = try OrganizationPolicySnapshot(store: store) + try organization.admit() + let document = try store.declarationDocument(prepared: baseline) + let ledger = try store.readLedger(prepared: baseline) + let roots = store.ledgerRoots(recordedIn: ledger) + if organization.evaluator.active { + let evaluation = try OrganizationInstallEvaluation( + policy: organization, store: store, + declaration: store.readDeclaration(prepared: baseline), + bytes: try baseline.bytes(for: store.declarationURL)) + let known = try (evaluation.beforeAcquisition() + evaluation.closure(ledger, roots: roots)) + .filter { $0.rule == "package-deny" || $0.rule == "dependency-policy-override" } + try organization.admit( + known + + organization.evaluator.packageIdentity( + .localBundle(package.name), requireAllow: false)) + } + let generation = try ResolvedLedgerCodec.digest([ + ResolvedLedgerCodec.digest(ledger), document?.digest ?? "absent", + ]) + guard !selections.isEmpty, selections.allSatisfy({ $0.generation == generation }) else { + throw CoreError.invalidState("select bundle components from the current scope inspection") + } + let inspections = try UpdateOperations.componentInspections( + ledger, roots: roots, generation: generation) + let byIdentity = Dictionary(grouping: inspections, by: { $0.selection.identity }) + var selected = Set() + for selection in selections { + let matches = (byIdentity[selection.identity] ?? []).filter { component in + selection.occurrence.map { occurrence in + component.occurrences.contains { $0.selection.occurrence == occurrence } + } ?? true + } + guard matches.count == 1, let component = matches.first, + BundleItem.Kind(rawValue: component.kind.rawValue) != nil + else { throw CoreError.invalidState("ambiguous or unsupported bundle component selection") } + selected.insert(component.record) + } + // The lock's occurrence order is the instruction render order. + var ordered: [String] = [] + for occurrence in ledger.occurrences where selected.remove(occurrence.component) != nil { + ordered.append(occurrence.component) + } + guard selected.isEmpty else { + throw CoreError.invalidState("selected bundle member has no occurrence") + } + let packageSources = try BundlePackageProvenance.locked( + for: Set(ordered), ledger: ledger, store: store, policy: policy.effective, + organization: organization) + let resources = Set(ordered.flatMap { ledger.components[$0]!.resources }) + let captured = try LedgerReplay.captureBundleResources( + resources, ledger: ledger, store: store, roots: roots, sourcePolicy: policy.effective) + var items: [BundleItem] = [] + var itemIDs = Set() + for id in ordered { + let component = ledger.components[id]! + let resources = component.resources.map { captured.resources[$0]! } + let declaringSource = try ledger.sources[component.declaringSource]?.location?.resolve( + roots: roots) + let alreadyPortable = + declaringSource.flatMap { BundleSourceLocation.container(of: $0, in: store) } != nil + let producers = try portableSources( + for: id, captured: resources, ledger: ledger, roots: roots, store: store) + let item = try BundleItem( + component: component, resources: resources, + sources: sortedSources(producers + (packageSources[id] ?? [])), + alreadyPortable: alreadyPortable) + try AuthorContentAudit.validatePaths(item.entries) + let shared = try item.forSharing(registrySchemas: registrySchemas) + guard shared.omissions == 0 else { + throw CoreError.invalidSource( + "MCP \(item.name) has credential-like arguments or overrides; use symbolic bindings before export" + ) + } + if itemIDs.insert(try shared.item.id).inserted { items.append(shared.item) } + } + let archive = try BundleArchive( + package: package, components: items, objects: captured.objects) + let bytes = try ResolvedLedgerCodec.bytes(archive) + try LedgerAdmission.check(bytes, limits: .standard) + try baseline.validate() + try policy.validate() + try organization.validate() + return bytes + } + } + + /// Validates the complete archive in memory and returns its importable inventory. + public static func inspect(_ archive: Data) throws -> BundleInspection { + let wire = try BundleArchive.read(archive) + return try BundleInspection( + package: wire.manifest.package, formatVersion: wire.version, + archiveDigest: BundleArchive.digest(archive), + components: wire.manifest.components.map { item in + BundleComponent( + id: try item.id, kind: DeclaredComponentKind(rawValue: item.kind.rawValue)!, + name: item.name, sources: item.sources, entries: item.entries, + configuration: item.configuration.map(UpdateOperations.symbolicValue), + mcpRegistry: item.mcpRegistry, + transport: item.kind == .mcpServer ? try item.transport() : nil, + native: try item.native()) + }, + archive: wire) + } + + static func portableSources( + for id: String, captured: [LedgerResource], ledger: ResolvedLedger, roots: [String: URL], + store: StateStore, lockedOnly: Bool = false + ) throws -> [BundleSourceEvidence] { + let component = ledger.components[id]! + let resourceRecords = component.resources.map { ledger.resources[$0]! } + let resourceSources = Set(resourceRecords.map(\.source)) + var pending = resourceSources.union([component.source, component.declaringSource]) + for occurrence in ledger.occurrences where occurrence.component == id { + pending.formUnion(occurrence.dependencies) + } + var visited = Set() + var result = Set() + if let registry = component.mcpRegistry { + let revision = try ResolvedLedgerCodec.digest(registry) + for origin in registry.origins { + result.insert(try .init(origin: origin, revision: revision, version: registry.version)) + } + } + for resource in resourceRecords { + if let artifact = resource.artifact { + for origin in EffectiveSourcePolicy.artifactOrigins(artifact) { + result.insert(try .init(origin: origin, revision: artifact.digest)) + } + } + } + let manifestRoot = LedgerLocation( + kind: .registered, root: store.scope == .project ? "project" : "state", path: ".") + let declared = Set(ledger.sourceUses.map(\.source)) + while let id = pending.popFirst() { + guard visited.insert(id).inserted else { continue } + let source = ledger.sources[id]! + if let container = source.container { + pending.insert(container) + continue + } + if let location = source.location, + let container = BundleSourceLocation.container( + of: try location.resolve(roots: roots), in: store) + { + // Keep the original producer claims when forwarding a previously imported member. + if lockedOnly, source.bundleSources == nil { + throw CoreError.invalidState("missing locked bundle producer evidence: " + component.name) + } + let producers = try source.bundleSources ?? BundleStoredSource.read(container).sources + result.formUnion(producers) + continue + } + let identity: String? + switch source.kind { + case .local: + if component.mcpRegistry != nil, source.revision == "live", source.location == manifestRoot, + !declared.contains(id), !resourceSources.contains(id) + { + continue + } + identity = nil + case .git, .wellKnown: identity = try ledger.sourceIdentity(id, roots: roots) + } + let revision: String + if source.revision == "live" { + var content = [component.kind, component.name] + if !lockedOnly, component.kind != BundleItem.Kind.mcpServer.rawValue { + content.append(try ResolvedLedgerCodec.digest(component.payload)) + } + revision = try ResolvedLedgerCodec.digest(content + captured.map(\.hash)) + } else { + revision = source.revision + } + let origin: SourceOrigin? + switch source.kind { + case .git: origin = try source.transport.map(SourceOrigin.git) + case .wellKnown: + origin = try source.transport.map(SourceOrigin.http) + case .local: + if component.kind == BundleItem.Kind.mcpServer.rawValue, source.location == manifestRoot, + !declared.contains(id), !resourceSources.contains(id) + { + origin = .inline + } else { + if lockedOnly, let location = source.location { + origin = .local(at: try location.resolve(roots: roots)) + } else { + origin = .missing + } + } + } + let version = + id == component.source && component.mcpRegistry == nil + ? component.version ?? source.version : source.version + let root = + lockedOnly && id == component.source && component.root != "." ? component.root : nil + if source.kind == .wellKnown, + identity.flatMap({ URLComponents(string: $0)?.query }) != nil, + let origin + { + result.insert(try .init(origin: origin, revision: revision, version: version, root: root)) + } else { + result.insert( + .init( + kind: source.kind, identity: identity, revision: revision, version: version, + origin: origin, root: root)) + } + } + if let url = component.payload.object?["transport"]?.object?["url"]?.text { + let origin = (try? SourceOrigin.http(url)) ?? .missing + if !result.contains(where: { $0.policyOrigin == origin }) { + result.insert(try .init(origin: origin, revision: ResolvedLedgerCodec.digest(origin))) + } + } + return try sortedSources(result) + } + + static func sortedSources(_ sources: S) throws -> [BundleSourceEvidence] + where S.Element == BundleSourceEvidence { + try Set(sources).map { (try ResolvedLedgerCodec.bytes($0), $0) } + .sorted { $0.0.lexicographicallyPrecedes($1.0) }.map { $0.1 } + } +} + +extension BundleItem { + init( + component: LedgerComponent, resources: [LedgerResource], sources: [BundleSourceEvidence], + alreadyPortable: Bool + ) throws { + let kind = Kind(rawValue: component.kind)! + let name = component.name + var tree = BundleTree() + var discovery: String? + var configuration: LedgerValue? + let root = alreadyPortable ? "." : "payload" + switch kind { + case .instructions: + guard !component.chatGPT, component.payload.object?["prompt"] == nil, + let first = resources.first + else { throw CoreError.invalidSource("select an installed instruction section") } + let section = try tree.add(first, under: root) + for resource in resources.dropFirst() { _ = try tree.add(resource, under: root) } + discovery = InstructionSnapshotReader.searchRoots(of: section, name: name).first(where: { + $0 == "payload" || $0.hasPrefix("payload/") + }) + case .skills: + guard resources.count == 1, let skill = resources.first else { + throw CoreError.invalidSource("bundle skill must have one complete tree") + } + discovery = try tree.add(skill, under: root) + case .mcpServer: + let transport = try MCPConnectionOperations.managedTransport(component.payload) + guard var fields = component.payload.object?["transport"]?.object, + let native = component.payload.object?["native"] + else { throw CoreError.invalidSource("missing locked MCP configuration") } + var index = 0 + func addResource() throws -> String { + guard index < resources.count else { + throw CoreError.invalidSource("missing bundle MCP resource") + } + defer { index += 1 } + let prefix = alreadyPortable ? "." : "payload/resource-\(index)" + return try tree.add(resources[index], under: prefix) + } + if case .stdio(let run) = transport { + var invocation = fields["run"]!.object! + invocation.removeValue(forKey: "executableSource") + if run.executable.contains("/") { invocation["executable"] = try .init(addResource()) } + if run.workingDirectory != nil { + invocation["workingDirectory"] = try .init(object: ["path": .init(addResource())]) + } + fields["run"] = .init(object: invocation) + } + guard index == resources.count else { + throw CoreError.invalidSource("unexpected MCP resources in bundle") + } + configuration = .init(object: ["transport": .init(object: fields), "native": native]) + } + self.init( + kind: kind, name: name, sources: sources, + entries: tree.entries.values.sorted { $0.path.utf8.lexicographicallyPrecedes($1.path.utf8) }, + discovery: discovery, configuration: configuration, mcpRegistry: component.mcpRegistry) + } +} + +struct BundleTree: Sendable { + var entries = [".": LedgerEntry(path: ".", kind: .directory, executable: false)] + + var sortedEntries: [LedgerEntry] { + entries.values.sorted { $0.path.utf8.lexicographicallyPrecedes($1.path.utf8) } + } + + mutating func insert(_ entry: LedgerEntry) throws { + if entry.path != "." { try BundleItem.validatePath(entry.path) } + let parts = entry.path.split(separator: "/") + for depth in 1.. String { + func joined(_ root: String, _ path: String) -> String { + if root == "." { return path } + return path == "." ? root : root + "/" + path + } + let selected = joined(prefix, resource.path) + let base = resource.support.isEmpty ? selected : prefix + for original in try LedgerResources.validatedEntries(resource).values { + var entry = original + entry.path = joined(base, original.path) + try insert(entry) + } + return selected + } +} diff --git a/Sources/AgentsUpdates/Bundles/BundleImport.swift b/Sources/AgentsUpdates/Bundles/BundleImport.swift new file mode 100644 index 0000000..73053d5 --- /dev/null +++ b/Sources/AgentsUpdates/Bundles/BundleImport.swift @@ -0,0 +1,190 @@ +import AgentsCore +import Foundation + +public struct BundleImportSelection: Equatable, Sendable { + public let componentID: String + public let targets: [AgentID] + + public init(componentID: String, targets: [AgentID]) { + self.componentID = componentID + self.targets = targets + } +} + +public struct BundleImportPreview: Sendable { + public let package: BundlePackage + public let archiveDigest: String + public let selections: [BundleImportSelection] + public let report: CombinedUpdateReport + /// An ownership conflict detected by the update transaction's normal target admission. + public let ownershipConflict: String? + fileprivate let marketplace: (package: VerifiedMarketplacePackage, name: String)? + fileprivate let bundle: BundleInspection + fileprivate let environment: RuntimeEnvironment + fileprivate let replace: Bool + fileprivate let organization: OrganizationPolicySnapshot + fileprivate let routes: Set + fileprivate let installations: [String: SkillInstallationTarget] +} + +extension BundleOperations { + /// Plans only the requested entries and recipients. A conflicting native composition may + /// throw before a report can be produced. Replace opts into the ordinary instruction policy. + public static func previewImport( + _ bundle: BundleInspection, selections: [BundleImportSelection], scope: InstallScope, + environment: RuntimeEnvironment, replace: Bool = false + ) throws -> BundleImportPreview { + try makeImportPreview( + bundle, selections: selections, scope: scope, environment: environment, + replace: replace, marketplace: nil) + } + + static func makeImportPreview( + _ bundle: BundleInspection, selections: [BundleImportSelection], scope: InstallScope, + environment: RuntimeEnvironment, replace: Bool, + marketplace: (package: VerifiedMarketplacePackage, name: String)? + ) throws -> BundleImportPreview { + guard bundle.package.dependencies == nil else { + throw MarketplaceError.dependenciesRequireResolution(bundle.package.name) + } + let store = StateStore(scope: scope, environment: environment) + return try BundleInstallation.withStagedSources( + bundle, selections: selections, store: store, marketplace: marketplace?.package + ) { installation in + let request = try installation.importRequest(replace: replace, marketplace: marketplace) + let (report, conflict, routes, installations) = try UpdateOperations.previewWithOwnership( + request, scope: scope, environment: environment, + organizationPolicy: installation.organizationPolicy) + return BundleImportPreview( + package: bundle.package, archiveDigest: bundle.archiveDigest, selections: selections, + report: report, ownershipConflict: conflict, marketplace: marketplace, bundle: bundle, + environment: environment, + replace: replace, organization: installation.organizationPolicy, routes: routes, + installations: installations) + } + } + + public static func previewImportLifecycle( + _ bundle: BundleInspection, selections: [BundleImportSelection], + intent: LifecycleOperationIntent, scope: InstallScope, + environment: RuntimeEnvironment, replace: Bool = false + ) throws -> LifecyclePackageReview { + try reviewImportLifecycle(intent: intent, scope: scope, environment: environment) { + try previewImport( + bundle, selections: selections, scope: scope, environment: environment, replace: replace) + } + } + + static func reviewImportLifecycle( + intent: LifecycleOperationIntent, scope: InstallScope, environment: RuntimeEnvironment, + preview preparePreview: @escaping @Sendable () throws -> BundleImportPreview + ) throws -> LifecyclePackageReview { + let context = LifecycleContext(scope: scope, environment: environment) + let (discovery, root) = try context.capturePackageRoot() + let preview = try preparePreview() + let plan = try context.packagePlan( + intent: intent, discovery: discovery, snapshot: preview.organization, + findings: preview.report.organizationPolicy, ownershipConflict: preview.ownershipConflict + ) { snapshot in + let current = try preparePreview() + try snapshot.requireSameLifecyclePolicy(as: current.organization) + if let conflict = current.ownershipConflict { throw CoreError.invalidState(conflict) } + } + return LifecyclePackageReview( + report: preview, lifecycle: plan.inspection, ownershipConflict: preview.ownershipConflict, + plan: plan + ) { provider in + performImport(preview, bindingProvider: provider, existingRoot: root) { + try $0.apply(ifUnchangedFrom: preview.report.displayedFingerprint) + } + } + } + + /// Re-prepares the displayed selection under the writer lock. The closure must call + /// PreparedUpdate.apply to publish. A changed destination requires a fresh preview. + public static func withPreparedImport( + _ preview: BundleImportPreview, bindingProvider: (any RuntimeBindingProvider)? = nil, + _ body: (PreparedUpdate) throws -> Result + ) throws -> Result { + try prepareImport(preview, bindingProvider: bindingProvider, completion: nil, body) + } + + /// Reports publication, rollback and outstanding recovery after a prepared import finishes. + public static func performImport( + _ preview: BundleImportPreview, bindingProvider: (any RuntimeBindingProvider)? = nil, + _ body: (PreparedUpdate) throws -> Value + ) -> UpdateCompletion { + performImport(preview, bindingProvider: bindingProvider, existingRoot: nil, body) + } + + private static func performImport( + _ preview: BundleImportPreview, bindingProvider: (any RuntimeBindingProvider)?, + existingRoot: ExistingProjectRoot?, _ body: (PreparedUpdate) throws -> Value + ) -> UpdateCompletion { + var outcome = TransactionOutcome() + var delivered = false + let result = Result { + try prepareImport( + preview, bindingProvider: bindingProvider, completion: { outcome = $0 }, + existingRoot: existingRoot + ) { + update in + delivered = true + return try body(update) + } + } + let recovered: Bool + if !delivered, case .failure(let error) = result, + case CoreError.transactionRecovered = (error as? UpdateApplyError)?.underlyingError ?? error + { + recovered = true + } else { + recovered = false + } + return UpdateOperations.completion( + result, outcome: outcome, recovered: recovered, + store: StateStore(scope: preview.report.scope, environment: preview.environment)) + } + + private static func prepareImport( + _ preview: BundleImportPreview, bindingProvider: (any RuntimeBindingProvider)?, + completion: ((TransactionOutcome) -> Void)?, existingRoot: ExistingProjectRoot? = nil, + _ body: (PreparedUpdate) throws -> Value + ) throws -> Value { + if let conflict = preview.ownershipConflict { + throw CoreError.invalidState(conflict) + } + let store = StateStore(scope: preview.report.scope, environment: preview.environment) + return try BundleInstallation.withStagedSources( + preview.bundle, selections: preview.selections, store: store, + marketplace: preview.marketplace?.package + ) { installation in + let request = try installation.importRequest( + replace: preview.replace, marketplace: preview.marketplace) + return try UpdateOperations.prepare( + request, scope: store.scope, environment: store.environment, checkpoint: { _ in }, + provider: bindingProvider ?? RequiredBindingProvider(), completion: completion, + admittedRoutes: preview.routes, + admittedInstallations: preview.installations, + admittedOrganizationPolicy: installation.organizationPolicy, existingRoot: existingRoot + ) { update in + guard update.report.displayedFingerprint == preview.report.displayedFingerprint else { + throw CoreError.invalidState("bundle import destination changed; refresh the preview") + } + return try body(update) + } + } + } +} + +extension BundleInstallation { + fileprivate func importRequest( + replace: Bool, marketplace: (package: VerifiedMarketplacePackage, name: String)? + ) throws -> UpdateRequest { + var request = UpdateRequest(replace: replace) + request.bundleInstallation = self + guard let marketplace else { return request } + return try marketplace.package.bindingImport( + request, as: marketplace.name, sourceAliases: members.map(\.alias)) + } +} diff --git a/Sources/AgentsUpdates/Bundles/BundleInstallation.swift b/Sources/AgentsUpdates/Bundles/BundleInstallation.swift new file mode 100644 index 0000000..7e214f7 --- /dev/null +++ b/Sources/AgentsUpdates/Bundles/BundleInstallation.swift @@ -0,0 +1,400 @@ +import AgentsCore +import AgentsManifest +import Components +import Foundation + +struct BundleInstallation: Sendable { + struct Member: Sendable { + let key: String + let item: BundleItem + let targets: Set + let stagedContainer: URL + let container: URL + var marketplaceNode: MarketplaceNodeID? = nil + + var source: URL { container.appendingPathComponent(BundleSourceLocation.tree) } + var identity: String { "local:" + source.path } + var alias: String { + (marketplaceNode == nil ? "bundle-" : MarketplaceResolvedNode.sourceAliasPrefix) + key + } + } + + static let groupName = "bundle" + let members: [Member] + let archiveDigest: String? + let policyFindings: [OrganizationPolicyFinding] + let organizationPolicy: OrganizationPolicySnapshot + private let store: StateStore + + static func withStagedSources( + _ bundle: BundleInspection, selections: [BundleImportSelection], store: StateStore, + marketplace: VerifiedMarketplacePackage? = nil, _ body: (Self) throws -> T + ) throws -> T { + let legacy = try marketplace.map { item in + MarketplaceNodeID( + catalog: MarketplaceCatalogID(item.release.origin, origin: try item.release.policyOrigin()), + package: item.release.coordinate.package) + } + return try withStagedSources( + [.init(bundle: bundle, selections: selections, legacyCatalogPackage: legacy)], + store: store, archiveDigest: bundle.archiveDigest, body) + } + + struct Input { + let bundle: BundleInspection + let selections: [BundleImportSelection] + var node: MarketplaceResolvedNode? = nil + var legacyCatalogPackage: MarketplaceNodeID? = nil + } + + static func withStagedSources( + _ inputs: [Input], store: StateStore, archiveDigest: String? = nil, + organizationPolicy: OrganizationPolicySnapshot? = nil, + _ body: (Self) throws -> T + ) throws -> T { + let policy = try SourcePolicySnapshot(store: store) + let organization = try organizationPolicy ?? OrganizationPolicySnapshot(store: store) + let findings = try inputs.flatMap { try policyFindings($0, evaluator: organization.evaluator) } + try organization.admit(findings) + let workspace = FileManager.default.temporaryDirectory.appendingPathComponent( + "agents-bundle-" + UUID().uuidString) + if !inputs.isEmpty { try FileSystem.createDirectory(at: workspace) } + defer { try? FileManager.default.removeItem(at: workspace) } + let members = try inputs.flatMap { + try stage($0, workspace: workspace, store: store, policy: policy, organization: organization) + } + guard Set(members.map(\.identity)).count == members.count else { + throw CoreError.invalidSource("duplicate bundle producer") + } + try policy.validate() + return try body( + Self( + members: members, archiveDigest: archiveDigest, policyFindings: findings, + organizationPolicy: organization, store: store)) + } + + private static func policyFindings( + _ input: Input, evaluator: OrganizationPolicyEvaluator + ) throws -> [OrganizationPolicyFinding] { + guard evaluator.active else { return [] } + let bundle = input.bundle + let catalogPackage = input.node?.id ?? input.legacyCatalogPackage + let identity = + catalogPackage.map(OrganizationPolicyIdentity.init) ?? .localBundle(bundle.package.name) + let selected = Set(input.selections.map(\.componentID)) + var findings = + catalogPackage.map { evaluator.marketplace($0) } + ?? evaluator.packageIdentity(identity, requireAllow: false) + for item in bundle.archive.manifest.components { + let sources = try item.installationSources() + for source in sources { + findings += evaluator.source( + source.policyOrigin, root: source.root, path: [identity.description, item.name]) + if source.packageName != nil { + findings += evaluator.recordedBundlePackage(source, path: [identity.description]) + } else if catalogPackage == nil, source.policyOrigin != .inline { + findings += evaluator.packageIdentity( + .init(source.policyOrigin, root: source.root), path: [identity.description]) + } + } + if try selected.contains(item.id), item.entries.contains(where: \.executable) { + findings += evaluator.executable(identity, name: item.name) + } + } + return findings + } + + private static func stage( + _ input: Input, workspace: URL, store: StateStore, policy: SourcePolicySnapshot, + organization: OrganizationPolicySnapshot + ) throws -> [Member] { + let bundle = input.bundle + let catalog: [BundleSourceEvidence] = + try input.node.map { node in + try policy.effective.require(node.id.catalog.origin, reference: node.id.description) + if let hosted = node.hostedEvidence { + try HostedMarketplaceReader.requireRequests( + hosted.requests, index: HostedMarketplaceLocation(node.catalog.location), + coordinate: node.coordinate, policy: policy.effective, organization: organization) + } + return try BundlePackageProvenance.capture(node) + } ?? [] + let inventory = Dictionary(uniqueKeysWithValues: bundle.components.map { ($0.id, $0) }) + var requested: [String: Set] = [:] + for selection in input.selections { + guard let component = inventory[selection.componentID], + requested[selection.componentID] == nil, !selection.targets.isEmpty, + Set(selection.targets).count == selection.targets.count + else { throw CoreError.invalidSource("select each bundle member and its targets once") } + let supported = Set(component.supportedTargets(in: store.scope)) + for agent in selection.targets { + guard supported.contains(agent) else { + throw CoreError.unsupported( + "bundle member \(component.name) cannot target \(agent.rawValue)") + } + } + requested[selection.componentID] = Set(selection.targets) + } + guard !requested.isEmpty else { + throw CoreError.invalidSource("select at least one bundle member") + } + for item in bundle.archive.manifest.components where try requested[item.id] != nil { + try policy.effective.requireBundleSources(item.installationSources(), reference: item.name) + for origin in item.mcpRegistry?.origins ?? [] { + try policy.effective.require(origin, reference: item.name) + } + } + let stored = store.directory.appendingPathComponent(BundleSourceLocation.directory) + var members: [Member] = [] + for item in bundle.archive.manifest.components { + try Task.checkCancellation() + let id = try item.id + guard let targets = requested[id] else { continue } + let staging = workspace.appendingPathComponent(UUID().uuidString) + let tree = staging.appendingPathComponent(BundleSourceLocation.tree) + try LedgerResources.materialize( + item.resource, objects: bundle.archive.contentObjects, at: tree) + let declaration = try item.producerDeclaration(targets: targets) + let manifest = tree.appendingPathComponent(".agent/agents.yaml") + let bytes = try DeclarationEditPlan.bytes( + replacing: Declaration(), with: declaration, in: nil, identity: .init(manifest.path), + environment: RuntimeEnvironment(projectDirectory: tree, environment: [:])) + guard let bytes else { throw CoreError.invalidSource("empty bundled declaration") } + try FileSystem.createDirectory(at: manifest.deletingLastPathComponent()) + try FileSystem.write(Data(bytes), to: manifest) + var sources = try item.installationSources() + sources += catalog.filter { !sources.contains($0) } + let seal = try BundleStoredSource( + package: .init(name: bundle.package.name, version: bundle.package.version), + componentID: id, sources: sources, treeDigest: BundleStoredSource.digest(tree), + marketplaceNode: input.node?.id) + let marker = try ResolvedLedgerCodec.bytes(seal) + let key = String(BundleArchive.digest(marker).dropFirst(7)) + try FileSystem.write(marker, to: staging.appendingPathComponent(BundleStoredSource.filename)) + let staged = workspace.appendingPathComponent(key) + try FileManager.default.moveItem(at: staging, to: staged) + members.append( + Member( + key: key, item: item, targets: targets, stagedContainer: staged, + container: stored.appendingPathComponent(key), marketplaceNode: input.node?.id)) + } + return members + } + + /// The seal binds marketplace provenance to the tree even if the installed package is + /// subsequently exported or the stored producer is selected outside the dependency. + func recordingCatalog(_ catalog: [PortableSourceEvidence], observedOrigin: SourceOrigin) throws + -> Self + { + let policy = try SourcePolicySnapshot(store: store) + try policy.effective.require(observedOrigin) + let sealed = try members.map { member in + let original = try BundleStoredSource.read(member.stagedContainer) + try policy.effective.requireBundleSources(original.sources, reference: member.item.name) + let additions = catalog.filter { !original.sources.contains($0) } + guard !additions.isEmpty else { return member } + let marker = try ResolvedLedgerCodec.bytes(additions.reduce(original) { $0.recording($1) }) + let key = FileHash.sha256Hex(data: marker) + let parent = member.stagedContainer.deletingLastPathComponent() + let staged = parent.appendingPathComponent(key) + if FileManager.default.fileExists(atPath: staged.path) { + _ = try BundleStoredSource.read(staged) + } else { + let temporary = parent.appendingPathComponent(UUID().uuidString) + try FileSystem.createDirectory(at: temporary) + let tree = BundleSourceLocation.tree + try FileManager.default.copyItem( + at: member.stagedContainer.appendingPathComponent(tree), + to: temporary.appendingPathComponent(tree)) + try FileSystem.write( + marker, to: temporary.appendingPathComponent(BundleStoredSource.filename)) + try FileManager.default.moveItem(at: temporary, to: staged) + } + return Member( + key: key, item: member.item, targets: member.targets, stagedContainer: staged, + container: member.container.deletingLastPathComponent().appendingPathComponent(key)) + } + try policy.validate() + return Self( + members: sealed, archiveDigest: archiveDigest, policyFindings: policyFindings, + organizationPolicy: organizationPolicy, store: store) + } + + var stagedContainers: [String: URL] { + Dictionary( + uniqueKeysWithValues: members.map { + ($0.identity, $0.stagedContainer) + }) + } + + func adding(to declaration: Declaration, store: StateStore) throws -> Declaration { + var candidate = declaration + for member in members { + let relative = + BundleSourceLocation.directory + "/" + member.key + "/" + BundleSourceLocation.tree + let location = store.scope == .project ? ".agent/" + relative : "~/.agents/" + relative + if let existing = candidate.sources[member.alias] { + guard existing.kind == .local, existing.path == nil, existing.requirement == nil, + try existing.identity(environment: store.environment) == member.identity + else { throw CoreError.invalidState("bundle source alias conflicts: " + member.alias) } + } else { + candidate.sourceDeclarations.append( + .init(name: member.alias, source: .init(kind: .local, location: location))) + } + if let index = candidate.uses.firstIndex(where: { + $0.name == Self.groupName && $0.source == member.alias + }) { + var use = candidate.uses[index] + var condition = use.condition ?? DeclarationCondition() + if let existing = condition.agents { + condition.agents = Set(existing).union(member.targets).sorted { + $0.rawValue < $1.rawValue + } + use.condition = condition + candidate.uses[index] = use + } + } else { + candidate.uses.append( + .init( + name: Self.groupName, source: member.alias, + condition: .init(agents: member.targets.sorted { $0.rawValue < $1.rawValue }))) + } + } + return candidate + } + + func selectedIdentities(_ ledger: ResolvedLedger, roots: [String: URL]) throws -> Set { + let identities = Set(members.map(\.identity)) + var bySource: [String: Set] = [:] + var selected = Set() + for component in ledger.components.values { + let identity = try ledger.sourceIdentity(component.declaringSource, roots: roots) + guard identities.contains(identity) else { continue } + bySource[identity, default: []].formUnion(component.recipients) + selected.insert(try LedgerImpact.identity(component, ledger: ledger, roots: roots)) + } + for member in members where !member.targets.isSubset(of: bySource[member.identity] ?? []) { + throw CoreError.unsupported( + "producer conditions exclude a selected target for " + member.item.name) + } + return selected + } +} + +extension BundleItem { + fileprivate func producerDeclaration(targets: Set) throws -> Declaration { + // The sealed tree digest includes the producer manifest. Preserve the existing producer + // bytes for installs that use the original skill and MCP targets. + let agents = AgentID.allCases.filter { $0 != .antigravity || targets.contains(.antigravity) } + let component: ComponentDeclaration + var sources: [String: SourceDeclaration] = [:] + switch kind { + case .instructions: + sources["unit"] = .init(kind: .local, location: ".", path: discovery!) + component = .instructions( + InstructionsDeclaration(agents: AgentID.allCases, sections: ["unit:" + name])) + case .skills: + component = .skills( + source: ".", + SkillDeclaration( + select: .names([PathSafety.sanitizeName(name)]), path: discovery, + agents: agents.filter(\.supportsSkills), mode: .link)) + case .mcpServer: + component = try .mcpServer( + name: name, transport: transport(), agents: agents, + native: native(), registry: mcpRegistry) + } + return Declaration( + sources: sources, + groups: [.init(name: BundleInstallation.groupName, components: [component])], + exports: [BundleInstallation.groupName]) + } +} + +struct BundleSourceInputs { + let preconditions: [TargetPrecondition] + let publications: [Publication] + let producers: [String: Producer] + + struct Producer { + let snapshot: SourceSnapshotID + let contents: URL + let seal: BundleStoredSource + } + + struct Publication { + let contents: URL + let destination: TargetPrecondition + + func stage(in transaction: FileTransaction) throws { + try transaction.replace(destination.url, with: .copy(contents), expecting: destination) + } + } + + static func capture( + _ linked: LinkedComponents, session: SourceResolutionSession, store: StateStore, + staged: [String: URL] + ) throws -> Self { + var seen = Set() + var preconditions: [TargetPrecondition] = [] + var publications: [Publication] = [] + var producers: [String: Producer] = [:] + for item in linked.sourceSnapshots + linked.declaringSnapshots + where item.container == nil && item.snapshot.source.hasPrefix("local:") + && seen.insert(item.snapshot).inserted + { + let source = URL(fileURLWithPath: String(item.snapshot.source.dropFirst(6))) + guard let container = BundleSourceLocation.container(of: source, in: store) else { continue } + let destination = try destination(container, in: store) + let snapshot = try session.resource(snapshot: item.snapshot, path: ".") + let producer: BundleStoredSource + if let selected = staged[item.snapshot.source] { + let stagedInput = try TargetPrecondition(selected) + producer = try BundleStoredSource.read(selected, snapshot: snapshot) + try stagedInput.validate() + preconditions.append(stagedInput) + if destination.exists { + _ = try BundleStoredSource.read(container) + } else { + publications.append(.init(contents: selected, destination: destination)) + } + } else { + producer = try BundleStoredSource.read(container, snapshot: snapshot) + } + guard producer.sources == session.bundleSources[item.snapshot] else { + throw CoreError.invalidState("bundle source evidence changed during preparation") + } + if producer.marketplaceNode != nil { + let alias = MarketplaceResolvedNode.sourceAliasPrefix + container.lastPathComponent + producers[alias] = Producer( + snapshot: item.snapshot, + contents: staged[item.snapshot.source] ?? container, + seal: producer) + } + try destination.validate() + preconditions.append(destination) + } + return Self(preconditions: preconditions, publications: publications, producers: producers) + } + + static func destination(_ container: URL, in store: StateStore) throws -> TargetPrecondition { + let base = store.directory.deletingLastPathComponent() + let physicalBase = PathSafety.realPath(base.path) ?? base.path + let expectedParent = URL(fileURLWithPath: physicalBase, isDirectory: true) + .appendingPathComponent(store.directory.lastPathComponent) + .appendingPathComponent(BundleSourceLocation.directory) + let expectedContainer = expectedParent.appendingPathComponent(container.lastPathComponent) + let destination = try TargetPrecondition(container) + if destination.exists { + guard PathSafety.realPath(container.path) == expectedContainer.path, + PathSafety.realPath(container.appendingPathComponent(BundleSourceLocation.tree).path) + == expectedContainer.appendingPathComponent(BundleSourceLocation.tree).path + else { throw CoreError.unsafePath("bundle source storage is not a real scope-owned tree") } + } else if PathSafety.realPath(container.deletingLastPathComponent().path) + .map({ $0 != expectedParent.path }) == true + { + throw CoreError.unsafePath("bundle source storage escapes the scope") + } + return destination + } +} diff --git a/Sources/AgentsUpdates/Bundles/BundlePackageProvenance.swift b/Sources/AgentsUpdates/Bundles/BundlePackageProvenance.swift new file mode 100644 index 0000000..1f34b0c --- /dev/null +++ b/Sources/AgentsUpdates/Bundles/BundlePackageProvenance.swift @@ -0,0 +1,97 @@ +import AgentsCore +import Foundation + +enum BundlePackageProvenance { + static func locked( + for selected: Set, ledger: ResolvedLedger, store: StateStore, + policy: EffectiveSourcePolicy, organization: OrganizationPolicySnapshot + ) throws -> [String: [BundleSourceEvidence]] { + var result: [String: [BundleSourceEvidence]] = [:] + if let graph = ledger.marketplaceGraph { + let byNode = Dictionary(uniqueKeysWithValues: graph.nodes.map { ($0.id, $0) }) + var recorded: [MarketplaceNodeID: [BundleSourceEvidence]] = [:] + for node in graph.nodes where node.componentRecords.contains(where: selected.contains) { + var sources: [BundleSourceEvidence] = [] + for id in graph.reachable(from: node.id).sorted(by: MarketplaceNodeID.ordered) { + if let evidence = recorded[id] { + sources += evidence + continue + } + let dependency = byNode[id]! + let evaluator = organization.evaluator + try policy.require(id.catalog.origin, reference: id.package) + try organization.admit(evaluator.marketplace(id)) + if let override = dependency.organizationRequirements { + let active = evaluator.marketplaceRequirements(for: id) + guard active.overrides, active.constraints == override else { + throw CoreError.invalidState( + "locked dependency needs matching organization policy: " + id.package) + } + } + if dependency.catalog.kind == .hosted { + try MarketplaceGraphChange.validateHosted( + dependency, archive: ledger.contentObjects[dependency.archiveDigest], policy: policy, + organizationPolicy: organization) + } + let evidence = try capture(dependency) + recorded[id] = evidence + sources += evidence + } + for record in node.componentRecords where selected.contains(record) { + result[record, default: []] += sources + } + } + } + for pin in ledger.marketplacePackages ?? [] + where pin.componentRecords.contains(where: selected.contains) { + let origin = try pin.policyOrigin(environment: store.marketplaceEnvironment) + let name = pin.dependency.coordinate.package + let root = pin.dependency.catalog.policyPath + try policy.require(origin, reference: name) + try organization.admit( + organization.evaluator.packageIdentity( + .init(origin, suffix: name, root: root), catalog: .init(origin, root: root))) + let sources = try release( + pin.dependency.coordinate, origin: origin, root: root, digest: pin.archiveDigest, + catalogCommit: pin.catalogCommit) + for record in pin.componentRecords where selected.contains(record) { + result[record, default: []] += sources + } + } + return result + } + + static func capture(_ node: MarketplaceResolvedNode) throws -> [BundleSourceEvidence] { + var evidence = try release( + node.coordinate, origin: node.id.catalog.origin, root: node.id.catalog.policyPath, + digest: node.archiveDigest, catalogCommit: node.catalogCommit) + if let hosted = node.hostedEvidence { + let index = try HostedMarketplaceLocation(node.catalog.location) + for request in hosted.requests where request != index.url { + let route = try HostedMarketplaceLocation(request.absoluteString) + evidence.append( + try .init( + origin: route.origin, revision: node.archiveDigest, root: route.policyPath)) + } + } + return evidence + } + + static func release( + _ coordinate: MarketplaceCoordinate, origin: SourceOrigin, root: String?, digest: String, + catalogCommit: String? + ) throws -> [BundleSourceEvidence] { + let catalog = origin == .missing ? .local : origin + var sources: [BundleSourceEvidence] = [ + try .init( + origin: catalog, revision: digest, version: coordinate.version, + packageName: coordinate.package, root: root) + ] + if let catalogCommit { + sources.append( + try .init(origin: catalog, revision: catalogCommit, version: coordinate.version, root: root) + ) + } + return sources + } +} diff --git a/Sources/AgentsUpdates/Bundles/NativePluginOperations.swift b/Sources/AgentsUpdates/Bundles/NativePluginOperations.swift new file mode 100644 index 0000000..2ddf9bd --- /dev/null +++ b/Sources/AgentsUpdates/Bundles/NativePluginOperations.swift @@ -0,0 +1,328 @@ +import AgentsCore +import AgentsSkills +import Foundation + +public enum NativePluginTarget: String, CaseIterable, Codable, Sendable { + case claudeCode = "claude-code" + case codex + + fileprivate var pluginManifest: String { + switch self { + case .claudeCode: ".claude-plugin/plugin.json" + case .codex: ".codex-plugin/plugin.json" + } + } + + fileprivate var marketplaceManifest: String { + switch self { + case .claudeCode: ".claude-plugin/marketplace.json" + case .codex: ".agents/plugins/marketplace.json" + } + } +} + +public struct NativePluginMarketplace: Equatable, Sendable { + public let name: String + public let category: String? + + public init(name: String, category: String? = nil) { + self.name = name + self.category = category + } +} + +/// One checked, client-specific distribution. The digest seals paths, content, links and modes. +public struct NativePluginArtifact: Sendable { + public let target: NativePluginTarget + public let package: BundlePackage + public let digest: String + public let entries: [LedgerEntry] + public let contentFindings: [ContentAuditFinding] + public let policyFindings: [OrganizationPolicyFinding] + public let warnings: [AuthorPackageWarning] + fileprivate let output: AuthorOutputTree + fileprivate let source: AuthorPackageArtifact + + public func contents(at path: String) -> Data? { + output.tree.entries[path]?.object.flatMap { output.objects[$0] } + } +} + +public enum NativePluginOperations { + /// Prepares a standalone plugin, or a local one-plugin marketplace containing it. + /// No client settings, marketplace registrations or installations are changed. + public static func preview( + _ artifact: AuthorPackageArtifact, for target: NativePluginTarget, + marketplace: NativePluginMarketplace? = nil, + environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> NativePluginArtifact { + let policy = try AuthorPackagePolicy(environment, registrySchemas: artifact.registrySchemas) + let findings = try policy.admit(artifact.inspection.archive) + let package = artifact.inspection.package + guard validName(package.name), + (try? MarketplaceCoordinate(package: package.name, version: package.version)) != nil, + let description = package.description, let author = package.author + else { + throw CoreError.invalidSource( + "native plugins require a kebab-case name, SemVer, description and author") + } + guard package.dependencies == nil else { + throw CoreError.unsupported("native plugins cannot resolve Agents catalog requirements") + } + if let marketplace, !validName(marketplace.name) { + throw CoreError.invalidSource("invalid native marketplace name") + } + let prefix = marketplace == nil ? "" : "plugins/" + package.name + "/" + var builder = NativePluginBuilder( + target: target, prefix: prefix, archive: artifact.inspection.archive) + for item in artifact.inspection.archive.manifest.components { + try Task.checkCancellation() + switch item.kind { + case .skills: try builder.addSkill(item) + case .mcpServer: try builder.addMCP(item) + case .instructions: + throw CoreError.unsupported( + "native plugin cannot load an Agents instruction section: " + item.name) + } + } + try builder.finish(package: package, description: description, author: author) + if let marketplace { + try builder.addMarketplace( + marketplace, package: package, description: description, author: author) + } + let entries = try builder.output.validatedEntries() + let digest = try ResolvedLedgerCodec.digest(entries) + try policy.validate() + return .init( + target: target, package: package, digest: digest, entries: entries, + contentFindings: artifact.contentFindings + builder.audit.findings, policyFindings: findings, + warnings: artifact.warnings, output: builder.output, source: artifact) + } + + /// Publishes the complete checked tree under an existing parent, never replacing a destination. + /// Pass a reviewed digest when using a capture rebuilt in a different process. + public static func write( + _ artifact: NativePluginArtifact, to destination: URL, expectedDigest: String? = nil, + environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws { + guard expectedDigest.map({ $0 == artifact.digest }) ?? true else { + throw CoreError.invalidState("native artifact digest differs from the reviewed tree") + } + let policy = try AuthorPackageOperations.outputPolicy(artifact.source, environment: environment) + try artifact.output.write(to: destination, beforeCommit: policy.validate) + } + + fileprivate static func validName(_ name: String) -> Bool { + name.utf8.count <= 64 + && name.range(of: #"^[a-z0-9]+(?:-[a-z0-9]+)*$"#, options: .regularExpression) != nil + } +} + +private struct NativePluginBuilder { + let target: NativePluginTarget + let prefix: String + let archive: BundleArchive + var output = AuthorOutputTree() + var audit = AuthorContentAudit() + private var skills = Set() + private var servers: [String: [String: Any]] = [:] + private var secretOptions = Set() + + init(target: NativePluginTarget, prefix: String, archive: BundleArchive) { + self.target = target + self.prefix = prefix + self.archive = archive + } + + mutating func addSkill(_ item: BundleItem) throws { + guard NativePluginOperations.validName(item.name), skills.insert(item.name).inserted, + let discovery = item.discovery, + let manifest = item.entries.first(where: { $0.path == discovery + "/SKILL.md" }), + let digest = manifest.object, let bytes = archive.contentObjects[digest], + try SkillSnapshotReader.manifestName(bytes, path: manifest.path) == item.name + else { throw CoreError.invalidSource("native plugin needs a unique named skill: " + item.name) } + try moveTree(item, from: discovery, to: "skills/" + item.name) + } + + mutating func addMCP(_ item: BundleItem) throws { + let name = item.name + guard name.utf8.count <= 128, + name.range(of: #"^[A-Za-z0-9][A-Za-z0-9_.-]*$"#, options: .regularExpression) != nil, + servers.keys.allSatisfy({ $0.lowercased() != name.lowercased() }) + else { throw CoreError.invalidSource("native plugin needs a unique named MCP: " + name) } + guard try item.native()[target.rawValue]?.isEmpty != false else { + throw CoreError.unsupported("client MCP overrides cannot be projected to plugin: " + name) + } + let unsupported = CoreError.unsupported( + target.rawValue + " plugin cannot represent MCP member: " + name) + var config: [String: Any] = [:] + let transport = try item.transport() + switch transport { + case .stdio(let run): + guard run.workingDirectory == nil else { throw unsupported } + var command = run.executable + if command.contains("/") { + guard target == .claudeCode, command.hasPrefix("payload/"), + item.entries.contains(where: { $0.path == command && $0.kind == .file && $0.executable }) + else { throw unsupported } + let destination = "mcp-resources/" + name + try moveTree(item, from: "payload", to: destination) + command = "${CLAUDE_PLUGIN_ROOT}/" + destination + "/" + command.dropFirst("payload/".count) + } else if item.entries.count != 1 { + throw unsupported + } + config["type"] = "stdio" + config["command"] = command + if !run.arguments.isEmpty { config["args"] = run.arguments } + if !run.environment.isEmpty { + switch target { + case .claudeCode: config["env"] = try claudeBindings(run.environment) + case .codex: + guard + run.environment.allSatisfy({ key, value in + value == .environment(key) && Self.validVariable(key) + }) + else { throw unsupported } + config["env_vars"] = run.environment.keys.sorted() + } + } + case .streamableHTTP(let url, let headers), .sse(let url, let headers): + guard item.entries.count == 1 else { throw unsupported } + let isSSE = transport.organizationPolicyName == "sse" + guard !isSSE || target != .codex else { throw unsupported } + config["type"] = isSSE ? "sse" : "http" + config["url"] = url + if !headers.isEmpty { + switch target { + case .claudeCode: config["headers"] = try claudeBindings(headers) + case .codex: + config["env_http_headers"] = try headers.mapValues { + guard case .environment(let key) = $0, Self.validVariable(key) + else { throw unsupported } + return key + } + } + } + } + servers[name] = config + } + + private mutating func claudeBindings(_ bindings: [String: RuntimeBinding]) throws + -> [String: String] + { + var rendered: [String: String] = [:] + for (field, binding) in bindings { + switch binding { + case .environment(let key) where Self.validVariable(key): + rendered[field] = "${" + key + "}" + case .secret(let key) where Self.validVariable(key): + secretOptions.insert(key) + rendered[field] = "${user_config." + key + "}" + default: throw CoreError.unsupported("invalid symbolic binding for Claude plugin") + } + } + return rendered + } + + private static func validVariable(_ name: String) -> Bool { + name.range(of: #"^[A-Za-z_][A-Za-z0-9_]*$"#, options: .regularExpression) != nil + } + + private mutating func moveTree(_ item: BundleItem, from root: String, to destination: String) + throws + { + let tree = try LedgerResources.validatedEntries(item.resource) + var moved: [LedgerEntry] = [] + for original in item.entries { + var entry = original + if original.path == root { + entry.path = "." + } else if original.path.hasPrefix(root + "/") { + entry.path = String(original.path.dropFirst(root.count + 1)) + } else if original.kind == .directory, + original.path == "." || root.hasPrefix(original.path + "/") + { + continue + } else { + throw CoreError.unsupported("native plugin member needs out-of-tree support: " + item.name) + } + moved.append(entry) + } + guard tree[root]?.kind == .directory else { + throw CoreError.invalidSource("missing native member root: " + item.name) + } + _ = try LedgerResources.validatedEntries( + .init(kind: .embedded, source: "", path: ".", hash: "", entries: moved)) + for var entry in moved { + entry.path = prefix + destination + (entry.path == "." ? "" : "/" + entry.path) + try output.tree.insert(entry) + if let digest = entry.object { output.objects[digest] = archive.contentObjects[digest]! } + } + } + + mutating func finish(package: BundlePackage, description: String, author: String) throws { + var manifest: [String: Any] = [ + "name": package.name, "version": package.version, "description": description, + "author": ["name": author], + ] + if !skills.isEmpty { manifest["skills"] = "./skills/" } + if !servers.isEmpty { + manifest["mcpServers"] = "./.mcp.json" + try addJSON(["mcpServers": servers], path: prefix + ".mcp.json") + } + if target == .codex { + manifest["interface"] = [ + "displayName": String(package.name.prefix(30)), + "shortDescription": String(description.prefix(30)), "longDescription": description, + ] + } + if !secretOptions.isEmpty { + manifest["userConfig"] = Dictionary( + uniqueKeysWithValues: secretOptions.sorted().map { + ( + $0, + [ + "type": "string", "title": $0, "description": "Credential required by an MCP server.", + "sensitive": true, "required": true, + ] as [String: Any] + ) + }) + } + try addJSON(manifest, path: prefix + target.pluginManifest) + } + + mutating func addMarketplace( + _ marketplace: NativePluginMarketplace, package: BundlePackage, description: String, + author: String + ) throws { + let source = "./" + prefix.dropLast() + var listing: [String: Any] = [ + "name": package.name, "description": description, "version": package.version, + "source": source, + ] + var catalog: [String: Any] = ["name": marketplace.name] + if target == .codex { + guard let category = marketplace.category, !category.isEmpty, !category.utf8.contains(0), + category.utf8.count <= 128 + else { throw CoreError.invalidSource("Codex marketplace needs an explicit category") } + listing = [ + "name": package.name, "source": ["source": "local", "path": source], + "policy": ["installation": "AVAILABLE", "authentication": "ON_INSTALL"], + "category": category, + ] + catalog["interface"] = ["displayName": marketplace.name] + } else { + catalog["owner"] = ["name": author] + catalog["metadata"] = ["description": description] + } + catalog["plugins"] = [listing] + try addJSON(catalog, path: target.marketplaceManifest) + } + + private mutating func addJSON(_ value: [String: Any], path: String) throws { + let data = try JSONSerialization.data( + withJSONObject: value, options: [.sortedKeys, .withoutEscapingSlashes]) + try output.add(path, bytes: data) + try audit.scan(data, path: path) + } +} diff --git a/Sources/AgentsUpdates/ComponentDiscovery.swift b/Sources/AgentsUpdates/ComponentDiscovery.swift new file mode 100644 index 0000000..911aef8 --- /dev/null +++ b/Sources/AgentsUpdates/ComponentDiscovery.swift @@ -0,0 +1,261 @@ +import AgentsCore +import AgentsManifest +import Components +import Foundation + +/// A linked authored graph or finite addition resolved in a temporary source session before deployment. +public struct ComponentDiscovery: Sendable { + package var catalogPreparation: CatalogPreparation? = nil + public let components: [ComponentInspection] + public let sourceRevisions: [String: [String]] + public let fingerprint: String + public let readLocations: [URL] + private let declaration: Declaration + private let declarationDigest: String + private let addition: CapturedAddition? + + /// Carries the captured declaration and exact discovered content into ordinary preparation. + public func updateRequest() -> UpdateRequest { + var request = UpdateRequest( + operation: .declaration(declaration), + expectedDeclarationDigest: declarationDigest) + request.expectedDiscoveryFingerprint = fingerprint + request.catalogPreparation = catalogPreparation + request.capturedAddition = addition + request.selectedIdentities = addition?.selectedIdentities + request.importPreparation = addition?.importPreparation + return request + } + + init( + components: [ComponentInspection], sourceRevisions: [String: [String]], fingerprint: String, + readLocations: [URL], declaration: Declaration, declarationDigest: String, + addition: CapturedAddition? = nil + ) { + self.components = components + self.sourceRevisions = sourceRevisions + self.fingerprint = fingerprint + self.readLocations = readLocations + self.declaration = declaration + self.declarationDigest = declarationDigest + self.addition = addition + } +} + +extension UpdateOperations { + /// Resolves authored selections and exported groups for every linked family. It neither lowers + /// native output nor executes source code, calls a binding provider, retains caches or recovers. + public static func discover( + _ declaration: Declaration, scope: InstallScope = .project, + environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> ComponentDiscovery { + let store = StateStore(scope: scope, environment: environment) + return try discover(declaration, store: store, destination: nil, importPreparation: nil) + } + + private static func discover( + _ declaration: Declaration, store: StateStore, destination: AdditionDestination?, + importPreparation: ImportPreparation?, allowNewIdentities: Bool = true, + catalogExpectation: CatalogCompositionExpectation? = nil + ) throws -> ComponentDiscovery { + return try store.withReadLock { + try destination?.validate(in: store) + let policy = try SourcePolicySnapshot(store: store) + try importPreparation?.requireSourcePolicy(policy.effective) + _ = try importPreparation?.capture() + let baseline = try StatePrecondition(store: store) + let previous = try store.readDeclaration(prepared: baseline) + let previousLedger = try store.readLedger(prepared: baseline) + _ = try store.readWatch(prepared: baseline) + let original = try store.declarationDocument(prepared: baseline) + let change = try store.planDeclaration(declaration, replacing: previous, prepared: baseline) + let document = try DeclarationDocument( + bytes: change.map { Array($0.bytes) } ?? original?.bytes ?? Array("version: 1\n".utf8), + identity: DocumentIdentity(store.declarationURL.path)) + let organization = try OrganizationPolicySnapshot(store: store) + let evaluation = try OrganizationInstallEvaluation( + policy: organization, store: store, declaration: declaration, + bytes: change?.bytes ?? original.map { Data($0.bytes) }) + let policyFindings = evaluation.beforeAcquisition() + try organization.admit(policyFindings) + #if os(macOS) + let platform = DeclarationPlatform.macOS + #else + let platform = DeclarationPlatform.linux + #endif + let impact = try LedgerImpact( + ledger: previousLedger, roots: store.ledgerRoots, kinds: [], names: [], updating: false) + let admitOrganization: @Sendable ([OrganizationPolicyFinding]) throws -> Void = { + try organization.admit(policyFindings + $0) + } + return try ComponentLinker.withLinkedComponents( + document: document, store: store, platform: platform, + preserving: destination == nil ? [:] : impact.pins, + directPins: destination == nil ? [:] : impact.directPins, + retaining: destination == nil ? nil : previousLedger, sourcePolicy: policy.effective, + organization: organization.evaluator, + admitOrganization: admitOrganization + ) { linked, session in + try catalogExpectation?.validate(linked) + let frozen = try LedgerFreeze.freezeWithSources( + linked, session: session, + locations: .init( + sources: UpdatePlan.sourceLocations(linked, declaration: declaration, store: store)), + limits: .standard) + let ledger = frozen.ledger + try organization.validate() + try policy.effective.require(ledger, store: store, roots: store.ledgerRoots) + let fingerprint = try LedgerImpact.discoveryFingerprint(ledger, roots: store.ledgerRoots) + let introduced = try Set( + ledger.components.values.map { + try LedgerImpact.identity($0, ledger: ledger, roots: store.ledgerRoots) + } + ).subtracting( + previousLedger.components.values.map { + try LedgerImpact.identity($0, ledger: previousLedger, roots: store.ledgerRoots) + }) + let selected = allowNewIdentities ? introduced : Set() + if destination != nil { + try LedgerImpact.requireProtected( + previous: previousLedger, next: ledger, kinds: [], roots: store.ledgerRoots, + selectedIdentities: selected) + } + let components = try componentInspections( + ledger, roots: store.ledgerRoots, + generation: ResolvedLedgerCodec.digest(ledger)) + var revisions: [String: [String]] = [:] + let locations = try readLocations( + declarations: [previous, declaration], ledgers: [ledger], store: store) + for id in ledger.sources.keys.sorted() { + let identity = try ledger.sourceIdentity(id, roots: store.ledgerRoots) + revisions[identity, default: []].append(ledger.sources[id]!.revision) + } + for key in revisions.keys { revisions[key] = Array(Set(revisions[key]!)).sorted() } + try baseline.validate() + try policy.validate() + return ComponentDiscovery( + components: components, sourceRevisions: revisions, + fingerprint: fingerprint, + readLocations: Array(Set(locations + policy.readDependencies.map(\.url))) + .sorted { $0.path < $1.path }, + declaration: declaration, declarationDigest: original?.digest ?? "absent", + addition: destination.map { + CapturedAddition( + destination: $0, declaration: declaration, fingerprint: fingerprint, + selectedIdentities: selected, importPreparation: importPreparation) + }) + } + } + } +} + +/// Immutable observations only; no source session, descriptor or borrowed resource is retained. +/// Core evidence types do not declare Sendable, but validate never mutates their captured values. +package final class AdditionDestination: @unchecked Sendable, CustomReflectable { + package var customMirror: Mirror { Mirror(self, children: [Mirror.Child]()) } + let store: StateStore + let declaration: Declaration + private let state: [TargetPrecondition] + private let roots: [String: String] + private let identities: [PathIdentity] + + init(store: StateStore, declaration: Declaration, baseline: StatePrecondition) throws { + self.store = store + self.declaration = declaration + state = try [store.declarationURL, store.resolvedURL, store.watchURL].map { + try baseline.evidence(for: $0) + } + roots = store.ledgerRoots.mapValues { $0.standardizedFileURL.resolvingSymlinksInPath().path } + identities = try [store.environment.projectDirectory, store.environment.homeDirectory].map { + try PathIdentity($0) + } + } + + func validate(in current: StateStore) throws { + guard current.scope == store.scope, + current.directory.standardizedFileURL.path == store.directory.standardizedFileURL.path + else { throw CoreError.invalidState("captured addition belongs to another destination") } + for identity in identities { try identity.validate() } + for evidence in state { try evidence.validate() } + let currentRoots = current.ledgerRoots.mapValues { + $0.standardizedFileURL.resolvingSymlinksInPath().path + } + // New named target roots are admitted separately by Core's closed-route coordination. + guard roots.allSatisfy({ currentRoots[$0.key] == $0.value }) else { + throw CoreError.invalidState("captured addition destination roots changed") + } + } +} + +package struct CapturedAddition: Sendable { + let destination: AdditionDestination + let declaration: Declaration + let fingerprint: String + let selectedIdentities: Set + let importPreparation: ImportPreparation? + + func validate(_ request: UpdateRequest, in store: StateStore) throws { + try destination.validate(in: store) + guard case .declaration(let candidate) = request.operation, candidate == declaration, + request.kinds == nil, request.names.isEmpty, request.selections.isEmpty, + request.agents == nil, + request.selectedIdentities == selectedIdentities, + request.expectedDiscoveryFingerprint == fingerprint + else { throw CoreError.invalidState("captured addition was modified; refresh selection") } + } +} + +extension UpdateOperations { + /// Composes finite root additions without refreshing any recorded component. Empty effects + /// return nil, including a source-only selection, and never initialize destination state. + package static func captureAddition( + _ additions: Declaration, in inspection: ScopeInspection, + importPreparation: ImportPreparation? = nil, + catalogExpectation: CatalogCompositionExpectation? = nil + ) throws -> ComponentDiscovery? { + guard !additions.components.isEmpty || !additions.groups.isEmpty || !additions.uses.isEmpty + else { return nil } + guard !inspection.recovery.pending, let destination = inspection.additionDestination else { + throw CoreError.invalidState("inspect the committed destination before selecting additions") + } + guard additions.agents == nil, additions.watch == nil, additions.exports.isEmpty else { + throw CoreError.invalidState("finite additions cannot replace scope defaults or exports") + } + try destination.validate(in: destination.store) + // Existing authored intent must already match its lock; selection cannot publish pending + // authoring changes merely because they happen to appear in the composed graph. + _ = try discover( + destination.declaration, store: destination.store, destination: destination, + importPreparation: nil, allowNewIdentities: false) + var candidate = destination.declaration + for entry in additions.sourceDeclarations { + if let existing = candidate.sources[entry.name] { + guard existing.kind == entry.source.kind, existing.requirement == entry.source.requirement, + existing.path == entry.source.path, + try existing.identity(environment: destination.store.environment) + == entry.source.identity(environment: destination.store.environment) + else { + throw CoreError.invalidState("source alias conflicts with the destination: " + entry.name) + } + } else { + candidate.sourceDeclarations.append(entry) + } + } + for group in additions.groups { + if let existing = candidate.groups.first(where: { $0.name == group.name }) { + guard existing == group else { + throw CoreError.invalidState("group conflicts with the destination: " + group.name) + } + } else { + candidate.groups.append(group) + } + } + for component in additions.components where !candidate.components.contains(component) { + candidate.components.append(component) + } + for use in additions.uses where !candidate.uses.contains(use) { candidate.uses.append(use) } + return try discover( + candidate, store: destination.store, destination: destination, + importPreparation: importPreparation, catalogExpectation: catalogExpectation) + } +} diff --git a/Sources/AgentsUpdates/ComponentInventory.swift b/Sources/AgentsUpdates/ComponentInventory.swift new file mode 100644 index 0000000..501fb76 --- /dev/null +++ b/Sources/AgentsUpdates/ComponentInventory.swift @@ -0,0 +1,267 @@ +import AgentsCore +import Foundation + +/// The JSON format for a distributable inventory of a captured scope. +public enum InventoryFormat: String, Sendable { + case cycloneDX = "cyclonedx" + case spdx +} + +extension ScopeInspection { + /// Exports the locked package and component inventory from this inspection generation. + public func cycloneDXInventory() throws -> Data { + try inventory(format: .cycloneDX) + } + + /// Encodes the captured lock evidence as CycloneDX 1.6 or SPDX 2.3 JSON. + /// A fixed creation date produces identical bytes for the same inventory. + /// With no date, CycloneDX omits the timestamp and SPDX uses the current time. + public func inventory(format: InventoryFormat, createdAt: Date? = nil) throws -> Data { + guard !recovery.pending else { + throw CoreError.recoveryPending(recovery.diagnostic ?? "Transaction recovery is pending") + } + if let marketplaceIssue { throw marketplaceIssue } + + let projection = try InventoryProjection(self) + let encoder = JSONEncoder() + encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes] + switch format { + case .cycloneDX: + return try encoder.encode(CycloneDXInventory(projection, createdAt: createdAt)) + case .spdx: + var document = SPDXInventory(projection, createdAt: createdAt ?? Date()) + let digest = FileHash.sha256Hex(data: try encoder.encode(document)) + document.documentNamespace = "https://github.com/agents-tools/core/spdxdocs/" + digest + return try encoder.encode(document) + } + } +} + +struct InventoryProjection { + struct Item { + let id: String + let name: String + let version: String? + let purl: String? + let archiveSHA256: String? + let properties: [Property] + let contains: [String] + } + + struct Property: Encodable { + let name: String + let value: String + + init(_ name: String, _ value: String) { + self.name = "agents:" + name + self.value = value + } + } + + let sources: [Item] + let components: [Item] + let releases: [Item] + let dependencies: [Dependency] + + struct Dependency: Encodable { + let ref: String + let dependsOn: [String] + } + + init(_ scope: ScopeInspection) throws { + let members = Dictionary(grouping: scope.components, by: \.sourceRecord) + let contained = Dictionary(grouping: scope.sources, by: \.container) + let byIdentity = Dictionary(grouping: scope.sources, by: \.identity) + let resources = Dictionary(uniqueKeysWithValues: scope.resources.map { ($0.identity, $0) }) + + sources = scope.sources.map { source in + let roots = Set(source.uses.map(\.root)).sorted() + let subpath = source.repositorySubpath(roots: roots) + let origin: SourceOrigin? + switch source.kind { + case .git: origin = try? .git(source.identity) + case .wellKnown: origin = try? .http(source.identity) + case .local: + origin = source.container.flatMap { identity in + guard subpath != nil, + byIdentity[identity]?.contains(where: { + $0.kind == .git && $0.revision == source.revision + }) == true + else { return nil } + return try? .git(identity) + } + } + let revision = Self.safeLabel(source.revision) + var properties = [Property("source-kind", source.kind.rawValue)] + if let name = origin?.identity { properties.append(Property("source-origin", name)) } + if let revision { properties.append(Property("revision", revision)) } + properties += roots.map { Property("source-root", $0) } + if let subpath { properties.append(Property("source-subpath", subpath)) } + + let matching = byIdentity[source.identity, default: []].filter { + $0.revision == source.revision + } + let children = + matching.count == 1 + ? contained[source.identity, default: []].filter { $0.revision == source.revision } : [] + let name = + origin?.identity.map { name in + if source.container != nil, let subpath { return name + "#" + subpath } + return name + } ?? source.kind.rawValue + return Item( + id: Self.id("source", source.record), name: name, + version: source.version.flatMap(Self.safeLabel) ?? revision, + purl: origin?.inventoryPackageURL(revision: source.revision, subpath: subpath), + archiveSHA256: nil, + properties: properties, + contains: members[source.record, default: []].map { Self.id("component", $0.record) } + + children.map { Self.id("source", $0.record) }) + } + components = scope.components.map { component in + let targets = component.recipients.map(\.rawValue) + (component.chatGPT ? ["chatgpt"] : []) + var properties = [Property("kind", component.kind.rawValue)] + properties += targets.sorted().map { Property("target", $0) } + if let registry = component.mcpRegistry { + if let origin = try? SourceOrigin.http(registry.registry).identity { + properties.append(Property("mcp-registry-origin", origin)) + } + if let server = Self.safeLabel(registry.server) { + properties.append(Property("mcp-registry-server", server)) + } + if let version = Self.safeLabel(registry.version) { + properties.append(Property("mcp-registry-version", version)) + } + properties.append(Property("mcp-installation-origin", registry.origin)) + } + let revision = component.revision.flatMap(Self.safeLabel) + if let revision { properties.append(Property("revision", revision)) } + for resource in component.resources.compactMap({ resources[$0] }) { + let rootKind = resource.entries.first { $0.path == "." }?.kind + let kind = resource.kind == "liveEdit" || rootKind == "directory" ? "tree" : "file" + let source = + resource.sourceRecord == component.sourceRecord + ? "" : " (\(Self.id("source", resource.sourceRecord)))" + properties.append( + Property("resource-\(kind)-sha256", "\(resource.hash) \(resource.path)" + source)) + } + return Item( + id: Self.id("component", component.record), + name: Self.safeLabel(component.name) ?? component.kind.rawValue, + version: component.version.flatMap(Self.safeLabel) ?? revision, + purl: nil, archiveSHA256: nil, properties: properties, contains: []) + } + func release( + id: String, coordinate: MarketplaceCoordinate, catalog: MarketplaceOrigin, + digest: String, commit: String?, records: [String], aliases: [String] + ) -> Item { + let origin = catalog.isLocal ? nil : try? SourceOrigin.git(catalog.location) + let releasePath = [catalog.subpath, coordinate.releasePath].compactMap { $0 }.joined( + separator: "/") + var properties = + aliases.map { Property("dependency", $0) } + [ + Property("marketplace-kind", catalog.kind.rawValue), + Property("marketplace-origin", origin?.identity ?? "local"), + Property("archive-digest", digest), + ] + if let commit { + properties.append(Property("catalog-commit", commit)) + properties.append(Property("catalog-release-path", releasePath)) + } + properties += records.filter { (try? StateValidation.digest($0)) != nil }.map { + Property("component-record", $0) + } + return Item( + id: id, name: coordinate.package, version: coordinate.version, + purl: commit.flatMap { origin?.inventoryPackageURL(revision: $0, subpath: releasePath) }, + archiveSHA256: String(digest.dropFirst("sha256:".count)), properties: properties, + contains: records.map { Self.id("component", $0) }) + } + let exact = scope.marketplacePackages.sorted { $0.dependency.name < $1.dependency.name }.map { + release( + id: Self.id("release", $0.dependency.name), coordinate: $0.dependency.coordinate, + catalog: $0.dependency.catalog, digest: $0.archiveDigest, + commit: $0.catalogCommit, records: $0.componentRecords, aliases: [$0.dependency.name]) + } + if let graph = scope.marketplaceGraph { + let ids = try Dictionary( + uniqueKeysWithValues: graph.nodes.map { + ($0.id, Self.id("release-node", try ResolvedLedgerCodec.digest($0.id))) + }) + releases = + exact + + graph.nodes.map { node in + release( + id: ids[node.id]!, coordinate: node.coordinate, catalog: node.catalog, + digest: node.archiveDigest, commit: node.catalogCommit, records: node.componentRecords, + aliases: graph.roots.filter { $0.node == node.id }.map(\.intent.name)) + } + dependencies = graph.nodes.filter { !$0.dependencies.isEmpty }.map { + Dependency( + ref: ids[$0.id]!, dependsOn: Set($0.dependencies.map { ids[$0.target]! }).sorted()) + } + } else { + releases = exact + dependencies = [] + } + } + + private static func id(_ category: String, _ record: String) -> String { + category + "-" + FileHash.sha256Hex(data: Data(record.utf8)) + } + + private static func safeLabel(_ value: String) -> String? { + guard (try? PathSafety.sanitizeSubpath(value)) != nil, !value.hasPrefix("~"), + !value.contains("://"), value.utf8.allSatisfy({ $0 >= 32 && $0 != 127 }) + else { return nil } + return value + } +} + +extension SourceOrigin { + fileprivate func inventoryPackageURL(revision: String, subpath: String?) -> String? { + guard kind == .git, SourceCache.isObjectID(revision), + let locator = policyLocator, let url = URLComponents(string: locator), + let host = url.host + else { return nil } + var path = url.path.dropLast(".git".count).split(separator: "/").map(String.init) + guard !path.isEmpty else { return nil } + + let type: String + if url.port == nil, path.count == 2, ["github.com", "bitbucket.org"].contains(host) { + type = host == "github.com" ? "github" : "bitbucket" + path = path.map { $0.lowercased() } + } else { + type = "git" + let authority = host + (url.port.map { ":\($0)" } ?? "") + path.insert(authority, at: 0) + } + let package = path.map(Self.encodePackageURLSegment).joined(separator: "/") + let suffix = + subpath.map { + "#" + $0.split(separator: "/").map(Self.encodePackageURLSegment).joined(separator: "/") + } ?? "" + return "pkg:\(type)/\(package)@\(revision)" + suffix + } + + fileprivate static func encodePackageURLSegment(_ value: some StringProtocol) -> String { + let allowed = CharacterSet( + charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~:") + return String(value).addingPercentEncoding(withAllowedCharacters: allowed)! + } +} + +extension SourceInspection { + fileprivate func repositorySubpath(roots: [String]) -> String? { + if let namespace, namespace.hasPrefix(":contained:") { + let fields = namespace.dropFirst(":contained:".count).split(separator: ":", maxSplits: 1) + if fields.count == 2, Int(fields[0]) == fields[1].utf8.count, + let path = try? PathSafety.sanitizeSubpath(String(fields[1])), path != "." + { + return path + } + } + guard kind == .git, roots.count == 1, roots[0] != "." else { return nil } + return roots[0] + } +} diff --git a/Sources/AgentsUpdates/ComponentInventoryEncoding.swift b/Sources/AgentsUpdates/ComponentInventoryEncoding.swift new file mode 100644 index 0000000..9f8b86c --- /dev/null +++ b/Sources/AgentsUpdates/ComponentInventoryEncoding.swift @@ -0,0 +1,173 @@ +import Foundation + +struct CycloneDXInventory: Encodable { + let bomFormat = "CycloneDX" + let specVersion = "1.6" + let version = 1 + let metadata: Metadata? + let components: [Component] + let dependencies: [InventoryProjection.Dependency]? + + init(_ inventory: InventoryProjection, createdAt: Date?) { + dependencies = inventory.dependencies.isEmpty ? nil : inventory.dependencies + metadata = createdAt.map { Metadata(timestamp: $0.ISO8601Format()) } + let members = Dictionary(uniqueKeysWithValues: inventory.components.map { ($0.id, $0) }) + components = + inventory.sources.map { source in + let children = source.contains.compactMap { members[$0] }.map { + Component($0, type: "data") + } + return Component( + source, type: "library", components: children, + additionalMembers: source.contains.filter { members[$0] == nil }) + } + + inventory.releases.map { + Component($0, type: "library", additionalMembers: $0.contains) + } + } + + struct Metadata: Encodable { + let timestamp: String + } + + struct Component: Encodable { + let type: String + let bomRef: String + let name: String + let version: String? + let purl: String? + let hashes: [Hash]? + let properties: [InventoryProjection.Property] + let components: [Component]? + + enum CodingKeys: String, CodingKey { + case type + case bomRef = "bom-ref" + case name, version, purl, hashes, properties + case components + } + + init( + _ item: InventoryProjection.Item, type: String, components: [Component]? = nil, + additionalMembers: [String] = [] + ) { + self.type = type + bomRef = item.id + name = item.name + version = item.version + purl = item.purl + hashes = item.archiveSHA256.map { [Hash(content: $0)] } + properties = + item.properties + + additionalMembers.map { + InventoryProjection.Property("contains", $0) + } + self.components = components + } + } + + struct Hash: Encodable { + let alg = "SHA-256" + let content: String + } +} + +struct SPDXInventory: Encodable { + private static let documentID = "SPDXRef-DOCUMENT" + + let spdxVersion = "SPDX-2.3" + let dataLicense = "CC0-1.0" + let spdxID = documentID + let name = "Agents scope inventory" + var documentNamespace = "" + let creationInfo: CreationInfo + let packages: [Package] + let relationships: [Relationship] + + enum CodingKeys: String, CodingKey { + case spdxVersion, dataLicense + case spdxID = "SPDXID" + case name, documentNamespace, creationInfo + case packages, relationships + } + + init(_ inventory: InventoryProjection, createdAt: Date) { + creationInfo = CreationInfo(created: createdAt.ISO8601Format()) + let roots = inventory.sources + inventory.releases + packages = (roots + inventory.components).map(Package.init) + let contained = Set(inventory.sources.flatMap(\.contains)) + relationships = + roots.filter { !contained.contains($0.id) }.map { + Relationship( + spdxElementId: Self.documentID, relationshipType: "DESCRIBES", + relatedSpdxElement: Self.id($0.id)) + } + + roots.flatMap { item in + item.contains.map { target in + Relationship( + spdxElementId: Self.id(item.id), relationshipType: "CONTAINS", + relatedSpdxElement: Self.id(target)) + } + } + + inventory.dependencies.flatMap { source in + source.dependsOn.map { + Relationship( + spdxElementId: Self.id(source.ref), relationshipType: "DEPENDS_ON", + relatedSpdxElement: Self.id($0)) + } + } + } + + private static func id(_ id: String) -> String { "SPDXRef-" + id } + + struct CreationInfo: Encodable { + let creators = ["Tool: agents"] + let created: String + } + + struct Package: Encodable { + let spdxID: String + let name: String + let versionInfo: String? + let downloadLocation = "NOASSERTION" + let filesAnalyzed = false + let licenseConcluded = "NOASSERTION" + let licenseDeclared = "NOASSERTION" + let copyrightText = "NOASSERTION" + let sourceInfo: String + let externalRefs: [ExternalRef]? + let checksums: [Checksum]? + + enum CodingKeys: String, CodingKey { + case spdxID = "SPDXID" + case name, versionInfo, downloadLocation, filesAnalyzed, licenseConcluded + case licenseDeclared, copyrightText, sourceInfo, externalRefs, checksums + } + + init(_ item: InventoryProjection.Item) { + spdxID = SPDXInventory.id(item.id) + name = item.name + versionInfo = item.version + sourceInfo = item.properties.map { $0.name + " " + $0.value }.joined(separator: "\n") + externalRefs = item.purl.map { [ExternalRef(referenceLocator: $0)] } + checksums = item.archiveSHA256.map { [Checksum(checksumValue: $0)] } + } + } + + struct Relationship: Encodable { + let spdxElementId: String + let relationshipType: String + let relatedSpdxElement: String + } + + struct ExternalRef: Encodable { + let referenceCategory = "PACKAGE-MANAGER" + let referenceType = "purl" + let referenceLocator: String + } + + struct Checksum: Encodable { + let algorithm = "SHA256" + let checksumValue: String + } +} diff --git a/Sources/AgentsUpdates/ContentAuditDiscovery.swift b/Sources/AgentsUpdates/ContentAuditDiscovery.swift new file mode 100644 index 0000000..016c2ee --- /dev/null +++ b/Sources/AgentsUpdates/ContentAuditDiscovery.swift @@ -0,0 +1,304 @@ +import AgentsCore +import Components +import Foundation + +struct ContentAuditProfile: Sendable { + enum Format: Equatable, Sendable { + case text + case native(NativePromptAudit.Format) + } + + struct Pattern: Sendable { + let directory: String + let selector: Selector + let format: Format + + func matches(_ name: String) -> Bool { + switch selector { + case .named(let value): name.utf8.elementsEqual(value.utf8) + case .suffix(let value): name.utf8.suffix(value.utf8.count).elementsEqual(value.utf8) + } + } + } + + enum Selector: Hashable, Sendable { + case named(String) + case suffix(String) + } + + let root: URL + private let otherRoot: String? + var files: [String: Format] = [:] + var directories: [Pattern] = [] + var outsideScope: Set = [] + var nestedInstructions: Set = [] + + init( + scope: InstallScope, environment: RuntimeEnvironment, agents: Set + ) { + root = + (scope == .project ? environment.projectDirectory : environment.homeDirectory) + .standardizedFileURL + let other = scope == .project ? environment.homeDirectory : environment.projectDirectory + otherRoot = Self.relative(other, to: root).flatMap { $0 == "." ? nil : $0 } + + func relative(_ url: URL) -> String? { Self.relative(url, to: root) } + let native = NativeTargetRoute.clientLocations(scope: scope, environment: environment) + func registered(_ name: String) -> URL? { + guard let location = native.first(where: { $0.identity == name + "." + scope.rawValue }) + else { return nil } + return try? location.location.get() + } + func base(_ agent: AgentID) -> URL { + switch agent { + case .codex: + registered("codex.hooks")?.deletingLastPathComponent() + ?? root.appendingPathComponent(".codex") + case .claudeCode: + registered("claude.settings")?.deletingLastPathComponent() + ?? root.appendingPathComponent(".claude") + case .cursor: root.appendingPathComponent(".cursor") + case .geminiCLI: + registered("gemini.mcp")?.deletingLastPathComponent() + ?? root.appendingPathComponent(".gemini") + case .antigravity: + AgentRegistry.installSkillsDirectory(for: agent, scope: scope, environment: environment) + .deletingLastPathComponent() + case .opencode: + scope == .project + ? root.appendingPathComponent(".opencode") + : (try? native.first { $0.identity == "opencode.mcp.user.json" }?.location.get())? + .deletingLastPathComponent() + ?? AgentRegistry.userSkillsDirectory(for: .opencode, environment: environment) + .deletingLastPathComponent() + } + } + func addFile(_ url: URL, _ format: Format = .text) { + if let path = relative(url), path != ".", !excludes(path) { + files[path] = format + } else { + outsideScope.insert(url.lastPathComponent) + } + } + func addDirectory(_ url: URL, _ selector: Selector, _ format: Format = .text) { + guard let path = relative(url), path != ".", !excludes(path) else { + outsideScope.insert(url.lastPathComponent + "/") + return + } + guard + !directories.contains(where: { + $0.directory == path && $0.selector == selector && $0.format == format + }) + else { return } + directories.append(.init(directory: path, selector: selector, format: format)) + } + + for agent in AgentID.allCases where agents.contains(agent) { + for (role, url) in InstructionLocations.clientFiles( + for: agent, scope: scope, environment: environment) + { + if role == "instructions.rules" { + addDirectory(url, .suffix(".md")) + } else { + addFile(url) + } + } + for (_, url) in AgentRegistry.clientSkillLocations( + for: agent, scope: scope, environment: environment) + { + addDirectory(url, .named("SKILL.md")) + } + + let directory = base(agent) + switch agent { + case .codex: + addDirectory( + registered("codexAgent") ?? directory.appendingPathComponent("agents"), + .suffix(".toml"), .native(.codexAgent)) + addFile(directory.appendingPathComponent("hooks.json"), .native(.commandHooks)) + addFile( + (scope == .project ? root : directory).appendingPathComponent("AGENTS.override.md")) + if scope == .project { nestedInstructions.formUnion(["AGENTS.md", "AGENTS.override.md"]) } + case .claudeCode: + addDirectory(directory.appendingPathComponent("rules"), .suffix(".md")) + addDirectory( + registered("claudeAgent") ?? directory.appendingPathComponent("agents"), + .suffix(".md")) + addDirectory( + registered("claudeCommand") ?? directory.appendingPathComponent("commands"), + .suffix(".md")) + addDirectory( + directory.appendingPathComponent("hooks"), .suffix(".json"), .native(.claudeHooks)) + addFile(directory.appendingPathComponent("settings.json"), .native(.claudeHooks)) + if scope == .project { + addFile(directory.appendingPathComponent("settings.local.json"), .native(.claudeHooks)) + nestedInstructions.formUnion(["AGENTS.md", "CLAUDE.md"]) + } + case .cursor: + addDirectory(directory.appendingPathComponent("rules"), .suffix(".mdc")) + addDirectory( + registered("cursorAgent") ?? directory.appendingPathComponent("agents"), + .suffix(".md")) + if scope == .project { + addDirectory( + registered("cursorCommand") ?? directory.appendingPathComponent("commands"), + .suffix(".md")) + addFile(root.appendingPathComponent(".cursorrules")) + nestedInstructions.insert("AGENTS.md") + } else { + addFile(directory.appendingPathComponent("AGENTS.md")) + } + addDirectory( + directory.appendingPathComponent("hooks"), .suffix(".json"), .native(.cursorHooks)) + addFile(directory.appendingPathComponent("hooks.json"), .native(.cursorHooks)) + case .geminiCLI: + addDirectory( + registered("geminiCommand") ?? directory.appendingPathComponent("commands"), + .suffix(".toml"), .native(.geminiCommand)) + addDirectory( + registered("geminiAgent") ?? directory.appendingPathComponent("agents"), + .suffix(".md")) + addDirectory( + directory.appendingPathComponent("hooks"), .suffix(".json"), .native(.commandHooks)) + addFile(directory.appendingPathComponent("settings.json"), .native(.commandHooks)) + if scope == .project { + nestedInstructions.insert("GEMINI.md") + } else { + addFile(directory.appendingPathComponent("GEMINI.md")) + addDirectory(directory.appendingPathComponent("skills"), .named("SKILL.md")) + } + case .opencode: + addDirectory(directory.appendingPathComponent("agents"), .suffix(".md")) + addDirectory(directory.appendingPathComponent("commands"), .suffix(".md")) + let prefix = "opencode.mcp." + scope.rawValue + for (suffix, format) in [ + ("json", NativePromptAudit.Format.openCodeJSON), ("jsonc", .openCodeJSONC), + ] { + let location = native.first { $0.identity == prefix + "." + suffix } + if let url = try? location?.location.get() { addFile(url, .native(format)) } + } + if scope == .project { + nestedInstructions.insert("AGENTS.md") + } else { + addFile(directory.appendingPathComponent("AGENTS.md")) + addDirectory(directory.appendingPathComponent("skills"), .named("SKILL.md")) + } + case .antigravity: + if let hooks = registered("antigravity.hooks") { + addFile(hooks, .native(.antigravityHooks)) + } + if scope == .project { nestedInstructions.insert("AGENTS.md") } + } + } + if scope == .project && !agents.isEmpty { + addDirectory(root.appendingPathComponent(".agent/instructions"), .suffix(".md")) + } + } + + func format(at path: String) -> Format? { + if let exact = files[path] { return exact } + let name = String(path.split(separator: "/").last ?? "") + for pattern in directories + where path.utf8.starts(with: (pattern.directory + "/").utf8) && pattern.matches(name) { + return pattern.format + } + if nestedInstructions.contains(name), + path.split(separator: "/").dropLast().allSatisfy({ + !$0.hasPrefix(".") + }) + { + return .text + } + return nil + } + + func explicitFormat(at path: String) -> Format? { + if let known = format(at: path) { return known } + let suffix = (path as NSString).pathExtension.lowercased() + return ["md", "mdc", "txt", "prompt"].contains(suffix) ? .text : nil + } + + static func isLocalFileURL(_ url: URL) -> Bool { + let host = url.host?.lowercased() ?? "" + return url.isFileURL && (host.isEmpty || host == "localhost") && url.path.hasPrefix("/") + && !url.path.contains("\0") && !url.path.contains("\\") + } + + static func relative(_ url: URL, to root: URL) -> String? { + guard isLocalFileURL(url), isLocalFileURL(root) else { return nil } + let target = url.standardizedFileURL.path + let base = root.path + if target.utf8.elementsEqual(base.utf8) { return "." } + let prefix = base == "/" ? "/" : base + "/" + guard target.utf8.starts(with: prefix.utf8) else { return nil } + return String(decoding: target.utf8.dropFirst(prefix.utf8.count), as: UTF8.self) + } + + func excludes(_ path: String, admittedCache: Bool = false) -> Bool { + if let otherRoot, + path.utf8.elementsEqual(otherRoot.utf8) + || path.utf8.starts(with: (otherRoot + "/").utf8) + { + return true + } + return Self.excludesName(in: path, admittedCache: admittedCache) + } + + static func excludesName(in path: String, admittedCache: Bool = false) -> Bool { + path.split(separator: "/").contains { component in + let name = component.lowercased() + if [ + ".git", ".hg", ".svn", ".ssh", ".aws", ".gnupg", ".netrc", ".npmrc", ".envrc", + "auth", "credentials", "secrets", "tokens", "session", "sessions", "transcripts", + "history", ".history", "logs", "worktrees", ".worktrees", "node_modules", ".build", + "dist", "vendor", "deriveddata", + ].contains(name) { + return true + } + if !admittedCache && ["cache", "caches", ".cache"].contains(name) { return true } + if name == ".env" || name.hasPrefix(".env.") { return true } + let stem = name.split(separator: ".").first.map(String.init) ?? name + return [ + "auth", "credential", "credentials", "secret", "secrets", "token", "tokens", + "history", "transcript", "id_rsa", "id_ed25519", "api-key", "apikey", + ].contains(stem) + || [".pem", ".key", ".p12", ".pfx", ".kdbx"].contains { name.hasSuffix($0) } + } + } +} + +struct ContentAuditTree { + let directory: DirectoryHandle + + init(profile: ContentAuditProfile) throws { + guard ContentAuditProfile.isLocalFileURL(profile.root), profile.root.path != "/" else { + throw ContentAuditProblem.outsideScope + } + directory = try DirectoryHandle.readDirectory(at: profile.root) + } + + func open(_ path: String, admittedRepository: String? = nil) throws -> DirectoryHandle? { + if path == "." { return directory } + var parent = directory + var prefix = "" + for component in path.split(separator: "/") { + guard let child = try parent.directory(String(component)) else { return nil } + if !prefix.isEmpty { prefix.append("/") } + prefix.append(contentsOf: component) + if try ContentAuditFiles.kind(".git", in: child) != nil, + admittedRepository?.utf8.elementsEqual(prefix.utf8) != true + { + throw ContentAuditProblem.unrelatedRepository + } + parent = child + } + return parent + } + + func parent(of path: String) throws -> (DirectoryHandle, String)? { + let parts = path.split(separator: "/") + guard let name = parts.last else { return nil } + let parent = parts.count == 1 ? "." : parts.dropLast().joined(separator: "/") + return try open(parent).map { ($0, String(name)) } + } +} diff --git a/Sources/AgentsUpdates/ContentAuditOperations.swift b/Sources/AgentsUpdates/ContentAuditOperations.swift new file mode 100644 index 0000000..c116996 --- /dev/null +++ b/Sources/AgentsUpdates/ContentAuditOperations.swift @@ -0,0 +1,546 @@ +import AgentsCore +import AgentsInstructions +import Components +import Foundation + +public enum ContentAuditOperations { + /// Inspect recognized prompt surfaces under the selected project or home. + public static func scan( + scope: InstallScope = .project, agents: Set = Set(AgentID.allCases), + environment: RuntimeEnvironment = RuntimeEnvironment() + ) -> ContentAuditReport { + inspect(file: nil, scope: scope, agents: agents, environment: environment) + } + + /// Inspect one scope-contained file. Native settings use their registered field profile. + /// An explicitly selected Markdown or plain text document is read as a whole. + public static func scan( + file: URL, scope: InstallScope = .project, + environment: RuntimeEnvironment = RuntimeEnvironment() + ) -> ContentAuditReport { + inspect(file: file, scope: scope, agents: Set(AgentID.allCases), environment: environment) + } + + private static func inspect( + file: URL?, scope: InstallScope, agents: Set, environment: RuntimeEnvironment + ) -> ContentAuditReport { + let profile = ContentAuditProfile(scope: scope, environment: environment, agents: agents) + let selected: String? + if let file { + guard let path = ContentAuditProfile.relative(file, to: profile.root), path != "." else { + return ContentAuditInspection.failure(path: file.lastPathComponent, reason: .outsideScope) + } + selected = path + if profile.excludes(path) || profile.explicitFormat(at: path) == nil { + return .init( + targets: [.init(path: path, ownership: .unknown, status: .skipped)], + findings: [], readLocations: []) + } + } else { + selected = nil + } + + let store = StateStore(scope: scope, environment: environment) + let tree: ContentAuditTree + do { + tree = try ContentAuditTree(profile: profile) + } catch ContentAuditProblem.outsideScope { + return ContentAuditInspection.failure(path: selected ?? ".", reason: .outsideScope) + } catch { + return ContentAuditInspection.failure(path: selected ?? ".", reason: .unreadable) + } + let state = store.directory.lastPathComponent + let stateLocations = + [state] + + [ + "agents.resolved", ".agents.lock", "transaction.json", "transaction.new", + "watch-refs.pending", + ].map { state + "/" + $0 } + do { + return try store.withContentAuditLedger(root: tree.directory) { ledger in + var inspection = ContentAuditInspection( + profile: profile, tree: tree, store: store, ledger: ledger, + checkRecordedContent: selected == nil) + for location in stateLocations { inspection.record(location) } + if ledger == nil { + inspection.issue(state + "/agents.resolved", .ownershipUnavailable) + } + if let selected { + inspection.inspect( + selected, format: profile.explicitFormat(at: selected)!, required: true) + } else { + inspection.discover() + } + return inspection.report + } + } catch CoreError.recoveryPending { + return ContentAuditInspection.failure( + path: state, reason: .pendingRecovery, + locations: stateLocations.map { profile.root.appendingPathComponent($0) }) + } catch { + return ContentAuditInspection.failure( + path: state + "/agents.resolved", reason: .ownershipUnavailable, + locations: stateLocations.map { profile.root.appendingPathComponent($0) }) + } + } +} + +struct ContentAuditInspection { + private static let maximumDepth = 64 + static let maximumFileBytes = 8 * 1024 * 1024 + private static let maximumReportFindings = 65_536 + private static let maximumEntries = 100_000 + + let profile: ContentAuditProfile + let tree: ContentAuditTree + let store: StateStore + let ledger: ResolvedLedger? + private let claims: ContentAuditClaims + private let checkRecordedContent: Bool + private var targets: [Data: ContentAuditTarget] = [:] + private var findings: [ContentAuditFinding] = [] + private var locations: [Data: URL] = [:] + private var entries = 0 + private var exhausted = false + + init( + profile: ContentAuditProfile, tree: ContentAuditTree, store: StateStore, + ledger: ResolvedLedger?, checkRecordedContent: Bool + ) { + self.profile = profile + self.tree = tree + self.store = store + self.ledger = ledger + self.checkRecordedContent = checkRecordedContent + claims = ContentAuditClaims(profile: profile, store: store, ledger: ledger) + } + + var report: ContentAuditReport { + let orderedTargets = targets.values.sorted { + $0.path.utf8.lexicographicallyPrecedes($1.path.utf8) + } + let orderedFindings = findings.sorted { + let a = $0.location + let b = $1.location + if !a.path.utf8.elementsEqual(b.path.utf8) { + return a.path.utf8.lexicographicallyPrecedes(b.path.utf8) + } + return ( + a.line ?? 0, a.column ?? 0, a.field ?? "", a.promptLine ?? 0, a.promptColumn ?? 0, + $0.reason.rawValue + ) + < ( + b.line ?? 0, b.column ?? 0, b.field ?? "", b.promptLine ?? 0, b.promptColumn ?? 0, + $1.reason.rawValue + ) + } + return .init( + targets: orderedTargets, findings: orderedFindings, + readLocations: locations.values.sorted { + $0.path.utf8.lexicographicallyPrecedes($1.path.utf8) + }) + } + + static func failure( + path: String, reason: ContentAuditReason, locations: [URL] = [] + ) -> ContentAuditReport { + .init( + targets: [.init(path: path, ownership: .unknown, status: .incomplete)], + findings: [diagnostic(path, reason, ownership: .unknown)], readLocations: locations) + } + + mutating func record(_ path: String) { + locations[Data(path.utf8)] = + path == "." ? profile.root : profile.root.appendingPathComponent(path) + } + + mutating func issue( + _ path: String, _ reason: ContentAuditReason, ownership: ContentAuditOwnership = .unknown, + field: String? = nil, coordinate: (line: Int, column: Int)? = nil + ) { + findings.append( + Self.diagnostic(path, reason, ownership: ownership, field: field, coordinate: coordinate)) + targets[Data(path.utf8)] = .init(path: path, ownership: ownership, status: .incomplete) + } + + private static func diagnostic( + _ path: String, _ reason: ContentAuditReason, ownership: ContentAuditOwnership, + field: String? = nil, coordinate: (line: Int, column: Int)? = nil + ) -> ContentAuditFinding { + .init( + severity: .critical, reason: reason, + location: .init( + path: path, field: field, line: coordinate?.line, column: coordinate?.column, + promptLine: nil, promptColumn: nil), + ownership: ownership, codePoint: nil) + } + + mutating func discover() { + record(".") + for path in profile.outsideScope.sorted() { issue(path, .outsideScope) } + for (path, format) in profile.files.sorted(by: { $0.key < $1.key }) { + inspect(path, format: format) + } + for pattern in profile.directories { + guard !exhausted else { return } + record(pattern.directory) + do { + if let directory = try tree.open(pattern.directory) { + walk(directory, path: pattern.directory, pattern: pattern, depth: 0) + } + } catch ContentAuditProblem.unrelatedRepository { + continue + } catch { + issue(pattern.directory, .unreadable) + } + } + if !profile.nestedInstructions.isEmpty { + walk(tree.directory, path: ".", pattern: nil, depth: 0) + } + } + + /// Profile traversal and nested context discovery share the same no-follow policy. + /// A nested worktree starts at its own .git file or directory. + private mutating func walk( + _ directory: DirectoryHandle, path: String, pattern: ContentAuditProfile.Pattern?, depth: Int + ) { + guard !exhausted else { return } + guard depth <= Self.maximumDepth else { + issue(path, .unsupportedContent) + return + } + record(path) + do { + for name in try directory.names() + where !name.hasPrefix(".") && !ContentAuditProfile.excludesName(in: name) { + guard !exhausted else { return } + entries += 1 + if entries > Self.maximumEntries { + exhausted = true + issue(".", .unsupportedContent) + return + } + let child = path == "." ? name : path + "/" + name + guard !profile.excludes(child) else { continue } + let match = pattern?.matches(name) ?? profile.nestedInstructions.contains(name) + let format = pattern?.format ?? .text + let kind = try ContentAuditFiles.kind(name, in: directory) + if match && (kind != .directory || pattern != nil) { + inspect(child, format: format) + continue + } + if kind == .directory, let handle = try directory.directory(name) { + if try ContentAuditFiles.kind(".git", in: handle) == nil { + walk(handle, path: child, pattern: pattern, depth: depth + 1) + } + } else if kind == .symbolicLink && pattern?.selector == .named("SKILL.md") && depth == 0 { + inspect(child + "/SKILL.md", format: format) + } + } + } catch { + issue(path, .unreadable) + } + } + + mutating func inspect( + _ path: String, format: ContentAuditProfile.Format, required: Bool = false + ) { + guard !exhausted else { return } + let key = Data(path.utf8) + guard targets[key] == nil else { return } + record(path) + let recorded = claims.files[key] ?? [] + let skill = claims.skills[key] + let whole = recorded.filter { $0.ownership == .generated } + let regional = recorded.filter { $0.ownership != .generated } + let baseOwnership: ContentAuditOwnership = + !whole.isEmpty || skill != nil + ? .managedFile : !regional.isEmpty ? .managedRegion : ledger == nil ? .unknown : .untracked + do { + guard let bytes = try read(path, skill: skill) else { + if required { issue(path, .unreadable, ownership: baseOwnership) } + return + } + guard let source = String(validating: bytes, as: UTF8.self) else { + issue(path, .unsupportedContent, ownership: baseOwnership) + return + } + if source.unicodeScalars.contains("\0") && format == .text { + issue(path, .unsupportedContent, ownership: baseOwnership) + return + } + targets[key] = .init(path: path, ownership: baseOwnership, status: .scanned) + verifyHash(bytes, path: path, whole: whole, skill: skill) + switch format { + case .text: + let importRange = try verifyText( + bytes, path: path, regional: regional) + let symbols = try ContentAuditUnicode.scan(source, leadingBOM: true) + let individualOwnership = baseOwnership == .managedRegion ? .untracked : baseOwnership + for symbol in symbols { + let ownership = + importRange?.contains(symbol.byteRange.lowerBound) == true + ? .managedRegion : individualOwnership + append( + symbol, path: path, field: nil, coordinate: (symbol.line, symbol.column), + ownership: ownership) + } + case .native(let native): + try inspectNative( + bytes, source: source, path: path, format: native, ownership: baseOwnership, + authorities: claims.regions[key] ?? []) + } + } catch ContentAuditProblem.outsideScope { + issue(path, .outsideScope, ownership: baseOwnership) + } catch ContentAuditProblem.unrelatedRepository { + if required || skill != nil { issue(path, .outsideScope, ownership: baseOwnership) } + } catch ContentAuditProblem.unsupportedContent { + issue(path, .unsupportedContent, ownership: baseOwnership) + } catch { + issue(path, .unreadable, ownership: baseOwnership) + } + } + + private mutating func read(_ path: String, skill: ContentAuditClaims.Skill?) throws -> Data? { + if path.hasSuffix("/SKILL.md") { + let slot = String(path.dropLast("/SKILL.md".count)) + if let (parent, name) = try tree.parent(of: slot), + try ContentAuditFiles.kind(name, in: parent) == .symbolicLink + { + guard let skill else { throw ContentAuditProblem.outsideScope } + return try readLinkedSkill(skill, parent: parent, name: name, slot: slot) + } + } + guard let (parent, name) = try tree.parent(of: path), + let kind = try ContentAuditFiles.kind(name, in: parent) + else { return nil } + guard kind != .symbolicLink else { throw ContentAuditProblem.outsideScope } + return try ContentAuditFiles.readPrompt(name, in: parent, maximumBytes: Self.maximumFileBytes) + } + + private mutating func readLinkedSkill( + _ skill: ContentAuditClaims.Skill, parent: DirectoryHandle, name: String, slot: String + ) throws -> Data { + guard let ledger, let resource = ledger.resources[skill.resourceID], + skill.mode == .link + || (skill.mode == .edit && resource.kind == .liveEdit + && ledger.sources[resource.source]?.kind == .local) + else { throw ContentAuditProblem.outsideScope } + let roots = [ + "project": store.environment.projectDirectory, "home": store.environment.homeDirectory, + "state": store.directory, + ] + let destination: URL + if let artifact = resource.artifact, resource.location != nil { + destination = try SourceCache.artifactContentLocation(digest: artifact.digest) + .resolve(roots: roots) + } else { + destination = try ArtifactAggregation.resourceDestination( + skill.resourceID, ledger: ledger, store: store, roots: roots) + } + guard let target = ContentAuditProfile.relative(destination, to: profile.root), target != "." + else { + throw ContentAuditProblem.outsideScope + } + let retained = + skill.mode == .link + && target.utf8.starts( + with: (store.directory.lastPathComponent + "/cache/").utf8) + guard !profile.excludes(target, admittedCache: retained), + skill.mode == .edit || retained + else { throw ContentAuditProblem.outsideScope } + let from = profile.root.appendingPathComponent(slot).deletingLastPathComponent().pathComponents + let to = destination.pathComponents + let common = zip(from, to).prefix { $0.utf8.elementsEqual($1.utf8) }.count + let relativeLink = (Array(repeating: "..", count: from.count - common) + to.dropFirst(common)) + .joined(separator: "/") + let spelling = try ContentAuditFiles.link(name, in: parent) + guard + spelling.utf8.elementsEqual(relativeLink.utf8) + || spelling.utf8.elementsEqual(destination.path.utf8) + else { throw ContentAuditProblem.outsideScope } + var admittedRepository: String? + if skill.mode == .edit { + guard let source = ledger.sources[resource.source]?.location, + let declaredRoot = ContentAuditProfile.relative( + try source.resolve(roots: roots), to: profile.root), + !profile.excludes(declaredRoot), + declaredRoot == "." || target.utf8.elementsEqual(declaredRoot.utf8) + || target.utf8.starts(with: (declaredRoot + "/").utf8) + else { throw ContentAuditProblem.outsideScope } + admittedRepository = declaredRoot + } + let entry = target + "/SKILL.md" + record(entry) + guard let targetDirectory = try tree.open(target, admittedRepository: admittedRepository) else { + throw CoreError.notFound("retained skill prompt") + } + let bytes = try ContentAuditFiles.readPrompt( + "SKILL.md", in: targetDirectory, maximumBytes: Self.maximumFileBytes) + guard try ContentAuditFiles.link(name, in: parent).utf8.elementsEqual(spelling.utf8) else { + throw CoreError.invalidState("skill link changed during content audit") + } + return bytes + } + + private mutating func verifyHash( + _ bytes: Data, path: String, whole: [LedgerDeployment], skill: ContentAuditClaims.Skill? + ) { + guard checkRecordedContent else { return } + if !whole.isEmpty || skill?.expectedEntryHash != nil { + let actual = "sha256:" + FileHash.sha256Hex(data: bytes) + if whole.contains(where: { $0.expectedHash != actual }) + || skill?.expectedEntryHash.map({ $0 != actual }) == true + { + findings.append(Self.diagnostic(path, .contentDrift, ownership: .managedFile)) + } + } + } + + private mutating func verifyText( + _ bytes: Data, path: String, regional: [LedgerDeployment] + ) throws -> Range? { + guard let record = regional.first(where: { $0.ownership == .importBlock }) else { return nil } + guard let block = try InstructionTargets.auditImportBlock(bytes) else { + if checkRecordedContent { + findings.append(Self.diagnostic(path, .contentDrift, ownership: .managedRegion)) + } + return nil + } + if checkRecordedContent + && record.expectedHash != "sha256:" + FileHash.sha256Hex(data: block.normalized) + { + findings.append(Self.diagnostic(path, .contentDrift, ownership: .managedRegion)) + } + return block.byteRange + } + + private mutating func inspectNative( + _ bytes: Data, source: String, path: String, format: NativePromptAudit.Format, + ownership: ContentAuditOwnership, authorities: [LedgerNativeOwnedRegion] + ) throws { + let readback: NativePromptAudit.Readback + do { + readback = try NativePromptAudit.read(bytes, format: format, authorities: authorities) + } catch NativePromptAudit.Failure.unsupported(let offset, let field) { + let coordinate = offset.flatMap { ContentAuditUnicode.coordinates(in: source, at: [$0])[$0] } + issue(path, .unsupportedContent, ownership: ownership, field: field, coordinate: coordinate) + return + } catch { + issue(path, .unsupportedContent, ownership: ownership) + return + } + if !readback.ownershipVerified { + issue(path, .ownershipUnavailable, ownership: ownership) + } else if readback.fields.isEmpty { + targets[Data(path.utf8)] = .init(path: path, ownership: ownership, status: .skipped) + } + let sourceBytes = Array(bytes) + var mapped: [(NativePromptAudit.Field, [ContentAuditScalar], [Int: Int])] = [] + var total = 0 + for field in readback.fields { + let symbols = try ContentAuditUnicode.scan(field.text, leadingBOM: false) + guard !symbols.isEmpty else { continue } + total += symbols.count + guard total <= ContentAuditUnicode.maximumFindings else { + throw ContentAuditProblem.unsupportedContent + } + let offsets = + field.sourceRange.map { + ContentAuditSourceMap.offsets( + in: sourceBytes, range: $0, decoded: field.text, toml: format.isTOML, + requested: Set(symbols.map(\.byteRange.lowerBound))) + } ?? [:] + mapped.append((field, symbols, offsets)) + } + let coordinates = ContentAuditUnicode.coordinates( + in: source, at: mapped.flatMap { $0.2.values }) + for (field, symbols, offsets) in mapped { + for symbol in symbols { + let fieldOwnership: ContentAuditOwnership = + ownership == .managedFile + ? .managedFile + : field.managed + ? .managedRegion + : (!readback.ownershipVerified || ledger == nil) ? .unknown : .untracked + append( + symbol, path: path, field: field.pointer, + coordinate: offsets[symbol.byteRange.lowerBound].flatMap { coordinates[$0] }, + ownership: fieldOwnership) + } + } + } + + private mutating func append( + _ symbol: ContentAuditScalar, path: String, field: String?, + coordinate: (line: Int, column: Int)?, ownership: ContentAuditOwnership + ) { + guard !exhausted else { return } + if findings.count >= Self.maximumReportFindings { + exhausted = true + issue(path, .unsupportedContent, ownership: ownership) + return + } + findings.append( + .init( + severity: symbol.severity, reason: symbol.reason, + location: .init( + path: path, field: field, line: coordinate?.line, column: coordinate?.column, + promptLine: field == nil ? nil : symbol.line, + promptColumn: field == nil ? nil : symbol.column), + ownership: ownership, codePoint: symbol.codePoint)) + } +} + +private struct ContentAuditClaims { + struct Skill { + let resourceID: String + let mode: InstallMode + let expectedEntryHash: String? + } + + var files: [Data: [LedgerDeployment]] = [:] + var skills: [Data: Skill] = [:] + var regions: [Data: [LedgerNativeOwnedRegion]] = [:] + + init(profile: ContentAuditProfile, store: StateStore, ledger: ResolvedLedger?) { + guard let ledger else { return } + var lowerings: [String: LockedLowering] = [:] + for lowering in ledger.lowerings { + for deployment in lowering.deployments { lowerings[deployment] = lowering } + } + for deployment in ledger.deployments { + guard let url = try? store.contentAuditLocation(deployment.target), + let path = ContentAuditProfile.relative(url, to: profile.root), + !profile.excludes(path) + else { continue } + if deployment.route == "agents/skill@1" { + let entry = path + "/SKILL.md" + guard profile.format(at: entry) == .text, + let lowering = lowerings[deployment.id], + let mode = lowering.layout.object?["mode"]?.text.flatMap(InstallMode.init(rawValue:)), + let resourceID = lowering.resources.first + ?? deployment.owners.first + .flatMap({ ledger.components[$0]?.resources.first }), + let resource = ledger.resources[resourceID] + else { continue } + skills[Data(entry.utf8)] = .init( + resourceID: resourceID, mode: mode, + expectedEntryHash: mode == .edit + ? nil + : resource.entries + .first(where: { $0.path == "SKILL.md" && $0.kind == .file })?.object) + } else if profile.explicitFormat(at: path) != nil { + files[Data(path.utf8), default: []].append(deployment) + } + } + for record in ledger.nativeAuthorities ?? [] { + guard let url = try? store.contentAuditLocation(record.target), + let path = ContentAuditProfile.relative(url, to: profile.root), + !profile.excludes(path), + case .native? = profile.format(at: path) + else { continue } + regions[Data(path.utf8), default: []].append(contentsOf: record.regions) + } + } +} diff --git a/Sources/AgentsUpdates/ContentAuditReport.swift b/Sources/AgentsUpdates/ContentAuditReport.swift new file mode 100644 index 0000000..8263b76 --- /dev/null +++ b/Sources/AgentsUpdates/ContentAuditReport.swift @@ -0,0 +1,190 @@ +import Foundation + +public enum ContentAuditSeverity: String, Codable, Sendable { + case critical, warning, info +} + +public enum ContentAuditOwnership: String, Codable, Sendable { + case managedFile, managedRegion, untracked, unknown +} + +public enum ContentAuditReason: String, CaseIterable, Codable, Sendable { + case tagCharacter, bidiControl, supplementaryVariationSelector + case zeroWidthCharacter, variationSelector, bidiMark, invisibleOperator + case annotationMarker, deprecatedFormatting, softHyphen, interiorBOM + case unusualWhitespace, emojiPresentation, contextualJoiner, emojiTagSequence + case unreadable, unsupportedContent, outsideScope, pendingRecovery, ownershipUnavailable, + contentDrift + + public var message: String { + switch self { + case .tagCharacter: "Invisible Unicode tag character." + case .bidiControl: "Bidirectional embedding, override, or isolate control." + case .supplementaryVariationSelector: "Supplementary Unicode variation selector." + case .zeroWidthCharacter: "Zero-width space or joiner without a recognized context." + case .variationSelector: "Invisible variation selector." + case .bidiMark: "Invisible bidirectional text mark." + case .invisibleOperator: "Invisible mathematical operator." + case .annotationMarker: "Interlinear annotation marker." + case .deprecatedFormatting: "Deprecated bidirectional formatting control." + case .softHyphen: "Conditional soft hyphen." + case .interiorBOM: "Byte order mark inside prompt content." + case .unusualWhitespace: "Non-breaking or unusual whitespace." + case .emojiPresentation: "Text or emoji presentation selector." + case .contextualJoiner: "Join control in a recognized text or emoji sequence." + case .emojiTagSequence: "Standard emoji flag tag sequence." + case .unreadable: "An admitted prompt or discovery location could not be read." + case .unsupportedContent: "The prompt format, syntax, or structure could not be inspected." + case .outsideScope: "The prompt is outside the selected filesystem scope." + case .pendingRecovery: "Scope recovery is pending." + case .ownershipUnavailable: "Recorded prompt ownership could not be verified." + case .contentDrift: "The managed prompt content differs from its recorded hash." + } + } +} + +public struct ContentAuditLocation: Codable, Equatable, Sendable { + /// Relative to the selected project or home, with '/' separators. + public let path: String + /// RFC 6901 pointer for a structured field. + public let field: String? + /// One-based source coordinates in UTF-16 code units. A field with no source + /// mapping has only its pointer and decoded prompt coordinates. + public let line: Int? + public let column: Int? + public let promptLine: Int? + public let promptColumn: Int? +} + +public struct ContentAuditFinding: Codable, Equatable, Sendable { + public let severity: ContentAuditSeverity + public let reason: ContentAuditReason + public let location: ContentAuditLocation + public let ownership: ContentAuditOwnership + public let codePoint: UInt32? + public var message: String { + guard let codePoint else { return reason.message } + return "U+" + String(format: "%04X", codePoint) + " " + reason.message + } +} + +public struct ContentAuditTarget: Codable, Equatable, Sendable { + public enum Status: String, Codable, Sendable { case scanned, skipped, incomplete } + public let path: String + public let ownership: ContentAuditOwnership + public let status: Status +} + +public enum ContentAuditReportFormat: Sendable { + case json, sarif, markdown +} + +public struct ContentAuditReport: Encodable, Sendable { + public let targets: [ContentAuditTarget] + public let findings: [ContentAuditFinding] + /// Scope-relative diagnostic locations are exported. Absolute inputs are available + /// separately to a local consumer that refreshes its inspection when files change. + public let readLocations: [URL] + + public var passesCI: Bool { !findings.contains { $0.severity == .critical } } + public var ciExitCode: Int32 { passesCI ? 0 : 1 } + public var scanExitCode: Int32 { + if !passesCI { return 1 } + return findings.contains { $0.severity == .warning } ? 2 : 0 + } + + private enum CodingKeys: String, CodingKey { case targets, findings, passesCI, ciExitCode } + + public func encode(to encoder: any Encoder) throws { + var values = encoder.container(keyedBy: CodingKeys.self) + try values.encode(targets, forKey: .targets) + try values.encode(findings, forKey: .findings) + try values.encode(passesCI, forKey: .passesCI) + try values.encode(ciExitCode, forKey: .ciExitCode) + } + + public func export(_ format: ContentAuditReportFormat) throws -> Data { + switch format { + case .json: + let encoder = JSONEncoder() + encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes] + return try encoder.encode(self) + case .sarif: return try sarif() + case .markdown: return Data(markdown().utf8) + } + } + + private func sarif() throws -> Data { + let results: [[String: Any]] = findings.map { finding in + let location = finding.location + var physical: [String: Any] = [ + "artifactLocation": ["uri": Self.relativeURI(location.path)] + ] + if let line = location.line, let column = location.column { + physical["region"] = ["startLine": line, "startColumn": column] + } + var properties: [String: Any] = ["ownership": finding.ownership.rawValue] + if let field = location.field { properties["field"] = field } + if let line = location.promptLine { properties["promptLine"] = line } + if let column = location.promptColumn { properties["promptColumn"] = column } + let level: String = + switch finding.severity { + case .critical: "error" + case .warning: "warning" + case .info: "note" + } + return [ + "ruleId": finding.reason.rawValue, "level": level, + "message": ["text": finding.message], "properties": properties, + "locations": [["physicalLocation": physical]], + ] + } + let rules = Set(findings.map(\.reason)).sorted { $0.rawValue < $1.rawValue }.map { + ["id": $0.rawValue, "shortDescription": ["text": $0.message]] as [String: Any] + } + return try JSONSerialization.data( + withJSONObject: [ + "$schema": + "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/sarif-2.1/schema/sarif-schema-2.1.0.json", + "version": "2.1.0", + "runs": [ + [ + "tool": ["driver": ["name": "Agents Content Audit", "rules": rules]], + "columnKind": "utf16CodeUnits", "results": results, + ] + ], + ], options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]) + } + + private func markdown() -> String { + let counts = Dictionary(grouping: targets, by: \.status).mapValues(\.count) + var lines = [ + "# Content audit", "", passesCI ? "CI gate passed." : "CI gate failed.", + "\(counts[.scanned, default: 0]) scanned, \(counts[.skipped, default: 0]) skipped, \(counts[.incomplete, default: 0]) incomplete.", + ] + if !findings.isEmpty { lines.append("") } + for finding in findings { + let location = finding.location + var coordinate = Self.relativeURI(location.path) + if let line = location.line, let column = location.column { + coordinate += ":\(line):\(column)" + } + if let field = location.field { + coordinate += " at " + Self.relativeURI(field) + if let line = location.promptLine, let column = location.promptColumn { + coordinate += " (decoded \(line):\(column))" + } + } + lines.append( + "- **\(finding.severity.rawValue)** `\(coordinate)` (\(finding.ownership.rawValue)) — \(finding.message)" + ) + } + return lines.joined(separator: "\n") + "\n" + } + + private static func relativeURI(_ value: String) -> String { + let allowed = CharacterSet( + charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~/") + return value.addingPercentEncoding(withAllowedCharacters: allowed) ?? "." + } +} diff --git a/Sources/AgentsUpdates/ContentAuditSourceMap.swift b/Sources/AgentsUpdates/ContentAuditSourceMap.swift new file mode 100644 index 0000000..fff5d99 --- /dev/null +++ b/Sources/AgentsUpdates/ContentAuditSourceMap.swift @@ -0,0 +1,101 @@ +import Foundation + +/// Maps a parser-validated literal to its source spelling. The decoded value is +/// authoritative. An unfamiliar spelling falls back to the decoded coordinates. +enum ContentAuditSourceMap { + static func offsets( + in bytes: [UInt8], range: Range, decoded: String, toml: Bool, requested: Set + ) -> [Int: Int] { + guard !requested.isEmpty, range.lowerBound >= 0, range.upperBound <= bytes.count, + range.count >= 2 + else { return [:] } + let quote = bytes[range.lowerBound] + guard quote == 34 || (toml && quote == 39) else { return [:] } + let multiline = + toml && range.count >= 6 + && bytes[range.lowerBound.. Int? { + guard start < end, bytes[start] == 92 else { return nil } + var next = start + 1 + while next < end && (bytes[next] == 32 || bytes[next] == 9) { next += 1 } + guard next < end, bytes[next] == 10 || bytes[next] == 13 else { return nil } + while next < end && [9, 10, 13, 32].contains(bytes[next]) { next += 1 } + return next + } + + private static func escaped( + _ bytes: [UInt8], from start: Int, end: Int, toml: Bool + ) -> (UInt32, Int)? { + guard start + 1 < end else { return nil } + let symbol = bytes[start + 1] + switch symbol { + case 34, 47, 92: return (UInt32(symbol), start + 2) + case 98: return (8, start + 2) + case 101: return (27, start + 2) + case 102: return (12, start + 2) + case 110: return (10, start + 2) + case 114: return (13, start + 2) + case 116: return (9, start + 2) + case 117, 85, 120: + let width = symbol == 117 ? 4 : symbol == 85 ? 8 : 2 + let firstEnd = start + 2 + width + guard firstEnd <= end, + let first = UInt32(String(decoding: bytes[start + 2.. + public let codePoint: UInt32 + public let reason: ContentAuditReason + public let severity: ContentAuditSeverity + public let line: Int + public let column: Int +} + +public struct ContentAuditStripPreview: Sendable { + public let file: URL + public let originalBytes: Data + public let replacementBytes: Data + public let edits: [ContentAuditStripEdit] + fileprivate let identity: ContentAuditFiles.FileIdentity + fileprivate let profile: ContentAuditProfile + +} + +extension ContentAuditOperations { + /// Prepare exact deletions from one explicitly selected regular UTF-8 prompt file. + /// The caller presents the preview and makes the separate decision to apply it. + public static func previewStrip( + file: URL, scope: InstallScope = .project, + environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> ContentAuditStripPreview { + let profile = ContentAuditProfile( + scope: scope, environment: environment, agents: Set(AgentID.allCases)) + let (admitted, parent) = try stripPath(file, profile: profile) + let (original, identity) = try ContentAuditFiles.readEditable( + admitted.lastPathComponent, in: parent, maximumBytes: ContentAuditInspection.maximumFileBytes) + guard let text = String(validating: original, as: UTF8.self), + !text.unicodeScalars.contains("\0") + else { throw ContentAuditStripError.unsupportedFile } + let symbols = try ContentAuditUnicode.scan(text, leadingBOM: true) + let edits = symbols.filter { $0.severity != .info }.map { + ContentAuditStripEdit( + bytes: $0.byteRange, codePoint: $0.codePoint, reason: $0.reason, severity: $0.severity, + line: $0.line, column: $0.column) + } + var replacement = Data() + replacement.reserveCapacity(original.count) + var offset = original.startIndex + for edit in edits { + replacement.append(original[offset.. (URL, DirectoryHandle) + { + guard let path = ContentAuditProfile.relative(file, to: profile.root), path != "." else { + throw ContentAuditStripError.outsideScope + } + guard !profile.excludes(path), profile.explicitFormat(at: path) == .text else { + throw ContentAuditStripError.unsupportedFile + } + let tree = try ContentAuditTree(profile: profile) + guard let (parent, name) = try tree.parent(of: path), + try ContentAuditFiles.kind(name, in: parent) == .regular + else { throw ContentAuditStripError.unsupportedFile } + return (profile.root.appendingPathComponent(path).standardizedFileURL, parent) + } +} diff --git a/Sources/AgentsUpdates/ContentAuditUnicode.swift b/Sources/AgentsUpdates/ContentAuditUnicode.swift new file mode 100644 index 0000000..6bbd9a5 --- /dev/null +++ b/Sources/AgentsUpdates/ContentAuditUnicode.swift @@ -0,0 +1,163 @@ +import Foundation + +struct ContentAuditScalar { + let codePoint: UInt32 + let reason: ContentAuditReason + let severity: ContentAuditSeverity + let byteRange: Range + let line: Int + let column: Int +} + +enum ContentAuditUnicode { + // Keeping diagnostics bounded also keeps a reviewed edit from silently omitting bytes. + static let maximumFindings = 16_384 + + static func scan(_ text: String, leadingBOM: Bool) throws -> [ContentAuditScalar] { + var findings: [ContentAuditScalar] = [] + var bytes = 0 + var cursor = Coordinates() + var previous: Unicode.Scalar? + let contextualZWNJ = joiningOffsets(in: text) + var utf16Offset = 0 + for character in text { + let cluster = character.unicodeScalars + let emojiTag = isStandardFlag(cluster) + for index in cluster.indices { + let scalar = cluster[index] + let length = scalar.utf8.count + let nextIndex = cluster.index(after: index) + let next = nextIndex == cluster.endIndex ? nil : cluster[nextIndex] + let position = cursor.position(for: scalar) + if let (reason, severity) = classify( + scalar, previous: previous, next: next, cluster: cluster, emojiTag: emojiTag, + leadingBOM: leadingBOM && bytes == 0, + joiningContext: contextualZWNJ.contains(utf16Offset)) + { + guard findings.count < maximumFindings else { + throw ContentAuditProblem.unsupportedContent + } + findings.append( + .init( + codePoint: scalar.value, reason: reason, severity: severity, + byteRange: bytes.. 0xffff ? 2 : 1 + bytes += length + previous = scalar + } + } + return findings + } + + static func coordinates( + in text: String, at offsets: [Int] + ) -> [Int: (line: Int, column: Int)] { + let ordered = Set(offsets).sorted() + var positions: [Int: (Int, Int)] = [:] + var index = 0 + var byte = 0 + var cursor = Coordinates() + for scalar in text.unicodeScalars { + guard index < ordered.count else { break } + let position = cursor.position(for: scalar) + if byte == ordered[index] { + positions[byte] = position + index += 1 + } + byte += scalar.utf8.count + } + if index < ordered.count, byte == ordered[index] { + positions[byte] = (cursor.line, cursor.column) + } + return positions + } + + private struct Coordinates { + var line = 1 + var column = 1 + var afterCR = false + + mutating func position(for scalar: Unicode.Scalar) -> (line: Int, column: Int) { + let current = (line, column) + if scalar == "\r" || scalar == "\n" { + if scalar == "\r" || !afterCR { line += 1 } + column = 1 + } else { + column += scalar.value > 0xffff ? 2 : 1 + } + afterCR = scalar == "\r" + return current + } + } + + private static func classify( + _ scalar: Unicode.Scalar, previous: Unicode.Scalar?, next: Unicode.Scalar?, + cluster: Character.UnicodeScalarView, emojiTag: Bool, leadingBOM: Bool, joiningContext: Bool + ) -> (ContentAuditReason, ContentAuditSeverity)? { + switch scalar.value { + case 0xe0001...0xe007f: + return emojiTag ? (.emojiTagSequence, .info) : (.tagCharacter, .critical) + case 0x202a...0x202e, 0x2066...0x2069: return (.bidiControl, .critical) + case 0xe0100...0xe01ef: return (.supplementaryVariationSelector, .critical) + case 0x200c, 0x200d: + let virama = previous?.properties.canonicalCombiningClass.rawValue == 9 + let emojiJoin = scalar.value == 0x200d && isEmojiJoin(previous, next, cluster: cluster) + if virama || emojiJoin || joiningContext { return (.contextualJoiner, .info) } + return (.zeroWidthCharacter, .warning) + case 0x200b: return (.zeroWidthCharacter, .warning) + case 0xfe0e where previous?.properties.isEmoji == true, 0xfe0f: + return (.emojiPresentation, .info) + case 0xfe00...0xfe0e: return (.variationSelector, .warning) + case 0x061c, 0x200e, 0x200f: return (.bidiMark, .warning) + case 0x2061...0x2064: return (.invisibleOperator, .warning) + case 0xfff9...0xfffb: return (.annotationMarker, .warning) + case 0x206a...0x206f: return (.deprecatedFormatting, .warning) + case 0x00ad: return (.softHyphen, .warning) + case 0xfeff: return leadingBOM ? nil : (.interiorBOM, .warning) + case 0x0085, 0x00a0, 0x1680, 0x2000...0x200a, 0x2028, 0x2029, 0x202f, 0x205f, 0x3000: + return (.unusualWhitespace, .info) + default: return nil + } + } + + private static func isStandardFlag(_ cluster: Character.UnicodeScalarView) -> Bool { + guard cluster.first?.value == 0x1f3f4, cluster.last?.value == 0xe007f, + cluster.count == 7 + else { return false } + let region = cluster.dropFirst().dropLast().map(\.value) + return region == [0xe0067, 0xe0062, 0xe0065, 0xe006e, 0xe0067] + || region == [0xe0067, 0xe0062, 0xe0073, 0xe0063, 0xe0074] + || region == [0xe0067, 0xe0062, 0xe0077, 0xe006c, 0xe0073] + } + + private static let joiningPattern = try? NSRegularExpression( + pattern: + #"(?=[\p{Joining_Type=Left_Joining}\p{Joining_Type=Dual_Joining}]\p{Joining_Type=Transparent}*(\u200C)\p{Joining_Type=Transparent}*[\p{Joining_Type=Right_Joining}\p{Joining_Type=Dual_Joining}])"# + ) + + private static func joiningOffsets(in text: String) -> Set { + guard text.unicodeScalars.contains("\u{200c}"), let joiningPattern else { return [] } + return Set( + joiningPattern.matches(in: text, range: NSRange(text.startIndex..., in: text)).map { + $0.range(at: 1).location + }) + } + + private static func isEmojiJoin( + _ previous: Unicode.Scalar?, _ next: Unicode.Scalar?, cluster: Character.UnicodeScalarView + ) -> Bool { + guard let previous, let next, next.value >= 0x00a9, next.properties.isEmoji else { + return false + } + if previous.value >= 0x00a9, previous.properties.isEmoji { return true } + if previous.value == 0xfe0f { + return cluster.first.map { $0.value >= 0x00a9 && $0.properties.isEmoji } ?? false + } + return false + } +} + +enum ContentAuditProblem: Error { + case unsupportedContent, outsideScope, unrelatedRepository +} diff --git a/Sources/AgentsUpdates/ExistingGlobalConfiguration.swift b/Sources/AgentsUpdates/ExistingGlobalConfiguration.swift new file mode 100644 index 0000000..74641df --- /dev/null +++ b/Sources/AgentsUpdates/ExistingGlobalConfiguration.swift @@ -0,0 +1,336 @@ +import AgentsCore +import AgentsManifest +import Components +import Foundation + +/// A read-only preview of the global configuration to apply. +public struct ExistingGlobalConfigurationPreview: Sendable { + /// The number of declared source aliases. + public let sourceCount: Int + /// The number of distinct skills in the saved installation records. + public let skillCount: Int + /// Existing managed skill installations, counting shared physical paths once. + public let installationCount: Int + /// Locked instruction sections, including the sections selected by each named prompt. + public let instructionCount: Int + /// The YAML declaration to be created on confirmation. + public let declarationURL: URL + /// The resolved ledger to write on confirmation. + public let ledgerURL: URL + /// The new file that will contain the exact bytes of the original lock. + public let originalLedgerURL: URL + + fileprivate let store: StateStore + fileprivate let declaration: Data + fileprivate let ledger: Data + fileprivate let originalLedger: Data + fileprivate let evidence: ConfigurationImportEvidence + + fileprivate init( + store: StateStore, declaration: Data, ledger: Data, originalLedger: Data, + sourceCount: Int, skillCount: Int, installationCount: Int, instructionCount: Int, + evidence: ConfigurationImportEvidence + ) { + self.store = store + self.declaration = declaration + self.ledger = ledger + self.originalLedger = originalLedger + self.sourceCount = sourceCount + self.skillCount = skillCount + self.installationCount = installationCount + self.instructionCount = instructionCount + self.evidence = evidence + declarationURL = store.declarationURL + ledgerURL = store.resolvedURL + originalLedgerURL = store.directory.appendingPathComponent(StateStore.originalLedgerFileName) + } +} + +public enum ExistingGlobalConfigurationError: LocalizedError, Equatable, Sendable { + case unavailable + case stalePreview(String) + case conflict(String) + case recovery(String) + + public var errorDescription: String? { + switch self { + case .unavailable: + "Use Existing Configuration requires agents.json and its associated agents.resolved in a scope without agents.yaml." + case .stalePreview(let detail): + "The global configuration changed after the preview. Preview it again. \(detail)" + case .conflict(let detail): + "There is a conflict in the existing global configuration. \(detail)" + case .recovery(let detail): + detail + } + } +} + +public enum ExistingGlobalConfiguration { + /// Checks whether a global configuration is available to import using its state files. + public static func isAvailable(environment: RuntimeEnvironment) throws -> Bool { + let store = StateStore(scope: .user, environment: environment) + return try withImportErrors { + try store.withReadLock(onPendingRecovery: { throw pendingOperation(in: store) }) { + try importableLedger(in: store) != nil + } + } + } + + public static func preview(environment: RuntimeEnvironment) throws + -> ExistingGlobalConfigurationPreview + { + let store = StateStore(scope: .user, environment: environment) + return try withImportErrors { + try store.withReadLock(onPendingRecovery: { throw pendingOperation(in: store) }) { + guard let bytes = try importableLedger(in: store) else { + throw ExistingGlobalConfigurationError.unavailable + } + let files = try configurationInputs(in: store) + guard files.yaml.bytes == nil, files.ledger.bytes == bytes, + let json = files.configurationJSON.bytes + else { + throw ExistingGlobalConfigurationError.stalePreview( + "The configuration files changed during inspection.") + } + guard files.originalLedger.bytes == nil else { + throw ExistingGlobalConfigurationError.conflict( + "A saved ledger copy already exists at \(files.originalLedger.evidence.url.path). " + + "Move that copy to a safe location before previewing again.") + } + try LedgerAdmission.check(json, limits: .standard) + let declaration = try StateStore.decode(json, as: ExistingGlobalConfigurationJSON.self) + .declaration(environment: environment) + let saved = try StateStore.decode(bytes, as: ResolvedState.self) + try saved.validate() + _ = try store.readWatch() + let yaml = + try DeclarationEditPlan.bytes( + replacing: Declaration(), with: declaration, in: nil, + identity: DocumentIdentity(store.declarationURL.path), environment: environment) + ?? Array("version: 1\n".utf8) + var conversion = ImportedConfigurationLedger( + store: store, declaration: declaration, saved: saved) + let candidate = try conversion.convert() + let encoded = try ResolvedLedgerCodec.encode(candidate, limits: .standard) + let evidence = ConfigurationImportEvidence( + yaml: files.yaml.evidence, ledger: files.ledger.evidence, + originalLedger: files.originalLedger.evidence, + untouched: [files.configurationJSON.evidence, files.watch.evidence] + + conversion.evidence.values.sorted { $0.url.path < $1.url.path }, + installationAuthorities: SkillInstallationTarget.distinctAuthorities( + conversion.installations), + editSources: conversion.editSources.values.sorted { + $0.directory.path < $1.directory.path + }, + offlinePins: conversion.offlinePins, store: store) + try evidence.validate(excludingTargets: []) + return ExistingGlobalConfigurationPreview( + store: store, declaration: Data(yaml), ledger: encoded, originalLedger: bytes, + sourceCount: declaration.sourceDeclarations.count, skillCount: saved.skills.count, + installationCount: conversion.installed.count, + instructionCount: saved.instructions.sections.count + + saved.instructions.chatgpt.values.reduce(0) { $0 + $1.sections.count }, + evidence: evidence) + } + } + } + + /// Publishes only the captured state files. Preview a changed scope again before confirming. + public static func apply(_ preview: ExistingGlobalConfigurationPreview) throws { + try apply(preview, checkpoint: { _ in }) + } + + package static func apply( + _ preview: ExistingGlobalConfigurationPreview, checkpoint: @escaping (String) throws -> Void + ) throws { + try withImportErrors { + let store = preview.store + let outcome = TransactionOutcome() + try store.withConfigurationImportLock( + checkpoint: checkpoint, + beforeCreatingLock: { try preview.evidence.validateFiles() } + ) { + try preview.evidence.validate(excludingTargets: []) + let transaction = FileTransaction(store: store, outcome: outcome, checkpoint: checkpoint) + transaction.requireUnchanged(since: preview.evidence) + try transaction.replace( + preview.originalLedgerURL, with: .data(preview.originalLedger), + expecting: preview.evidence.originalLedger) + try transaction.replace( + preview.declarationURL, with: .data(preview.declaration), + expecting: preview.evidence.yaml) + try transaction.replace( + preview.ledgerURL, with: .data(preview.ledger), + expecting: preview.evidence.ledger) + do { + try transaction.commit() + } catch { + if outcome.recoveryPending { + throw ExistingGlobalConfigurationError.recovery( + FileTransaction.recoveryDiagnostic(store: store).message) + } + if outcome.terminal != .committed { throw error } + } + } + } + } + + private static func importableLedger(in store: StateStore) throws -> Data? { + struct Version: Decodable { let version: Int } + guard try !store.stateEntryExists(StateStore.declarationFileName), + try store.stateEntryExists(StateStore.configurationJSONFileName), + let ledger = try store.configurationInputBytes(StateStore.resolvedFileName) + else { return nil } + try LedgerAdmission.check(ledger, limits: .standard) + return try JSONDecoder().decode(Version.self, from: ledger).version == 1 ? ledger : nil + } + + private static func pendingOperation(in store: StateStore) -> ExistingGlobalConfigurationError { + .recovery( + "A configuration operation is pending at \(store.directory.path). " + + "Finish it in the tool that started it, then preview again.") + } + + private typealias StateInput = (bytes: Data?, evidence: TargetPrecondition) + + private static func configurationInputs(in store: StateStore) throws -> ( + configurationJSON: StateInput, yaml: StateInput, ledger: StateInput, originalLedger: StateInput, + watch: StateInput + ) { + try ( + TargetPrecondition.readingFile( + store.directory.appendingPathComponent(StateStore.configurationJSONFileName)), + TargetPrecondition.readingFile(store.declarationURL), + TargetPrecondition.readingFile(store.resolvedURL), + TargetPrecondition.readingFile( + store.directory.appendingPathComponent(StateStore.originalLedgerFileName)), + TargetPrecondition.readingFile(store.watchURL) + ) + } + + private static func withImportErrors(_ operation: () throws -> T) throws -> T { + do { + return try operation() + } catch let error as ExistingGlobalConfigurationError { + throw error + } catch let error as CoreError { + switch error { + case .recoveryPending(let detail): + throw ExistingGlobalConfigurationError.recovery(detail) + case .transactionRecovered: + throw ExistingGlobalConfigurationError.recovery(error.description) + default: + throw ExistingGlobalConfigurationError.conflict(error.description) + } + } catch is CancellationError { + throw CancellationError() + } catch { + throw ExistingGlobalConfigurationError.conflict(String(describing: error)) + } + } +} + +struct ConfigurationImportEvidence: PreparedEvidence, Sendable { + let yaml: TargetPrecondition + let ledger: TargetPrecondition + let originalLedger: TargetPrecondition + let untouched: [TargetPrecondition] + let installationAuthorities: [SkillInstallationTarget] + let editSources: [EditSourceEvidence] + let offlinePins: [OfflinePin] + let store: StateStore + + func validateFiles(excludingTargets targets: Set = []) throws { + for installation in installationAuthorities { + do { try installation.validateAuthority() } catch { + throw ExistingGlobalConfigurationError.stalePreview(installation.url.path) + } + } + for file in [yaml, ledger, originalLedger] + untouched where !targets.contains(file.url.path) { + do { try file.validate() } catch { + throw ExistingGlobalConfigurationError.stalePreview(file.url.path) + } + } + for source in editSources { + do { try source.validate() } catch { + throw ExistingGlobalConfigurationError.stalePreview(source.directory.path) + } + } + } + + func validate(excludingTargets targets: Set) throws { + try validateFiles(excludingTargets: targets) + // Cached resources are covered by file evidence. An exact Git object can disappear + // independently of the scope, even though its content cannot mutate. + for pin in offlinePins { + do { + try SourceCache(store: store).withOfflineSnapshot( + sourceID: pin.identity, source: pin.source, revision: pin.revision + ) { _, _ in () } + } catch { + throw ExistingGlobalConfigurationError.stalePreview( + "Git commit \(pin.revision) for \(pin.identity).") + } + } + } + + struct OfflinePin: Equatable, Sendable { + let identity: String + let source: LockedSource + let revision: String + } +} + +/// A live edit source supplies preview metadata and a content digest. Its directory is +/// read in place. Transaction preimages cover the managed link and the small state files. +struct EditSourceEvidence: Sendable { + let directory: URL + let hash: String + private let authoredURL: URL + private let authoredIdentity: PathIdentity + private let directoryIdentity: PathIdentity + private let linkedMetadata: (url: URL, identity: PathIdentity, hash: String)? + + init(authoredURL: URL, directory: URL, metadata: URL) throws { + self.authoredURL = authoredURL + self.directory = directory + authoredIdentity = try PathIdentity(authoredURL) + directoryIdentity = try PathIdentity(directory) + // The tree digest records a symlink's destination spelling. Metadata parsing also + // depends on the bytes at that destination when SKILL.md is itself a link. + if metadata.path == directory.appendingPathComponent("SKILL.md").path { + linkedMetadata = nil + } else { + linkedMetadata = try (metadata, PathIdentity(metadata), FileHash.sha256Hex(file: metadata)) + } + hash = try "sha256:" + FileHash.folderHash(directory) + try validateIdentity() + } + + func validate() throws { + try validateIdentity() + guard try "sha256:" + FileHash.folderHash(directory) == hash else { + throw ExistingGlobalConfigurationError.stalePreview(directory.path) + } + if let linkedMetadata, try FileHash.sha256Hex(file: linkedMetadata.url) != linkedMetadata.hash { + throw ExistingGlobalConfigurationError.stalePreview(linkedMetadata.url.path) + } + try validateIdentity() + } + + private func validateIdentity() throws { + try authoredIdentity.validate() + try directoryIdentity.validate() + guard authoredURL.resolvingSymlinksInPath() == directory else { + throw ExistingGlobalConfigurationError.stalePreview(authoredURL.path) + } + if let linkedMetadata { + try linkedMetadata.identity.validate() + guard + directory.appendingPathComponent("SKILL.md").resolvingSymlinksInPath() + == linkedMetadata.url + else { throw ExistingGlobalConfigurationError.stalePreview(linkedMetadata.url.path) } + } + } +} diff --git a/Sources/AgentsUpdates/ExistingGlobalConfigurationJSON.swift b/Sources/AgentsUpdates/ExistingGlobalConfigurationJSON.swift new file mode 100644 index 0000000..37a6272 --- /dev/null +++ b/Sources/AgentsUpdates/ExistingGlobalConfigurationJSON.swift @@ -0,0 +1,159 @@ +import AgentsCore +import Foundation + +/// The declaration wire format read from agents.json. +struct ExistingGlobalConfigurationJSON: Codable { + let agents: [AgentID]? + let sources: [String: Source]? + let skills: [String: Skill]? + let instructions: InstructionSelection? + let watch: [String]? + + func declaration(environment: RuntimeEnvironment) throws -> Declaration { + let sources = (sources ?? [:]).mapValues { $0.declaration(environment: environment) } + // Installation records name a source by normalized identity, with one discovery root + // per identity in agents.json and agents.resolved. + var aliases: [String: String] = [:] + for alias in sources.keys.sorted() { + let identity = try sources[alias]!.identity(environment: environment) + if let existing = aliases.updateValue(alias, forKey: identity) { + throw CoreError.invalidState( + "Source aliases '\(existing)' and '\(alias)' in agents.json identify the same source. " + + "Use one alias per source and reconcile its selections before previewing again.") + } + } + let declaration = Declaration( + agents: agents, sources: sources, skills: skills?.mapValues(\.declaration), + instructions: instructions?.declaration, watch: watch) + try declaration.validate(environment: environment) + if let instructions = try declaration.instructions { + let sections = + instructions.sectionReferences + + instructions.prompts.flatMap { $0.prompt.sectionReferences } + guard sections.allSatisfy({ $0.source != nil && $0.source != "." }) else { + throw CoreError.invalidState("global instruction selections need a named source") + } + } + return declaration + } + + struct Source: Codable { + private enum CodingKeys: String, CodingKey { + case git, local, path + case wellKnown = "well-known" + } + + let kind: SourceKind + let location: String + let requirement: SourceRequirement? + let path: String? + + init(from decoder: any Decoder) throws { + let fields = try decoder.container(keyedBy: CodingKeys.self) + let kinds: [(CodingKeys, SourceKind)] = [ + (.git, .git), (.local, .local), (.wellKnown, .wellKnown), + ] + let present = kinds.filter { fields.contains($0.0) } + guard present.count == 1, let (key, kind) = present.first else { + throw CoreError.invalidState("a source in agents.json must specify one location") + } + self.kind = kind + location = try fields.decode(String.self, forKey: key) + path = try fields.decodeIfPresent(String.self, forKey: .path) + requirement = try SourceRequirement.decodeIfPresent(from: decoder) + } + + func encode(to encoder: any Encoder) throws { + var fields = encoder.container(keyedBy: CodingKeys.self) + try fields.encode( + location, forKey: kind == .git ? .git : kind == .local ? .local : .wellKnown) + try fields.encodeIfPresent(path, forKey: .path) + try requirement?.encode(to: encoder) + } + + func declaration(environment: RuntimeEnvironment) -> SourceDeclaration { + var source = SourceDeclaration( + kind: kind, location: location, requirement: requirement, path: path) + if kind == .local, !location.hasPrefix("/"), location != "~", !location.hasPrefix("~/") { + source.location = source.localURL(environment: environment).path + } + return source + } + } + + struct Skill: Codable { + let select: Selection + let exclude: [String]? + let agents: [AgentID]? + let mode: InstallMode? + let overrides: [String: Override]? + + private enum CodingKeys: String, CodingKey { case select, exclude, agents, mode, overrides } + private enum UnsupportedKeys: String, CodingKey { case path } + + init(from decoder: any Decoder) throws { + let unsupported = try decoder.container(keyedBy: UnsupportedKeys.self) + if unsupported.contains(.path) { + let alias = decoder.codingPath.last?.stringValue ?? "unknown" + throw CoreError.invalidState( + "skills.\(alias).path is unsupported in agents.json. " + + "Set the discovery path on sources.\(alias).path before previewing again.") + } + let fields = try decoder.container(keyedBy: CodingKeys.self) + select = try fields.decode(Selection.self, forKey: .select) + exclude = try fields.decodeIfPresent([String].self, forKey: .exclude) + agents = try fields.decodeIfPresent([AgentID].self, forKey: .agents) + mode = try fields.decodeIfPresent(InstallMode.self, forKey: .mode) + overrides = try fields.decodeIfPresent([String: Override].self, forKey: .overrides) + } + + var declaration: SkillDeclaration { + .init( + select: select.value, exclude: exclude, agents: agents, mode: mode, + overrides: overrides?.mapValues { .init(agents: $0.agents, mode: $0.mode) }) + } + } + + struct Override: Codable { + let agents: [AgentID]? + let mode: InstallMode? + } + + struct Selection: Codable { + let value: SkillSelection + + init(from decoder: any Decoder) throws { + let field = try decoder.singleValueContainer() + if (try? field.decode(String.self)) == "all" { + value = .all + } else { + value = .names(try field.decode([String].self)) + } + } + + func encode(to encoder: any Encoder) throws { + var field = encoder.singleValueContainer() + switch value { + case .all: try field.encode("all") + case .names(let names): try field.encode(names) + } + } + } + + struct InstructionSelection: Codable { + let agents: [AgentID]? + let sections: [String] + let chatgpt: [String: Prompt]? + + var declaration: InstructionsDeclaration { + .init( + agents: agents, sections: sections, + chatgpt: chatgpt?.mapValues { .init(sections: $0.sections, append: $0.append) }) + } + } + + struct Prompt: Codable { + let sections: [String] + let append: String? + } +} diff --git a/Sources/AgentsUpdates/ImportedConfigurationLedger.swift b/Sources/AgentsUpdates/ImportedConfigurationLedger.swift new file mode 100644 index 0000000..64e41dc --- /dev/null +++ b/Sources/AgentsUpdates/ImportedConfigurationLedger.swift @@ -0,0 +1,460 @@ +import AgentsCore +import AgentsInstructions +import AgentsSkills +import Components +import Foundation + +/// Builds the resolved ledger from saved installation records and independently pinned sources. +struct ImportedConfigurationLedger { + let store: StateStore + let declaration: Declaration + let saved: ResolvedState + var ledger = ResolvedLedger() + var evidence: [URL: TargetPrecondition] = [:] + var installations: [SkillInstallationTarget] = [] + var editSources: [URL: EditSourceEvidence] = [:] + var offlinePins: [ConfigurationImportEvidence.OfflinePin] = [] + var installed = Set() + private var skillTargets: [String: InstallMode] = [:] + private var declaringSource = "" + private var objectBytes = 0 + + private var cache: SourceCache { SourceCache(store: store) } + + init(store: StateStore, declaration: Declaration, saved: ResolvedState) { + self.store = store + self.declaration = declaration + self.saved = saved + } + + mutating func convert() throws -> ResolvedLedger { + let root = LedgerSource( + kind: .local, location: .init(kind: .registered, root: "state", path: "."), revision: "live") + declaringSource = try ResolvedLedgerCodec.digest(root) + ledger.sources[declaringSource] = root + for name in saved.skills.keys.sorted() { + try Task.checkCancellation() + try addSkill(name, locked: saved.skills[name]!) + } + try addInstructions() + if ledger.occurrences.isEmpty { ledger.sources.removeValue(forKey: declaringSource) } + let roots = store.ledgerRoots(recordedIn: ledger) + return try LedgerReplay.withPreparedLowerings( + ledger, store: store, roots: roots, limits: .standard, offline: true + ) { prepared, outputs, _, _ in + let rendered = Dictionary(uniqueKeysWithValues: outputs.map { ($0.name, $0) }) + for deployment in prepared.deployments + where InstructionLocations.isInstructionFormat(deployment.route) { + guard let bytes = rendered[deployment.id]?.bytes, + Instructions.hash(bytes) == deployment.expectedHash + else { + throw ExistingGlobalConfigurationError.conflict( + "The pinned sections do not reproduce \(deployment.id). Restore the pinned " + + "sources and reconcile the recorded instruction target before previewing again.") + } + } + var expected = saved.normalized + let sourceIDs = Set( + saved.skills.values.map(\.source) + saved.instructions.sections.map(\.source) + + saved.instructions.chatgpt.values.flatMap { $0.sections.map(\.source) }) + expected.sources = expected.sources.filter { sourceIDs.contains($0.key) } + for id in expected.sources.keys { + let path = try PathSafety.sanitizeSubpath(expected.sources[id]?.path ?? ".") + expected.sources[id]?.path = path == "." ? nil : path + } + guard try prepared.domainProjection(roots: roots).normalized == expected else { + throw ExistingGlobalConfigurationError.conflict( + "The selected configuration cannot represent the recorded items or targets. " + + "Reconcile agents.json and agents.resolved before previewing again.") + } + return prepared + } + } + + private mutating func addSkill(_ name: String, locked: LockedSkill) throws { + let source = saved.sources[locked.source]! + let path = try PathSafety.sanitizeSubpath(locked.path ?? ".") + let edit = locked.installs.values.contains(.edit) + let sourceID = try addSource( + locked.source, revision: locked.revision ?? locked.artifact?.digest ?? "live", + version: locked.version) + var resource: LedgerResource + let metadata: Skill + let linkDestination: URL + if edit { + let root = URL(fileURLWithPath: String(locked.source.dropFirst("local:".count))) + let item = try contained(path, in: root) + let physical = item.resolvingSymlinksInPath() + var directory: ObjCBool = false + guard FileManager.default.fileExists(atPath: physical.path, isDirectory: &directory), + directory.boolValue + else { + throw unavailable("live skill \(name)", at: item.path) + } + let metadataFile = try contained( + path == "." ? "SKILL.md" : path + "/SKILL.md", in: root) + let edit = try EditSourceEvidence( + authoredURL: item, directory: physical, metadata: metadataFile.resolvingSymlinksInPath()) + editSources[item] = edit + metadata = try SkillOperations.lockedMetadata(at: physical, installedName: name) + resource = .init( + kind: .liveEdit, source: sourceID, path: path, + hash: edit.hash, entries: [], + location: .init(kind: .absolute, path: item.path)) + linkDestination = item + } else if let artifact = locked.artifact { + let item = try cache.artifactContentURL(digest: artifact.digest) + guard try remember(item).exists else { + throw unavailable("skill \(name)", at: item.path) + } + resource = try capture( + item, path: path, source: sourceID, expectedHash: locked.hash!, + root: item, artifact: artifact) + resource.location = try SourceCache.artifactContentLocation(digest: artifact.digest) + metadata = try SkillOperations.lockedMetadata(at: item, installedName: name) + linkDestination = item + } else { + let revision = locked.revision! + (resource, metadata) = try withPin(locked.source, source: source, revision: revision) { + conversion, root, durable in + let item = try conversion.contained(path, in: root) + let captured = try conversion.capture( + item, path: path, source: sourceID, expectedHash: locked.hash!, root: root) + if durable { try conversion.remember(captured, at: item, in: root) } + return (captured, try SkillOperations.lockedMetadata(at: item, installedName: name)) + } + linkDestination = try PathSafety.resolvedChild( + base: cache.materializedURL(sourceID: locked.source, revision: revision), subpath: path) + } + let resourceID = try storeResource(resource) + let modes = Dictionary(grouping: locked.installs.keys.sorted(), by: { locked.installs[$0]! }) + for mode in modes.keys.sorted(by: { $0.rawValue < $1.rawValue }) { + let agents = try modes[mode]!.map { raw in + guard let agent = AgentID(rawValue: raw), agent.supportsSkills else { + throw ExistingGlobalConfigurationError.conflict( + "Skill \(name) has an unsupported recipient \(raw).") + } + return agent + } + let occurrence = ledger.occurrences.count + let owner = try addComponent( + kind: .skills, name: name, source: sourceID, + revision: locked.revision, version: locked.version, + payload: [ + "name": .init(metadata.name), "description": .init(metadata.description), + "mode": .init(mode.rawValue), "native": .init(object: [:]), + ], agents: agents, prompt: nil, resource: resourceID) + for agent in agents { + let target = try store.skillInstallationTarget(for: agent, named: name) + try inspectSkill(target.url, mode: mode, resource: resource, link: linkDestination) + installations.append(target) + let id = "skill:\(occurrence):\(agent.rawValue)" + addLowering( + id: id, format: "agents/skill@1", owners: [owner], resources: [resourceID], + target: .init( + id: id, target: .init(kind: .registered, root: "skills-" + agent.rawValue, path: name), + route: "agents/skill@1", owners: [owner], recipients: [agent], ownership: .generated, + expectedHash: resource.hash, created: false, headingOffset: 0), + layout: ["name": .init(id), "mode": .init(mode.rawValue)]) + } + } + } + + private mutating func inspectSkill( + _ target: URL, mode: InstallMode, resource: LedgerResource, link: URL + ) throws { + let physical = InstructionLocations.physical(target) + if let previous = skillTargets.updateValue(mode, forKey: physical.path), previous != mode { + throw ExistingGlobalConfigurationError.conflict( + "Conflicting installation modes share \(target.path).") + } + guard try remember(target).exists else { return } + if mode == .copy { + let attributes = try FileManager.default.attributesOfItem(atPath: target.path) + let flags = Dictionary( + uniqueKeysWithValues: resource.entries.filter { $0.kind == .file }.map { + ($0.path, $0.executable) + }) + guard attributes[.type] as? FileAttributeType == .typeDirectory, + try "sha256:" + FileHash.folderHash(target) == resource.hash, + try FileHash.executableFlags(target) == flags + else { throw modifiedSkill(target) } + } else { + guard PathSafety.matchesSymbolicLink(at: target, destination: link) + else { throw modifiedSkill(target) } + if !FileManager.default.fileExists(atPath: target.path) { return } + } + installed.insert(physical.path) + } + + private func modifiedSkill(_ target: URL) -> ExistingGlobalConfigurationError { + .conflict( + "The skill at \(target.path) differs from its installation record. Restore the recorded " + + "contents or move the changed entry aside before previewing again.") + } + + private mutating func addInstructions() throws { + let instructions = saved.instructions + let recipients = Set(instructions.targets.values.flatMap(\.agents)) + let declared = try declaration.instructions + let agents = + (recipients.isEmpty ? Set(declared?.agents ?? declaration.defaultAgents) : recipients) + .sorted { $0.rawValue < $1.rawValue } + guard instructions.sections.isEmpty || !agents.isEmpty else { + throw ExistingGlobalConfigurationError.conflict( + "Saved instruction sections have no recipients. Reconcile the instruction selection " + + "in agents.json before previewing again.") + } + var owners: [String] = [] + for section in instructions.sections { + owners.append(try addSection(section, agents: agents)) + } + let resources = owners.map { ledger.components[$0]!.resources[0] } + for key in instructions.targets.keys.sorted() { + let target = instructions.targets[key]! + let file = try InstructionLocations.file(for: key, store: store) + let agents = target.agents.sorted { $0.rawValue < $1.rawValue } + let locations = agents.compactMap { + InstructionLocations.file(for: $0, scope: .user, environment: store.environment) + } + guard !owners.isEmpty, let agent = agents.first, Set(agents).count == agents.count, + locations.count == agents.count, + locations.allSatisfy({ InstructionLocations.physical($0) == file }) + else { + throw ExistingGlobalConfigurationError.conflict( + "The agent home settings do not resolve to the recorded target \(key). " + + "Check those settings before previewing again.") + } + let input = try TargetPrecondition.readingFile(locations[0]) + evidence[locations[0]] = input.evidence + for location in locations.dropFirst() { try remember(location) } + guard locations.allSatisfy({ InstructionLocations.physical($0) == file }) else { + throw ExistingGlobalConfigurationError.stalePreview(file.path) + } + let id = "instructions:" + key + let format: String + var layout: [String: LedgerValue] = ["name": .init(id)] + if let reference = target.import { + guard agents == [.claudeCode], + let path = ClaudeInstructionPath(rawValue: file.lastPathComponent), + reference == String(path.importLine.dropFirst()), + try input.bytes == nil + || InstructionTargets.ownedImportBytes(input.bytes).map(Instructions.hash) + == target.blockHash + else { + throw ExistingGlobalConfigurationError.conflict( + "The forwarding block at \(file.path) differs from the recorded block. " + + "Restore the recorded block before previewing again.") + } + format = "agents/claude-import@1" + } else { + format = "agents/instructions@1" + layout["headingOffset"] = .init(integer: 0) + } + addLowering( + id: id, format: format, owners: owners, resources: target.import == nil ? resources : [], + target: .init( + id: id, + target: .init( + kind: .registered, root: "instructions-" + agent.rawValue, path: file.lastPathComponent), + route: format, owners: owners, recipients: agents, + ownership: target.import == nil ? .generated : .importBlock, + expectedHash: target.blockHash, + created: target.created, importReference: target.import, + headingOffset: target.headingOffset), + layout: layout) + } + for name in instructions.chatgpt.keys.sorted() { + let prompt = instructions.chatgpt[name]! + guard !prompt.sections.isEmpty else { + throw ExistingGlobalConfigurationError.conflict( + "Locked ChatGPT prompt \(name) has no sections.") + } + var inputs: [String] = [] + for section in prompt.sections { + inputs.append(try addSection(section, agents: [], prompt: name, append: prompt.append)) + } + let id = "prompt:" + name + addLowering( + id: id, format: "agents/chatgpt@1", owners: inputs, + resources: inputs.map { ledger.components[$0]!.resources[0] }, target: nil, + layout: ["name": .init(id), "sectionCount": .init(integer: inputs.count)]) + } + } + + private mutating func addSection( + _ section: LockedSection, agents: [AgentID], prompt: String? = nil, append: String? = nil + ) throws -> String { + guard let source = saved.sources[section.source], let revision = section.revision else { + throw ExistingGlobalConfigurationError.conflict( + "Locked section \(section.name) requires a named Git source and an exact commit.") + } + let path = try PathSafety.sanitizeSubpath(section.path) + let sourceID = try addSource(section.source, revision: revision, version: section.version) + let resource = try withPin(section.source, source: source, revision: revision) { + conversion, root, durable in + let file = try conversion.contained(path, in: root) + let resource = try conversion.capture( + file, path: path, source: sourceID, expectedHash: section.hash, root: root) + if durable { try conversion.remember(resource, at: file, in: root) } + return resource + } + var payload: [String: LedgerValue] = [ + "name": .init(section.name), "sourceHash": .init(section.hash), "native": .init(object: [:]), + ] + payload["prompt"] = prompt.map { .init($0) } + if let append { + let location = LedgerLocation( + kind: .registered, root: "home", path: try PathSafety.sanitizeSubpath(append)) + payload["localAppend"] = location.ledgerValue + } + let resourceID = try storeResource(resource) + return try addComponent( + kind: .instructions, name: section.name, source: sourceID, + revision: revision, version: section.version, payload: payload, + agents: agents, prompt: prompt, resource: resourceID) + } + + private mutating func withPin( + _ identity: String, source: LockedSource, revision: String, + _ body: (inout Self, URL, Bool) throws -> T + ) throws -> T { + let sourceCache = cache + do { + return try sourceCache.withOfflineSnapshot( + sourceID: identity, source: source, revision: revision + ) { root, durable in + if !durable { + let materialized = sourceCache.materializedURL(sourceID: identity, revision: revision) + guard try !remember(materialized).exists else { + throw ExistingGlobalConfigurationError.stalePreview(materialized.path) + } + let pin = ConfigurationImportEvidence.OfflinePin( + identity: identity, source: source, revision: revision) + if !offlinePins.contains(pin) { offlinePins.append(pin) } + } + return try body(&self, root, durable) + } + } catch CoreError.notFound(let item) { + throw ExistingGlobalConfigurationError.conflict( + "Cannot read \(item) at locked commit \(revision) for \(identity). " + + "Restore the original cached content or the exact commit in the local source before retrying." + ) + } + } + + private func contained(_ path: String, in root: URL) throws -> URL { + let file = try PathSafety.resolvedChild(base: root, subpath: path) + guard PathSafety.isContained(file.resolvingSymlinksInPath(), in: root.resolvingSymlinksInPath()) + else { throw CoreError.unsafePath("locked resource escapes \(root.path)") } + return file + } + + private mutating func capture( + _ file: URL, path: String, source: String, expectedHash: String, root: URL, + artifact: LockedArtifact? = nil + ) throws -> LedgerResource { + let captured = try LedgerResources.capture( + file, embed: artifact != nil, limits: .standard, sourceRoot: root) + guard captured.hash == expectedHash else { + throw ExistingGlobalConfigurationError.conflict( + "Pinned content differs from the saved contents at \(path). Restore the matching " + + "cached content before previewing again.") + } + for (key, bytes) in captured.objects where ledger.contentObjects[key] == nil { + guard bytes.count <= LedgerLimits.standard.objectBytes - objectBytes else { + throw CoreError.invalidState("ledger aggregate content budget") + } + ledger.contentObjects[key] = bytes + objectBytes += bytes.count + } + return .init( + kind: artifact == nil ? .git : .artifact, source: source, path: path, + hash: expectedHash, entries: captured.entries, support: captured.support, artifact: artifact) + } + + @discardableResult + private mutating func remember(_ file: URL) throws -> TargetPrecondition { + if let existing = evidence[file] { return existing } + let item = try TargetPrecondition(file) + evidence[file] = item + return item + } + + private mutating func remember(_ resource: LedgerResource, at file: URL, in root: URL) throws { + try remember(file) + for entry in resource.support where entry.kind != .directory { + try remember(try contained(entry.path, in: root)) + } + } + + private func unavailable(_ name: String, at path: String) -> ExistingGlobalConfigurationError { + .conflict( + "The source for \(name) is missing at \(path). Restore the source or its cached contents " + + "and preview again.") + } + + private mutating func addSource(_ identity: String, revision: String, version: String?) throws + -> String + { + let locked = saved.sources[identity]! + let location: LedgerLocation? = + locked.kind == .local + ? .init(kind: .absolute, path: String(identity.dropFirst("local:".count))) : nil + let source = LedgerSource( + kind: locked.kind, transport: locked.kind == .wellKnown ? identity : locked.url, + location: location, revision: revision, version: version) + let id = try ResolvedLedgerCodec.digest(source) + if ledger.sources.updateValue(source, forKey: id) == nil { + ledger.sourceUses.append( + .init( + source: id, root: try PathSafety.sanitizeSubpath(locked.path ?? "."), + requirement: locked.requirement?.canonical)) + } + return id + } + + private mutating func storeResource(_ resource: LedgerResource) throws -> String { + let id = try ResolvedLedgerCodec.digest(resource) + ledger.resources[id] = resource + return id + } + + private mutating func addComponent( + kind: DeclaredComponentKind, name: String, source: String, + revision: String?, version: String?, payload: [String: LedgerValue], + agents: [AgentID], prompt: String?, resource: String + ) throws -> String { + let condition = LedgerCondition(DeclarationCondition()) + let component = LedgerComponent( + declaringSource: declaringSource, source: source, root: ".", + kind: kind.rawValue, name: name, revision: revision, version: version, + payload: .init(object: payload), conditions: [condition], recipients: agents, + chatGPT: prompt != nil, resources: [resource]) + let id = try ResolvedLedgerCodec.digest(component) + ledger.components[id] = component + ledger.occurrences.append( + .init( + declaringSource: declaringSource, manifestPath: StateStore.declarationFileName, + id: ledger.occurrences.count, component: id, dependencies: [source], + condition: condition, recipients: agents, consumerEditable: true)) + return id + } + + private mutating func addLowering( + id: String, format: String, owners: [String], resources: [String], + target: LedgerDeployment?, layout: [String: LedgerValue] + ) { + #if os(macOS) + let platform = DeclarationPlatform.macOS + #else + let platform = DeclarationPlatform.linux + #endif + if let target { ledger.deployments.append(target) } + ledger.lowerings.append( + .init( + id: id, format: format, inputs: owners, resources: resources, + deployments: target.map { [$0.id] } ?? [], layout: .init(object: layout), + platform: platform.rawValue, artifacts: [])) + } +} diff --git a/Sources/AgentsUpdates/InitializationOperations.swift b/Sources/AgentsUpdates/InitializationOperations.swift new file mode 100644 index 0000000..6cc74f8 --- /dev/null +++ b/Sources/AgentsUpdates/InitializationOperations.swift @@ -0,0 +1,96 @@ +import AgentsCore +import AgentsInstructions +import AgentsSkills +import Foundation + +/// A pure local authoring request. Its existing root identity is retained through publication. +public struct InitializationDescription: Sendable { + public enum Kind: String, Sendable { case skill, instructions } + public let kind: Kind + public let file: URL + public let template: String + public let existingRoot: URL + public let readLocations: [URL] + private enum Request: Sendable { + case skill(SkillInitialization) + case instructions(InstructionInitialization) + } + private let request: Request + let store: StateStore + + init(skill: SkillInitialization) { + kind = .skill + request = .skill(skill) + store = skill.store + file = skill.file + existingRoot = skill.root.directory + template = String(decoding: skill.template, as: UTF8.self) + readLocations = [existingRoot, file, store.declarationURL, store.resolvedURL, store.watchURL] + } + + init(instructions: InstructionInitialization) { + kind = .instructions + request = .instructions(instructions) + store = instructions.store + file = instructions.file + existingRoot = instructions.root.directory + template = String(decoding: instructions.template, as: UTF8.self) + readLocations = [existingRoot, file, store.declarationURL, store.resolvedURL, store.watchURL] + } + + func apply(outcome: TransactionOutcome, checkpoint: @escaping (String) throws -> Void) throws + -> URL + { + switch request { + case .skill(let skill): return try skill.apply(outcome: outcome, checkpoint: checkpoint) + case .instructions(let instructions): + return try instructions.apply(outcome: outcome, checkpoint: checkpoint) + } + } +} + +extension UpdateOperations { + public static func describeInstructionsInitialization( + named name: String, environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> InitializationDescription { + .init(instructions: try InstructionInitialization(named: name, environment: environment)) + } + + /// Creates in a registered project, which must already exist even during description. + public static func describeProjectSkillInitialization( + named name: String? = nil, environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> InitializationDescription { + .init( + skill: try SkillInitialization( + named: name, directory: environment.projectDirectory, environment: environment, + requiresExistingDirectory: true)) + } + + /// Explicit standalone authoring. The selected directory may be absent when its immediate parent already exists. + public static func describeSkillInitialization( + named name: String? = nil, directory: URL, + environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> InitializationDescription { + .init( + skill: try SkillInitialization(named: name, directory: directory, environment: environment)) + } + + /// Returns after all executing resources are released, including on retained journal recovery. + public static func initialize(_ description: InitializationDescription) -> UpdateCompletion { + initialize(description, checkpoint: { _ in }) + } + + package static func initialize( + _ description: InitializationDescription, checkpoint: @escaping (String) throws -> Void + ) -> UpdateCompletion { + let outcome = TransactionOutcome() + var recovered = false + let result = Result { + do { return try description.apply(outcome: outcome, checkpoint: checkpoint) } catch { + if case CoreError.transactionRecovered = error { recovered = true } + throw error + } + } + return completion(result, outcome: outcome, recovered: recovered, store: description.store) + } +} diff --git a/Sources/AgentsUpdates/InstructionOperations.swift b/Sources/AgentsUpdates/InstructionOperations.swift new file mode 100644 index 0000000..b439acb --- /dev/null +++ b/Sources/AgentsUpdates/InstructionOperations.swift @@ -0,0 +1,336 @@ +import AgentsCore +import AgentsInstructions +import AgentsManifest +import Components +import Foundation + +struct InstructionAddition: Sendable { + let source: String + let units: [InstructionUnit] + let alias: String? + let agents: [AgentID]? +} + +extension InstructionOperations { + /// Compiles the saved instruction outputs under read locks without preparing publication. + public static func previewOutputs( + scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> CombinedUpdateReport { + try UpdateOperations.previewInstructionOutputs(scope: scope, environment: environment) + } + + public static func add( + _ options: InstructionAddOptions, beforeApply: ((InstructionUpdateReport) throws -> Void)? = nil + ) throws -> InstructionAddOutcome { + let store = StateStore(scope: options.scope, environment: options.environment) + let organization = try OrganizationPolicySnapshot(store: store) + try organization.admit() + let (digest, initial, available, id, alias) = try store.withReadLock { + let declaration = try store.readDeclaration() + let digest = try store.declarationDocument(prepared: nil)?.digest ?? "absent" + var next = declaration + let available: [InstructionUnit] + let id: String + let alias: String? + if options.source == "." { + available = try inspectOwn( + names: options.listOnly || options.all ? [] : options.names, + environment: options.environment) + id = "." + alias = nil + } else { + let argument = try SourceArgument(options.source) + guard argument.name == nil else { + throw CoreError.invalidSource("@skill: selects skills; pass section names separately") + } + let selection = try argument.selection( + in: declaration, requirement: options.sourceRequirement, path: options.path, + environment: options.environment) + var source = selection.applied(to: selection.source) + id = try source.identity(environment: options.environment) + let existing = try argument.existingAlias( + in: declaration, sourceID: id, path: source.path, environment: options.environment) + let name = options.alias ?? existing ?? declaration.derivedAlias(for: source.location) + if let prior = declaration.sources[name] { + let sameRoot = + try PathSafety.sanitizeSubpath(prior.path ?? ".") + == PathSafety.sanitizeSubpath(source.path ?? ".") + guard try prior.identity(environment: options.environment) == id, + sameRoot || argument.location == name + else { throw CoreError.invalidSource("source alias already refers to another source") } + source = selection.applied(to: prior) + if sameRoot { source.path = prior.path } + } + try organization.requireSource( + source, reference: options.alias ?? "instruction source", in: store) + available = try inspectSource(source, store: store) + next.sources[name] = source + alias = name + } + try organization.validate() + return (digest, next, available, id, alias) + } + if options.listOnly || (options.names.isEmpty && !options.all && available.count > 1) { + return InstructionAddOutcome(sourceID: id, available: available, result: nil) + } + let selected = + options.names.isEmpty + ? available + : try options.names.map { name in + guard let item = available.first(where: { $0.record.name == name }) else { + throw CoreError.notFound("instruction section: " + name) + } + return item + } + guard !selected.isEmpty else { throw CoreError.notFound("source provides no instructions") } + var request = UpdateRequest( + operation: .declaration(initial), kinds: [.instructions], replace: options.replace, + expectedDeclarationDigest: digest) + request.instructionAddition = InstructionAddition( + source: id == "." ? "local:" + store.environment.projectDirectory.path : id, + units: selected, alias: alias, agents: options.agents) + var delivered = false + do { + return try UpdateOperations.withDomainUpdate( + request, scope: options.scope, environment: options.environment + ) { prepared in + delivered = true + try beforeApply?(prepared.report.instructions) + return InstructionAddOutcome( + sourceID: id, available: available, result: try prepared.apply().report.instructions) + } + } catch let error as LinkError { + if !delivered, options.names.isEmpty, !options.all, + case .missing(let missing, _) = error, + missing == "instruction '\(selected[0].record.name)'" + { + throw CoreError.invalidState( + "automatic instruction selection changed during discovery; retry the command") + } + throw error + } + } + + static func addLocalRecipients( + _ addition: InstructionAddition, scope: InstallScope, platform: DeclarationPlatform, + groups: [LinkedComponent], to declaration: inout Declaration + ) -> (paths: Set, requested: Set) { + let defaults = declaration.defaultAgents + func canAppend(to selection: InstructionsDeclaration) -> Bool { + selection.condition == nil && selection.native.isEmpty + } + let appendable = declaration.components.compactMap { component -> InstructionsDeclaration? in + guard case .instructions(let selection) = component, canAppend(to: selection), + selection.sectionReferences.allSatisfy({ $0.condition == nil }) + else { return nil } + return selection + } + let inherited = + appendable.count == 1 && !defaults.contains(.antigravity) + && appendable[0].agents?.contains(.antigravity) != true ? appendable[0].agents : nil + let configured = addition.agents ?? inherited + let requestedAgents = configured ?? defaults + let requested = Set(requestedAgents) + var changedPaths = Set() + for unit in addition.units { + let reference = SectionDeclaration(name: unit.record.name, source: addition.alias) + let groupRoutes = groups.filter { $0.resources.first?.path == unit.record.path } + var missing = requested + for group in groupRoutes { missing.subtract(group.recipients) } + let hasInactiveGroup = groupRoutes.contains { component in + component.conditions.contains { !$0.matches(scope: scope, platform: platform) } + } + let scoped = DeclarationCondition(scopes: [scope], platforms: [platform]) + var assignments: [AgentID: [DeclarationCondition]] = [:] + var matches: [(component: Int, section: Int, condition: DeclarationCondition)] = [] + for (componentIndex, component) in declaration.components.enumerated() { + guard case .instructions(let selection) = component else { continue } + for (index, section) in selection.sectionReferences.enumerated() + where section.reference == reference.reference { + let condition = (selection.condition ?? DeclarationCondition()) + .intersecting(section.condition ?? DeclarationCondition()) + let agents = section.recipients?.compactMap(\.localAgent) ?? selection.agents ?? defaults + for agent in agents where condition.agents?.contains(agent) ?? true { + assignments[agent, default: []].append(condition) + } + missing.subtract( + condition.recipients( + requested: agents, scope: scope, platform: platform)) + matches.append((componentIndex, index, condition)) + } + } + for match in matches where !missing.isEmpty { + let allowed = match.condition.recipients( + requested: requestedAgents, scope: scope, platform: platform) + let additions = missing.intersection(allowed).filter { agent in + if hasInactiveGroup, match.condition.intersecting(scoped) != match.condition { + return false + } + return (assignments[agent] ?? []).allSatisfy { + let overlap = match.condition.intersecting($0) + return overlap.scopes?.isEmpty == true || overlap.platforms?.isEmpty == true + } + }.sorted { $0.rawValue < $1.rawValue } + guard !additions.isEmpty, + case .instructions(var selection) = declaration.components[match.component] + else { continue } + let existing = + selection.sectionReferences[match.section].recipients + ?? (selection.agents ?? defaults).map(InstructionRecipient.local) + selection.sectionReferences[match.section].recipients = + existing + additions.map(InstructionRecipient.local) + declaration.components[match.component] = .instructions(selection) + changedPaths.insert(unit.record.path) + missing.subtract(additions) + } + guard !missing.isEmpty || (requested.isEmpty && matches.isEmpty && groupRoutes.isEmpty) + else { continue } + changedPaths.insert(unit.record.path) + var fallback = reference + // A fallback for an already assigned agent must stay disjoint from its other routes. + if hasInactiveGroup || missing.contains(where: { assignments[$0] != nil }) { + fallback.condition = scoped + } + if let index = declaration.components.firstIndex(where: { component in + guard case .instructions(let selection) = component, canAppend(to: selection) else { + return false + } + return Set(selection.agents ?? defaults) == missing + }), case .instructions(var selection) = declaration.components[index] { + selection.sectionReferences.append(fallback) + declaration.components[index] = .instructions(selection) + } else { + let agents = + missing == requested ? configured : missing.sorted { $0.rawValue < $1.rawValue } + var selection = InstructionsDeclaration(agents: agents) + selection.sectionReferences = [fallback] + declaration.components.append(.instructions(selection)) + } + } + return (changedPaths, requested) + } + + public static func updateInstalled( + scope: InstallScope = .project, agents: [AgentID]? = nil, + environment: RuntimeEnvironment = RuntimeEnvironment(), apply: Bool = false, + replace: Bool = false, + beforeApply: ((InstructionUpdateReport) throws -> Void)? = nil + ) throws -> InstructionUpdateReport { + let request = try installedUpdateRequest( + scope: scope, agents: agents, environment: environment, replace: replace) + if !apply { + return try UpdateOperations.preview(request, scope: scope, environment: environment) + .instructions + } + return try UpdateOperations.withDomainUpdate(request, scope: scope, environment: environment) { + prepared in + try beforeApply?(prepared.report.instructions) + return try prepared.apply().report.instructions + } + } + + static func installedUpdateRequest( + scope: InstallScope, agents: [AgentID]?, environment: RuntimeEnvironment, replace: Bool + ) throws -> UpdateRequest { + var request = UpdateRequest(kinds: [.instructions], replace: replace) + if let agents { + var declaration = try StateStore(scope: scope, environment: environment).loadDeclaration() + declaration.components = declaration.components.map { component in + if case .instructions(var selection) = component { + selection.agents = agents + return .instructions(selection) + } + return component + } + request.operation = .declaration(declaration) + } + return request + } + + public static func installResolvedReport( + scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> InstructionUpdateReport { + try UpdateOperations.withDomainUpdate( + UpdateRequest(operation: .restore, kinds: [.instructions]), scope: scope, + environment: environment + ) { try $0.apply().report.instructions } + } + + @discardableResult + public static func remove( + names: [String], scope: InstallScope = .project, agents: [AgentID]? = nil, + environment: RuntimeEnvironment = RuntimeEnvironment(), + beforeApply: ((InstructionUpdateReport) throws -> Void)? = nil + ) throws -> InstructionUpdateReport { + try UpdateOperations.withDomainUpdate( + UpdateRequest(operation: .remove, kinds: [.instructions], names: names, agents: agents), + scope: scope, environment: environment + ) { prepared in + try beforeApply?(prepared.report.instructions) + return try prepared.apply().report.instructions + } + } +} + +extension InstructionOperations { + public static func renderChatGPT( + prompt name: String, scope: InstallScope = .project, + environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> Data { + try inspectChatGPTExport(prompt: name, scope: scope, environment: environment).bytes + } + + /// Locked ordered content plus the live consumer appendix, with the actual durable read inputs. + public static func inspectChatGPTExport( + prompt name: String, scope: InstallScope = .project, + environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> InstructionExportInspection { + let store = StateStore(scope: scope, environment: environment) + return try store.withReadLock { + let baseline = try StatePrecondition(store: store) + let declaration = try store.readDeclaration(prepared: baseline) + let ledger = try store.readLedger(prepared: baseline) + guard let lowering = ledger.lowerings.first(where: { $0.id == "prompt:" + name }) else { + throw InstructionError.emptyPrompt + } + return try LedgerReplay.withLockedResources( + ledger, store: store, roots: store.ledgerRoots, limits: .standard + ) { _, resources, _ in + let bytes = try LedgerReplay.exportPrompt( + lowering, ledger: ledger, resources: resources, roots: store.ledgerRoots) + let paths = try UpdateOperations.readLocations( + declarations: [declaration], ledgers: [ledger], store: store) + try baseline.validate() + return InstructionExportInspection(bytes: bytes, readLocations: paths) + } + } + } + + public static func inspectOwnInstructions( + environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> OwnInstructionsInspection { + let store = StateStore(scope: .project, environment: environment) + return try store.withReadLock { + let baseline = try StatePrecondition(store: store) + _ = try store.readDeclaration(prepared: baseline) + let paths = ownReadLocations(environment: environment) + let evidence = try paths.map(TargetPrecondition.init) + let units = try inspectOwn(names: [], environment: environment) + for input in evidence { try input.validate() } + try baseline.validate() + return OwnInstructionsInspection( + units: units, + readLocations: ownReadLocations(names: units.map(\.record.name), environment: environment)) + } + } +} + +public struct InstructionExportInspection: Sendable { + public let bytes: Data + public let readLocations: [URL] +} + +public struct OwnInstructionsInspection: Sendable { + public let units: [InstructionUnit] + public let readLocations: [URL] +} diff --git a/Sources/AgentsUpdates/InstructionOutputPreview.swift b/Sources/AgentsUpdates/InstructionOutputPreview.swift new file mode 100644 index 0000000..6d12136 --- /dev/null +++ b/Sources/AgentsUpdates/InstructionOutputPreview.swift @@ -0,0 +1,69 @@ +import AgentsCore +import AgentsInstructions +import AgentsManifest +import Components +import Foundation + +enum InstructionOutputPreview { + static func report( + _ complete: DeploymentConstruction.Result, previous: ResolvedLedger, store: StateStore, + baseline: StatePrecondition, roots: [String: URL], sourcePolicy: SourcePolicySnapshot, + organization: OrganizationInstallEvaluation, initialFindings: [OrganizationPolicyFinding], + acquisitions: GitAcquisitionCaptures + ) throws -> CombinedUpdateReport { + var prior = previous + prior.deployments.removeAll { !InstructionLocations.isInstructionFormat($0.route) } + prior.lowerings.removeAll { + !InstructionLocations.isInstructionFormat($0.format) && $0.format != "agents/chatgpt@1" + && $0.instructionCopyRecipient == nil + } + prior.nativeAuthorities = nil + prior.marketplacePackages = nil + prior.marketplaceGraph = nil + return try LedgerReplay.withPreparedLowerings( + complete.ledger, store: store, roots: roots, limits: .standard, + sourcePolicy: sourcePolicy.effective, + requireRecordedTransport: organization.evaluator.requiresRecordedGitOrigin, + acquisitions: acquisitions + ) { next, artifacts, resources, workspace in + let aggregation = try ArtifactAggregation( + ledger: next, previous: prior, artifacts: artifacts, resources: resources, + workspace: workspace, store: store, roots: roots, + replace: false, changingAccess: false, kinds: [.instructions], + sourcePolicy: sourcePolicy.effective) + let workspacePolicy = try OrganizationWorkspaceInspection( + evaluator: organization.evaluator, store: store, ledger: aggregation.ledger, + previous: previous, roots: roots, inspectDrift: false) + let policyReport = try organization.policy.report( + initialFindings + + organization.instructionPreviewClosure( + aggregation.ledger, previous: previous, roots: roots) + + workspacePolicy.findings) + try policyReport.requireAdmission() + let lockMissing = try baseline.bytes(for: store.resolvedURL) == nil + let report = try UpdateReporting.instructions( + before: prior.domainProjection(roots: roots).instructions, + after: aggregation.ledger.domainProjection(roots: roots).instructions, + changes: aggregation.changes, ledger: aggregation.ledger, artifacts: artifacts, + lockMissing: lockMissing, included: true, store: store, + stateChanged: prior.lowerings.flatMap(\.artifacts) != next.lowerings.flatMap(\.artifacts), + conflicts: aggregation.antigravityConflicts) + let locations = + try UpdateOperations.readLocations( + declarations: [], ledgers: [aggregation.ledger], store: store, roots: roots) + + complete.inputs.map(\.url) + aggregation.instructionDecisionLocations + + sourcePolicy.readDependencies.map(\.url) + + organization.policy.readDependencies.map(\.url) + try baseline.validate() + try sourcePolicy.validate() + try organization.policy.validate() + return CombinedUpdateReport( + scope: store.scope, skills: [], instructions: report, lockMissing: lockMissing, + hasChanges: report.hasChanges, displayedFingerprint: try ResolvedLedgerCodec.digest(report), + marketplaceChanges: nil, marketplaceGraphChange: nil, + organizationPolicy: policyReport.policies.isEmpty ? nil : policyReport, + archiveRepresentationChanges: nil, + readLocations: Array(Set(locations)).sorted { $0.path < $1.path }, components: []) + } + } +} diff --git a/Sources/AgentsUpdates/Lifecycle/LifecycleDiscovery.swift b/Sources/AgentsUpdates/Lifecycle/LifecycleDiscovery.swift new file mode 100644 index 0000000..259161b --- /dev/null +++ b/Sources/AgentsUpdates/Lifecycle/LifecycleDiscovery.swift @@ -0,0 +1,309 @@ +import AgentsCore +import AgentsManifest +import Foundation +import NativeDocuments + +public enum LifecycleOperations { + #if os(macOS) + static let administratorDirectory = URL(fileURLWithPath: "/private/etc/agents/lifecycle.d") + #else + static let administratorDirectory = URL(fileURLWithPath: "/etc/agents/lifecycle.d") + #endif + + // Tests supply an isolated path; production authority comes only from the system location. + @TaskLocal package static var administratorDirectoryForTesting: URL? + + public static func list( + scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment() + ) -> LifecycleInspection { + let context = LifecycleContext(scope: scope, environment: environment) + let discovery = context.discover() + let gate = LifecycleInvocation.policy( + context: context, offline: false, expected: nil, requireInstallPreview: false) + return context.inspection(discovery, policy: gate.withheld) + } + + public static func validate( + scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment() + ) -> [LifecycleDiagnostic] { + LifecycleContext(scope: scope, environment: environment).discover().diagnostics + } +} + +public struct LifecycleProjectIdentity: Codable, Equatable, Hashable, Sendable { + public let canonicalPath: String + let physicalIdentity: String + + init(_ directory: DirectoryHandle) throws { + canonicalPath = directory.lifecycleDirectoryURL.path + physicalIdentity = try directory.lifecycleIdentity + } + + var key: String { + // Separate the path and identity without relying on JSONEncoder's escaping. + FileHash.sha256Hex( + data: Data( + ("agents.lifecycle.root.v1\0" + canonicalPath + "\0" + + physicalIdentity).utf8)) + } + + public static func == (lhs: Self, rhs: Self) -> Bool { + lhs.canonicalPath.utf8.elementsEqual(rhs.canonicalPath.utf8) + && lhs.physicalIdentity == rhs.physicalIdentity + } + + public func hash(into hasher: inout Hasher) { hasher.combine(key) } +} + +struct LifecycleContext: Sendable { + let store: StateStore + let adminDirectory: URL + + init(scope: InstallScope, environment: RuntimeEnvironment) { + store = StateStore(scope: scope, environment: environment) + adminDirectory = + LifecycleOperations.administratorDirectoryForTesting + ?? LifecycleOperations.administratorDirectory + } + + var userStore: StateStore { .init(scope: .user, environment: store.environment) } + var disabled: Bool { + store.environment.environment["APM_NO_SCRIPTS"] == "1" + || ProcessInfo.processInfo.environment["APM_NO_SCRIPTS"] == "1" + } + + func openProject() throws -> DirectoryHandle { + try DirectoryHandle.readDirectory( + at: store.environment.projectDirectory.resolvingSymlinksInPath()) + } + + func openHome() throws -> DirectoryHandle? { + let home = store.environment.homeDirectory + if store.scope == .project { + let project = Array( + store.environment.projectDirectory.resolvingSymlinksInPath().path.utf8) + let user = Array(home.resolvingSymlinksInPath().path.utf8) + guard project != user, !user.starts(with: project + [47]), project != [47] else { + throw CoreError.unsafePath("User lifecycle state is inside the consuming project.") + } + } + return try DirectoryHandle.lifecycleDirectory(at: home, authority: .user) + } + + func discover() -> LifecycleDiscovery { + var result = LifecycleDiscovery() + let admin = LifecycleSource(authority: .administrator, file: adminDirectory) + do { + if let directory = try DirectoryHandle.lifecycleDirectory( + at: adminDirectory, authority: .administrator) + { + for name in try directory.names(maximumCount: 256) where name.hasSuffix(".json") { + let source = LifecycleSource( + authority: .administrator, file: adminDirectory.appendingPathComponent(name)) + do { + guard + let input = try directory.readLifecycleFile( + name, authority: .administrator, maximumBytes: 256 * 1024) + else { throw CoreError.invalidState("Administrator lifecycle file disappeared.") } + try result.addAdmin(input: input, source: source) + } catch { + result.reject(source, "Administrator lifecycle file could not be admitted or parsed.") + } + } + } + } catch { + result.reject(admin, "Administrator lifecycle directory could not be admitted or read.") + } + + let user = LifecycleSource(authority: .user, file: userStore.declarationURL) + do { + if let directory = try openHome()?.lifecycleChild(".agents", authority: .user) { + try result.addNative(directory: directory, source: user, authority: .user) + } + } catch { + result.reject(user, "User lifecycle source could not be admitted or read.") + } + + if store.scope == .project { + let source = LifecycleSource(authority: .project, file: store.declarationURL) + do { + let root = try openProject() + result.root = try LifecycleProjectIdentity(root) + if let directory = try root.lifecycleChild(".agent", authority: .project) { + try result.addNative(directory: directory, source: source, authority: .project) + } + } catch { + result.reject(source, "Project lifecycle source could not be admitted or read.") + } + } + return result + } + + func inspection( + _ discovery: LifecycleDiscovery, events: Set? = nil, + policy: LifecycleWithholding? = nil, + receipt observation: Result? = nil + ) -> LifecycleInspection { + let observation = observation ?? Result { try trustReceipt(discovery.root) } + let receipt = try? observation.get() + let trusted = discovery.projectDigest != nil && receipt?.digest == discovery.projectDigest + let all: LifecycleWithholding? = + disabled + ? .disabled + : discovery.administratorInvalid + ? .administratorSourceInvalid + : policy ?? (store.scope == .project && discovery.root == nil ? .projectChanged : nil) + let actions = discovery.actions.filter { events?.contains($0.value.event) ?? true } + return LifecycleInspection( + actions: actions.map { action in + let local: LifecycleWithholding? + if case .failure = observation { + local = .receiptUnavailable + } else { + local = trusted ? nil : .projectUntrusted + } + return action.summary(withheld: all ?? (action.source.authority == .project ? local : nil)) + }, diagnostics: discovery.diagnostics, project: discovery.root, projectTrusted: trusted, + allStartsWithheld: all) + } +} + +struct LifecycleDiscovery: Sendable { + var actions: [CapturedLifecycleAction] = [] + var diagnostics: [LifecycleDiagnostic] = [] + var root: LifecycleProjectIdentity? + var projectDeclaration: DeclarationValue? + var projectDigest: String? + var administratorInvalid = false + + mutating func reject(_ source: LifecycleSource, _ message: String, field: String? = nil) { + diagnostics.append( + .init(source: source, event: nil, index: nil, field: field, message: message)) + if source.authority == .administrator { administratorInvalid = true } + } + + mutating func addNative( + directory: DirectoryHandle, source: LifecycleSource, authority: LifecycleFileAuthority + ) throws { + guard + let input = try directory.readLifecycleFile( + StateStore.declarationFileName, authority: authority, maximumBytes: 2 * 1024 * 1024) + else { return } + let document: DeclarationDocument + do { + document = try DeclarationDocument( + bytes: Array(input.bytes), identity: DocumentIdentity(source.file.path)) + } catch let failure as ManifestFailure { + for diagnostic in failure.diagnostics { + if let issue = diagnostic.lifecycleIssue { + add(issue, source: source) + } else { + reject( + source, "Invalid manifest (\(diagnostic.code)) at line \(diagnostic.span.line).") + } + } + return + } + guard let declaration = document.declaration.lifecycle else { return } + let digest = try LifecycleDeclaration.digest(declaration) + if source.authority == .project { + projectDeclaration = declaration + projectDigest = digest + } + append( + LifecycleDeclaration(declaration), source: source, digest: digest, + provenance: nil) + } + + mutating func addAdmin(input: (bytes: Data, provenance: String), source: LifecycleSource) throws { + let budget = NativeDocumentBudget( + limits: .init( + storage: 16 * 1024 * 1024, work: 32 * 1024 * 1024, nodes: 20_000, depth: 16, + uninterruptedBytes: 256 * 1024)) + let doc = try NativeDocument(bytes: input.bytes, format: .json, budget: budget) + guard case .object(let root) = try doc.read(.init(keys: []))?.value else { + reject(source, "Expected an administrator lifecycle object.") + return + } + let initial = diagnostics.count + if root["version"] != .integer(1) { + reject(source, "Expected administrator lifecycle version 1.", field: "version") + } + for key in root.keys.sorted() where key != "version" && key != "scripts" { + reject(source, "Unknown administrator lifecycle field.", field: key) + } + guard let raw = root["scripts"] else { + reject(source, "Missing administrator scripts mapping.", field: "scripts") + return + } + let subtree = Self.declarationValue(raw) + let declaration = LifecycleDeclaration(subtree) + for issue in declaration.issues { add(issue, source: source) } + guard diagnostics.count == initial else { return } + append( + declaration, source: source, digest: try LifecycleDeclaration.digest(subtree), + provenance: input.provenance) + } + + private mutating func add(_ issue: LifecycleDeclarationIssue, source: LifecycleSource) { + diagnostics.append( + .init( + source: source, event: issue.event, index: issue.index, + field: issue.field.isEmpty ? nil : issue.field, message: issue.message)) + if source.authority == .administrator { administratorInvalid = true } + } + + private mutating func append( + _ declaration: LifecycleDeclaration, source: LifecycleSource, digest: String, + provenance: String? + ) { + for action in declaration.actions { + actions.append( + .init(source: source, value: action, digest: digest, provenance: provenance)) + } + } + + private static func declarationValue(_ value: NativeValue) -> DeclarationValue { + switch value { + case .object(let entries): .dictionary(entries.mapValues(declarationValue)) + case .array(let entries): .array(entries.map(declarationValue)) + case .string(let text): .string(text) + case .integer(let value): .integer(value) + case .boolean(let value): .boolean(value) + case .null, .decimal: .null + } + } +} + +struct CapturedLifecycleAction: Sendable { + let source: LifecycleSource + let value: DeclaredLifecycleAction + let digest: String + let provenance: String? + + func summary(withheld: LifecycleWithholding? = nil) -> LifecycleActionSummary { + let kind: LifecycleActionSummary.Kind + let target: String + switch value.body { + case .command(let field, _, _): + kind = .command + target = field == .bash ? "/bin/bash" : "/bin/sh" + case .http(let url, _, _): + kind = .http + var origin = URLComponents() + origin.scheme = "https" + origin.host = url.host + origin.port = url.port + target = origin.string ?? "https" + } + return .init( + source: source, event: value.event, index: value.index, kind: kind, target: target, + timeoutSeconds: value.timeout, withheld: withheld) + } + + func matches(_ current: CapturedLifecycleAction) -> Bool { + source == current.source && value.event == current.value.event + && value.index == current.value.index + && digest == current.digest && provenance == current.provenance + } +} diff --git a/Sources/AgentsUpdates/Lifecycle/LifecycleExecution.swift b/Sources/AgentsUpdates/Lifecycle/LifecycleExecution.swift new file mode 100644 index 0000000..60bfd82 --- /dev/null +++ b/Sources/AgentsUpdates/Lifecycle/LifecycleExecution.swift @@ -0,0 +1,341 @@ +import AgentsCore +import Foundation + +#if canImport(FoundationNetworking) + import FoundationNetworking +#endif +#if canImport(Security) + import Security +#endif + +struct LifecyclePayload: Encodable { + let version = 1 + let event: LifecycleEvent + let scope: InstallScope + let test: Bool +} + +enum LifecycleCommand { + static func spawn( + _ action: CapturedLifecycleAction, in directory: DirectoryHandle, + environment: RuntimeEnvironment + ) throws -> OwnedDuplexProcess { + guard case .command(let field, let script, let overrides) = action.value.body else { + throw CoreError.invalidState("Expected a lifecycle command.") + } + var child = environment.environment.merging(overrides) { _, authored in authored } + child["APM_NO_SCRIPTS"] = "1" + return try OwnedDuplexProcess( + .init( + executable: field == .bash ? "/bin/bash" : "/bin/sh", arguments: ["-c", script], + directory: directory.lifecycleDirectoryURL, environment: child), + workingDirectory: directory) + } + + static func finish( + _ process: OwnedDuplexProcess, action: LifecycleActionSummary, payload: Data + ) async -> LifecycleActionResult { + let deadline = ContinuousClock.now + .seconds(action.timeoutSeconds) + let outputLimit = 64 * 1024 + var stdout = 0 + var stderr = 0 + var offset = 0 + var outputEnded = false + var errorEnded = false + var disposition = LifecycleActionDisposition.commandTimedOut + while ContinuousClock.now < deadline && !Task.isCancelled { + if offset < payload.count { + do { offset += try process.write(payload, offset: offset) } catch { offset = payload.count } + } + if offset == payload.count { process.closeInput() } + do { + switch try process.readStandardOutput() { + case .bytes(let bytes): stdout += bytes.count + case .end: outputEnded = true + case .wouldBlock: break + } + switch try process.readStandardError() { + case .bytes(let bytes): stderr += bytes.count + case .end: errorEnded = true + case .wouldBlock: break + } + } catch { + disposition = .commandFailed + break + } + if stdout + stderr > outputLimit { + disposition = .commandOutputLimit + break + } + if outputEnded && errorEnded, let exited = process.exitIfFinished() { + switch exited { + case .status(let status): + return result(status == 0 ? .commandSucceeded : .commandFailed, status: status) + case .signal(let signal): + return result(.commandFailed, signal: signal) + } + } + try? await Task.sleep(for: .milliseconds(2)) + } + if Task.isCancelled { disposition = .commandCancelled } + let cleaned = await process.finish( + grace: .zero, terminate: .milliseconds(100), killWait: .seconds(1)) + switch process.exitIfFinished() { + case .status(let status): return result(disposition, status: status, cleaned: cleaned) + case .signal(let signal): return result(disposition, signal: signal, cleaned: cleaned) + case nil: return result(disposition, cleaned: cleaned) + } + + func result( + _ disposition: LifecycleActionDisposition, status: Int32? = nil, signal: Int32? = nil, + cleaned: Bool = true + ) -> LifecycleActionResult { + LifecycleActionResult( + action: action, disposition: disposition, dispatched: true, withholding: nil, + exitStatus: status, signal: signal, httpStatus: nil, stdoutBytes: min(stdout, outputLimit), + stderrBytes: min(stderr, outputLimit), processGroupCleanedUp: cleaned, diagnostics: []) + } + } + + static func launchFailed(_ action: LifecycleActionSummary) -> LifecycleActionResult { + LifecycleActionResult( + action: action, disposition: .commandLaunchFailed, dispatched: false, withholding: nil, + exitStatus: nil, signal: nil, httpStatus: nil, stdoutBytes: 0, stderrBytes: 0, + processGroupCleanedUp: nil, diagnostics: []) + } +} + +struct LifecycleHTTPInput { + let request: URLRequest + + init?(action: DeclaredLifecycleAction, environment: [String: String], payload: Data) { + guard case .http(let url, let headers, let allowed) = action.body else { return nil } + var request = URLRequest( + url: url, cachePolicy: .reloadIgnoringLocalCacheData, + timeoutInterval: TimeInterval(action.timeout)) + request.httpMethod = "POST" + request.httpBody = payload + request.setValue("application/json", forHTTPHeaderField: "Content-Type") + request.httpShouldHandleCookies = false + for (field, template) in headers { + guard let value = Self.expand(template, environment: environment, allowed: allowed), + value.utf8.count <= 8_192 + else { return nil } + request.setValue(value, forHTTPHeaderField: field) + } + self.request = request + } + + static func expand( + _ template: String, environment: [String: String], allowed: Set + ) -> String? { + let bytes = Array(template.utf8) + var output = Data() + var offset = 0 + while offset < bytes.count { + guard bytes[offset] == 36, offset + 1 < bytes.count else { + output.append(bytes[offset]) + offset += 1 + continue + } + var end = offset + 1 + let braced = bytes[end] == 123 + if braced { end += 1 } + let start = end + while end < bytes.count, + (65...90).contains(bytes[end]) || (97...122).contains(bytes[end]) + || (48...57).contains(bytes[end]) || bytes[end] == 95 + { + end += 1 + } + let name = String(decoding: bytes[start.. 8_192 { return nil } + offset = end + (braced ? 1 : 0) + } + let value = String(decoding: output, as: UTF8.self) + guard value.unicodeScalars.allSatisfy({ $0.value == 9 || ($0.value >= 32 && $0.value != 127) }) + else { return nil } + return value + } + + private static func isCredentialName(_ name: String) -> Bool { + let upper = name.uppercased() + let fragments = ["TOKEN", "SECRET", "PASSWORD", "PASSWD", "CREDENTIAL", "APIKEY", "PRIVATEKEY"] + let words: Set = [ + "KEY", "PAT", "PASS", "AUTH", "AUTHORIZATION", "COOKIE", "SESSION", "PASSPHRASE", + ] + return fragments.contains(where: upper.contains) + || !words.isDisjoint(with: upper.split(separator: "_")) + } +} + +/// The delegate consumes response metadata only. URLSession owns all network work after resume. +final class LifecycleHTTPClient: NSObject, URLSessionDataDelegate, @unchecked Sendable { + private let lock = NSLock() + private var transfers: [Int: LifecycleHTTPTransfer] = [:] + + // Test fixtures can assign an ephemeral loopback-only anchor without changing OS trust. + @TaskLocal static var loopbackTrustAnchorForTesting: Data? + private let loopbackTrustAnchor = loopbackTrustAnchorForTesting + + func session() -> URLSession { + let configuration = URLSessionConfiguration.ephemeral + configuration.urlCache = nil + configuration.httpCookieStorage = nil + configuration.urlCredentialStorage = nil + configuration.httpShouldSetCookies = false + configuration.timeoutIntervalForResource = 300 + return URLSession(configuration: configuration, delegate: self, delegateQueue: nil) + } + + func start( + _ request: URLRequest, in session: URLSession, action: LifecycleActionSummary + ) -> LifecycleHTTPTransfer { + let task = session.dataTask(with: request) + let transfer = LifecycleHTTPTransfer(task: task, action: action) + lock.withLock { transfers[task.taskIdentifier] = transfer } + task.resume() + return transfer + } + + func urlSession( + _ session: URLSession, task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest, completionHandler: @escaping @Sendable (URLRequest?) -> Void + ) { + complete(task, status: response.statusCode) + completionHandler(nil) + } + + func urlSession( + _ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, + completionHandler: + @escaping @Sendable (URLSession.AuthChallengeDisposition, URLCredential?) -> + Void + ) { + respond(to: challenge, task: task, completionHandler: completionHandler) + } + + func urlSession( + _ session: URLSession, didReceive challenge: URLAuthenticationChallenge, + completionHandler: + @escaping @Sendable (URLSession.AuthChallengeDisposition, URLCredential?) -> + Void + ) { + respond(to: challenge, task: nil, completionHandler: completionHandler) + } + + private func respond( + to challenge: URLAuthenticationChallenge, task: URLSessionTask?, + completionHandler: @Sendable (URLSession.AuthChallengeDisposition, URLCredential?) -> Void + ) { + #if canImport(Security) + if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { + guard let loopbackTrustAnchor else { + completionHandler(.performDefaultHandling, nil) + return + } + guard challenge.protectionSpace.host == "127.0.0.1", + let trust = challenge.protectionSpace.serverTrust, + let anchor = SecCertificateCreateWithData(nil, loopbackTrustAnchor as CFData), + SecTrustSetAnchorCertificates(trust, [anchor] as CFArray) == errSecSuccess, + SecTrustSetAnchorCertificatesOnly(trust, true) == errSecSuccess, + SecTrustEvaluateWithError(trust, nil) + else { + completionHandler(.cancelAuthenticationChallenge, nil) + return + } + completionHandler(.useCredential, URLCredential(trust: trust)) + return + } + #endif + if let task, let response = challenge.failureResponse as? HTTPURLResponse { + complete(task, status: response.statusCode) + } + completionHandler(.cancelAuthenticationChallenge, nil) + } + + func urlSession( + _ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, + completionHandler: @escaping @Sendable (URLSession.ResponseDisposition) -> Void + ) { + complete(dataTask, status: (response as? HTTPURLResponse)?.statusCode) + completionHandler(.cancel) + } + + func urlSession( + _ session: URLSession, task: URLSessionTask, didCompleteWithError error: (any Error)? + ) { + complete(task, status: nil) + } + + private func complete(_ task: URLSessionTask, status: Int?) { + let transfer = lock.withLock { transfers.removeValue(forKey: task.taskIdentifier) } + transfer?.complete(status: status) + } +} + +final class LifecycleHTTPTransfer: @unchecked Sendable { + private enum Response { + case pending + case received(Int) + case unknown + } + private let lock = NSLock() + private let task: URLSessionDataTask + private let action: LifecycleActionSummary + private let deadline: ContinuousClock.Instant + private var response = Response.pending + + init(task: URLSessionDataTask, action: LifecycleActionSummary) { + self.task = task + self.action = action + deadline = ContinuousClock.now + .seconds(action.timeoutSeconds) + } + + func complete(status: Int?) { + lock.withLock { + guard case .pending = response else { return } + response = (ContinuousClock.now < deadline ? status : nil).map(Response.received) ?? .unknown + } + } + + func result(drainBy: ContinuousClock.Instant? = nil) async -> LifecycleActionResult { + let limit = min(deadline, drainBy ?? deadline) + while true { + let snapshot = lock.withLock { response } + switch snapshot { + case .received(let status): + return result((200...299).contains(status) ? .httpSucceeded : .httpRejected, status: status) + case .unknown: return result(.deliveryUnknown) + case .pending: + if Task.isCancelled || ContinuousClock.now >= limit { + complete(status: nil) + task.cancel() + } else { + try? await Task.sleep(for: .milliseconds(5)) + } + } + } + } + + private func result( + _ disposition: LifecycleActionDisposition, status: Int? = nil + ) -> LifecycleActionResult { + .init( + action: action, disposition: disposition, dispatched: true, withholding: nil, + exitStatus: nil, signal: nil, httpStatus: status, stdoutBytes: 0, stderrBytes: 0, + processGroupCleanedUp: nil, diagnostics: []) + } +} diff --git a/Sources/AgentsUpdates/Lifecycle/LifecycleInvocation.swift b/Sources/AgentsUpdates/Lifecycle/LifecycleInvocation.swift new file mode 100644 index 0000000..761380b --- /dev/null +++ b/Sources/AgentsUpdates/Lifecycle/LifecycleInvocation.swift @@ -0,0 +1,455 @@ +import AgentsCore +import AgentsInstructions +import AgentsManifest +import Foundation + +#if canImport(FoundationNetworking) + import FoundationNetworking +#endif + +struct LifecycleInvocation: Sendable { + let context: LifecycleContext + let discovery: LifecycleDiscovery + let inspection: LifecycleInspection + let pre: LifecycleEvent + let post: LifecycleEvent? + let receipt: LifecycleTrustRecord? + let offline: Bool + let policyFingerprint: String? + let requireInstallPreview: Bool + let usesPendingClosure: Bool + let preflight: (@Sendable (OrganizationPolicySnapshot) throws -> Void)? + + init( + context: LifecycleContext, discovery: LifecycleDiscovery? = nil, + pre: LifecycleEvent, post: LifecycleEvent? = nil, offline: Bool = false, policy: Policy, + requireInstallPreview: Bool = false, usesPendingClosure: Bool = false, + preflight: (@Sendable (OrganizationPolicySnapshot) throws -> Void)? = nil + ) { + self.context = context + let discovery = discovery ?? context.discover() + self.discovery = discovery + self.pre = pre + self.post = post + self.offline = offline + self.requireInstallPreview = requireInstallPreview + self.preflight = preflight + self.usesPendingClosure = usesPendingClosure + policyFingerprint = policy.snapshot?.fingerprint + let observation = Result { try context.trustReceipt(discovery.root) } + receipt = try? observation.get() + inspection = context.inspection( + discovery, events: Set([pre] + (post.map { [$0] } ?? [])), policy: policy.withheld, + receipt: observation) + } + + struct Policy { + let snapshot: OrganizationPolicySnapshot? + let withheld: LifecycleWithholding? + } + + static func policy( + context: LifecycleContext, offline: Bool, expected: String?, requireInstallPreview: Bool, + snapshot: OrganizationPolicySnapshot? = nil, findings: OrganizationPolicyReport? = nil + ) -> Policy { + if context.disabled { return Policy(snapshot: nil, withheld: .disabled) } + do { + let current = + try snapshot ?? OrganizationPolicySnapshot(store: context.store, offline: offline) + if current.statuses.contains(where: { $0.outcome != .loaded }) + || current.loadFindings.contains(where: { $0.rule == "policy-unavailable" }) + { + return Policy(snapshot: current, withheld: .policyUnavailable) + } + if current.chains.contains(where: { chain in + chain.mode != .off && chain.layers.contains { $0.rules.executableDenyAll } + }) { + return Policy(snapshot: current, withheld: .policyDenied) + } + guard expected == nil || expected == current.fingerprint else { + return Policy(snapshot: current, withheld: .policyDenied) + } + if current.report().isBlocked || findings?.isBlocked == true { + return Policy(snapshot: current, withheld: .packageAdmission) + } + if requireInstallPreview { + do { + let (_, conflict, _, _) = try UpdateOperations.previewWithOwnership( + UpdateRequest(), scope: context.store.scope, environment: context.store.environment, + organizationPolicy: current) + if conflict != nil { return Policy(snapshot: current, withheld: .packageAdmission) } + } catch CoreError.recoveryPending { + return Policy(snapshot: current, withheld: .recoveryPending) + } catch { + return Policy(snapshot: current, withheld: .packageAdmission) + } + } + return Policy(snapshot: current, withheld: nil) + } catch { + return Policy(snapshot: nil, withheld: .policyUnavailable) + } + } + + func validateRoot() throws { + if let project = discovery.root { + guard try LifecycleProjectIdentity(context.openProject()) == project else { + throw CoreError.invalidState("The reviewed project root changed.") + } + } + } + + private func validateInstalledPolicy(_ policy: OrganizationPolicySnapshot) throws { + let store = context.store + try store.withReadLock { + let baseline = try StatePrecondition(store: store) + let declaration = try store.readDeclaration(prepared: baseline) + let bytes = try store.declarationBytes(prepared: baseline) + let ledger = try store.readLedger(prepared: baseline) + let selected = + try usesPendingClosure ? ledger.pendingDeployment?.desired(in: ledger) : ledger + let evaluation = try OrganizationInstallEvaluation( + policy: policy, store: store, declaration: declaration, bytes: bytes) + try policy.admit( + evaluation.beforeAcquisition() + + evaluation.closure( + selected, roots: store.ledgerRoots(recordedIn: ledger))) + try baseline.validate() + } + } + + private struct Withheld: Error { + let reason: LifecycleWithholding + var diagnostics: [LifecycleDiagnostic] = [] + } + + private func handoff( + _ captured: CapturedLifecycleAction, _ start: (DirectoryHandle) throws -> Value + ) throws -> Value { + LifecycleOperations.checkpoint?(.beforeHandoff) + if Task.isCancelled { throw Withheld(reason: .cancelled) } + do { + try context.store.withReadLock {} + } catch { + throw Withheld(reason: .recoveryPending) + } + let policy = Self.policy( + context: context, offline: offline, expected: policyFingerprint, + requireInstallPreview: requireInstallPreview) + if let reason = policy.withheld { throw Withheld(reason: reason) } + if let snapshot = policy.snapshot, snapshot.evaluator.active { + do { + if captured.value.event == pre { + try preflight?(snapshot) + } else { + try validateInstalledPolicy(snapshot) + } + } catch { throw Withheld(reason: .packageAdmission) } + } + + func requireCurrentSource() throws { + let current = context.discover() + if current.administratorInvalid { + throw Withheld( + reason: .administratorSourceInvalid, + diagnostics: current.diagnostics.filter { $0.source.authority == .administrator }) + } + guard current.root == discovery.root else { throw Withheld(reason: .projectChanged) } + guard current.actions.contains(where: captured.matches) else { + throw Withheld( + reason: .sourceChanged, + diagnostics: current.diagnostics.filter { $0.source == captured.source }) + } + } + + func admitAndStart() throws -> Value { + if Task.isCancelled { throw Withheld(reason: .cancelled) } + if context.disabled { throw Withheld(reason: .disabled) } + if captured.source.authority == .project { + let latest: LifecycleTrustRecord? + do { latest = try context.trustReceipt(discovery.root) } catch { + throw Withheld(reason: .receiptUnavailable) + } + guard latest?.revision == receipt?.revision, latest?.digest == captured.digest else { + throw Withheld(reason: .trustChanged) + } + } + let directory: DirectoryHandle + switch context.store.scope { + case .project: + guard let expected = discovery.root, let opened = try? context.openProject(), + (try? LifecycleProjectIdentity(opened)) == expected + else { throw Withheld(reason: .projectChanged) } + directory = opened + case .user: + guard let home = try? context.openHome() else { throw Withheld(reason: .sourceChanged) } + directory = home + } + do { try policy.snapshot?.validate() } catch { throw Withheld(reason: .policyUnavailable) } + if Task.isCancelled { throw Withheld(reason: .cancelled) } + let launched = try start(directory) + LifecycleOperations.checkpoint?(.handedOff) + return launched + } + + try requireCurrentSource() + if captured.source.authority == .project, let root = discovery.root { + var waited = false + do { + return try context.withHandoff( + for: root, onContention: { waited = true }, + { + if waited { try requireCurrentSource() } + return try admitAndStart() + }) + } catch let refusal as Withheld { + throw refusal + } catch let failure as DuplexProcessError { + throw failure + } catch { + throw Withheld(reason: Task.isCancelled ? .cancelled : .receiptUnavailable) + } + } + return try admitAndStart() + } + + enum Pending { + case complete(LifecycleActionResult) + case web(LifecycleHTTPTransfer) + } + + func run( + _ event: LifecycleEvent, test: Bool, client: LifecycleHTTPClient, session: URLSession, + withheld: LifecycleWithholding? = nil, + onDispatch: (@Sendable (LifecycleActionSummary) -> Void)? = nil + ) async -> [Pending] { + let actions = discovery.actions.filter { $0.value.event == event } + let summaries = inspection.actions.filter { $0.event == event } + guard !actions.isEmpty else { return [] } + guard + let payload = try? JSONEncoder().encode( + LifecyclePayload(event: event, scope: context.store.scope, test: test)) + else { + return summaries.map { .complete(.withheld($0, reason: .packageAdmission)) } + } + + var results: [Pending] = [] + for (action, summary) in zip(actions, summaries) { + if let reason = withheld ?? summary.withheld { + results.append(.complete(.withheld(summary, reason: reason))) + continue + } + do { + switch action.value.body { + case .command: + let process = try handoff(action) { + try LifecycleCommand.spawn(action, in: $0, environment: context.store.environment) + } + onDispatch?(summary) + let result = await LifecycleCommand.finish(process, action: summary, payload: payload) + results.append(.complete(result)) + case .http: + guard + let input = LifecycleHTTPInput( + action: action.value, environment: context.store.environment.environment, + payload: payload) + else { + results.append(.complete(.withheld(summary, reason: .headerExpansionRefused))) + continue + } + let transfer = try handoff(action) { _ in + client.start(input.request, in: session, action: summary) + } + onDispatch?(summary) + if test { + results.append(.complete(await transfer.result())) + } else { + results.append(.web(transfer)) + } + } + } catch let refusal as Withheld { + results.append( + .complete( + .withheld( + summary, reason: refusal.reason, diagnostics: refusal.diagnostics))) + } catch { + results.append(.complete(LifecycleCommand.launchFailed(summary))) + } + } + return results + } + + static func drain( + _ results: [Pending], by deadline: ContinuousClock.Instant? = nil + ) async -> [LifecycleActionResult] { + var completed: [LifecycleActionResult] = [] + for result in results { + switch result { + case .complete(let action): completed.append(action) + case .web(let transfer): completed.append(await transfer.result(drainBy: deadline)) + } + } + return completed + } +} + +extension LifecycleOperations { + public static func simulate( + _ event: LifecycleEvent = .postInstall, scope: InstallScope = .project, + environment: RuntimeEnvironment = RuntimeEnvironment() + ) -> LifecycleTestReview { + let context = LifecycleContext(scope: scope, environment: environment) + let policy = LifecycleInvocation.policy( + context: context, offline: false, expected: nil, requireInstallPreview: true) + let plan = LifecycleInvocation( + context: context, pre: event, policy: policy, requireInstallPreview: true) + return LifecycleTestReview(inspection: plan.inspection, plan: plan) + } + + public static func executeTest( + _ review: LifecycleTestReview, + onDispatch: (@Sendable (LifecycleActionSummary) -> Void)? = nil + ) async -> LifecycleSubmission<[LifecycleActionResult]> { + await review.confirmation.submit { + checkpoint?(.confirmationClaimed) + let client = LifecycleHTTPClient() + let session = client.session() + defer { session.invalidateAndCancel() } + return await LifecycleInvocation.drain( + review.plan.run( + review.plan.pre, test: true, client: client, session: session, onDispatch: onDispatch)) + } + } +} + +extension UpdateOperations { + /// Read-only package and lifecycle preparation with an explicit operation intent. + public static func previewLifecycle( + _ request: UpdateRequest = UpdateRequest(), intent: LifecycleOperationIntent, + scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> LifecyclePackageReview { + let context = LifecycleContext(scope: scope, environment: environment) + let (discovery, existingRoot) = try context.capturePackageRoot() + let offline = request.deployPendingMarketplace + let snapshot = try OrganizationPolicySnapshot(store: context.store, offline: offline) + let (report, conflict, _, _) = try previewWithOwnership( + request, scope: scope, environment: environment, organizationPolicy: snapshot) + let plan = try context.packagePlan( + intent: intent, discovery: discovery, offline: offline, snapshot: snapshot, + findings: report.organizationPolicy, ownershipConflict: conflict + ) { current in + let (_, currentConflict, _, _) = try previewWithOwnership( + request, scope: scope, environment: environment, organizationPolicy: current) + if let currentConflict { throw CoreError.invalidState(currentConflict) } + } + return LifecyclePackageReview( + report: report, lifecycle: plan.inspection, ownershipConflict: conflict, plan: plan + ) { bindingProvider in + perform( + request, scope: scope, environment: environment, bindingProvider: bindingProvider, + checkpoint: { try LifecycleOperations.transactionCheckpointForTesting?($0) }, + existingRoot: existingRoot, + expectedFingerprint: offline ? report.displayedFingerprint : nil + ) { try $0.apply(ifUnchangedFrom: report.displayedFingerprint) } + } + } + + /// Consumes a reviewed invocation. Effects are owned by the same in-memory confirmation. + public static func perform( + _ review: LifecyclePackageReview, + bindingProvider: (any RuntimeBindingProvider)? = nil, + onDispatch: (@Sendable (LifecycleActionSummary) -> Void)? = nil + ) async -> LifecycleSubmission> { + await review.confirmation.submit { + LifecycleOperations.checkpoint?(.confirmationClaimed) + let plan = review.plan + let client = LifecycleHTTPClient() + let session = client.session() + defer { session.invalidateAndCancel() } + let pre = await plan.run( + plan.pre, test: false, client: client, session: session, onDispatch: onDispatch) + let package: UpdateCompletion + do { + try Task.checkCancellation() + try plan.validateRoot() + package = review.apply(bindingProvider) + } catch { + package = completion( + .failure(error), outcome: TransactionOutcome(), recovered: false, + store: plan.context.store) + } + let postReason: LifecycleWithholding? + if Task.isCancelled { + postReason = .cancelled + } else if package.recovery.pending || package.recoveredBeforePreparation { + postReason = .recoveryPending + } else if case .success = package.result, package.disposition != .rolledBack, + package.disposition != .recoveryRequired + { + postReason = nil + } else { + postReason = .packageDidNotComplete + } + let post: [LifecycleInvocation.Pending] + if let event = plan.post { + post = await plan.run( + event, test: false, client: client, session: session, withheld: postReason, + onDispatch: onDispatch) + } else { + post = [] + } + let deadline = ContinuousClock.now + .seconds(10) + return await LifecycleInvocationResult( + package: package, pre: LifecycleInvocation.drain(pre, by: deadline), + post: LifecycleInvocation.drain(post, by: deadline)) + } + } +} + +extension InstructionOperations { + /// Reviews the same request used by updateInstalled, with pre-compile lifecycle intent. + public static func previewCompilation( + scope: InstallScope = .project, agents: [AgentID]? = nil, + environment: RuntimeEnvironment = RuntimeEnvironment(), replace: Bool = false + ) throws -> LifecyclePackageReview { + try UpdateOperations.previewLifecycle( + installedUpdateRequest( + scope: scope, agents: agents, environment: environment, replace: replace), + intent: .compile, scope: scope, environment: environment) + } +} + +extension LifecycleContext { + func capturePackageRoot() throws -> (LifecycleDiscovery, ExistingProjectRoot?) { + let existing = try? store.captureExistingProjectRoot() + let discovery = discover() + try existing?.validateForLifecycle() + return (discovery, existing) + } + + func packagePlan( + intent: LifecycleOperationIntent, discovery: LifecycleDiscovery, offline: Bool = false, + snapshot: OrganizationPolicySnapshot, findings: OrganizationPolicyReport?, + ownershipConflict: String? = nil, usesPendingClosure: Bool = false, + preflight: (@Sendable (OrganizationPolicySnapshot) throws -> Void)? = nil + ) throws -> LifecycleInvocation { + let events = intent.events + let policy = LifecycleInvocation.policy( + context: self, offline: offline, expected: nil, requireInstallPreview: false, + snapshot: snapshot, findings: findings) + let plan = LifecycleInvocation( + context: self, discovery: discovery, pre: events.pre, post: events.post, offline: offline, + policy: ownershipConflict == nil + ? policy : .init(snapshot: snapshot, withheld: .packageAdmission), + usesPendingClosure: usesPendingClosure, preflight: preflight) + try plan.validateRoot() + return plan + } +} + +extension OrganizationPolicySnapshot { + func requireSameLifecyclePolicy(as fresh: Self) throws { + guard fingerprint == fresh.fingerprint else { + throw CoreError.invalidState("Organization policy changed during lifecycle admission.") + } + } +} diff --git a/Sources/AgentsUpdates/Lifecycle/LifecycleModels.swift b/Sources/AgentsUpdates/Lifecycle/LifecycleModels.swift new file mode 100644 index 0000000..cd9ed57 --- /dev/null +++ b/Sources/AgentsUpdates/Lifecycle/LifecycleModels.swift @@ -0,0 +1,148 @@ +import AgentsCore +import AgentsManifest +import Foundation + +public enum LifecycleOperationIntent: String, Codable, Sendable { + case install, update, uninstall, compile + + var events: (pre: LifecycleEvent, post: LifecycleEvent?) { + switch self { + case .install: (.preInstall, .postInstall) + case .update: (.preUpdate, .postUpdate) + case .uninstall: (.preUninstall, .postUninstall) + case .compile: (.preCompile, nil) + } + } +} + +public enum LifecycleAuthority: String, Codable, Sendable { + case administrator, user, project +} + +public struct LifecycleSource: Equatable, Codable, Sendable { + public let authority: LifecycleAuthority + public let file: URL +} + +public struct LifecycleDiagnostic: Equatable, Codable, Sendable { + public let source: LifecycleSource + public let event: String? + /// Zero-based position in the event's authored sequence. + public let index: Int? + public let field: String? + public let message: String +} + +public enum LifecycleWithholding: String, Equatable, Codable, Sendable { + case administratorSourceInvalid, sourceChanged, projectChanged, receiptUnavailable + case projectUntrusted, trustChanged, disabled, policyDenied, policyUnavailable, packageAdmission + case recoveryPending, packageDidNotComplete, cancelled, headerExpansionRefused +} + +public struct LifecycleActionSummary: Equatable, Codable, Sendable { + public enum Kind: String, Codable, Sendable { case command, http } + + public let source: LifecycleSource + public let event: LifecycleEvent + public let index: Int + public let kind: Kind + /// Shell name or HTTPS origin. Authored values and expanded headers never appear here. + public let target: String + public let timeoutSeconds: Int + public let withheld: LifecycleWithholding? +} + +public struct LifecycleInspection: Sendable, Codable { + public let actions: [LifecycleActionSummary] + public let diagnostics: [LifecycleDiagnostic] + public let project: LifecycleProjectIdentity? + public let projectTrusted: Bool + public let allStartsWithheld: LifecycleWithholding? +} + +public enum LifecycleActionDisposition: String, Codable, Sendable { + case withheld, commandSucceeded, commandFailed, commandTimedOut, commandOutputLimit, + commandCancelled + case commandLaunchFailed, httpSucceeded, httpRejected, deliveryUnknown +} + +public struct LifecycleActionResult: Codable, Sendable { + public let action: LifecycleActionSummary + public let disposition: LifecycleActionDisposition + /// The OS accepted the spawn or URLSession handoff. A handoff does not establish delivery. + public let dispatched: Bool + public let withholding: LifecycleWithholding? + public let exitStatus: Int32? + public let signal: Int32? + public let httpStatus: Int? + public let stdoutBytes: Int + public let stderrBytes: Int + public let processGroupCleanedUp: Bool? + public let diagnostics: [LifecycleDiagnostic] +} + +public struct LifecycleInvocationResult: Sendable { + public let package: UpdateCompletion + public let pre: [LifecycleActionResult] + public let post: [LifecycleActionResult] +} + +public enum LifecycleSubmission: Sendable { + case alreadyRunning + case completed(Value) +} + +/// Each review has one token. Concurrent submission observes its in-progress state, and a +/// later duplicate receives the original result, including failures and withheld actions. +final class LifecycleConfirmation: @unchecked Sendable { + private enum State { + case ready, running + case finished(Value) + } + private let lock = NSLock() + private var state = State.ready + + func submit(_ body: () async -> Value) async -> LifecycleSubmission { + let prior = lock.withLock { () -> LifecycleSubmission? in + switch state { + case .ready: + state = .running + return nil + case .running: return .alreadyRunning + case .finished(let result): return .completed(result) + } + } + if let prior { return prior } + let result = await body() + lock.withLock { state = .finished(result) } + return .completed(result) + } +} + +/// Holds the exact reviewed package preparation and both phases' lifecycle definitions. +public struct LifecyclePackageReview: Sendable { + public let report: Report + public let lifecycle: LifecycleInspection + public let ownershipConflict: String? + let plan: LifecycleInvocation + let apply: @Sendable ((any RuntimeBindingProvider)?) -> UpdateCompletion + let confirmation = LifecycleConfirmation>() +} + +public struct LifecycleTestReview: Sendable { + public let inspection: LifecycleInspection + let plan: LifecycleInvocation + let confirmation = LifecycleConfirmation<[LifecycleActionResult]>() +} + +extension LifecycleActionResult { + static func withheld( + _ action: LifecycleActionSummary, reason: LifecycleWithholding, + diagnostics: [LifecycleDiagnostic] = [] + ) -> Self { + .init( + action: action, disposition: .withheld, dispatched: false, withholding: reason, + exitStatus: nil, signal: nil, httpStatus: nil, stdoutBytes: 0, stderrBytes: 0, + processGroupCleanedUp: nil, diagnostics: diagnostics) + } +} diff --git a/Sources/AgentsUpdates/Lifecycle/LifecycleTrust.swift b/Sources/AgentsUpdates/Lifecycle/LifecycleTrust.swift new file mode 100644 index 0000000..b928a10 --- /dev/null +++ b/Sources/AgentsUpdates/Lifecycle/LifecycleTrust.swift @@ -0,0 +1,331 @@ +import AgentsCore +import AgentsManifest +import Foundation + +public struct LifecycleTrustRecord: Codable, Equatable, Sendable { + public let project: LifecycleProjectIdentity + public let revision: UInt64 + /// Nil records a revocation with its own revision. + public let digest: String? +} + +public struct LifecycleEnablement: Sendable { + public let project: LifecycleProjectIdentity + /// The complete authored lifecycle subtree for the local review UI. + public let declaration: DeclarationValue + public let digest: String + public let expectedRevision: UInt64 + public var shellAccessNotice: String { + "Shell actions run with your access and may invoke mutable checkout files outside the reviewed digest." + } + +} + +public struct LifecycleEnableReview: Sendable { + public let enablement: LifecycleEnablement + let context: LifecycleContext + let confirmation = LifecycleConfirmation>() +} + +public struct LifecycleDeclarationReview: Sendable { + public let destination: URL + public let documentChange: DocumentChange + /// The complete proposed lifecycle subtree for the local review UI. + public let declaration: DeclarationValue? + public let enablement: LifecycleEnablement? + + let context: LifecycleContext + let root: ExistingProjectRoot? + let confirmation = LifecycleConfirmation>() +} + +public enum LifecycleSaveResult: Sendable { + case saved + case savedAndEnabled(LifecycleTrustRecord) + case savedEnablementIncomplete +} + +extension LifecycleOperations { + enum Checkpoint: Sendable { + case confirmationClaimed + case beforeReceiptPublication + case receiptPublished + case declarationSaved + case beforeHandoff + case handedOff + } + + @TaskLocal static var checkpoint: (@Sendable (Checkpoint) -> Void)? + @TaskLocal package static var transactionCheckpointForTesting: + (@Sendable (String) throws -> Void)? + + public static func storedTrust( + environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> [LifecycleTrustRecord] { + let context = LifecycleContext(scope: .user, environment: environment) + return try context.readTrust().entries.values.sorted { + if $0.project.canonicalPath != $1.project.canonicalPath { + return $0.project.canonicalPath < $1.project.canonicalPath + } + return $0.project.key < $1.project.key + } + } + + public static func reviewEnable( + environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> LifecycleEnableReview { + let context = LifecycleContext(scope: .project, environment: environment) + let discovery = try context.readProject() + guard let project = discovery.root, let declaration = discovery.projectDeclaration, + let digest = discovery.projectDigest + else { throw CoreError.invalidState("A valid project lifecycle declaration is required.") } + return try context.enableReview(project: project, declaration: declaration, digest: digest) + } + + public static func enable( + _ review: LifecycleEnableReview + ) async -> LifecycleSubmission> { + await review.confirmation.submit { + checkpoint?(.confirmationClaimed) + return Result { try review.context.publishEnable(review.enablement) } + } + } + + /// Revokes the selected stored identity even when its path no longer names that checkout. + @discardableResult + public static func revoke( + _ project: LifecycleProjectIdentity, environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> LifecycleTrustRecord { + let context = LifecycleContext(scope: .user, environment: environment) + let record = try context.writeTrust(project: project, digest: nil) + try context.withHandoff(for: project) {} + return record + } + + public static func previewScaffold( + scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment(), + force: Bool = false + ) throws -> LifecycleDeclarationReview { + let starter: DeclarationValue = .dictionary([ + LifecycleEvent.preInstall.rawValue: .array([]), + LifecycleEvent.postInstall.rawValue: .array([]), + ]) + return try declarationReview( + starter, scope: scope, environment: environment, requireAbsent: !force, offerEnablement: false + ) + } + + /// Prepares a lifecycle-only edit of an existing manifest. It may be saved and enabled + /// in one reviewed project operation. + public static func previewDeclaration( + _ declaration: DeclarationValue?, scope: InstallScope = .project, + environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> LifecycleDeclarationReview { + try declarationReview( + declaration, scope: scope, environment: environment, requireAbsent: false, + offerEnablement: true) + } + + public static func save( + _ review: LifecycleDeclarationReview, enable: Bool = false + ) async -> LifecycleSubmission> { + await review.confirmation.submit { + checkpoint?(.confirmationClaimed) + return Result { + let proposed = enable ? review.enablement : nil + if enable && proposed == nil { + throw CoreError.invalidState("Enablement requires a reviewed project declaration.") + } + try review.context.publishDeclaration(review) + checkpoint?(.declarationSaved) + guard let proposed else { return .saved } + do { + return .savedAndEnabled(try review.context.publishEnable(proposed)) + } catch { + return .savedEnablementIncomplete + } + } + } + } + + private static func declarationReview( + _ declaration: DeclarationValue?, scope: InstallScope, environment: RuntimeEnvironment, + requireAbsent: Bool, offerEnablement: Bool + ) throws -> LifecycleDeclarationReview { + let context = LifecycleContext(scope: scope, environment: environment) + let root = scope == .project ? try context.store.captureExistingProjectRoot() : nil + let directory = + try scope == .project + ? context.openProject().lifecycleChild(".agent", authority: .project) + : context.openHome()?.lifecycleChild(".agents", authority: .user) + guard + let input = try directory?.readLifecycleFile( + StateStore.declarationFileName, authority: scope == .project ? .project : .user, + maximumBytes: 2 * 1024 * 1024) + else { + throw CoreError.notFound("existing declaration at \(context.store.declarationURL.path)") + } + let document = try DeclarationDocument( + bytes: Array(input.bytes), identity: DocumentIdentity(context.store.declarationURL.path)) + if requireAbsent && document.declaration.lifecycle != nil { + throw CoreError.invalidState("A lifecycle declaration already exists. Confirm replacement.") + } + let change = try document.preparing([.setLifecycle(declaration)]) + let installed = change.expectedDeclaration.lifecycle + let enablement: LifecycleEnablement? + if offerEnablement, scope == .project, let installed, + let project = try? LifecycleProjectIdentity(context.openProject()) + { + try root?.validateForLifecycle() + enablement = try? context.enablement( + project: project, declaration: installed, digest: LifecycleDeclaration.digest(installed)) + } else { + enablement = nil + } + return LifecycleDeclarationReview( + destination: context.store.declarationURL, documentChange: change, declaration: installed, + enablement: enablement, context: context, root: root) + } +} + +struct LifecycleReceipts: Codable { + let version: Int + var entries: [String: LifecycleTrustRecord] + + static let empty = Self(version: 1, entries: [:]) + static let file = "receipts.json" + static let maximumBytes = 2 * 1024 * 1024 +} + +extension LifecycleContext { + func readProject() throws -> LifecycleDiscovery { + let root = try openProject() + var discovery = LifecycleDiscovery() + discovery.root = try LifecycleProjectIdentity(root) + let source = LifecycleSource(authority: .project, file: store.declarationURL) + if let directory = try root.lifecycleChild(".agent", authority: .project) { + try discovery.addNative(directory: directory, source: source, authority: .project) + } + return discovery + } + + func trustReceipt(_ project: LifecycleProjectIdentity?) throws -> LifecycleTrustRecord? { + guard let project else { return nil } + return try readTrust().entries[project.key] + } + + func enableReview( + project: LifecycleProjectIdentity, declaration: DeclarationValue, digest: String + ) throws -> LifecycleEnableReview { + try LifecycleEnableReview( + enablement: enablement(project: project, declaration: declaration, digest: digest), + context: self) + } + + func enablement( + project: LifecycleProjectIdentity, declaration: DeclarationValue, digest: String + ) throws -> LifecycleEnablement { + try LifecycleEnablement( + project: project, declaration: declaration, digest: digest, + expectedRevision: trustReceipt(project)?.revision ?? 0) + } + + func publishEnable(_ review: LifecycleEnablement) throws -> LifecycleTrustRecord { + try writeTrust( + project: review.project, digest: review.digest, expectedRevision: review.expectedRevision + ) { + let current = try self.readProject() + guard current.root == review.project, current.projectDigest == review.digest else { + throw CoreError.invalidState("The reviewed project lifecycle declaration changed.") + } + } + } + + func publishDeclaration(_ review: LifecycleDeclarationReview) throws { + try Task.checkCancellation() + if store.scope == .user { _ = try openHome()?.lifecycleChild(".agents", authority: .user) } + try store.withLock(createIfMissing: false, existingRoot: review.root) { + let baseline = try StatePrecondition(store: store) + let original = try store.declarationDocument(prepared: baseline) + guard original?.digest == review.documentChange.originalDigest else { + throw CoreError.invalidState("The reviewed declaration changed before saving.") + } + if review.documentChange.patches.isEmpty { return } + let transaction = FileTransaction(store: store) + transaction.requireUnchanged(since: baseline) + try store.stageDeclaration( + DeclarationChange(bytes: Data(review.documentChange.bytes)), in: transaction, + prepared: baseline) + try transaction.commit() + } + } + + func readTrust() throws -> LifecycleReceipts { + try readTrust(in: privateState()) + } + + func writeTrust( + project: LifecycleProjectIdentity, digest: String?, expectedRevision: UInt64? = nil, + validate: () throws -> Void = {} + ) throws -> LifecycleTrustRecord { + try Task.checkCancellation() + guard let home = try openHome() else { + throw CoreError.invalidState("An existing protected user home is required.") + } + _ = try home.createPrivateLifecycleChild(".agents", existingAuthority: .user) + let record = try userStore.withLock(createIfMissing: false) { + guard let directory = try privateState(create: true) else { + throw CoreError.invalidState("Private lifecycle state is unavailable.") + } + var latest = try readTrust(in: directory) + let revision = latest.entries[project.key]?.revision ?? 0 + guard expectedRevision == nil || revision == expectedRevision, revision < UInt64.max else { + throw CoreError.invalidState("The project's lifecycle trust revision changed.") + } + LifecycleOperations.checkpoint?(.beforeReceiptPublication) + try validate() + try Task.checkCancellation() + let record = LifecycleTrustRecord(project: project, revision: revision + 1, digest: digest) + latest.entries[project.key] = record + let bytes = try StateStore.encodeState(latest) + guard bytes.count <= LifecycleReceipts.maximumBytes else { + throw CoreError.invalidState("Lifecycle receipt storage exceeds its size limit.") + } + try directory.replacePrivateLifecycleFile(LifecycleReceipts.file, bytes: bytes) + return record + } + LifecycleOperations.checkpoint?(.receiptPublished) + return record + } + + func withHandoff( + for project: LifecycleProjectIdentity, onContention: () -> Void = {}, + _ body: () throws -> T + ) throws -> T { + guard let directory = try privateState() else { + throw CoreError.invalidState("Private lifecycle handoff state is unavailable.") + } + return try FileLock.withPrivateLock( + in: directory, named: "handoff-" + project.key, onContention: onContention, body) + } + + private func privateState(create: Bool = false) throws -> DirectoryHandle? { + guard let base = try openHome()?.lifecycleChild(".agents", authority: .user) else { return nil } + return try create + ? base.createPrivateLifecycleChild("lifecycle") + : base.lifecycleChild("lifecycle", authority: .privateState) + } + + private func readTrust(in directory: DirectoryHandle?) throws -> LifecycleReceipts { + guard + let data = try directory?.readLifecycleFile( + LifecycleReceipts.file, authority: .privateState, + maximumBytes: LifecycleReceipts.maximumBytes) + else { return .empty } + let receipts = try StateStore.decode(data.bytes, as: LifecycleReceipts.self) + guard receipts.version == 1, + receipts.entries.allSatisfy({ $0.key == $0.value.project.key && $0.value.revision > 0 }) + else { throw CoreError.invalidState("Invalid lifecycle trust receipts.") } + return receipts + } +} diff --git a/Sources/AgentsUpdates/MCPConnectionOperations.swift b/Sources/AgentsUpdates/MCPConnectionOperations.swift new file mode 100644 index 0000000..9a84f79 --- /dev/null +++ b/Sources/AgentsUpdates/MCPConnectionOperations.swift @@ -0,0 +1,444 @@ +import AgentsCore +import Components +import Foundation + +public enum MCPConnectionPreparationError: String, Error, Sendable { + case invalidSelection, invalidConfiguration, invalidResource, resourceChanged +} + +/// Fixed selected input; it neither resolves sources nor looks up a component by +/// name. Literal configuration and captured resource bytes have no debug dump. +public struct MCPConnectionSnapshot: Sendable, CustomStringConvertible, + CustomDebugStringConvertible, CustomReflectable +{ + public let id: UUID + public let selectionID: String + var durableReadDependencies: [ReadDependency] + /// Durable invalidation interests. Live resources observe entries; independently required + /// source inputs may observe subtrees. Borrowed and per-test staging paths are never exposed. + public var readDependencies: [ReadDependency] { durableReadDependencies } + fileprivate let inputBytes: Int + fileprivate let transport: MCPTransportDeclaration + fileprivate let directory: MCPConnectionResource? + fileprivate let executable: MCPConnectionResource? + public var description: String { "" } + public var debugDescription: String { description } + public var customMirror: Mirror { Mirror(self, children: [Mirror.Child]()) } +} + +public struct MCPConnectionDescription: Codable, Sendable, Equatable { + public enum Transport: String, Codable, Sendable { case stdio, streamableHTTP, sse } + public let snapshotID: UUID + public let transport: Transport + public let startsOwnedProcess: Bool + public let requiredBindings: [String] + public let environmentBindings: [String] + /// Display text only; never reconstruct a command from this redacted projection. + public let executable: String? + public let arguments: [String]? + public let workingDirectory: String? + /// Captured paths identify fixed source content, not a future staging location. + public let executableIsCaptured: Bool + public let workingDirectoryIsCaptured: Bool + /// Origin with path/query withheld; no header or credential values are exposed. + public let endpoint: String? + public let readDependencies: [ReadDependency] +} + +/// Protocol time excludes the separately bounded owned cleanup. The total timer +/// also includes synchronous binding and per-test resource materialization. +public struct MCPConnectionTestOptions: Sendable { + fileprivate var limits = MCPConnectionLimits() + public var clientName = "agents-tools" + public var clientVersion = "1" + public var totalTimeout: TimeInterval { + get { limits.totalTimeout } + set { limits.totalTimeout = newValue } + } + public var requestTimeout: TimeInterval { + get { limits.requestTimeout } + set { limits.requestTimeout = newValue } + } + public var maximumTools: Int { + get { limits.tools } + set { limits.tools = newValue } + } + public var maximumPages: Int { + get { limits.pages } + set { limits.pages = newValue } + } + public init() {} +} + +public struct MCPConnectionTestResult: Codable, Sendable, Equatable { + public enum Outcome: String, Codable, Sendable { + case discovered + /// Handshake succeeded; the server did not advertise tools discovery. + case noTools + case incomplete, failed + } + public enum Issue: String, Error, Codable, Sendable { + case invalidInput, bindingUnavailable, invalidBinding, resourceChanged + case connectionFailed, connectionClosed, protocolError, unsupportedVersion + case authenticationRequired, forbidden, authorityChanged, sessionExpired + case messageLimit, receiveLimit, sendLimit, stderrLimit, queueLimit + case pageLimit, toolLimit, textLimit, redirectLimit, resumeLimit, cursorCycle + case timeout, cancelled, cleanupFailed + } + public struct Tool: Codable, Sendable, Equatable { + public let name: String + public let title: String? + public let description: String? + } + public let snapshotID: UUID + public let startedAt: Date + public let finishedAt: Date + /// Monotonic elapsed time, including owned cleanup. + public let elapsed: TimeInterval + public let transport: MCPConnectionDescription.Transport + public let outcome: Outcome + public let issue: Issue? + public let negotiatedVersion: String? + public let tools: [Tool] + public let cleanupComplete: Bool +} + +public enum MCPConnectionOperations { + /// Call within the source borrowing scope after selecting an exact payload. + /// Resource handles already captured that scope's bytes; no lock survives here. + public static func snapshot( + selectionID: String, transport: MCPTransportDeclaration, + workingDirectory: MCPConnectionResource? = nil, executable: MCPConnectionResource? = nil + ) throws -> MCPConnectionSnapshot { + guard !selectionID.isEmpty, selectionID.utf8.count <= 4096, !selectionID.utf8.contains(0) else { + throw MCPConnectionPreparationError.invalidSelection + } + var remaining = MCPConnectionLimits().inputBytes + func charge(_ text: String) throws { + guard !text.utf8.contains(0), text.utf8.count < remaining else { + throw MCPConnectionPreparationError.invalidConfiguration + } + remaining -= text.utf8.count + 1 + } + func chargeBinding(_ binding: RuntimeBinding) throws { + switch binding { + case .environment(let name), .secret(let name): + guard !name.isEmpty else { throw MCPConnectionPreparationError.invalidConfiguration } + case .literal: break + } + try charge(binding.text) + } + switch transport { + case .stdio(let run): + guard workingDirectory?.directory == true, + !run.executable.isEmpty, run.executable.contains("/") == (executable != nil), + executable?.directory != true + else { throw MCPConnectionPreparationError.invalidConfiguration } + if let source = run.executableSource { + guard !source.isEmpty, run.executable.contains("/") else { + throw MCPConnectionPreparationError.invalidConfiguration + } + try charge(source) + } + try charge(run.executable) + for argument in run.arguments { try charge(argument) } + for (key, binding) in run.environment { + guard !key.isEmpty, !key.contains("=") else { + throw MCPConnectionPreparationError.invalidConfiguration + } + try charge(key) + try chargeBinding(binding) + } + case .streamableHTTP(let url, let headers), .sse(let url, let headers): + guard workingDirectory == nil, executable == nil, + let parsed = URL(string: url), + ["http", "https"].contains(parsed.scheme?.lowercased() ?? ""), + parsed.host?.isEmpty == false, parsed.user == nil, parsed.password == nil, + parsed.fragment == nil + else { throw MCPConnectionPreparationError.invalidConfiguration } + try charge(url) + let token = Set( + "!#$%&'*+-.^_`|~0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".utf8) + let reserved = Set([ + "host", "content-length", "transfer-encoding", "connection", "content-type", "accept", + "mcp-session-id", "mcp-protocol-version", "last-event-id", + ]) + var names = Set() + for (key, binding) in headers { + guard !key.isEmpty, key.utf8.allSatisfy({ token.contains($0) }), + !reserved.contains(key.lowercased()), names.insert(key.lowercased()).inserted + else { + throw MCPConnectionPreparationError.invalidConfiguration + } + try charge(key) + try chargeBinding(binding) + if case .literal(let value) = binding, + !value.utf8.allSatisfy({ $0 == 9 || ($0 >= 32 && $0 != 127) }) + { + throw MCPConnectionPreparationError.invalidConfiguration + } + } + } + let bytes = (workingDirectory?.byteCount ?? 0) + (executable?.byteCount ?? 0) + guard bytes <= LedgerLimits.standard.resourceBytes else { + throw MCPConnectionPreparationError.invalidResource + } + return MCPConnectionSnapshot( + id: UUID(), selectionID: selectionID, + durableReadDependencies: Array( + Set( + (workingDirectory?.readDependencies ?? []) + (executable?.readDependencies ?? []) + ) + ).sorted { $0.url.path < $1.url.path }, + inputBytes: MCPConnectionLimits().inputBytes - remaining, + transport: transport, + directory: workingDirectory, executable: executable) + } + + /// Pure metadata projection: no filesystem, provider, process or network access. + public static func describe(_ snapshot: MCPConnectionSnapshot) -> MCPConnectionDescription { + let bindings = snapshot.transport.bindings.values + var privateValues = bindings.compactMap { + if case .literal(let value) = $0 { value } else { nil } + } + if snapshot.transport.kind != .stdio { + privateValues += privateValues.flatMap { + $0.split(whereSeparator: { $0.isWhitespace }).map(String.init) + } + } + let redaction = MCPConnectionRedaction( + privateValues: privateValues, byteLimit: MCPConnectionLimits().textBytes) + var executable: String? + var arguments: [String]? + var directory: String? + var endpoint: String? + switch snapshot.transport { + case .stdio(let run): + executable = redaction.text(snapshot.executable?.displayPath ?? run.executable) + arguments = run.arguments.map(redaction.text) + directory = snapshot.directory.map { redaction.text($0.displayPath) } + case .streamableHTTP(let url, _), .sse(let url, _): + if var origin = URLComponents(string: url) { + let withheld = !origin.percentEncodedPath.isEmpty || origin.percentEncodedQuery != nil + origin.percentEncodedPath = "" + origin.percentEncodedQuery = nil + endpoint = redaction.text((origin.string ?? "[redacted]") + (withheld ? "/[redacted]" : "")) + } + } + return MCPConnectionDescription( + snapshotID: snapshot.id, transport: snapshot.transport.kind, + startsOwnedProcess: snapshot.transport.kind == .stdio, + requiredBindings: Set( + bindings.compactMap { if case .secret(let name) = $0 { name } else { nil } } + ).sorted(), + environmentBindings: Set( + bindings.compactMap { if case .environment(let name) = $0 { name } else { nil } } + ).sorted(), + executable: executable, arguments: arguments, workingDirectory: directory, + executableIsCaptured: snapshot.executable?.isCaptured ?? false, + workingDirectoryIsCaptured: snapshot.directory?.isCaptured ?? false, + endpoint: endpoint, readDependencies: snapshot.readDependencies) + } + + /// Tests only this selected value, never a refreshed source or matching name. + /// The sole shared provider must obey its bounded synchronous data contract. + public static func test( + _ snapshot: MCPConnectionSnapshot, options: MCPConnectionTestOptions = .init(), + environment: RuntimeEnvironment, bindings provider: any RuntimeBindingProvider + ) async -> MCPConnectionTestResult { + let started = Date() + let clock = ContinuousClock.now + var workspace: URL? + var tools: [MCPConnectionTestResult.Tool] = [] + var version: String? + var outcome = MCPConnectionTestResult.Outcome.failed + var issue: MCPConnectionTestResult.Issue? + var clean = true + do { + guard + [options.totalTimeout, options.requestTimeout].allSatisfy({ + $0.isFinite && $0 > 0 && $0 < Double(Int64.max) / 1_000_000_000 + }), options.maximumTools > 0, options.maximumPages > 0 + else { + throw MCPConnectionTestResult.Issue.invalidInput + } + guard !options.clientName.isEmpty, !options.clientVersion.isEmpty, + [options.clientName, options.clientVersion].allSatisfy({ + !$0.utf8.contains(0) && $0.utf8.count <= options.limits.textBytes + }) + else { throw MCPConnectionTestResult.Issue.invalidInput } + try Task.checkCancellation() + try snapshot.directory?.revalidate() + try snapshot.executable?.revalidate() + let description = describe(snapshot) + var remaining = options.limits.inputBytes - snapshot.inputBytes + for (key, value) in environment.environment { + guard !key.isEmpty, !key.contains("="), !key.utf8.contains(0), !value.utf8.contains(0), + key.utf8.count < remaining + else { throw MCPConnectionTestResult.Issue.invalidInput } + remaining -= key.utf8.count + 1 + guard value.utf8.count < remaining else { throw MCPConnectionTestResult.Issue.invalidInput } + remaining -= value.utf8.count + 1 + } + for name in description.environmentBindings { + guard environment.environment[name] != nil else { + throw MCPConnectionTestResult.Issue.bindingUnavailable + } + } + var secrets: [String: String] = [:] + for name in description.requiredBindings { + try Task.checkCancellation() + let data: Data + do { + data = try provider.value(for: name, environment: environment) + } catch is CancellationError { + throw CancellationError() + } catch { throw MCPConnectionTestResult.Issue.bindingUnavailable } + guard data.count < remaining, let value = String(data: data, encoding: .utf8), + !value.utf8.contains(0) + else { throw MCPConnectionTestResult.Issue.invalidBinding } + remaining -= data.count + 1 + secrets[name] = value + } + var privateValues = + Array(environment.environment.values) + Array(secrets.values) + + [options.clientName, options.clientVersion] + func resolve(_ binding: RuntimeBinding, header: Bool) throws -> String { + let value: String + switch binding { + case .literal(let text): value = text + case .environment(let name): + guard let text = environment.environment[name] else { + throw MCPConnectionTestResult.Issue.bindingUnavailable + } + value = text + case .secret(let name): value = secrets[name]! + } + guard !value.utf8.contains(0), + !header || value.utf8.allSatisfy({ $0 == 9 || ($0 >= 32 && $0 != 127) }) + else { + throw MCPConnectionTestResult.Issue.invalidBinding + } + privateValues.append(value) + if header { + privateValues += value.split(whereSeparator: { $0.isWhitespace }).map(String.init) + } + return value + } + let input: MCPConnectionInput + switch snapshot.transport { + case .stdio(let run): + let directory = FileManager.default.temporaryDirectory.appendingPathComponent( + "agents-mcp-test-" + UUID().uuidString) + try FileManager.default.createDirectory( + at: directory, withIntermediateDirectories: false, + attributes: [.posixPermissions: 0o700]) + workspace = directory + let cwd = try snapshot.directory!.materialize(in: directory, name: "cwd") + let executable = + try snapshot.executable?.materialize(in: directory, name: "executable") + .path ?? run.executable + var values = environment.environment + for key in run.environment.keys.sorted() { + values[key] = try resolve(run.environment[key]!, header: false) + } + try snapshot.directory?.revalidate() + try snapshot.executable?.revalidate() + privateValues += + run.arguments + [run.executable, executable, directory.path, cwd.path] + + (snapshot.directory?.sensitivePaths ?? []) + (snapshot.executable?.sensitivePaths ?? []) + input = .stdio( + .init( + executable: executable, arguments: run.arguments, directory: cwd, environment: values)) + case .streamableHTTP(let endpoint, let headers), .sse(let endpoint, let headers): + var values: [String: String] = [:] + for key in headers.keys.sorted() { values[key] = try resolve(headers[key]!, header: true) } + privateValues.append(endpoint) + if let url = URL(string: endpoint) { + privateValues += + URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems?.compactMap(\.value) + ?? [] + } + if snapshot.transport.kind == .sse { + input = .legacySSE(URL(string: endpoint)!, headers: values) + } else { + input = .streamableHTTP(URL(string: endpoint)!, headers: values) + } + } + try Task.checkCancellation() + let elapsed = clock.duration(to: .now) + let spent = Double(elapsed.components.seconds) + Double(elapsed.components.attoseconds) / 1e18 + guard spent < options.totalTimeout else { throw MCPConnectionTestResult.Issue.timeout } + var limits = options.limits + limits.totalTimeout -= spent + let result = await MCPConnectionRunner.run( + input, client: .init(name: options.clientName, version: options.clientVersion), + limits: limits) + clean = result.cleanupComplete + version = result.negotiatedVersion + switch result.status { + case .discovered: outcome = .discovered + case .noTools: outcome = .noTools + case .incomplete(let error): + outcome = .incomplete + issue = .init(rawValue: error.rawValue) + case .failed(let error): + outcome = .failed + issue = .init(rawValue: error.rawValue) + } + let redaction = MCPConnectionRedaction( + privateValues: privateValues, byteLimit: options.limits.textBytes) + tools = result.tools.map { + .init( + name: redaction.text($0.name), title: $0.title.map(redaction.text), + description: $0.description.map(redaction.text)) + } + } catch is CancellationError { + issue = .cancelled + } catch is MCPConnectionPreparationError { + issue = .resourceChanged + } catch let error as MCPConnectionTestResult.Issue { + issue = error + } catch { + issue = .invalidInput + } + if let workspace { + do { try FileManager.default.removeItem(at: workspace) } catch { clean = false } + } + if !clean { + outcome = .failed + issue = .cleanupFailed + } + let elapsed = clock.duration(to: .now) + return MCPConnectionTestResult( + snapshotID: snapshot.id, startedAt: started, finishedAt: Date(), + elapsed: Double(elapsed.components.seconds) + Double(elapsed.components.attoseconds) / 1e18, + transport: snapshot.transport.kind, outcome: outcome, + issue: issue, + negotiatedVersion: version, tools: tools, cleanupComplete: clean) + } +} + +extension RuntimeBinding { + fileprivate var text: String { + switch self { + case .literal(let text), .environment(let text), .secret(let text): text + } + } +} + +extension MCPTransportDeclaration { + fileprivate var bindings: [String: RuntimeBinding] { + switch self { + case .stdio(let run): run.environment + case .streamableHTTP(_, let headers), .sse(_, let headers): headers + } + } + fileprivate var kind: MCPConnectionDescription.Transport { + switch self { + case .stdio: .stdio + case .streamableHTTP: .streamableHTTP + case .sse: .sse + } + } +} diff --git a/Sources/AgentsUpdates/MCPConnectionRedaction.swift b/Sources/AgentsUpdates/MCPConnectionRedaction.swift new file mode 100644 index 0000000..b853f23 --- /dev/null +++ b/Sources/AgentsUpdates/MCPConnectionRedaction.swift @@ -0,0 +1,35 @@ +import Foundation + +/// One final public text projection: controls are removed before known private +/// values are masked, then the valid UTF8 result is bounded in bytes. +struct MCPConnectionRedaction { + private let expression: NSRegularExpression? + private let byteLimit: Int + private let hasPrivateValues: Bool + init(privateValues: [String], byteLimit: Int) { + self.byteLimit = byteLimit + let values = Set(privateValues.map(Self.withoutControls).filter { !$0.isEmpty }).sorted { + $0.count > $1.count + } + hasPrivateValues = !values.isEmpty + expression = + values.isEmpty + ? nil + : try? NSRegularExpression( + pattern: values.map(NSRegularExpression.escapedPattern(for:)).joined(separator: "|")) + } + func text(_ value: String) -> String { + guard !hasPrivateValues || expression != nil else { return "[redacted]" } + let filtered = Self.withoutControls(value) + let text = + expression?.stringByReplacingMatches( + in: filtered, range: NSRange(filtered.startIndex..., in: filtered), + withTemplate: "[redacted]") ?? filtered + var bytes = Data(text.utf8.prefix(byteLimit)) + while String(data: bytes, encoding: .utf8) == nil { bytes.removeLast() } + return String(decoding: bytes, as: UTF8.self) + } + private static func withoutControls(_ value: String) -> String { + String(value.unicodeScalars.filter { !CharacterSet.controlCharacters.contains($0) }) + } +} diff --git a/Sources/AgentsUpdates/MCPConnectionResources.swift b/Sources/AgentsUpdates/MCPConnectionResources.swift new file mode 100644 index 0000000..635dbc9 --- /dev/null +++ b/Sources/AgentsUpdates/MCPConnectionResources.swift @@ -0,0 +1,204 @@ +import AgentsCore +import Foundation + +/// A fixed source resource or explicitly live local path. Capture borrowed source +/// resources before their read scope ends; no borrowed URL is retained. +public struct MCPConnectionResource: Sendable, CustomStringConvertible, + CustomDebugStringConvertible, CustomReflectable +{ + private enum Storage: Sendable { + case live(URL, Identity) + case captured(LedgerResource, [String: Data], [String: Bool]) + } + private struct Identity: Equatable, Sendable { + let device: UInt64 + let inode: UInt64 + let targetDevice: UInt64 + let targetInode: UInt64 + let realPath: String + } + private let storage: Storage + private let sourcePath: String + let directory: Bool + let byteCount: Int + var sensitivePaths: [String] { + if case .live(let url, let identity) = storage { return [url.path, identity.realPath] } + return [] + } + var isCaptured: Bool { + if case .captured = storage { true } else { false } + } + var displayPath: String { sourcePath } + var readDependencies: [ReadDependency] { + sensitivePaths.map { .entry(URL(fileURLWithPath: $0).standardizedFileURL) } + } + public var description: String { "" } + public var debugDescription: String { description } + public var customMirror: Mirror { Mirror(self, children: [Mirror.Child]()) } + + /// Live directories preserve live content semantics; their physical identity is + /// checked again immediately before starting the connection. + public static func live(_ url: URL) throws -> Self { + do { + guard url.isFileURL else { throw MCPConnectionPreparationError.invalidResource } + let url = url.standardizedFileURL + let identity = try identity(url) + let attributes = try FileManager.default.attributesOfItem(atPath: identity.realPath) + let directory = attributes[.type] as? FileAttributeType == .typeDirectory + guard directory || attributes[.type] as? FileAttributeType == .typeRegular else { + throw MCPConnectionPreparationError.invalidResource + } + return Self( + storage: .live(url, identity), sourcePath: url.path, directory: directory, byteCount: 0) + } catch { throw MCPConnectionPreparationError.invalidResource } + } + + /// Reads only the selected resource and its contained symlink support. The + /// expected hash comes from the caller's exact linked/frozen selection. + public static func capture( + sourceRoot: URL, path: String, expectedHash: String, + expectedExecutableFiles: [String: Bool] + ) throws -> Self { + do { + let view = try SourceSnapshot( + snapshot: .init(source: "selected", revision: expectedHash), pin: nil, root: sourceRoot) + let url = try view.resource(path) + try view.validateResourceTree(url) + let captured = try LedgerResources.capture( + url, embed: true, limits: .standard, sourceRoot: sourceRoot) + guard captured.hash == expectedHash, captured.flags == expectedExecutableFiles else { + throw MCPConnectionPreparationError.resourceChanged + } + let resource = LedgerResource( + kind: .embedded, source: "selected", path: try view.relativePath(url), + hash: captured.hash, entries: captured.entries, support: captured.support) + let type = + try FileManager.default.attributesOfItem( + atPath: url.resolvingSymlinksInPath().path)[.type] as? FileAttributeType + let directory = type == .typeDirectory + guard directory || type == .typeRegular else { + throw MCPConnectionPreparationError.invalidResource + } + let count = (captured.entries + captured.support).reduce(0) { $0 + ($1.byteCount ?? 0) } + return Self( + storage: .captured(resource, captured.objects, expectedExecutableFiles), + sourcePath: resource.path, directory: directory, byteCount: count) + } catch is CancellationError { + throw CancellationError() + } catch let error as MCPConnectionPreparationError { + throw error + } catch { throw MCPConnectionPreparationError.invalidResource } + } + + /// Selected retained closure only; never acquires a source or reads deployed settings. + static func retaining( + _ resource: LedgerResource, objects: [String: Data], gitRoot: URL? + ) throws -> Self { + let workspace = FileManager.default.temporaryDirectory.appendingPathComponent( + "agents-mcp-capture-" + UUID().uuidString) + try FileManager.default.createDirectory( + at: workspace, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700]) + let result = Result { () throws -> Self in + let root: URL + let path: String + if resource.kind == .git { + guard let gitRoot else { throw MCPConnectionPreparationError.invalidResource } + root = gitRoot + path = resource.path + } else { + guard resource.kind == .embedded || resource.kind == .artifact else { + throw MCPConnectionPreparationError.invalidResource + } + let destination = workspace.appendingPathComponent("tree") + var embedded = resource + embedded.kind = .embedded + try LedgerResources.materialize(embedded, objects: objects, at: destination) + root = resource.support.isEmpty ? workspace : destination + path = resource.support.isEmpty ? "tree" : resource.path + } + let view = try SourceSnapshot( + snapshot: .init(source: "selected", revision: resource.hash), pin: nil, root: root) + let file = try view.resource(path) + try view.validateResourceTree(file) + let captured = try LedgerResources.capture( + file, embed: true, limits: .standard, sourceRoot: root) + func metadata(_ entries: [LedgerEntry]) -> [LedgerEntry] { + entries.map { entry in + var entry = entry + entry.object = nil + return entry + } + } + guard captured.hash == resource.hash, + metadata(captured.entries) == metadata(resource.entries), + metadata(captured.support) == metadata(resource.support) + else { throw MCPConnectionPreparationError.resourceChanged } + let type = + try FileManager.default.attributesOfItem(atPath: file.resolvingSymlinksInPath().path)[.type] + as? FileAttributeType + guard type == .typeDirectory || type == .typeRegular else { + throw MCPConnectionPreparationError.invalidResource + } + let retained = LedgerResource( + kind: .embedded, source: "selected", path: path, hash: captured.hash, + entries: captured.entries, support: captured.support) + let count = (captured.entries + captured.support).reduce(0) { $0 + ($1.byteCount ?? 0) } + return Self( + storage: .captured(retained, captured.objects, captured.flags), + sourcePath: resource.path, directory: type == .typeDirectory, byteCount: count) + } + try FileManager.default.removeItem(at: workspace) + return try result.get() + } + + func materialize(in workspace: URL, name: String) throws -> URL { + switch storage { + case .live(let url, _): + try revalidate() + return url + case .captured(let resource, let objects, let expectedFlags): + let destination = workspace.appendingPathComponent(name) + try LedgerResources.materialize(resource, objects: objects, at: destination) + let file = + resource.support.isEmpty + ? destination : try PathSafety.resolvedChild(base: destination, subpath: resource.path) + let hash = try directory ? FileHash.folderHash(file) : FileHash.sha256Hex(file: file) + let flags: [String: Bool] + if directory { + flags = try FileHash.executableFlags(file) + } else { + let mode = try FileManager.default.attributesOfItem(atPath: file.path)[.posixPermissions] + flags = [".": ((mode as? NSNumber)?.intValue ?? 0) & 0o111 != 0] + } + guard "sha256:" + hash == resource.hash, flags == expectedFlags else { + throw MCPConnectionPreparationError.resourceChanged + } + return file + } + } + + func revalidate() throws { + if case .live(let url, let expected) = storage { + do { + guard try Self.identity(url) == expected else { + throw MCPConnectionPreparationError.resourceChanged + } + } catch { throw MCPConnectionPreparationError.resourceChanged } + } + } + + private static func identity(_ url: URL) throws -> Identity { + let attributes = try FileManager.default.attributesOfItem(atPath: url.path) + let real = url.resolvingSymlinksInPath().standardizedFileURL + let target = try FileManager.default.attributesOfItem(atPath: real.path) + guard let device = attributes[.systemNumber] as? NSNumber, + let inode = attributes[.systemFileNumber] as? NSNumber, + let targetDevice = target[.systemNumber] as? NSNumber, + let targetInode = target[.systemFileNumber] as? NSNumber + else { throw MCPConnectionPreparationError.resourceChanged } + return Identity( + device: device.uint64Value, inode: inode.uint64Value, + targetDevice: targetDevice.uint64Value, targetInode: targetInode.uint64Value, + realPath: real.path) + } +} diff --git a/Sources/AgentsUpdates/MCPConnectionSelection.swift b/Sources/AgentsUpdates/MCPConnectionSelection.swift new file mode 100644 index 0000000..3821dd3 --- /dev/null +++ b/Sources/AgentsUpdates/MCPConnectionSelection.swift @@ -0,0 +1,118 @@ +import AgentsCore +import AgentsManifest +import Components +import Foundation + +extension MCPConnectionOperations { + /// Prepares one managed inspection selection without resolving sources, reading + /// native configuration, acquiring bindings or starting the selected program. + /// All read locks and borrowed resource scopes end before this value returns. + public static func snapshot( + selection: ComponentSelection, scope: InstallScope, environment: RuntimeEnvironment + ) throws -> MCPConnectionSnapshot { + let store = StateStore(scope: scope, environment: environment) + do { + return try store.withReadLock { + let baseline = try StatePrecondition(store: store) + let document = try store.declarationDocument(prepared: baseline) + let ledger = try store.readLedger(prepared: baseline) + let generation = try ResolvedLedgerCodec.digest([ + ResolvedLedgerCodec.digest(ledger), document?.digest ?? "absent", + ]) + guard generation == selection.generation else { + throw MCPConnectionPreparationError.invalidSelection + } + let matches = try ledger.components.filter { + try LedgerImpact.identity($0.value, ledger: ledger, roots: store.ledgerRoots) + == selection.identity + } + guard matches.count == 1, let selected = matches.first, + selected.value.kind == DeclaredComponentKind.mcpServer.rawValue + else { throw MCPConnectionPreparationError.invalidSelection } + let occurrences = ledger.occurrences.filter { $0.component == selected.key } + guard !occurrences.isEmpty, + selection.occurrence.map({ id in occurrences.contains { $0.id == id } }) ?? true + else { throw MCPConnectionPreparationError.invalidSelection } + guard selected.value.payload.object?["name"]?.kind == .string, + selected.value.payload.object?["name"]?.text == selected.value.name + else { throw MCPConnectionPreparationError.invalidConfiguration } + let transport = try managedTransport(selected.value.payload) + var remaining = LedgerLimits.standard.resourceBytes + for id in selected.value.resources { + guard let resource = ledger.resources[id] else { + throw MCPConnectionPreparationError.invalidResource + } + for entry in resource.entries + resource.support { + let count = entry.byteCount ?? 0 + guard count >= 0, count <= remaining else { + throw MCPConnectionPreparationError.invalidResource + } + remaining -= count + } + } + var resources = selected.value.resources.makeIterator() + func capture() throws -> MCPConnectionResource { + guard let id = resources.next(), let resource = ledger.resources[id] else { + throw MCPConnectionPreparationError.invalidResource + } + if resource.kind == .liveEdit { + guard let location = resource.location else { + throw MCPConnectionPreparationError.invalidResource + } + return try .live(location.resolve(roots: store.ledgerRoots)) + } + var root: URL? + if resource.kind == .git { + var sourceID = resource.source + while let parent = ledger.sources[sourceID]?.container { sourceID = parent } + guard let source = ledger.sources[sourceID] else { + throw MCPConnectionPreparationError.invalidResource + } + let cache = SourceCache(store: store) + let retained = cache.materializedURL( + sourceID: try ledger.sourceIdentity(sourceID, roots: store.ledgerRoots), + revision: source.revision) + try cache.validatePath(retained) + root = retained + } + return try .retaining(resource, objects: ledger.contentObjects, gitRoot: root) + } + var directory: MCPConnectionResource? + var executable: MCPConnectionResource? + if case .stdio(let run) = transport { + if run.executable.contains("/") { executable = try capture() } + directory = + try run.workingDirectory == nil ? .live(environment.projectDirectory) : capture() + } + guard resources.next() == nil else { throw MCPConnectionPreparationError.invalidResource } + var result = try snapshot( + selectionID: selection.identity, transport: transport, + workingDirectory: directory, executable: executable) + result.durableReadDependencies = Array( + Set( + result.readDependencies + + (try UpdateOperations.readLocations( + declarations: [], ledgers: [ledger], store: store)).map(ReadDependency.subtree) + ) + ).sorted { + if $0.url.path != $1.url.path { return $0.url.path < $1.url.path } + if case .entry = $0 { return false } + if case .entry = $1 { return true } + return false + } + try baseline.validate() + return result + } + } catch is CancellationError { + throw CancellationError() + } catch let error as MCPConnectionPreparationError { + throw error + } catch { throw MCPConnectionPreparationError.invalidSelection } + } + + static func managedTransport(_ payload: LedgerValue) throws -> MCPTransportDeclaration { + do { return try MCPTransportDeclaration(ledgerPayload: payload) } catch { + throw MCPConnectionPreparationError.invalidConfiguration + } + } +} diff --git a/Sources/AgentsUpdates/MCPRegistry.swift b/Sources/AgentsUpdates/MCPRegistry.swift new file mode 100644 index 0000000..a95f41c --- /dev/null +++ b/Sources/AgentsUpdates/MCPRegistry.swift @@ -0,0 +1,351 @@ +import AgentsCore +import AgentsManifest +import Foundation +import Synchronization + +#if canImport(FoundationNetworking) + import FoundationNetworking +#endif + +public enum MCPRegistryError: Error, Equatable, LocalizedError, Sendable { + case invalidEndpoint + case invalidQuery + case invalidCredentials + case requestFailed + case redirectRejected + case httpStatus(Int) + case responseTooLarge + case invalidResponse + case unavailableChoice(String) + case invalidSelection + case invalidBinding(String) + case missingBinding(String) + case invalidPackageCommand + case missingPackageCommand + + public var errorDescription: String? { + switch self { + case .invalidEndpoint: "The MCP registry needs an HTTP(S) base URL without credentials." + case .invalidQuery: "The MCP registry query is invalid." + case .invalidCredentials: "The request credentials are invalid for this MCP registry." + case .requestFailed: "The MCP registry request failed." + case .redirectRejected: "The MCP registry redirected the request. Use its canonical base URL." + case .httpStatus(let code): "The MCP registry returned HTTP \(code)." + case .responseTooLarge: "The MCP registry response exceeded the page size budget." + case .invalidResponse: "The MCP registry response does not match the request or v0.1 format." + case .unavailableChoice(let reason): reason + case .invalidSelection: "Choose a name and at least one distinct MCP recipient." + case .invalidBinding(let name): "Invalid symbolic MCP binding for \(name)." + case .missingBinding(let name): "An input is required for \(name)." + case .invalidPackageCommand: "The package console command is invalid for this choice." + case .missingPackageCommand: "Enter the console command provided by the Python distribution." + } + } +} + +public struct MCPRegistryPage: Sendable { + public let servers: [MCPRegistryServer] + /// Pass this opaque value back with the same search and version filter. + public let nextCursor: String? +} + +/// A read-only MCP Registry v0.1 client. Authentication is supplied to each request explicitly. +public struct MCPRegistry: Sendable { + public static let official = try! MCPRegistry( + endpoint: URL(string: "https://registry.modelcontextprotocol.io")!) + + /// The operator-selected registry for this runtime, or the public registry when unset. + public static func configured(environment: RuntimeEnvironment = RuntimeEnvironment()) throws + -> Self + { + guard let setting = environment.environment["MCP_REGISTRY_URL"], !setting.isEmpty else { + return .official + } + guard let url = URL(string: setting) else { throw MCPRegistryError.invalidEndpoint } + return try MCPRegistry(endpoint: url) + } + + /// The registry base including any path prefix, before `/v0.1`. + public let endpoint: URL + private let servers: URLComponents + + public init(endpoint: URL) throws { + guard var servers = URLComponents(url: endpoint, resolvingAgainstBaseURL: true), + RegistryHTTP.validURL(servers), servers.query == nil, + let absolute = servers.url + else { throw MCPRegistryError.invalidEndpoint } + servers.percentEncodedPath = + servers.percentEncodedPath.replacingOccurrences( + of: #"/+$"#, with: "", options: .regularExpression) + + "/v0.1/servers" + self.endpoint = absolute + self.servers = servers + } + + /// An omitted query lists servers. An omitted version lists all versions. Credential + /// headers are scoped to this call and are never attached to results or selections. + public func search( + _ query: String? = nil, version: String? = "latest", limit: Int = 20, cursor: String? = nil, + credentials: [String: String] = [:], scope: InstallScope = .project, + environment: RuntimeEnvironment = RuntimeEnvironment(), refresh: Bool = false + ) async throws -> MCPRegistryPage { + let policy = try SourcePolicySnapshot(store: StateStore(scope: scope, environment: environment)) + try policy.effective.require(.http(endpoint.absoluteString)) + guard (1...100).contains(limit), version?.isEmpty != true else { + throw MCPRegistryError.invalidQuery + } + var url = servers + var fields = [("limit", String(limit))] + if let query, !query.isEmpty { fields.append(("search", query)) } + if let version { fields.append(("version", version)) } + if let cursor, !cursor.isEmpty { fields.append(("cursor", cursor)) } + url.percentEncodedQuery = fields.map { $0.0 + "=" + Self.escape($0.1) }.joined(separator: "&") + return try await read( + RegistryPageResponse.self, from: url, credentials: credentials, environment: environment, + refresh: refresh + ) { page in + try policy.validate() + return MCPRegistryPage( + servers: try page.servers.map { try $0.inspection(registry: endpoint) }, + nextCursor: page.metadata?.nextCursor.flatMap { $0.isEmpty ? nil : $0 }) + } + } + + /// Retrieves one server by its full registry name and exact version or the `latest` alias. + public func server( + named name: String, version: String = "latest", credentials: [String: String] = [:], + scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment(), + refresh: Bool = false + ) async throws -> MCPRegistryServer { + let policy = try SourcePolicySnapshot(store: StateStore(scope: scope, environment: environment)) + try policy.effective.require(.http(endpoint.absoluteString), reference: name) + let invalidSegments = ["", ".", ".."] + guard !invalidSegments.contains(name), !invalidSegments.contains(version) else { + throw MCPRegistryError.invalidQuery + } + var url = servers + url.percentEncodedPath += "/" + Self.escape(name) + "/versions/" + Self.escape(version) + return try await read( + RegistryServerResponse.self, from: url, credentials: credentials, environment: environment, + refresh: refresh + ) { result in + guard result.server.name.utf8.elementsEqual(name.utf8), + version == "latest" || result.server.version.utf8.elementsEqual(version.utf8) + else { throw MCPRegistryError.invalidResponse } + try policy.validate() + return try result.inspection(registry: endpoint) + } + } + + private static func escape(_ value: String) -> String { + value.addingPercentEncoding( + withAllowedCharacters: CharacterSet( + charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"))! + } + + private func read( + _ type: Value.Type, from components: URLComponents, credentials: [String: String], + environment: RuntimeEnvironment, refresh: Bool, validate: (Value) throws -> Result + ) async throws -> Result { + guard let url = components.url else { throw MCPRegistryError.invalidQuery } + try environment.requireMCPRegistry(endpoint) + let reserved = [ + "accept", "connection", "content-length", "content-type", "host", "proxy-authorization", + "proxy-connection", "te", "trailer", "transfer-encoding", "upgrade", + ] + guard credentials.isEmpty || RegistryHTTP.protectsCredentials(url), + Set(credentials.keys.map { $0.lowercased() }).count == credentials.count, + credentials.allSatisfy({ + RegistryHTTP.isHeaderName($0.key) && !reserved.contains($0.key.lowercased()) + && RegistryHTTP.isHeaderValue($0.value) + }) + else { throw MCPRegistryError.invalidCredentials } + + var request = URLRequest(url: url) + request.setValue("application/json", forHTTPHeaderField: "Accept") + for (name, value) in credentials { request.setValue(value, forHTTPHeaderField: name) } + + request.httpShouldHandleCookies = false + return try await RegistryAcquisition(environment: environment, endpoint: endpoint).read( + request, anonymous: credentials.isEmpty, refresh: refresh + ) { data in + try Task.checkCancellation() + try environment.requireMCPRegistry(endpoint) + let value: Value + do { + value = try JSONDecoder().decode(type, from: data) + } catch { + // Decoder errors can contain server-provided content, including reflected credentials. + throw MCPRegistryError.invalidResponse + } + return try validate(value) + } + } +} + +/// Bounded in-memory response transfer. The delegate refuses redirects before any new request. +final class RegistryHTTP: NSObject, URLSessionDataDelegate { + static let responseLimit = AcquisitionCache.registryResponseLimit + struct Response: Sendable { + let url: URL + let status: Int + let headers: [String: String] + let body: Data + } + + private struct Transfer { + var response: HTTPURLResponse? + var body = Data() + var failure: MCPRegistryError? + var continuation: CheckedContinuation? + var cancelled = false + } + private let transfer = Mutex(Transfer()) + + static func validURL(_ url: URLComponents) -> Bool { + ["http", "https"].contains(url.scheme?.lowercased() ?? "") && url.host?.isEmpty == false + && url.user == nil && url.password == nil && url.fragment == nil + } + + static func protectsCredentials(_ url: URL) -> Bool { + url.scheme?.lowercased() == "https" || ["127.0.0.1", "[::1]", "::1"].contains(url.host ?? "") + } + + static func isHeaderName(_ name: String) -> Bool { + !name.isEmpty + && name.utf8.allSatisfy { + (65...90).contains($0) || (97...122).contains($0) || (48...57).contains($0) + || "!#$%&'*+-.^_`|~".utf8.contains($0) + } + } + + static func isHeaderValue(_ value: String) -> Bool { + value.utf8.allSatisfy { $0 == 9 || (32...126).contains($0) } + } + + func read(_ request: URLRequest) async throws -> Response { + let configuration = URLSessionConfiguration.ephemeral + configuration.httpCookieStorage = nil + configuration.httpShouldSetCookies = false + configuration.urlCredentialStorage = nil + configuration.urlCache = nil + configuration.connectionProxyDictionary = [ + "HTTPEnable": 0, "HTTPSEnable": 0, "SOCKSEnable": 0, + "ProxyAutoConfigEnable": 0, "ProxyAutoDiscoveryEnable": 0, + ] + configuration.requestCachePolicy = .reloadIgnoringLocalCacheData + configuration.timeoutIntervalForRequest = 30 + configuration.timeoutIntervalForResource = 30 + let session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil) + defer { session.finishTasksAndInvalidate() } + let task = session.dataTask(with: request) + return try await withTaskCancellationHandler { + try await withCheckedThrowingContinuation { continuation in + transfer.withLock { + if $0.cancelled { + continuation.resume(throwing: CancellationError()) + } else { + $0.continuation = continuation + task.resume() + } + } + } + } onCancel: { + let started = self.transfer.withLock { + $0.cancelled = true + return $0.continuation != nil + } + if started { task.cancel() } + } + } + + func urlSession( + _ session: URLSession, task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, + completionHandler: @escaping @Sendable (URLRequest?) -> Void + ) { + transfer.withLock { $0.failure = .redirectRejected } + completionHandler(nil) + } + + func urlSession( + _ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, + completionHandler: + @escaping @Sendable (URLSession.AuthChallengeDisposition, URLCredential?) -> Void + ) { + #if canImport(Security) + if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { + completionHandler(.performDefaultHandling, nil) + return + } + #endif + let status = (challenge.failureResponse as? HTTPURLResponse)?.statusCode + transfer.withLock { $0.failure = status.map(MCPRegistryError.httpStatus) ?? .requestFailed } + completionHandler(.cancelAuthenticationChallenge, nil) + } + + func urlSession( + _ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, + completionHandler: @escaping @Sendable (URLSession.ResponseDisposition) -> Void + ) { + let allowed = transfer.withLock { + guard $0.failure == nil else { return false } + guard let response = response as? HTTPURLResponse else { + $0.failure = .invalidResponse + return false + } + guard response.statusCode == 200 || response.statusCode == 304 else { + $0.failure = .httpStatus(response.statusCode) + return false + } + guard response.expectedContentLength <= Self.responseLimit else { + $0.failure = .responseTooLarge + return false + } + $0.response = response + return true + } + completionHandler(allowed ? .allow : .cancel) + } + + func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + let exceeded = transfer.withLock { + guard data.count <= Self.responseLimit - $0.body.count else { + $0.failure = .responseTooLarge + return true + } + $0.body.append(data) + return false + } + if exceeded { dataTask.cancel() } + } + + func urlSession( + _ session: URLSession, task: URLSessionTask, didCompleteWithError error: (any Error)? + ) { + transfer.withLock { + guard let continuation = $0.continuation else { return } + $0.continuation = nil + if $0.cancelled { + continuation.resume(throwing: CancellationError()) + } else if let failure = $0.failure { + continuation.resume(throwing: failure) + } else if error != nil { + continuation.resume(throwing: MCPRegistryError.requestFailed) + } else if let response = $0.response, let url = response.url { + var headers: [String: String] = [:] + for (key, value) in response.allHeaderFields { + if let key = key as? String, let value = value as? String { + let field = key.lowercased() + headers[field] = headers[field].map { $0 + ", " + value } ?? value + } + } + continuation.resume( + returning: .init( + url: url, status: response.statusCode, headers: headers, body: $0.body)) + } else { + continuation.resume(throwing: MCPRegistryError.invalidResponse) + } + } + } +} diff --git a/Sources/AgentsUpdates/MCPRegistrySelection.swift b/Sources/AgentsUpdates/MCPRegistrySelection.swift new file mode 100644 index 0000000..4374b70 --- /dev/null +++ b/Sources/AgentsUpdates/MCPRegistrySelection.swift @@ -0,0 +1,641 @@ +import AgentsCore +import Components +import Foundation + +/// One version returned by a registry. Its choices retain the fetched definition. +public struct MCPRegistryServer: Sendable { + public let registry: URL + public let name: String + public let version: String + public let title: String? + public let description: String + public let status: String? + public let choices: [MCPRegistryChoice] + + static func attestsBindings( + in transport: MCPTransportDeclaration, for registry: MCPRegistryEvidence, + schemas: [Self] + ) -> Bool { + var matched = false + for server in schemas + where server.registry.absoluteString.utf8.elementsEqual(registry.registry.utf8) + && server.name.utf8.elementsEqual(registry.server.utf8) + && server.version.utf8.elementsEqual(registry.version.utf8) + { + guard server.choices.filter({ $0.attestsBindings(in: transport, for: registry) }).count == 1 + else { return false } + matched = true + } + return matched + } +} + +public struct MCPRegistryPackage: Sendable { + public let registryType: String + public let identifier: String + public let version: String? + public let registryBaseURL: URL? + public let runtimeHint: String? + public let fileSHA256: String? +} + +/// A configurable server header or process environment variable. +public struct MCPRegistryBindingRequirement: Sendable { + public let name: String + public let description: String? + public let isRequired: Bool + public let isSecret: Bool + /// Non-secret registry default. A caller can override it through the binding. + public let defaultValue: String? + /// When present, selection requires one of these non-secret registry values. + public let choices: [String] +} + +public enum MCPRegistryBinding: Sendable { + /// The client reads this variable at run time. For headers it supplies the complete value. + case environment(String) + /// A value literally listed in the requirement's choices. + case choice(String) +} + +/// A single remote or package choice from an immutable server version. +public struct MCPRegistryChoice: Sendable { + public enum Source: Sendable { + case remote(endpoint: URL?) + case package(MCPRegistryPackage) + } + + public let source: Source + /// The v0.1 transport discriminator, including kinds this package cannot deploy. + public let transport: String + public let bindings: [MCPRegistryBindingRequirement] + public let unavailableReason: String? + /// PyPI metadata identifies the distribution. The caller supplies its console command. + public var requiresPackageCommand: Bool { + if case .package(let launcher) = plan { return launcher.coordinate == nil } + return false + } + private let plan: RegistryMCPPlan? + private let slots: [RegistryMCPSlot] + private let evidence: MCPRegistryEvidence? + + fileprivate func attestsBindings( + in definition: MCPTransportDeclaration, for registry: MCPRegistryEvidence + ) -> Bool { + guard let plan, evidence?.origin == registry.origin, evidence?.package == registry.package + else { + return false + } + let fields: [String: RuntimeBinding] + switch (plan, definition) { + case (.remote(let expected), .streamableHTTP(let url, let headers)) + where transport == "streamable-http" && expected.absoluteString.utf8.elementsEqual(url.utf8): + fields = headers + case (.remote(let expected), .sse(let url, let headers)) + where transport == "sse" && expected.absoluteString.utf8.elementsEqual(url.utf8): + fields = headers + case (.package(let launcher), .stdio(let run)): + let packageCommand = + launcher.coordinate == nil + ? run.arguments.dropLast(launcher.arguments.count).last : nil + guard + let expected = try? launcher.executable( + environment: run.environment, packageCommand: packageCommand), expected == run + else { return false } + fields = run.environment + default: return false + } + let requirements = Dictionary(uniqueKeysWithValues: slots.map { ($0.name, $0) }) + guard + slots.allSatisfy({ + ($0.literal == nil && $0.requirement?.isRequired != true) || fields[$0.name] != nil + }) + else { return false } + return fields.allSatisfy { name, field in + guard let slot = requirements[name] else { return false } + guard case .literal(let value) = field else { return true } + return slot.requirement?.isSecret != true + && slot.candidateValues.contains { $0.utf8.elementsEqual(value.utf8) } + } + } + + /// Checks the portable choice and current native mappings for these references. Scope + /// ownership and existing configuration are checked by the ordinary preview. + public func compatibleAgents( + in scope: InstallScope, bindings: [String: MCPRegistryBinding] = [:], + packageCommand: String? = nil + ) throws -> [AgentID] { + let declaration = try transportDeclaration(bindings, packageCommand: packageCommand) + return AgentID.allCases.filter { agent in + (try? DeploymentConstruction.validateMCP( + declaration, named: "mcp", agent: agent, scope: scope, requiresSymbolicBindings: true)) + != nil + } + } + + /// Composes this captured choice into a finite managed addition. Binding keys are the + /// requirement names. Selection makes no registry request and targets are explicit. + public func select( + named name: String, agents: [AgentID], in destination: ScopeInspection, + bindings: [String: MCPRegistryBinding] = [:], packageCommand: String? = nil + ) throws -> ComponentDiscovery { + guard !name.isEmpty, !agents.isEmpty, Set(agents).count == agents.count else { + throw MCPRegistryError.invalidSelection + } + let transport = try transportDeclaration(bindings, packageCommand: packageCommand) + for agent in agents { + try DeploymentConstruction.validateMCP( + transport, named: name, agent: agent, scope: destination.scope, + requiresSymbolicBindings: true) + } + guard let evidence else { throw MCPRegistryError.invalidSelection } + let addition = Declaration(components: [ + .mcpServer( + name: name, transport: transport, agents: agents, + registry: try evidence.bound(to: transport)) + ]) + guard let discovery = try UpdateOperations.captureAddition(addition, in: destination) else { + throw MCPRegistryError.invalidSelection + } + return discovery + } + + private func transportDeclaration( + _ supplied: [String: MCPRegistryBinding], packageCommand: String? + ) throws -> MCPTransportDeclaration { + guard let plan else { + throw MCPRegistryError.unavailableChoice( + unavailableReason ?? "MCP choice cannot be deployed.") + } + let expected = Set(bindings.map(\.name)) + if let unknown = supplied.keys.sorted().first(where: { !expected.contains($0) }) { + throw MCPRegistryError.invalidBinding(unknown) + } + var values: [String: RuntimeBinding] = [:] + for slot in slots { + if let literal = slot.literal { + values[slot.name] = .literal(literal) + continue + } + guard let requirement = slot.requirement else { continue } + switch supplied[slot.name] { + case .environment(let name): + guard requirement.choices.isEmpty, RegistryInput.isEnvironmentName(name) else { + throw MCPRegistryError.invalidBinding(slot.name) + } + values[slot.name] = .environment(name) + case .choice(let value): + guard requirement.choices.contains(value) else { + throw MCPRegistryError.invalidBinding(slot.name) + } + values[slot.name] = .literal(value) + case nil: + if requirement.choices.isEmpty, let fallback = requirement.defaultValue { + values[slot.name] = .literal(fallback) + } else if requirement.isRequired { + throw MCPRegistryError.missingBinding(slot.name) + } + } + } + switch plan { + case .remote(let url): + guard packageCommand == nil else { throw MCPRegistryError.invalidPackageCommand } + if supplied.values.contains(where: { + if case .environment = $0 { return true } + return false + }), !RegistryHTTP.protectsCredentials(url) { + throw MCPRegistryError.unavailableChoice("An MCP endpoint with bindings requires HTTPS.") + } + return transport == "sse" + ? .sse(url: url.absoluteString, headers: values) + : .streamableHTTP(url: url.absoluteString, headers: values) + case .package(let launcher): + return .stdio(try launcher.executable(environment: values, packageCommand: packageCommand)) + } + } + + fileprivate init( + source: Source, transport: String, slots: [RegistryMCPSlot], deleted: Bool, + registry: RegistryServerCoordinate, + prepare: () throws -> RegistryMCPPlan + ) { + self.source = source + self.transport = transport + self.slots = slots + bindings = slots.compactMap(\.requirement) + do { + if deleted { throw unavailable("This MCP registry version was deleted.") } + guard slots.allSatisfy(\.isRepresentable) else { + throw unavailable("The registry listed choices that cannot be preserved for an MCP input.") + } + let prepared = try prepare() + evidence = try registry.evidence(for: prepared) + plan = prepared + unavailableReason = nil + } catch { + evidence = nil + plan = nil + unavailableReason = + (error as? MCPRegistryError)?.errorDescription + ?? "MCP choice cannot be deployed." + } + } +} + +struct RegistryPageResponse: Decodable { + struct Metadata: Decodable { + let nextCursor: String? + } + let servers: [RegistryServerResponse] + let metadata: Metadata? +} + +struct RegistryServerResponse: Decodable { + struct Server: Decodable { + let name: String + let description: String + let title: String? + let version: String + let remotes: [RegistryTransport]? + let packages: [RegistryPackage]? + } + + struct Metadata: Decodable { + struct Official: Decodable { + let status: String? + } + enum CodingKeys: String, CodingKey { + case official = "io.modelcontextprotocol.registry/official" + } + let official: Official? + } + + let server: Server + let _meta: Metadata? + + func inspection(registry: URL) throws -> MCPRegistryServer { + guard !server.name.isEmpty, !server.version.isEmpty, server.version != "latest" else { + throw MCPRegistryError.invalidResponse + } + let status = _meta?.official?.status + let deleted = status == "deleted" + let coordinate = RegistryServerCoordinate( + registry: registry, name: server.name, version: server.version) + return .init( + registry: registry, name: server.name, version: server.version, title: server.title, + description: server.description, status: status, + choices: (server.remotes ?? []).map { $0.choice(deleted: deleted, registry: coordinate) } + + (server.packages ?? []).map { $0.choice(deleted: deleted, registry: coordinate) }) + } +} + +struct RegistryTransport: Decodable { + let type: String + let url: String? + let headers: [RegistryInput]? + let variables: [String: RegistryInput]? + + fileprivate func choice(deleted: Bool, registry: RegistryServerCoordinate) -> MCPRegistryChoice { + let resolved = RegistryInput.resolve(url, variables: variables) + let endpoint = resolved.flatMap { URLComponents(string: $0) }.flatMap { url in + RegistryHTTP.validURL(url) + && url.queryItems?.contains(where: { + RegistryInput.isCredentialName($0.name) + }) != true ? url.url : nil + } + let slots = (headers ?? []).compactMap { $0.slot() } + return MCPRegistryChoice( + source: .remote(endpoint: endpoint), transport: type, slots: slots, deleted: deleted, + registry: registry + ) { + guard type == "streamable-http" || type == "sse" else { + throw unavailable("The registry listed an unsupported remote transport.") + } + guard let endpoint else { + throw unavailable("The registry endpoint needs a fixed, credential-free HTTP URL.") + } + let reserved = [ + "host", "connection", "content-length", "proxy-authorization", "proxy-connection", + "transfer-encoding", "te", "trailer", "upgrade", + ] + let names = slots.map { $0.name.lowercased() } + guard slots.count == (headers ?? []).count, Set(names).count == names.count, + slots.allSatisfy({ + RegistryHTTP.isHeaderName($0.name) && !reserved.contains($0.name.lowercased()) + && $0.candidateValues.allSatisfy(RegistryHTTP.isHeaderValue) + }) + else { throw unavailable("The registry listed invalid or duplicate MCP headers.") } + return .remote(endpoint) + } + } +} + +struct RegistryPackage: Decodable { + let registryType: String + let registryBaseUrl: String? + let identifier: String + let version: String? + let fileSha256: String? + let runtimeHint: String? + let transport: RegistryTransport + let runtimeArguments: [RegistryInput]? + let packageArguments: [RegistryInput]? + let environmentVariables: [RegistryInput]? + + fileprivate func choice(deleted: Bool, registry: RegistryServerCoordinate) -> MCPRegistryChoice { + let baseURL = registryBaseUrl.flatMap { URLComponents(string: $0) }.flatMap { url in + RegistryHTTP.validURL(url) && url.scheme?.lowercased() == "https" && url.query == nil + ? url : nil + } + let package = MCPRegistryPackage( + registryType: registryType, identifier: identifier, version: version, + registryBaseURL: baseURL?.url, runtimeHint: runtimeHint, fileSHA256: fileSha256) + let slots = (environmentVariables ?? []).compactMap { $0.slot() } + return MCPRegistryChoice( + source: .package(package), transport: transport.type, slots: slots, deleted: deleted, + registry: registry + ) { + guard transport.type == "stdio" else { + throw unavailable("Managed packages support stdio only.") + } + guard fileSha256 == nil else { + throw unavailable("This package requires launcher-level checksum verification.") + } + guard runtimeArguments?.isEmpty != false else { + throw unavailable("This package requires custom launcher arguments.") + } + guard registryBaseUrl == nil || baseURL?.url != nil else { + throw unavailable("The package registry needs a credential-free HTTPS base URL.") + } + let names = slots.map(\.name) + guard slots.count == (environmentVariables ?? []).count, Set(names).count == names.count, + names.allSatisfy(RegistryInput.isEnvironmentName) + else { throw unavailable("The registry listed invalid or duplicate environment names.") } + let arguments = try (packageArguments ?? []).flatMap { try $0.argument() } + return .package(try launcher(baseURL: baseURL, arguments: arguments)) + } + } + + private func launcher(baseURL: URLComponents?, arguments: [String]) throws -> RegistryLauncher { + let runtime: String + let prefix: [String] + let coordinate: String? + let package: String + let origin: String + switch registryType { + case "npm": + runtime = "npx" + guard identifier.matches(#"^(?:@[a-z0-9][a-z0-9._-]*/)?[a-z0-9][a-z0-9._-]*$"#), + let version, + version.matches(#"^v?[0-9]+\.[0-9]+\.[0-9]+(?:-[A-Za-z0-9.-]+)?(?:\+[A-Za-z0-9.-]+)?$"#) + else { throw unavailable("The npm choice needs a package name and an exact version.") } + origin = baseURL?.string ?? "https://registry.npmjs.org" + prefix = ["--yes", "--registry=" + origin, "--"] + package = identifier + "@" + version + coordinate = package + case "pypi": + runtime = "uvx" + guard identifier.matches(#"^[A-Za-z0-9][A-Za-z0-9._-]*$"#), + let version, version.matches(#"^[0-9][A-Za-z0-9._+!-]*$"#) + else { throw unavailable("The PyPI choice needs a distribution name and an exact version.") } + let index = baseURL.flatMap { url in + url.host == "pypi.org" && ["", "/"].contains(url.path) + ? "https://pypi.org/simple" : url.string + } + origin = index ?? "https://pypi.org/simple" + package = identifier + "==" + version + prefix = ["--default-index", origin, "--from", package, "--"] + coordinate = nil + case "oci": + runtime = "docker" + prefix = ["run", "--rm", "-i"] + let image = try image(baseURL: baseURL) + package = image.reference + coordinate = package + origin = "https://" + image.host + default: + throw unavailable("The registry listed an unsupported package type.") + } + guard runtimeHint == nil || runtimeHint == runtime else { + throw unavailable("The package requires an unsupported launcher.") + } + return .init( + command: runtime, prefix: prefix, coordinate: coordinate, arguments: arguments, + package: package, origin: origin) + } + + private func image(baseURL: URLComponents?) throws -> (reference: String, host: String) { + let reference = identifier.split(separator: "@", omittingEmptySubsequences: false) + guard let coordinate = reference.first, reference.count <= 2 else { + throw unavailable("The OCI choice needs a valid image name.") + } + let path = coordinate.split(separator: "/", omittingEmptySubsequences: false) + let tail = path.last?.split(separator: ":", omittingEmptySubsequences: false) ?? [] + guard let last = tail.first, tail.count <= 2 else { + throw unavailable("The OCI choice needs a valid image name.") + } + let segments = path.dropLast() + [last] + let first = segments[0] + let qualified = + path.count > 1 && (first.contains(".") || first.contains(":") || first == "localhost") + let registryHost = baseURL?.host.map { $0 + (baseURL?.port.map { ":" + String($0) } ?? "") } + let repositoryPath = qualified ? segments.dropFirst() : segments[...] + guard repositoryPath.allSatisfy({ $0.matches(#"^[a-z0-9][a-z0-9._-]*$"#) }), + !qualified || first.matches(#"^[a-z0-9][a-z0-9.-]*(?::[0-9]+)?$"#), + baseURL.map({ ["", "/"].contains($0.path) }) ?? true, + registryHost == nil || !qualified || String(first) == registryHost + else { throw unavailable("The OCI image and its registry are inconsistent.") } + + let repository = + (qualified ? "" : registryHost.map { $0 + "/" } ?? "") + + segments.joined(separator: "/") + let host = qualified ? String(first) : registryHost ?? "docker.io" + if reference.count == 2 { + guard reference[1].matches(#"^sha256:[a-f0-9]{64}$"#) else { + throw unavailable("The OCI image digest is invalid.") + } + return (repository + "@" + reference[1], host) + } + let tag = tail.count == 2 ? String(tail[1]) : version + guard let tag, tag.lowercased() != "latest", + tag.matches(#"^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$"#), + version == nil || tag == version + else { throw unavailable("The OCI choice needs an exact image tag or digest.") } + return (repository + ":" + tag, host) + } +} + +private struct RegistryServerCoordinate: Sendable { + let registry: URL + let name: String + let version: String + + func evidence(for plan: RegistryMCPPlan) throws -> MCPRegistryEvidence { + let url: String + let package: String? + switch plan { + case .remote(let endpoint): + url = endpoint.absoluteString + package = nil + case .package(let launcher): + url = launcher.origin + package = launcher.package + } + let origin = try SourceOrigin.http(url) + let evidence = MCPRegistryEvidence( + registry: registry.absoluteString, server: name, version: version, + origin: origin.identity!, package: package) + try evidence.validate() + return evidence + } +} + +private enum RegistryMCPPlan: Sendable { + case remote(URL) + case package(RegistryLauncher) +} + +private struct RegistryLauncher: Sendable { + let command: String + let prefix: [String] + let coordinate: String? + let arguments: [String] + let package: String + let origin: String + + func executable( + environment: [String: RuntimeBinding], packageCommand: String? + ) throws -> ExecutableDeclaration { + let target: String + if let coordinate { + guard packageCommand == nil else { throw MCPRegistryError.invalidPackageCommand } + target = coordinate + } else { + guard let packageCommand else { throw MCPRegistryError.missingPackageCommand } + guard packageCommand.matches(#"^[A-Za-z0-9][A-Za-z0-9._-]*$"#) else { + throw MCPRegistryError.invalidPackageCommand + } + target = packageCommand + } + let forwarded = command == "docker" ? environment.keys.sorted().flatMap { ["-e", $0] } : [] + return .init( + executable: command, arguments: prefix + forwarded + [target] + arguments, + environment: environment) + } +} + +private struct RegistryMCPSlot: Sendable { + let name: String + let literal: String? + let requirement: MCPRegistryBindingRequirement? + let isRepresentable: Bool + + var candidateValues: [String] { + if let literal { return [literal] } + return (requirement?.choices ?? []) + (requirement?.defaultValue.map { [$0] } ?? []) + } +} + +struct RegistryInput: Decodable { + let name: String? + let type: String? + let valueHint: String? + let description: String? + let value: String? + let `default`: String? + let isRequired: Bool? + let isSecret: Bool? + let choices: [String]? + let variables: [String: RegistryInput]? + + private var secret: Bool { + isSecret == true || (name ?? valueHint).map(Self.isCredentialName) == true + || variables?.contains(where: { Self.isCredentialName($0.key) || $0.value.secret }) == true + } + + fileprivate func slot() -> RegistryMCPSlot? { + guard let name else { return nil } + let fixed = secret ? nil : Self.resolve(value, variables: variables) + let options = choices ?? [] + let unrepresentableOptions = + (fixed.map { !options.isEmpty && !options.contains($0) } ?? (secret && !options.isEmpty)) + || (fixed == nil + && variables?.values.contains(where: { $0.choices?.isEmpty == false }) == true) + let fallback = secret ? nil : Self.resolve(`default`, variables: variables) + return .init( + name: name, literal: fixed, + requirement: fixed == nil + ? .init( + name: name, description: description, + isRequired: isRequired == true || value != nil || !options.isEmpty + || (secret && `default` != nil), + isSecret: secret, defaultValue: fallback, choices: secret ? [] : options) + : nil, + isRepresentable: !unrepresentableOptions) + } + + fileprivate func argument() throws -> [String] { + let fixed = secret ? nil : Self.resolve(value, variables: variables) + let options = choices ?? [] + if let fixed, !options.isEmpty, !options.contains(fixed) { + throw unavailable("The package argument is outside its declared choices.") + } + switch type { + case "named": + guard let name, name.matches(#"^-{1,2}[A-Za-z0-9][A-Za-z0-9_-]*$"#) else { + throw unavailable("The package listed an invalid command-line option.") + } + if let fixed { return [name + "=" + fixed] } + if !secret, value == nil, `default` == nil, options.isEmpty, variables == nil { + if isRequired != true { return [] } + } + case "positional": + if let fixed { return [fixed] } + default: break + } + throw unavailable("The package requires an unrepresentable command-line argument.") + } + + static func isEnvironmentName(_ value: String) -> Bool { + value.matches(#"^[A-Za-z_][A-Za-z0-9_]*$"#) + } + + static func isCredentialName(_ value: String) -> Bool { + let key = value.lowercased().filter { $0.isASCII && $0.isLetter } + return key == "key" || key == "sig" || key.hasSuffix("auth") + || [ + "authorization", "token", "apikey", "password", "secret", "credential", "privatekey", + "cookie", "signature", + ].contains(where: key.contains) + } + + /// Substitute only fixed, non-secret variable values. The portable declaration cannot + /// interpolate run-time values into a URL or an individual argument. + static func resolve(_ value: String?, variables: [String: RegistryInput]?) -> String? { + guard var value else { return nil } + for (name, variable) in variables ?? [:] { + let token = "{" + name + "}" + guard value.contains(token), !isCredentialName(name), !variable.secret, + let fixed = variable.value, + variable.choices?.isEmpty != false || variable.choices?.contains(fixed) == true, + !Self.containsTemplate(fixed) + else { continue } + value = value.replacingOccurrences(of: token, with: fixed) + } + return containsTemplate(value) ? nil : value + } + + private static func containsTemplate(_ value: String) -> Bool { + value.range(of: #"\{[A-Za-z_][A-Za-z0-9_]*\}"#, options: .regularExpression) != nil + } +} + +private func unavailable(_ reason: String) -> MCPRegistryError { + .unavailableChoice(reason) +} + +extension StringProtocol { + fileprivate func matches(_ expression: String) -> Bool { + range(of: expression, options: .regularExpression).map { $0 == startIndex.. URL { + let inspection = try BundleOperations.inspect(archive) + let policy = try AuthorPackagePolicy(environment, registrySchemas: registrySchemas) + _ = try policy.admit(inspection.archive) + try policy.admitCatalog(directory, package: inspection.package) + try policy.validate() + return try exportHostedBundle( + archive, to: directory, summary: summary, inspection: inspection, + validatePolicy: policy.validate, beforeIndexReplacement: {}) + } + + static func exportHostedBundle( + _ archive: Data, to directory: URL, summary: String?, + inspection: BundleInspection? = nil, validatePolicy: () throws -> Void = {}, + beforeIndexReplacement: () throws -> Void + ) throws -> URL { + let bundle = try inspection ?? BundleOperations.inspect(archive) + let coordinate = try MarketplaceCoordinate( + package: bundle.package.name, version: bundle.package.version) + let entry = HostedMarketplaceIndex.Entry( + coordinate: coordinate, archiveDigest: bundle.archiveDigest, archiveByteCount: archive.count, + summary: summary, archivePath: coordinate.releasePath + "/" + ReleaseMetadata.archiveName) + try entry.metadata.validate() + guard archive.count <= LedgerLimits.standard.objectBytes else { + throw HostedMarketplaceError.responseTooLarge + } + try validatePolicy() + let root = try DirectoryHandle.readDirectory(at: directory) + let indexName = hostedIndexFilename + let indexURL = directory.appendingPathComponent(indexName) + return try FileLock.withLock(in: root, named: ".marketplace.lock") { + try validatePolicy() + let existing = try root.readRegularFileIfPresent( + indexName, maximumBytes: HostedMarketplaceIndex.maximumBytes) + var entries = + try existing.map { + try HostedMarketplaceIndex.read( + $0, maximumReleases: HostedMarketplaceIndex.maximumReleases + ) + .releases + } ?? [] + for published in entries { + try Task.checkCancellation() + let bytes = try readArchive(published, in: root) + let package = try BundleOperations.inspect(bytes).package + guard package.name == published.coordinate.package, + package.version == published.coordinate.version + else { throw MarketplaceError.integrityMismatch(published.coordinate.label) } + } + if let published = entries.first(where: { $0.coordinate == coordinate }) { + guard published.archiveDigest == entry.archiveDigest, + published.archiveByteCount == entry.archiveByteCount + else { throw MarketplaceError.publicationConflict(coordinate.label) } + try validatePolicy() + return indexURL + } + entries.append(entry) + let next = HostedMarketplaceIndex( + formatVersion: 1, releases: entries.sorted(by: HostedMarketplaceIndex.Entry.ordered)) + let indexBytes = try ResolvedLedgerCodec.bytes(next) + _ = try HostedMarketplaceIndex.read( + indexBytes, maximumReleases: HostedMarketplaceIndex.maximumReleases) + + try validatePolicy() + let releases = try root.createDirectoryIfAbsent("releases") + let package = try releases.createDirectoryIfAbsent(coordinate.package) + if try !package.publishDirectory( + named: coordinate.version, files: [ReleaseMetadata.archiveName: archive]) + { + guard let bytes = try? readArchive(entry, in: root), bytes == archive else { + throw MarketplaceError.publicationConflict(coordinate.label) + } + } + try root.publishIndex(indexName, data: indexBytes) { + try Task.checkCancellation() + try validatePolicy() + try beforeIndexReplacement() + } + return indexURL + } + } + + private static func readArchive(_ entry: HostedMarketplaceIndex.Entry, in root: DirectoryHandle) + throws -> Data + { + let parts = entry.archivePath.split(separator: "/").map(String.init) + var directory = root + for part in parts.dropLast() { + guard let child = try directory.directory(part) else { + throw MarketplaceError.integrityMismatch(entry.coordinate.label) + } + directory = child + } + let bytes = try directory.readRegularFile(parts.last!, maximumBytes: entry.archiveByteCount) + try entry.metadata.validateArchive(bytes) + return bytes + } +} diff --git a/Sources/AgentsUpdates/Marketplace/HostedMarketplaceHTTP.swift b/Sources/AgentsUpdates/Marketplace/HostedMarketplaceHTTP.swift new file mode 100644 index 0000000..3a33174 --- /dev/null +++ b/Sources/AgentsUpdates/Marketplace/HostedMarketplaceHTTP.swift @@ -0,0 +1,347 @@ +import AgentsCore +import AgentsManifest +import Foundation +import Synchronization + +#if canImport(Security) + import Security +#endif + +#if canImport(FoundationNetworking) + import FoundationNetworking +#endif + +/// Trusted host inputs for hosted marketplace reads. The credential callback receives the +/// canonical index URL only when that exact identity has a user-scoped registration. +public struct HostedMarketplaceAccess: Sendable { + public typealias CredentialProvider = @Sendable (URL) -> String? + + let downloadOrigins: Set + let credentialProvider: CredentialProvider? + let transport: HostedMarketplaceHTTP.Transport + + /// Download origins are HTTPS authorities. Credentials are ephemeral bearer tokens whose + /// lookup and lifetime are owned by the host. + public init( + trustedDownloadOrigins: [URL] = [], credentialProvider: CredentialProvider? = nil + ) throws { + let origins = try Set( + trustedDownloadOrigins.map { url in + guard let parts = URLComponents(url: url, resolvingAgainstBaseURL: false), + parts.scheme?.lowercased() == "https", parts.query == nil, + parts.path.isEmpty || parts.path == "/" + else { throw MarketplaceError.invalidOrigin("expected an HTTPS download origin") } + return try SourceOrigin.http(url.absoluteString) + }) + self.init(downloadOrigins: origins, credentialProvider: credentialProvider) + } + + init( + downloadOrigins: Set = [], credentialProvider: CredentialProvider? = nil, + transport: @escaping HostedMarketplaceHTTP.Transport = HostedMarketplaceHTTP.fetch + ) { + self.downloadOrigins = downloadOrigins + self.credentialProvider = credentialProvider + self.transport = transport + } +} + +public enum HostedMarketplaceError: Error, Equatable, Sendable, CustomStringConvertible { + case registrationRequired + case credentialRequired + case invalidCredential + case redirectDenied + case requestFailed + case responseStatus(Int) + case responseTooLarge + + public var description: String { + switch self { + case .registrationRequired: + "Register the exact hosted catalog in the user marketplace directory." + case .credentialRequired: + "Supply a bearer credential for the exact hosted index in your host's user settings." + case .invalidCredential: "The hosted marketplace bearer credential has an invalid header value." + case .redirectDenied: "The hosted marketplace redirect exceeds its admitted HTTPS locations." + case .requestFailed: "The hosted marketplace HTTPS request failed." + case .responseStatus(let status): "The hosted marketplace returned HTTP \(status)." + case .responseTooLarge: "The hosted marketplace response exceeded its byte limit." + } + } +} + +enum HostedMarketplaceHTTP { + struct Response: Sendable { + let status: Int + let location: String? + let bytes: Data + } + + typealias Transport = @Sendable (URLRequest, Int) throws -> Response + + static func fetch(_ request: URLRequest, maximumBytes: Int) throws -> Response { + try fetch(request, maximumBytes: maximumBytes, localTrustAnchor: nil) + } + + // A synthetic TLS fixture can establish trust for its own session without writing to the keychain. + static func fetch( + _ request: URLRequest, maximumBytes: Int, localTrustAnchor: Data? + ) throws -> Response { + let reader = Reader(maximumBytes: maximumBytes, localTrustAnchor: localTrustAnchor) + let configuration = URLSessionConfiguration.ephemeral + configuration.httpCookieStorage = nil + configuration.httpShouldSetCookies = false + configuration.urlCredentialStorage = nil + configuration.urlCache = nil + configuration.requestCachePolicy = .reloadIgnoringLocalCacheData + configuration.timeoutIntervalForRequest = 15 + configuration.timeoutIntervalForResource = 30 + let session = URLSession(configuration: configuration, delegate: reader, delegateQueue: nil) + defer { session.invalidateAndCancel() } + let task = session.dataTask(with: request) + task.resume() + while reader.finished.wait(timeout: .now() + .milliseconds(100)) == .timedOut { + try Task.checkCancellation() + } + try Task.checkCancellation() + return try reader.state.withLock { state in + if state.exceeded { throw HostedMarketplaceError.responseTooLarge } + guard let status = state.status, status != 200 || !state.failed else { + throw HostedMarketplaceError.requestFailed + } + return Response(status: status, location: state.location, bytes: state.bytes) + } + } + + private final class Reader: NSObject, URLSessionDataDelegate { + struct State { + var status: Int? + var location: String? + var bytes = Data() + var exceeded = false + var failed = false + } + + let state = Mutex(State()) + let finished = DispatchSemaphore(value: 0) + let maximumBytes: Int + let localTrustAnchor: Data? + + init(maximumBytes: Int, localTrustAnchor: Data?) { + self.maximumBytes = maximumBytes + self.localTrustAnchor = localTrustAnchor + } + + func urlSession( + _ session: URLSession, task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest, completionHandler: @escaping @Sendable (URLRequest?) -> Void + ) { + state.withLock { + $0.status = response.statusCode + $0.location = response.value(forHTTPHeaderField: "Location") + } + completionHandler(nil) + } + + func urlSession( + _ session: URLSession, didReceive challenge: URLAuthenticationChallenge, + completionHandler: + @escaping @Sendable (URLSession.AuthChallengeDisposition, URLCredential?) -> + Void + ) { + respond(to: challenge, completionHandler: completionHandler) + } + + func urlSession( + _ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, + completionHandler: + @escaping @Sendable (URLSession.AuthChallengeDisposition, URLCredential?) -> + Void + ) { + respond(to: challenge, completionHandler: completionHandler) + } + + private func respond( + to challenge: URLAuthenticationChallenge, + completionHandler: @Sendable (URLSession.AuthChallengeDisposition, URLCredential?) -> Void + ) { + #if canImport(Security) + if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { + guard let localTrustAnchor else { + completionHandler(.performDefaultHandling, nil) + return + } + guard challenge.protectionSpace.host == "127.0.0.1", + let trust = challenge.protectionSpace.serverTrust, + let cert = SecCertificateCreateWithData(nil, localTrustAnchor as CFData), + SecTrustSetAnchorCertificates(trust, [cert] as CFArray) == errSecSuccess, + SecTrustSetAnchorCertificatesOnly(trust, true) == errSecSuccess, + SecTrustEvaluateWithError(trust, nil) + else { + completionHandler(.cancelAuthenticationChallenge, nil) + return + } + completionHandler(.useCredential, URLCredential(trust: trust)) + return + } + #endif + if let response = challenge.failureResponse as? HTTPURLResponse, + [401, 403].contains(response.statusCode) + { + state.withLock { $0.status = response.statusCode } + } + completionHandler(.cancelAuthenticationChallenge, nil) + } + + func urlSession( + _ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, + completionHandler: @escaping @Sendable (URLSession.ResponseDisposition) -> Void + ) { + guard let http = response as? HTTPURLResponse else { + completionHandler(.cancel) + return + } + let allow = state.withLock { state in + state.status = http.statusCode + state.location = http.value(forHTTPHeaderField: "Location") + guard http.statusCode == 200 else { return false } + state.exceeded = http.expectedContentLength > maximumBytes + return !state.exceeded + } + completionHandler(allow ? .allow : .cancel) + } + + func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + let overflow = state.withLock { state in + if data.count > maximumBytes - state.bytes.count { state.exceeded = true } + if !state.exceeded { state.bytes.append(data) } + return state.exceeded + } + if overflow { dataTask.cancel() } + } + + func urlSession( + _ session: URLSession, task: URLSessionTask, didCompleteWithError error: (any Error)? + ) { + state.withLock { $0.failed = error != nil } + finished.signal() + } + } +} + +struct HostedMarketplaceReader { + let index: HostedMarketplaceLocation + let access: HostedMarketplaceAccess + let policy: SourcePolicySnapshot + let organization: OrganizationPolicySnapshot + let trustedRegistration: TargetPrecondition? + let credentialRegistration: TargetPrecondition? + let credentialEligible: Bool + let sourceAccess: SourceAccessConfiguration + + init( + origin: MarketplaceOrigin, store: StateStore, access: HostedMarketplaceAccess?, + policy: SourcePolicySnapshot, organization: OrganizationPolicySnapshot, + trustedRegistration: TargetPrecondition? = nil + ) throws { + index = try HostedMarketplaceLocation(origin.location) + sourceAccess = store.environment.sourceAccess + try sourceAccess.requireDirectHTTP(index.url, policy: policy.effective) + self.access = access ?? HostedMarketplaceAccess(downloadOrigins: []) + self.policy = policy + self.organization = organization + self.trustedRegistration = trustedRegistration + if self.access.credentialProvider != nil { + let trusted = try MarketplaceDirectory.trustedHostedOrigins(environment: store.environment) + credentialEligible = trusted.origins.contains(origin) + credentialRegistration = trusted.evidence + } else { + credentialEligible = false + credentialRegistration = nil + } + } + + func read( + _ initial: HostedMarketplaceLocation, coordinate: MarketplaceCoordinate? = nil, + maximumBytes: Int + ) throws -> (bytes: Data, requests: [URL]) { + var current = initial + var visited: [URL] = [] + var prefixes = [index.origin: index] + var authorization: String? + while true { + try Task.checkCancellation() + guard visited.count <= HostedMarketplaceLocation.maximumRedirects, + !visited.contains(current.url) + else { throw HostedMarketplaceError.redirectDenied } + try index.admit(current, prefixes: &prefixes, archive: coordinate != nil) + if current.origin != index.origin { + guard access.downloadOrigins.contains(current.origin) else { + throw HostedMarketplaceError.redirectDenied + } + authorization = nil + } + try sourceAccess.requireDirectHTTP(current.url) + try policy.effective.require(current.origin, reference: coordinate?.label) + try organization.admit( + Self.findings( + for: current, index: index, coordinate: coordinate, evaluator: organization.evaluator)) + try policy.validate() + try organization.validate() + try trustedRegistration?.validate() + try credentialRegistration?.validate() + if visited.isEmpty, credentialEligible, let token = access.credentialProvider?(index.url) { + guard !token.isEmpty, token.utf8.count <= 8192, + token.utf8.allSatisfy({ (33...126).contains($0) }) + else { throw HostedMarketplaceError.invalidCredential } + authorization = "Bearer " + token + } + + var request = URLRequest(url: current.url) + request.httpShouldHandleCookies = false + request.setValue("identity", forHTTPHeaderField: "Accept-Encoding") + request.setValue(authorization, forHTTPHeaderField: "Authorization") + visited.append(current.url) + try trustedRegistration?.validate() + try credentialRegistration?.validate() + try policy.validate() + try organization.validate() + let response = try access.transport(request, maximumBytes) + switch response.status { + case 200: + guard response.bytes.count <= maximumBytes else { + throw HostedMarketplaceError.responseTooLarge + } + try policy.validate() + try organization.validate() + try credentialRegistration?.validate() + try trustedRegistration?.validate() + return (response.bytes, visited) + case 301, 302, 303, 307, 308: + guard let location = response.location else { throw HostedMarketplaceError.redirectDenied } + current = try current.redirect(to: location) + case 401 where authorization == nil, 403 where authorization == nil: + throw HostedMarketplaceError.credentialRequired + default: throw HostedMarketplaceError.responseStatus(response.status) + } + } + } + + static func findings( + for destination: HostedMarketplaceLocation, index: HostedMarketplaceLocation, + coordinate: MarketplaceCoordinate?, evaluator: OrganizationPolicyEvaluator + ) -> [OrganizationPolicyFinding] { + let catalog = OrganizationPolicyIdentity(index.origin, root: index.policyPath) + var result = evaluator.catalogAdmission(catalog) + if destination != index { + result += evaluator.source(destination.origin, root: destination.policyPath) + } + if let coordinate { + result += evaluator.packageIdentity( + .init(index.origin, suffix: coordinate.package, root: index.policyPath), + catalog: catalog) + } + return result + } +} diff --git a/Sources/AgentsUpdates/Marketplace/HostedMarketplaceIndex.swift b/Sources/AgentsUpdates/Marketplace/HostedMarketplaceIndex.swift new file mode 100644 index 0000000..a3b4b87 --- /dev/null +++ b/Sources/AgentsUpdates/Marketplace/HostedMarketplaceIndex.swift @@ -0,0 +1,125 @@ +import AgentsCore +import AgentsManifest +import Foundation + +struct HostedMarketplaceIndex: Codable { + static let maximumBytes = 8 * 1024 * 1024 + static let maximumReleases = 4096 + + struct Entry: Codable { + let coordinate: MarketplaceCoordinate + let archiveDigest: String + let archiveByteCount: Int + let summary: String? + let archivePath: String + + var metadata: ReleaseMetadata { + ReleaseMetadata( + coordinate: coordinate, archiveDigest: archiveDigest, archiveByteCount: archiveByteCount, + summary: summary) + } + + static func ordered(_ lhs: Self, _ rhs: Self) -> Bool { + if lhs.coordinate.package != rhs.coordinate.package { + return lhs.coordinate.package < rhs.coordinate.package + } + return MarketplaceCoordinate.newer(lhs.coordinate, than: rhs.coordinate) + } + } + + let formatVersion: Int + let releases: [Entry] + + static func read(_ bytes: Data, maximumReleases: Int) + throws -> Self + { + var limits = LedgerLimits.standard + limits.encodedBytes = maximumBytes + limits.nodes = Self.maximumReleases * 16 + 16 + try LedgerAdmission.check(bytes, limits: limits) + guard let document = try? JSONDecoder().decode(Self.self, from: bytes), + document.formatVersion == 1 + else { throw MarketplaceError.invalidPackage("invalid hosted marketplace index") } + guard document.releases.count <= min(maximumReleases, Self.maximumReleases) else { + throw MarketplaceError.resolutionLimit("catalog release metadata") + } + var coordinates = Set() + var paths = Set() + for entry in document.releases { + try Task.checkCancellation() + try entry.metadata.validate() + try HostedMarketplaceLocation.validateArchivePath(entry.archivePath) + guard entry.archiveByteCount <= LedgerLimits.standard.objectBytes, + coordinates.insert(entry.coordinate).inserted, + paths.insert(entry.archivePath).inserted + else { throw MarketplaceError.invalidPackage("invalid or duplicate hosted release") } + } + return document + } +} + +struct HostedReleaseLocation: Equatable, Sendable { + let archive: HostedMarketplaceLocation + let indexDigest: String + let indexRequests: [URL] +} + +extension HostedMarketplaceReader { + func observe( + origin: MarketplaceOrigin, maximumReleases: Int + ) throws -> ObservedMarketplaceCatalog { + let observation = try read(index, maximumBytes: HostedMarketplaceIndex.maximumBytes) + let effective = try HostedMarketplaceLocation(observation.requests.last!.absoluteString) + let document = try HostedMarketplaceIndex.read( + observation.bytes, maximumReleases: maximumReleases) + let digest = ReleaseMetadata.digest(observation.bytes) + return try ObservedMarketplaceCatalog( + location: .hosted(self), commit: nil, indexDigest: digest, + releases: document.releases.sorted(by: HostedMarketplaceIndex.Entry.ordered).map { entry in + let archive = try effective.archive(entry.archivePath) + guard !observation.requests.contains(archive.url) else { + throw MarketplaceError.invalidPackage("archive points to a hosted marketplace index") + } + return MarketplaceRelease( + origin: origin, catalogCommit: nil, metadata: entry.metadata, originPath: nil, + hosted: HostedReleaseLocation( + archive: archive, indexDigest: digest, + indexRequests: observation.requests)) + }) + } + + func acquire(_ release: MarketplaceRelease) throws -> VerifiedMarketplacePackage { + guard let hosted = release.hosted else { + throw MarketplaceError.integrityMismatch(release.coordinate.label) + } + // A release can outlive its browse operation. Re-admit the observed index redirects + // before reading the archive, even when their URLs will not be contacted again. + try Self.requireRequests( + hosted.indexRequests, index: index, coordinate: release.coordinate, + policy: policy.effective, organization: organization) + let archive = try read( + hosted.archive, coordinate: release.coordinate, maximumBytes: release.archiveByteCount) + let evidence = HostedMarketplaceEvidence( + indexDigest: hosted.indexDigest, archiveByteCount: release.archiveByteCount, + indexRequests: hosted.indexRequests, archiveRequests: archive.requests) + try evidence.validate(index: release.origin.location) + try release.metadata.validateArchive(archive.bytes) + let result = VerifiedMarketplacePackage( + release: release, archive: archive.bytes, hostedEvidence: evidence) + _ = try result.inspectBundle() + return result + } + + static func requireRequests( + _ requests: [URL], index: HostedMarketplaceLocation, coordinate: MarketplaceCoordinate, + policy: EffectiveSourcePolicy, organization: OrganizationPolicySnapshot + ) throws { + for url in requests { + let request = try HostedMarketplaceLocation(url.absoluteString) + try policy.require(request.origin, reference: coordinate.label) + try organization.admit( + findings( + for: request, index: index, coordinate: coordinate, evaluator: organization.evaluator)) + } + } +} diff --git a/Sources/AgentsUpdates/Marketplace/MarketplaceCatalog.swift b/Sources/AgentsUpdates/Marketplace/MarketplaceCatalog.swift new file mode 100644 index 0000000..787dac1 --- /dev/null +++ b/Sources/AgentsUpdates/Marketplace/MarketplaceCatalog.swift @@ -0,0 +1,531 @@ +import AgentsCore +import AgentsManifest +import Foundation + +/// A catalog name in a front end's registration list. Project dependencies store the origin. +public struct MarketplaceRegistration: Codable, Equatable, Sendable { + public let name: String + public let origin: MarketplaceOrigin + + public init(name: String, origin: MarketplaceOrigin) throws { + guard MarketplaceCoordinate.isName(name) else { throw MarketplaceError.invalidPackage(name) } + try origin.validate() + self.name = name + self.origin = origin + } + + private enum CodingKeys: String, CodingKey { case name, origin } + + public init(from decoder: any Decoder) throws { + let fields = try decoder.container(keyedBy: CodingKeys.self) + try self.init( + name: fields.decode(String.self, forKey: .name), + origin: fields.decode(MarketplaceOrigin.self, forKey: .origin)) + } +} + +public struct MarketplaceRelease: Equatable, Sendable { + public var coordinate: MarketplaceCoordinate { metadata.coordinate } + public var archiveDigest: String { metadata.archiveDigest } + public var archiveByteCount: Int { metadata.archiveByteCount } + public var summary: String? { metadata.summary } + public let origin: MarketplaceOrigin + public let catalogCommit: String? + let metadata: ReleaseMetadata + let originPath: String? + var hosted: HostedReleaseLocation? = nil + + public var indexDigest: String? { hosted?.indexDigest } + + func policyOrigin() throws -> SourceOrigin { + if let originPath { return .local(path: originPath) } + return try origin.remotePolicyOrigin() + } +} + +/// One catalog observation. Registration carries no write to consumer configuration. +public struct MarketplaceCatalog: Sendable { + public let registration: MarketplaceRegistration + public let catalogCommit: String? + public let releases: [MarketplaceRelease] + public let indexDigest: String? + + /// Case-insensitive substring search over the package name and release summary. + public func search(_ query: String) -> [MarketplaceRelease] { + guard !query.isEmpty else { return releases } + return releases.filter { + $0.coordinate.package.range(of: query, options: .caseInsensitive) != nil + || $0.summary?.range(of: query, options: .caseInsensitive) != nil + } + } + + /// Selects an exact version or the highest available SemVer precedence. + public func select(package: String, version: String? = nil) throws -> MarketplaceRelease { + guard + let release = releases.first(where: { + $0.coordinate.package == package && (version == nil || $0.coordinate.version == version) + }) + else { throw MarketplaceError.releaseNotFound(package + (version.map { "@" + $0 } ?? "")) } + return release + } + + /// Available higher versions for this exact origin. A changed digest at a locked coordinate + /// is an integrity failure even when newer versions are present. + public func updates(for pin: MarketplacePin) throws -> [MarketplaceRelease] { + guard registration.origin == pin.dependency.catalog else { + throw MarketplaceError.originConflict(pin.dependency.name) + } + let coordinate = pin.dependency.coordinate + if let current = releases.first(where: { $0.coordinate == coordinate }), + current.archiveDigest != pin.archiveDigest + { + throw MarketplaceError.integrityMismatch(coordinate.label) + } + return releases.filter { + $0.coordinate.package == coordinate.package + && $0.coordinate.hasHigherPrecedence(than: coordinate) + } + } +} + +/// The exact bytes verified against the immutable release observation. The bundle importer +/// validates their format, package coordinates, selections and producer evidence. +public struct VerifiedMarketplacePackage: Sendable { + public let release: MarketplaceRelease + public let archive: Data + + public let hostedEvidence: HostedMarketplaceEvidence? + + init( + release: MarketplaceRelease, archive: Data, hostedEvidence: HostedMarketplaceEvidence? = nil + ) { + self.hostedEvidence = hostedEvidence + self.release = release + self.archive = archive + } +} + +public enum MarketplaceOperations { + /// Publishes an archive already admitted by its format owner. The callback returns the + /// coordinate read from that archive. The catalog root must exist. + @discardableResult + public static func publish( + _ archive: Data, to directory: URL, summary: String? = nil, + scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment(), + registrySchemas: [MCPRegistryServer] = [], + inspecting inspect: (Data) throws -> MarketplaceCoordinate + ) throws -> MarketplaceRelease { + try ReleaseMetadata.validateSize(archive.count) + let coordinate = try inspect(archive) + if let bundle = try? BundleOperations.inspect(archive) { + guard bundle.package.name == coordinate.package, bundle.package.version == coordinate.version + else { throw MarketplaceError.integrityMismatch(coordinate.label) } + return try publishAdmitted( + archive, inspection: bundle, to: directory, summary: summary, scope: scope, + environment: environment, registrySchemas: registrySchemas) + } + let policy = try AuthorPackagePolicy(environment, scope: scope) + try AuthorPackageOperations.requireLocalFileURL(directory) + let destination = try PathIdentity(directory) + let package = BundlePackage(name: coordinate.package, version: coordinate.version) + try policy.admit(package) + try policy.source.effective.require(.missing, reference: coordinate.package) + try policy.organization.admit(policy.organization.evaluator.source(.missing)) + try policy.admitCatalog(directory, package: package) + return try publish(archive, coordinate: coordinate, to: directory, summary: summary) { + try policy.validate() + try destination.validate() + } + } + + static func publish( + _ archive: Data, coordinate: MarketplaceCoordinate, to directory: URL, summary: String?, + beforeCommit: () throws -> Void + ) throws -> MarketplaceRelease { + try ReleaseMetadata.validateSize(archive.count) + let metadata = ReleaseMetadata( + coordinate: coordinate, archiveDigest: ReleaseMetadata.digest(archive), + archiveByteCount: archive.count, summary: summary) + try metadata.validate() + let origin = try MarketplaceOrigin( + kind: .directory, location: directory.standardizedFileURL.path) + let root = try DirectoryHandle.readDirectory(at: directory) + let path = SourceOrigin.local(at: directory).identity + try beforeCommit() + let releases = try root.createDirectoryIfAbsent("releases") + let package = try releases.createDirectoryIfAbsent(coordinate.package) + let bytes = try ResolvedLedgerCodec.bytes(metadata) + if try package.directory(coordinate.version) == nil, + try package.publishDirectory( + named: coordinate.version, + files: [ + ReleaseMetadata.filename: bytes, ReleaseMetadata.archiveName: archive, + ], beforeCommit: beforeCommit) + { + return MarketplaceRelease( + origin: origin, catalogCommit: nil, metadata: metadata, originPath: path) + } + guard let existing = try package.directory(coordinate.version), + try ReleaseMetadata.read(in: existing, at: coordinate) == metadata + else { throw MarketplaceError.publicationConflict(coordinate.label) } + guard try metadata.readArchive(in: existing) == archive else { + throw MarketplaceError.publicationConflict(coordinate.label) + } + return MarketplaceRelease( + origin: origin, catalogCommit: nil, metadata: metadata, originPath: path) + } + + /// Reads release metadata from a local directory, exact Git tree or hosted HTTPS index. + public static func browse( + _ registration: MarketplaceRegistration, scope: InstallScope = .project, + environment: RuntimeEnvironment = RuntimeEnvironment(), + hostedAccess: HostedMarketplaceAccess? = nil + ) throws -> MarketplaceCatalog { + try withObservedCatalog( + registration.origin, scope: scope, environment: environment, + maximumReleases: LedgerLimits.standard.entries, hostedAccess: hostedAccess + ) { observed in + MarketplaceCatalog( + registration: registration, catalogCommit: observed.commit, releases: observed.releases, + indexDigest: observed.indexDigest) + } + } + + static func withObservedCatalog( + _ origin: MarketplaceOrigin, scope: InstallScope, environment: RuntimeEnvironment, + maximumReleases: Int, expectedOrigin: SourceOrigin? = nil, + requireRecordedTransport: Bool = false, hostedAccess: HostedMarketplaceAccess? = nil, + organizationPolicy: OrganizationPolicySnapshot? = nil, + trustedRegistration: TargetPrecondition? = nil, _ body: (ObservedMarketplaceCatalog) throws -> T + ) throws -> T { + if origin.kind == .hosted { + try origin.validate() + let store = StateStore(scope: scope, environment: environment) + let policy = try SourcePolicySnapshot(store: store) + let organization = try organizationPolicy ?? OrganizationPolicySnapshot(store: store) + let reader = try HostedMarketplaceReader( + origin: origin, store: store, access: hostedAccess, policy: policy, + organization: organization, + trustedRegistration: trustedRegistration) + if let expectedOrigin, expectedOrigin != reader.index.origin { + throw MarketplaceError.originConflict(origin.location) + } + return try body(reader.observe(origin: origin, maximumReleases: maximumReleases)) + } + return try withCatalog( + origin, commit: nil, scope: scope, environment: environment, expectedOrigin: expectedOrigin, + requireRecordedTransport: requireRecordedTransport + ) { root, commit, source in + let path = source.kind == .local ? source.identity : nil + var entries: [MarketplaceRelease] = [] + if let releases = try root.directory("releases") { + for name in try releases.names(maximumCount: maximumReleases) where !name.hasPrefix(".") { + guard MarketplaceCoordinate.isName(name), let package = try releases.directory(name) + else { throw MarketplaceError.invalidPackage(name) } + for version in try package.names(maximumCount: maximumReleases) + where !version.hasPrefix(".") { + try Task.checkCancellation() + guard entries.count < maximumReleases else { + throw MarketplaceError.resolutionLimit("catalog release metadata") + } + let coordinate = try MarketplaceCoordinate(package: name, version: version) + guard let directory = try package.directory(version) else { + throw MarketplaceError.invalidPackage(coordinate.label) + } + let metadata = try ReleaseMetadata.read(in: directory, at: coordinate) + entries.append( + MarketplaceRelease( + origin: origin, catalogCommit: commit, metadata: metadata, originPath: path)) + } + } + } + return try body( + ObservedMarketplaceCatalog( + location: .directory(root), commit: commit, indexDigest: nil, + releases: entries.sorted { + if $0.coordinate.package != $1.coordinate.package { + return $0.coordinate.package < $1.coordinate.package + } + return MarketplaceCoordinate.newer($0.coordinate, than: $1.coordinate) + })) + } + } + + /// Reads from the selected Git commit or directory and verifies metadata and archive bytes. + /// A moving Git ref never changes the observation used for this acquisition. + public static func acquire( + _ release: MarketplaceRelease, scope: InstallScope = .project, + environment: RuntimeEnvironment = RuntimeEnvironment(), + hostedAccess: HostedMarketplaceAccess? = nil + ) throws -> VerifiedMarketplacePackage { + let origin = try release.policyOrigin() + let store = StateStore(scope: scope, environment: environment) + let organization = try OrganizationPolicySnapshot(store: store) + if release.origin.kind == .hosted { + return try HostedMarketplaceReader( + origin: release.origin, store: store, access: hostedAccess, + policy: SourcePolicySnapshot(store: store), organization: organization + ).acquire(release) + } + try organization.admit( + organization.evaluator.packageIdentity( + .init(origin, suffix: release.coordinate.package, root: release.origin.subpath), + catalog: .init(origin, root: release.origin.subpath))) + try organization.validate() + return try withRelease( + release.coordinate, origin: release.origin, commit: release.catalogCommit, + scope: scope, environment: environment, expectedOrigin: origin, + requireRecordedTransport: organization.evaluator.requiresRecordedGitOrigin + ) { directory, current, _ in + guard current == release.metadata else { + throw MarketplaceError.integrityMismatch(release.coordinate.label) + } + return VerifiedMarketplacePackage( + release: release, archive: try current.readArchive(in: directory)) + } + } + + /// Reacquires the exact archive referenced by a committed pin, including its original + /// catalog commit. Restore can use the embedded closure without reacquiring the archive. + public static func acquire( + _ pin: MarketplacePin, scope: InstallScope = .project, + environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> VerifiedMarketplacePackage { + try pin.validate() + let dependency = pin.dependency + let store = StateStore(scope: scope, environment: environment) + let origin = try pin.policyOrigin(environment: store.marketplaceEnvironment) + let organization = try OrganizationPolicySnapshot(store: store) + try organization.admit( + organization.evaluator.packageIdentity( + .init(origin, suffix: dependency.coordinate.package, root: dependency.catalog.subpath), + catalog: .init(origin, root: dependency.catalog.subpath))) + try organization.validate() + return try withRelease( + dependency.coordinate, origin: dependency.catalog, commit: pin.catalogCommit, + scope: scope, environment: environment, expectedOrigin: pin.catalogOrigin, + additionalOrigin: origin, + requireRecordedTransport: organization.evaluator.requiresRecordedGitOrigin + ) { directory, metadata, source in + guard metadata.archiveDigest == pin.archiveDigest else { + throw MarketplaceError.integrityMismatch(dependency.coordinate.label) + } + let release = MarketplaceRelease( + origin: dependency.catalog, catalogCommit: pin.catalogCommit, metadata: metadata, + originPath: source.kind == .local ? source.identity : nil) + return VerifiedMarketplacePackage( + release: release, archive: try metadata.readArchive(in: directory)) + } + } + + private static func withRelease( + _ coordinate: MarketplaceCoordinate, origin: MarketplaceOrigin, commit: String?, + scope: InstallScope, environment: RuntimeEnvironment, expectedOrigin: SourceOrigin?, + additionalOrigin: SourceOrigin? = nil, requireRecordedTransport: Bool = false, + _ body: (DirectoryHandle, ReleaseMetadata, SourceOrigin) throws -> Result + ) throws -> Result { + try withCatalog( + origin, commit: commit, scope: scope, environment: environment, + expectedOrigin: expectedOrigin, additionalOrigin: additionalOrigin, + requireRecordedTransport: requireRecordedTransport + ) { root, observedCommit, source in + guard observedCommit == commit, + let directory = try root.directory("releases")?.directory(coordinate.package)? + .directory(coordinate.version) + else { throw MarketplaceError.releaseNotFound(coordinate.label) } + let metadata = try ReleaseMetadata.read(in: directory, at: coordinate) + return try body(directory, metadata, source) + } + } + + private static func withCatalog( + _ origin: MarketplaceOrigin, commit: String?, scope: InstallScope, + environment: RuntimeEnvironment, expectedOrigin: SourceOrigin? = nil, + additionalOrigin: SourceOrigin? = nil, requireRecordedTransport: Bool = false, + _ body: (DirectoryHandle, String?, SourceOrigin) throws -> Result + ) throws -> Result { + try origin.validate() + let store = StateStore(scope: scope, environment: environment) + let policy = try SourcePolicySnapshot(store: store) + let source = try origin.policyOrigin(environment: environment) + if let expectedOrigin, expectedOrigin != source { + throw MarketplaceError.originConflict(origin.location) + } + if let additionalOrigin, additionalOrigin != source { + try policy.effective.require(additionalOrigin) + } + try policy.effective.require(source) + let result: Result + if origin.kind == .directory { + result = try body( + DirectoryHandle.readDirectory(at: URL(fileURLWithPath: source.identity!)), nil, source) + } else { + let gitSource = + source.kind == .local + ? SourceDeclaration( + kind: .local, location: source.identity!, + requirement: (commit ?? origin.ref).map(SourceRequirement.revision)) + : origin.gitSource(commit: commit) + let cache = SourceCache( + store: store, sourcePolicy: policy.effective, + requireRecordedTransport: requireRecordedTransport) + try cache.requireGit(gitSource) + result = try cache.withResolvedSnapshot( + gitSource, cacheSource: false + ) { pin, root in + var directory = try DirectoryHandle.readDirectory(at: root) + for name in origin.subpath?.split(separator: "/") ?? [] { + guard let child = try directory.directory(String(name)) else { + throw MarketplaceError.invalidOrigin("catalog subpath is absent") + } + directory = child + } + return try body(directory, pin.revision, source) + } + } + try policy.validate() + return result + } +} + +/// One catalog observation and its archive acquisition context. +struct ObservedMarketplaceCatalog { + enum Location { + case directory(DirectoryHandle) + case hosted(HostedMarketplaceReader) + } + + let location: Location + let commit: String? + let indexDigest: String? + let releases: [MarketplaceRelease] + + func acquire(_ release: MarketplaceRelease) throws -> VerifiedMarketplacePackage { + switch location { + case .hosted(let reader): return try reader.acquire(release) + case .directory(let root): return try acquire(release, in: root) + } + } + + private func acquire(_ release: MarketplaceRelease, in root: DirectoryHandle) throws + -> VerifiedMarketplacePackage + { + let coordinate = release.coordinate + guard + let directory = try root.directory("releases")?.directory(coordinate.package)? + .directory(coordinate.version), + try ReleaseMetadata.read(in: directory, at: coordinate) == release.metadata + else { throw MarketplaceError.integrityMismatch(coordinate.label) } + return VerifiedMarketplacePackage( + release: release, archive: try release.metadata.readArchive(in: directory)) + } +} + +/// Records a mutable catalog's observed metadata and the archives read by the solver. +struct MarketplaceCatalogInput: Sendable { + let origin: MarketplaceOrigin + let source: SourceOrigin + let releases: [MarketplaceRelease] + let archives: Set + + var readLocations: [URL] { + guard let path = source.identity else { return [] } + let root = URL(fileURLWithPath: path, isDirectory: true) + return [root.appendingPathComponent("releases")] + + releases.flatMap { release in + let directory = root.appendingPathComponent(release.coordinate.releasePath) + let metadata = directory.appendingPathComponent(ReleaseMetadata.filename) + return archives.contains(release.coordinate) + ? [metadata, directory.appendingPathComponent(ReleaseMetadata.archiveName)] : [metadata] + } + } + + func validate(scope: InstallScope, environment: RuntimeEnvironment) throws { + try MarketplaceOperations.withObservedCatalog( + origin, scope: scope, environment: environment, + maximumReleases: MarketplaceSolver.maximumMetadataReleases, + expectedOrigin: source + ) { observed in + guard observed.releases == releases else { + throw CoreError.invalidState("marketplace catalog changed; refresh the preview") + } + for release in observed.releases where archives.contains(release.coordinate) { + _ = try observed.acquire(release) + } + } + } +} +struct ReleaseMetadata: Codable, Equatable, Sendable { + static let filename = "release.json" + static let archiveName = "package.bundle" + static let maximumMetadataBytes = 8192 + + let formatVersion: Int + let coordinate: MarketplaceCoordinate + let archiveDigest: String + let archiveByteCount: Int + let summary: String? + + init( + coordinate: MarketplaceCoordinate, archiveDigest: String, archiveByteCount: Int, + summary: String? + ) { + formatVersion = 1 + self.coordinate = coordinate + self.archiveDigest = archiveDigest + self.archiveByteCount = archiveByteCount + self.summary = summary + } + + static func digest(_ bytes: Data) -> String { "sha256:" + FileHash.sha256Hex(data: bytes) } + + static func validateSize(_ bytes: Int) throws { + guard bytes > 0, bytes <= LedgerLimits.standard.encodedBytes else { + throw MarketplaceError.invalidPackage("archive byte limit") + } + } + + func validate() throws { + try coordinate.validate() + try StateValidation.digest(archiveDigest) + try Self.validateSize(archiveByteCount) + guard formatVersion == 1, summary.map({ $0.utf8.count <= 1024 }) ?? true else { + throw MarketplaceError.invalidPackage(coordinate.label) + } + } + + static func read(in directory: DirectoryHandle, at coordinate: MarketplaceCoordinate) throws + -> Self + { + let bytes = try directory.readRegularFile(filename, maximumBytes: maximumMetadataBytes) + guard let metadata = try? JSONDecoder().decode(Self.self, from: bytes), + metadata.coordinate == coordinate + else { throw MarketplaceError.integrityMismatch(coordinate.label) } + try metadata.validate() + guard try ResolvedLedgerCodec.bytes(metadata) == bytes, + try directory.regularFileSize(archiveName) == metadata.archiveByteCount + else { throw MarketplaceError.integrityMismatch(coordinate.label) } + return metadata + } + + func readArchive(in directory: DirectoryHandle) throws -> Data { + let bytes = try directory.readRegularFile(Self.archiveName, maximumBytes: archiveByteCount) + try validateArchive(bytes) + return bytes + } + + func validateArchive(_ bytes: Data) throws { + guard bytes.count == archiveByteCount, Self.digest(bytes) == archiveDigest else { + throw MarketplaceError.integrityMismatch(coordinate.label) + } + } +} + +extension StateStore { + /// Relative catalog locators are authored against the owning project or home. + var marketplaceEnvironment: RuntimeEnvironment { + var environment = environment + if scope == .user { environment.projectDirectory = environment.homeDirectory } + return environment + } +} diff --git a/Sources/AgentsUpdates/Marketplace/MarketplaceDirectory.swift b/Sources/AgentsUpdates/Marketplace/MarketplaceDirectory.swift new file mode 100644 index 0000000..0378309 --- /dev/null +++ b/Sources/AgentsUpdates/Marketplace/MarketplaceDirectory.swift @@ -0,0 +1,155 @@ +import AgentsCore +import AgentsManifest +import Foundation + +public struct RegisteredMarketplace: Equatable, Sendable { + public let registration: MarketplaceRegistration + public let scope: InstallScope +} + +/// A named catalog is only a discovery address. Installing freezes its resolved origin in the package pin. +public enum MarketplaceDirectory { + public static func list( + scope: InstallScope, environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> [RegisteredMarketplace] { + let scopes: [InstallScope] = scope == .project ? [.user, .project] : [.user] + var result: [String: RegisteredMarketplace] = [:] + for layer in scopes { + let store = StateStore(scope: layer, environment: environment) + let entries = try store.withReadLock { try read(store).entries } + for entry in entries { + var origin = entry.origin + if layer == .user, !origin.location.hasPrefix("/") { + let home = RuntimeEnvironment( + projectDirectory: environment.homeDirectory, homeDirectory: environment.homeDirectory, + environment: environment.environment) + if let file = origin.fileURL(environment: home) { + origin = try MarketplaceOrigin( + kind: origin.kind, location: file.path, ref: origin.ref, subpath: origin.subpath) + } + } + result[entry.name] = try RegisteredMarketplace( + registration: MarketplaceRegistration(name: entry.name, origin: origin), scope: layer) + } + } + return result.values.sorted { $0.registration.name < $1.registration.name } + } + + public static func lookup( + _ name: String, scope: InstallScope, environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> MarketplaceRegistration { + guard + let entry = try list(scope: scope, environment: environment).first(where: { + $0.registration.name == name + }) + else { throw CoreError.notFound("marketplace registration " + name) } + return entry.registration + } + + public static func register( + _ entry: MarketplaceRegistration, scope: InstallScope, + environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws { + try edit(scope: scope, environment: environment) { entries in + if let old = entries.first(where: { $0.name == entry.name }) { + guard old == entry else { throw MarketplaceError.originConflict(entry.name) } + } else { + entries.append(entry) + } + } + } + + public static func unregister( + _ name: String, scope: InstallScope, environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws { + try edit(scope: scope, environment: environment) { entries in + guard let index = entries.firstIndex(where: { $0.name == name }) else { + throw CoreError.notFound( + "marketplace registration " + name + " in " + scope.rawValue + " scope") + } + entries.remove(at: index) + } + } + + static func trustedHostedOrigins(environment: RuntimeEnvironment) throws -> ( + origins: Set, evidence: TargetPrecondition + ) { + let store = StateStore(scope: .user, environment: environment) + let directory = try read(store) + return (Set(directory.entries.map(\.origin).filter { $0.kind == .hosted }), directory.file) + } + + private static func edit( + scope: InstallScope, environment: RuntimeEnvironment, + change: (inout [MarketplaceRegistration]) throws -> Void + ) throws { + let store = StateStore(scope: scope, environment: environment) + let root = scope == .project ? try store.captureExistingProjectRoot() : nil + try store.withLock(existingRoot: root) { + let current = try read(store) + var entries = current.entries + try change(&entries) + guard current.entries != entries else { return } + let encoder = JSONEncoder() + encoder.outputFormatting = [.withoutEscapingSlashes] + func quote(_ text: String) throws -> String { + String(decoding: try encoder.encode(text), as: UTF8.self) + } + var yaml = entries.isEmpty ? "{}\n" : "" + for entry in entries.sorted(by: { $0.name < $1.name }) { + let origin = entry.origin + yaml += + try quote(entry.name) + ":\n " + origin.kind.rawValue + ": " + quote(origin.location) + + "\n" + if let ref = origin.ref { yaml += try " ref: " + quote(ref) + "\n" } + if let path = origin.subpath { yaml += try " subpath: " + quote(path) + "\n" } + } + let transaction = FileTransaction(store: store) + try transaction.replace( + current.file.url, with: .data(Data(yaml.utf8)), expecting: current.file) + try transaction.commit() + } + } + + private static func read(_ store: StateStore) throws -> ( + entries: [MarketplaceRegistration], file: TargetPrecondition + ) { + let url = store.directory.appendingPathComponent(StateStore.marketplaceDirectoryFileName) + let file = try TargetPrecondition.readingFile(url) + guard let bytes = file.bytes else { return ([], file.evidence) } + let reader = try YAMLReader(bytes: Array(bytes), identity: DocumentIdentity(url.path)) + func string(_ node: YAMLNode) throws -> String { + guard let scalar = node.scalar, !scalar.decimalTag, + scalar.quoted || YAMLScalar.classify(scalar.text) == .string + else { throw MarketplaceError.invalidOrigin("expected a string in " + url.lastPathComponent) } + return scalar.text + } + guard let pairs = reader.root.pairs else { + throw MarketplaceError.invalidOrigin("expected a mapping of marketplace names") + } + let entries = try pairs.map { key, value in + let name = try string(key) + guard let fields = value.pairs else { throw MarketplaceError.invalidOrigin(name) } + var kind: MarketplaceOrigin.Kind? + var location: String? + var ref: String? + var subpath: String? + for field in fields { + switch try string(field.key) { + case "directory", "git", "hosted": + guard kind == nil else { throw MarketplaceError.invalidOrigin(name) } + kind = MarketplaceOrigin.Kind(rawValue: try string(field.key)) + location = try string(field.value) + case "ref": ref = try string(field.value) + case "subpath": subpath = try string(field.value) + default: throw MarketplaceError.invalidOrigin("unknown field in " + name) + } + } + guard let kind, let location else { throw MarketplaceError.invalidOrigin(name) } + return try MarketplaceRegistration( + name: name, + origin: MarketplaceOrigin(kind: kind, location: location, ref: ref, subpath: subpath)) + } + return (entries, file.evidence) + } +} diff --git a/Sources/AgentsUpdates/Marketplace/MarketplaceGraphChange.swift b/Sources/AgentsUpdates/Marketplace/MarketplaceGraphChange.swift new file mode 100644 index 0000000..66d7c7d --- /dev/null +++ b/Sources/AgentsUpdates/Marketplace/MarketplaceGraphChange.swift @@ -0,0 +1,405 @@ +import AgentsCore +import AgentsManifest +import Components +import Foundation + +struct MarketplaceGraphChange: Sendable { + let graph: MarketplaceGraph? + let stateDigest: String + let policyFingerprint: String + let directoryInputs: [MarketplaceCatalogInput] + let promotedLegacy: Set + let hostedArchives: [String: Data] + let hostedGeneration: [TargetPrecondition] + + static func admitHostedRegistrations( + _ graph: MarketplaceGraph?, environment: RuntimeEnvironment + ) throws -> TargetPrecondition? { + let required = Set( + (graph?.nodes ?? []).flatMap { node in + node.dependencies.compactMap { edge -> MarketplaceOrigin? in + guard let catalog = edge.requirement.catalog, catalog.kind == .hosted, + catalog != node.catalog + else { return nil } + return catalog + } + }) + guard !required.isEmpty else { return nil } + let registration = try MarketplaceDirectory.trustedHostedOrigins(environment: environment) + guard required.isSubset(of: registration.origins) else { + throw HostedMarketplaceError.registrationRequired + } + try registration.evidence.validate() + return registration.evidence + } + + func validateCatalogs(in store: StateStore) throws { + for input in directoryInputs { + try input.validate(scope: store.scope, environment: store.marketplaceEnvironment) + } + } + + static func stateDigest(in baseline: StatePrecondition, store: StateStore) throws -> String { + let digests = try [store.declarationURL, store.resolvedURL, store.watchURL].map { file in + try baseline.bytes(for: file).map(BundleArchive.digest) ?? "absent" + } + return try ResolvedLedgerCodec.digest(digests) + } + + static func deploymentIdentities( + from previous: ResolvedLedger, to next: ResolvedLedger, roots: [String: URL] + ) throws -> Set { + var identities = Set() + let retainedLegacy = Set((next.marketplacePackages ?? []).map { $0.dependency.name }) + for ledger in [previous, next] { + let records = ledger.marketplaceGraph?.nodes.flatMap(\.componentRecords) ?? [] + // Promotion withdraws the legacy contribution from the actual deployment. + let promoted = (ledger.marketplacePackages ?? []).filter { + !retainedLegacy.contains($0.dependency.name) + }.flatMap(\.componentRecords) + for record in records + promoted { + if let component = ledger.components[record] { + try identities.insert(LedgerImpact.identity(component, ledger: ledger, roots: roots)) + } + } + } + return identities + } + + func validate( + _ baseline: StatePrecondition, policy: SourcePolicySnapshot, + organizationPolicy: OrganizationPolicySnapshot, store: StateStore + ) throws { + for file in hostedGeneration { try file.validate() } + guard try stateDigest == Self.stateDigest(in: baseline, store: store), + policyFingerprint + == (try ResolvedLedgerCodec.digest([policy.fingerprint, organizationPolicy.fingerprint])) + else { + throw CoreError.invalidState( + "marketplace scope or source policy changed; refresh the preview") + } + } + + func compose( + _ original: Declaration, previous: ResolvedLedger, store: StateStore + ) throws -> Declaration { + var result = original + result.marketplaceRoots = graph?.roots.map(\.intent) ?? [] + result.packages.removeAll { promotedLegacy.contains($0.name) } + var owned = Set(previous.marketplaceGraph?.nodes.flatMap(\.sourceAliases) ?? []) + owned.formUnion( + (previous.marketplacePackages ?? []).filter { + promotedLegacy.contains($0.dependency.name) + }.flatMap(\.sourceAliases)) + if previous.marketplaceGraph == nil, !original.marketplaceRoots.isEmpty { + // A committed declaration may arrive before its lock. These names and paths belong + // to the graph's generated producers and are rebuilt from the authored roots. + for source in original.sourceDeclarations + where source.name.hasPrefix(MarketplaceResolvedNode.sourceAliasPrefix) + && BundleSourceLocation.isKey( + String(source.name.dropFirst(MarketplaceResolvedNode.sourceAliasPrefix.count))) + && source.source.kind == .local && source.source.path == nil + && source.source.requirement == nil + && source.source.location == Self.source(for: source.name, scope: store.scope).location + { + owned.insert(source.name) + } + } + result.sourceDeclarations.removeAll { owned.contains($0.name) } + result.uses.removeAll { $0.source.map(owned.contains) ?? false } + + var aliases = Set(result.sourceDeclarations.map(\.name)) + for node in graph?.nodes ?? [] { + for member in node.members { + guard aliases.insert(member.sourceAlias).inserted else { + throw MarketplaceError.contributionMismatch(node.id.description) + } + result.sourceDeclarations.append( + .init( + name: member.sourceAlias, + source: Self.source(for: member.sourceAlias, scope: store.scope))) + result.uses.append( + .init( + name: BundleInstallation.groupName, source: member.sourceAlias, + condition: .init(agents: member.targets))) + } + } + return result + } + + static func validate( + _ declaration: Declaration, matching ledger: ResolvedLedger, store: StateStore, + allowingIntentDrift: Bool = false + ) throws { + let graph = ledger.marketplaceGraph + if !allowingIntentDrift { + let frozen = Dictionary( + uniqueKeysWithValues: (graph?.roots ?? []).map { + ($0.intent.name, $0.intent) + }) + for root in declaration.marketplaceRoots { + guard let previous = frozen[root.name] else { throw MarketplaceError.missingPin(root.name) } + guard previous == root else { throw MarketplaceError.selectionMismatch(root.name) } + } + let names = Set(declaration.marketplaceRoots.map(\.name)) + if let unexpected = graph?.roots.first(where: { !names.contains($0.intent.name) }) { + throw MarketplaceError.selectionMismatch(unexpected.intent.name) + } + guard (graph?.roots.map(\.intent) ?? []) == declaration.marketplaceRoots else { + throw MarketplaceError.selectionMismatch("root order") + } + } + guard let graph else { return } + let closure = try PackageClosure(ledger, store: store) + for node in graph.nodes { + let evidence = try evidence( + for: node, closure: closure, declaration: declaration, store: store) + guard node.contributionDigest == evidence.contributionDigest, + node.componentRecords == evidence.componentRecords + else { throw MarketplaceError.contributionMismatch(node.id.description) } + } + } + + static func freeze( + _ graph: MarketplaceGraph?, in frozen: ResolvedLedger, sourceIDs: [SourceSnapshotID: String], + producers: [String: BundleSourceInputs.Producer], declaration: Declaration, store: StateStore, + hostedArchives: [String: Data] + ) throws -> ResolvedLedger { + guard var graph else { return frozen } + let closure = try PackageClosure(frozen, store: store) + var ledger = frozen + let limits = LedgerLimits.standard + var remaining = limits.objectBytes - ledger.contentObjects.values.reduce(0) { $0 + $1.count } + graph.nodes = try graph.nodes.map { node in + var node = node + if node.hostedEvidence != nil, ledger.contentObjects[node.archiveDigest] == nil { + guard let bytes = hostedArchives[node.archiveDigest], bytes.count <= remaining else { + throw MarketplaceError.resolutionLimit("embedded hosted archives") + } + ledger.contentObjects[node.archiveDigest] = bytes + remaining -= bytes.count + } + node.members = try node.members.map { member in + var member = member + guard let producer = producers[member.sourceAlias], + let source = sourceIDs[producer.snapshot], + producer.seal.marketplaceNode == node.id, producer.seal.componentID == member.componentID + else { throw MarketplaceError.contributionMismatch(node.id.description) } + let captured = try LedgerResources.capture( + producer.contents, embed: true, limits: limits, sourceRoot: producer.contents) + for (id, data) in captured.objects where ledger.contentObjects[id] == nil { + guard data.count <= remaining else { + throw MarketplaceError.resolutionLimit("embedded producer bytes") + } + remaining -= data.count + ledger.contentObjects[id] = data + } + let resource = LedgerResource( + kind: .embedded, source: source, path: ".", hash: captured.hash, + entries: captured.entries, support: captured.support) + let digest = try ResolvedLedgerCodec.digest(resource) + member.producerResource = digest + ledger.resources[digest] = resource + return member + } + return try evidence(for: node, closure: closure, declaration: declaration, store: store) + } + ledger.marketplaceGraph = graph + return ledger + } + + static func validateHosted( + _ graph: MarketplaceGraph?, objects: [String: Data], policy: EffectiveSourcePolicy, + organizationPolicy: OrganizationPolicySnapshot + ) throws { + for node in graph?.nodes ?? [] where node.catalog.kind == .hosted { + try Task.checkCancellation() + try validateHosted( + node, archive: objects[node.archiveDigest], policy: policy, + organizationPolicy: organizationPolicy) + } + } + + static func validateHosted( + _ node: MarketplaceResolvedNode, archive bytes: Data?, policy: EffectiveSourcePolicy, + organizationPolicy: OrganizationPolicySnapshot + ) throws { + guard let hosted = node.hostedEvidence, let bytes, bytes.count == hosted.archiveByteCount + else { throw MarketplaceError.integrityMismatch(node.coordinate.label) } + try hosted.validate(index: node.catalog.location) + try HostedMarketplaceReader.requireRequests( + hosted.requests, index: HostedMarketplaceLocation(node.catalog.location), + coordinate: node.coordinate, policy: policy, organization: organizationPolicy) + let bundle = try BundleOperations.inspect(bytes) + guard bundle.archiveDigest == node.archiveDigest, + bundle.package.name == node.coordinate.package, + bundle.package.version == node.coordinate.version, + bundle.package.dependencies ?? [] == node.dependencies.map(\.requirement) + else { throw MarketplaceError.integrityMismatch(node.coordinate.label) } + let members = Dictionary( + uniqueKeysWithValues: bundle.components.map { ($0.id, $0.marketplaceKey) }) + guard node.members.allSatisfy({ members[$0.componentID] == $0.key }) else { + throw MarketplaceError.contributionMismatch(node.id.description) + } + for item in bundle.archive.manifest.components { + let sources = try item.installationSources() + try policy.requireBundleSources(sources, reference: node.id.description) + for origin in Set(sources.map(\.policyOrigin) + (item.mcpRegistry?.origins ?? [])) { + try policy.require(origin, reference: node.id.description) + try organizationPolicy.admit( + organizationPolicy.evaluator.source(origin, path: [node.id.description])) + } + } + } + + static func validateProducers( + _ graph: MarketplaceGraph?, replayed resources: [String: URL] + ) throws { + for node in graph?.nodes ?? [] { + for member in node.members { + guard let id = member.producerResource, let contents = resources[id] else { + throw MarketplaceError.contributionMismatch(node.id.description) + } + try validateProducer(contents, member: member, node: node.id) + } + } + } + + private static func validateProducer( + _ contents: URL, member: MarketplaceResolvedMember, node: MarketplaceNodeID + ) throws { + let key = String(member.sourceAlias.dropFirst(MarketplaceResolvedNode.sourceAliasPrefix.count)) + let seal = try BundleStoredSource.read(contents, expectedKey: key) + guard seal.marketplaceNode == node, seal.componentID == member.componentID else { + throw MarketplaceError.contributionMismatch(node.description) + } + } + + static func restoreProducers( + _ graph: MarketplaceGraph?, replayed resources: [String: URL], store: StateStore + ) throws -> [BundleSourceInputs.Publication] { + try (graph?.nodes ?? []).flatMap { node in + try node.members.compactMap { member in + let container = Self.container(for: member.sourceAlias, in: store) + let destination = try BundleSourceInputs.destination(container, in: store) + let contents: URL + if destination.exists { + contents = container + } else if let id = member.producerResource, let replayed = resources[id] { + contents = replayed + } else { + throw MarketplaceError.contributionMismatch(node.id.description) + } + try validateProducer(contents, member: member, node: node.id) + return destination.exists ? nil : .init(contents: contents, destination: destination) + } + } + } + + static func pruneProducers( + previous: ResolvedLedger, next: ResolvedLedger, store: StateStore, roots: [String: URL], + declaration: Declaration, watch: WatchState + ) throws -> [TargetPrecondition] { + guard previous.marketplaceGraph != nil || previous.marketplacePackages != nil else { return [] } + var containers = Set( + try next.sources.values.compactMap { source in + try source.location.flatMap { + BundleSourceLocation.container(of: try $0.resolve(roots: roots), in: store) + } + }) + containers.formUnion( + declaration.sourceDeclarations.compactMap { entry in + let source = entry.source + guard source.kind == .local else { return nil } + return BundleSourceLocation.container( + of: source.localURL(environment: store.environment), in: store) + }) + func orphan(_ container: URL) throws -> TargetPrecondition? { + guard !containers.contains(container), + watch.sources["local:" + container.appendingPathComponent(BundleSourceLocation.tree).path] + == nil + else { return nil } + let destination = try BundleSourceInputs.destination(container, in: store) + return destination.exists ? destination : nil + } + let graphOrphans = try (previous.marketplaceGraph?.nodes ?? []).flatMap { node in + try node.members.compactMap { member -> TargetPrecondition? in + let container = Self.container(for: member.sourceAlias, in: store) + guard let destination = try orphan(container) else { return nil } + try validateProducer(container, member: member, node: node.id) + return destination + } + } + let legacyOrphans = try (previous.marketplacePackages ?? []).flatMap { pin in + let aliases = Set(pin.sourceAliases.filter { $0.hasPrefix("bundle-") }) + let sources = Set( + pin.componentRecords.compactMap { previous.components[$0]?.declaringSource }) + var seen = Set() + return try sources.sorted().compactMap { id -> TargetPrecondition? in + guard let location = previous.sources[id]?.location, + let container = BundleSourceLocation.container( + of: try location.resolve(roots: roots), in: store), + aliases.contains("bundle-" + container.lastPathComponent), + seen.insert(container).inserted, + let destination = try orphan(container) + else { return nil } + _ = try BundleStoredSource.read(container) + return destination + } + } + return graphOrphans + legacyOrphans + } + + private static func evidence( + for node: MarketplaceResolvedNode, closure: PackageClosure, declaration: Declaration, + store: StateStore + ) throws -> MarketplaceResolvedNode { + let sources = declaration.sources + let aliases = Set(node.sourceAliases) + let uses = declaration.uses.filter { $0.source.map(aliases.contains) ?? false } + guard uses.count == aliases.count else { + throw MarketplaceError.contributionMismatch(node.id.description) + } + for member in node.members { + let source = sources[member.sourceAlias] + let expected = Self.source(for: member.sourceAlias, scope: store.scope) + guard source?.kind == expected.kind, source?.location == expected.location, + source?.requirement == nil, source?.path == nil, + uses.contains(where: { + $0.source == member.sourceAlias && $0.name == BundleInstallation.groupName + && $0.condition == DeclarationCondition(agents: member.targets) + }) + else { throw MarketplaceError.contributionMismatch(node.id.description) } + } + + var pinned = node + if !node.members.isEmpty { + let dependency = try MarketplaceDependency( + name: "package-" + ResolvedLedgerCodec.digest(node.id).dropFirst(7), + catalog: node.catalog, coordinate: node.coordinate) + let evidence = try closure.evidence( + for: dependency, archiveDigest: node.archiveDigest, catalogCommit: node.catalogCommit, + catalogOrigin: node.id.catalog.origin, aliases: node.sourceAliases, in: declaration) + pinned.componentRecords = evidence.components + pinned.contributionDigest = evidence.digest + } else { + pinned.componentRecords = [] + pinned.contributionDigest = "" + } + pinned.contributionDigest = try ResolvedLedgerCodec.digest(pinned) + return pinned + } + + private static func container(for alias: String, in store: StateStore) -> URL { + let key = String(alias.dropFirst(MarketplaceResolvedNode.sourceAliasPrefix.count)) + return store.directory.appendingPathComponent(BundleSourceLocation.directory) + .appendingPathComponent(key) + } + + static func source(for alias: String, scope: InstallScope) -> SourceDeclaration { + let key = alias.dropFirst(MarketplaceResolvedNode.sourceAliasPrefix.count) + let base = scope == .project ? ".agent/" : "~/.agents/" + let relative = BundleSourceLocation.directory + "/" + key + "/" + BundleSourceLocation.tree + return SourceDeclaration(kind: .local, location: base + relative) + } +} diff --git a/Sources/AgentsUpdates/Marketplace/MarketplaceLegacyRoot.swift b/Sources/AgentsUpdates/Marketplace/MarketplaceLegacyRoot.swift new file mode 100644 index 0000000..df56e9a --- /dev/null +++ b/Sources/AgentsUpdates/Marketplace/MarketplaceLegacyRoot.swift @@ -0,0 +1,52 @@ +import AgentsCore + +/// Converts a portable exact install to root intent when a graph first shares its release. +struct MarketplaceLegacyRoot { + let pin: MarketplacePin + let id: MarketplaceNodeID + + init(_ pin: MarketplacePin, store: StateStore) throws { + self.pin = pin + let catalog = pin.dependency.catalog + let origin = + try pin.catalogOrigin ?? catalog.policyOrigin(environment: store.marketplaceEnvironment) + id = MarketplaceNodeID( + catalog: MarketplaceCatalogID(catalog, origin: origin), + package: pin.dependency.coordinate.package) + } + + var name: String { pin.dependency.name } + + func intent(in declaration: Declaration, ledger: ResolvedLedger, store: StateStore) + throws -> MarketplaceRoot + { + let roots = store.ledgerRoots(recordedIn: ledger) + let selections = try pin.sourceAliases.map { alias in + guard alias.hasPrefix("bundle-"), BundleSourceLocation.isKey(String(alias.dropFirst(7))), + let source = declaration.sources[alias], + BundleSourceLocation.container( + of: source.localURL(environment: store.environment), in: store) + != nil, + let use = declaration.uses.first(where: { + $0.source == alias && $0.name == BundleInstallation.groupName + }), + let targets = use.condition?.agents + else { throw MarketplaceError.selectionMismatch(name + " has a custom exact installation") } + let identity = try source.identity(environment: store.environment) + let matches = try pin.componentRecords.compactMap { record -> LedgerComponent? in + guard let component = ledger.components[record], + try ledger.sourceIdentity(component.declaringSource, roots: roots) == identity + else { return nil } + return component + } + guard matches.count == 1, let component = matches.first, + let kind = DeclaredComponentKind(rawValue: component.kind) + else { throw MarketplaceError.selectionMismatch(name + " / " + alias) } + return try MarketplaceMemberSelection( + package: id.package, member: .init(kind: kind, name: component.name), targets: targets) + } + return try MarketplaceRoot( + name: name, catalog: pin.dependency.catalog, package: id.package, + requirement: .exact(pin.dependency.coordinate.version), selections: selections) + } +} diff --git a/Sources/AgentsUpdates/Marketplace/MarketplaceLockOperations.swift b/Sources/AgentsUpdates/Marketplace/MarketplaceLockOperations.swift new file mode 100644 index 0000000..81776f7 --- /dev/null +++ b/Sources/AgentsUpdates/Marketplace/MarketplaceLockOperations.swift @@ -0,0 +1,171 @@ +import AgentsCore +import Foundation + +public struct MarketplaceLockReport: Codable, Equatable, Sendable { + public let scope: InstallScope + public let pendingDeployment: MarketplacePendingDeployment + public let deployedGraph: MarketplaceGraph? + public let marketplaceGraphChange: MarketplaceGraphUpdate? + public let marketplaceChanges: [MarketplacePackageUpdate]? + public let organizationPolicy: OrganizationPolicyReport? + public let hasChanges: Bool + public let displayedFingerprint: String +} + +public struct MarketplaceLockPreview: Sendable { + public let resolution: MarketplaceResolution + public let report: MarketplaceLockReport + fileprivate let request: MarketplaceResolutionRequest + fileprivate let environment: RuntimeEnvironment + fileprivate let captured: MarketplacePreparation? + fileprivate let observations: String + fileprivate let organization: OrganizationPolicySnapshot +} + +public struct MarketplaceDeploymentPreview: Sendable { + public let report: CombinedUpdateReport + public let ownershipConflict: String? + fileprivate let environment: RuntimeEnvironment + fileprivate let replace: Bool +} + +extension MarketplaceOperations { + /// Resolves and freezes the selected recipients while leaving native targets untouched. + public static func previewLockOnly( + _ request: MarketplaceResolutionRequest = .reconcile, scope: InstallScope = .project, + environment: RuntimeEnvironment = RuntimeEnvironment(), + hostedAccess: HostedMarketplaceAccess? = nil + ) throws -> MarketplaceLockPreview { + let store = StateStore(scope: scope, environment: environment) + let preparation = try MarketplacePreparation( + request, store: store, usingPendingResolution: true, hostedAccess: hostedAccess) + let report = try preparation.withUpdateRequest(store: store, replace: false) { update in + try UpdateOperations.marketplaceLockPlan( + update, store: store, organizationPolicy: preparation.organizationPolicy + ).report + } + return MarketplaceLockPreview( + resolution: preparation.resolution, report: report, request: request, + environment: environment, captured: preparation.usesHostedCatalog ? preparation : nil, + observations: preparation.solution.observationDigest, + organization: preparation.organizationPolicy) + } + + /// Rechecks the reviewed inputs and commits only the declaration and pending resolution. + /// Publication failures report their durable disposition in `UpdateApplyError`. + @discardableResult + public static func writeLockOnly(_ preview: MarketplaceLockPreview) throws + -> MarketplaceLockReport + { + try writeLockOnly(preview, checkpoint: { _ in }) + } + + package static func writeLockOnly( + _ preview: MarketplaceLockPreview, checkpoint: @escaping (String) throws -> Void + ) throws -> MarketplaceLockReport { + try withReviewedLockPlan(preview) { try $0.write(checkpoint: checkpoint) } + } + + private static func withReviewedLockPlan( + _ preview: MarketplaceLockPreview, _ body: (MarketplaceLockPlan) throws -> Value + ) throws -> Value { + let store = StateStore(scope: preview.report.scope, environment: preview.environment) + let preparation: MarketplacePreparation + if let captured = preview.captured { + preparation = try captured.revalidating(in: store) + } else { + preparation = try MarketplacePreparation( + preview.request, store: store, usingPendingResolution: true) + } + guard preview.observations == preparation.solution.observationDigest else { + throw CoreError.invalidState("marketplace catalog changed; refresh the preview") + } + return try preparation.withUpdateRequest(store: store, replace: false) { update in + let plan = try UpdateOperations.marketplaceLockPlan( + update, store: store, organizationPolicy: preparation.organizationPolicy) + guard preview.report.displayedFingerprint == plan.report.displayedFingerprint else { + throw CoreError.invalidState("marketplace lock candidate changed; refresh the preview") + } + return try body(plan) + } + } + + public static func previewLockOnlyLifecycle( + _ request: MarketplaceResolutionRequest = .reconcile, intent: LifecycleOperationIntent, + scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment(), + hostedAccess: HostedMarketplaceAccess? = nil + ) throws -> LifecyclePackageReview { + let context = LifecycleContext(scope: scope, environment: environment) + let (discovery, root) = try context.capturePackageRoot() + let preview = try previewLockOnly( + request, scope: scope, environment: environment, hostedAccess: hostedAccess) + let plan = try context.packagePlan( + intent: intent, discovery: discovery, snapshot: preview.organization, + findings: preview.report.organizationPolicy, usesPendingClosure: true + ) { snapshot in + try withReviewedLockPlan(preview) { + try snapshot.requireSameLifecyclePolicy(as: $0.organizationPolicy) + } + } + return LifecyclePackageReview( + report: preview, lifecycle: plan.inspection, ownershipConflict: nil, plan: plan + ) { _ in + let outcome = TransactionOutcome() + let result = Result { + try withReviewedLockPlan(preview) { + try $0.write(checkpoint: { _ in }, outcome: outcome, existingRoot: root) + } + } + var recovered = false + if case .failure(let error) = result, + case CoreError.transactionRecovered = (error as? UpdateApplyError)?.underlyingError ?? error + { + recovered = true + } + return UpdateOperations.completion( + result, outcome: outcome, recovered: recovered, store: context.store) + } + } + + public static func previewFrozenLifecycle( + intent: LifecycleOperationIntent, scope: InstallScope = .project, + environment: RuntimeEnvironment = RuntimeEnvironment(), replace: Bool = false + ) throws -> LifecyclePackageReview { + try UpdateOperations.previewLifecycle( + frozenDeploymentRequest(replace: replace), intent: intent, scope: scope, + environment: environment) + } + + /// Previews the pending closure using its exact frozen resources without catalog discovery. + public static func previewFrozenDeployment( + scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment(), + replace: Bool = false + ) throws -> MarketplaceDeploymentPreview { + let (report, conflict, _, _) = try UpdateOperations.previewWithOwnership( + frozenDeploymentRequest(replace: replace), scope: scope, environment: environment) + return MarketplaceDeploymentPreview( + report: report, ownershipConflict: conflict, environment: environment, replace: replace) + } + + /// Publishes the reviewed frozen deployment and retires the pending closure atomically. + public static func deployFrozen( + _ preview: MarketplaceDeploymentPreview, + bindingProvider: (any RuntimeBindingProvider)? = nil + ) throws -> UpdateApplyResult { + if let conflict = preview.ownershipConflict { throw CoreError.invalidState(conflict) } + let checkpoint: (String) throws -> Void = { _ in } + return try UpdateOperations.prepare( + frozenDeploymentRequest(replace: preview.replace), scope: preview.report.scope, + environment: preview.environment, checkpoint: checkpoint, + provider: bindingProvider ?? RequiredBindingProvider(), + expectedFingerprint: preview.report.displayedFingerprint + ) { try $0.apply(ifUnchangedFrom: preview.report.displayedFingerprint) } + } + + /// Creates an offline deployment for callers using the shared preview and transaction lifecycle. + public static func frozenDeploymentRequest(replace: Bool = false) -> UpdateRequest { + var request = UpdateRequest(operation: .restore, replace: replace) + request.deployPendingMarketplace = true + return request + } +} diff --git a/Sources/AgentsUpdates/Marketplace/MarketplaceLockPlan.swift b/Sources/AgentsUpdates/Marketplace/MarketplaceLockPlan.swift new file mode 100644 index 0000000..05a1c34 --- /dev/null +++ b/Sources/AgentsUpdates/Marketplace/MarketplaceLockPlan.swift @@ -0,0 +1,143 @@ +import AgentsCore +import AgentsManifest +import Foundation + +/// The reviewed desired closure has no native authority. Its publication preserves the outer +/// ledger that owns the actual workspace and writes only the declaration and resolved file. +struct MarketplaceLockPlan: PreparedEvidence { + let report: MarketplaceLockReport + let store: StateStore + let baseline: StatePrecondition + let sourcePolicy: SourcePolicySnapshot + let organizationPolicy: OrganizationPolicySnapshot + let graphChange: MarketplaceGraphChange + let roots: [String: URL] + let inputs: UpdateInputs + let declaration: DeclarationChange? + let ledger: ResolvedLedger + let acquisitions: GitAcquisitionCaptures + let requireRecordedTransport: Bool + let previousReferences: RetentionReferences + + init( + store: StateStore, baseline: StatePrecondition, sourcePolicy: SourcePolicySnapshot, + organization: OrganizationInstallEvaluation, initialFindings: [OrganizationPolicyFinding], + graphChange: MarketplaceGraphChange, previous: ResolvedLedger, desired: ResolvedLedger, + declaration: DeclarationChange?, roots: [String: URL], resources: [String: URL], + decisionInputs: [TargetPrecondition], originalInputs: [TargetPrecondition], + acquisitions: GitAcquisitionCaptures + ) throws { + var desired = desired + desired.nativeAuthorities = nil + try sourcePolicy.effective.require(desired, store: store, roots: roots) + if desired.sources.values.contains(where: { $0.archive != nil }) { + try SourceCache(store: store).requireArchivePublicationAccess() + } + let policyReport = try organization.policy.report( + initialFindings + organization.closure(desired, roots: roots)) + try policyReport.requireAdmission() + + guard + desired.marketplaceGraph != nil || previous.marketplaceGraph != nil + || previous.pendingDeployment != nil, + let bytes = try declaration?.bytes ?? baseline.bytes(for: store.declarationURL) + else { throw CoreError.notFound("marketplace requirements to lock") } + let pending = try MarketplacePendingDeploymentRecord( + ledger: desired, deployed: previous, declarationDigest: BundleArchive.digest(bytes)) + var next = previous + next.pendingDeployment = pending + // Validate the exact wire record before asking for writer ownership. + _ = try ResolvedLedgerCodec.encode(next, limits: .standard) + + self.store = store + self.acquisitions = acquisitions + requireRecordedTransport = organization.evaluator.requiresRecordedGitOrigin + self.baseline = baseline + self.sourcePolicy = sourcePolicy + organizationPolicy = organization.policy + self.graphChange = graphChange + self.roots = roots + inputs = try UpdateInputs( + ledger: desired, roots: roots, resources: resources, + decisions: decisionInputs, originals: originalInputs) + self.declaration = declaration + ledger = next + previousReferences = try RetentionReferences(ledger: previous, roots: roots) + report = try MarketplaceLockReport( + scope: store.scope, pendingDeployment: pending.info, deployedGraph: previous.marketplaceGraph, + marketplaceGraphChange: MarketplaceGraphUpdate.between(previous, desired), + marketplaceChanges: MarketplacePackageUpdate.between(previous, desired), + organizationPolicy: policyReport.policies.isEmpty ? nil : policyReport, + hasChanges: previous != next || declaration != nil, + displayedFingerprint: ResolvedLedgerCodec.digest([ + graphChange.stateDigest, graphChange.policyFingerprint, pending.digest, + pending.declarationDigest, ResolvedLedgerCodec.digest(policyReport.findings), + ])) + try validate() + } + + func validate(excludingTargets targets: Set = []) throws { + try baseline.validate(excludingTargets: targets) + try sourcePolicy.validate(excludingTargets: targets) + try organizationPolicy.validate(excludingTargets: targets) + try inputs.validate(excludingTargets: targets) + try graphChange.validateCatalogs(in: store) + } + + func write( + checkpoint: @escaping (String) throws -> Void, + outcome: TransactionOutcome = TransactionOutcome(), + existingRoot: ExistingProjectRoot? = nil + ) throws -> MarketplaceLockReport { + let validateBeforeLock = { try validate() } + do { + return try store.withLock( + checkpoint: checkpoint, outcome: outcome, existingRoot: existingRoot, + beforeScopeLock: validateBeforeLock + ) { + try validate() + try graphChange.validate( + baseline, policy: sourcePolicy, organizationPolicy: organizationPolicy, store: store) + try ledger.validate() + if let pending = ledger.pendingDeployment { + try sourcePolicy.effective.require( + pending.desired(in: ledger), store: store, roots: roots) + } + if report.hasChanges { + let cache = SourceCache( + store: store, sourcePolicy: sourcePolicy.effective, + requireRecordedTransport: requireRecordedTransport, acquisitions: acquisitions, + checkpoint: checkpoint) + try cache.withArchivePublication( + previous: previousReferences, + next: RetentionReferences(ledger: ledger, roots: roots), offline: false + ) { + if let pending = ledger.pendingDeployment { + try cache.retain( + references: RetentionReferences(ledger: pending.desired(in: ledger), roots: roots)) + } + let transaction = FileTransaction( + store: store, outcome: outcome, checkpoint: checkpoint) + transaction.requireUnchanged(since: self) + try store.stageDeclaration(declaration, in: transaction, prepared: baseline) + try store.stageLedger( + ledger, limits: .standard, transaction: transaction, prepared: baseline) + try transaction.commit() + } + } + organizationPolicy.rememberVerifiedPolicies() + return report + } + } catch { + throw UpdateApplyError(outcome: outcome, underlyingError: error) + } + } +} + +extension MarketplacePendingDeploymentRecord { + func requireDeclaration(_ bytes: Data?) throws { + guard let bytes, declarationDigest == BundleArchive.digest(bytes) else { + throw MarketplaceError.changedPendingDeclaration + } + } +} diff --git a/Sources/AgentsUpdates/Marketplace/MarketplaceResolution.swift b/Sources/AgentsUpdates/Marketplace/MarketplaceResolution.swift new file mode 100644 index 0000000..e7b1249 --- /dev/null +++ b/Sources/AgentsUpdates/Marketplace/MarketplaceResolution.swift @@ -0,0 +1,485 @@ +import AgentsCore +import AgentsManifest +import Foundation + +public enum MarketplaceResolutionRequest: Sendable { + /// Resolve authored roots, including an edited declaration or a missing lock. + case reconcile + /// Add or edit a root, retaining locked versions that satisfy the resulting graph. + case install(MarketplaceRoot) + /// Prefer newer releases within the named root's constraints and reachable packages. + /// Supplied intent replaces the corresponding part of the existing root in the same preview. + case upgrade( + String, requirement: SourceRequirement? = nil, + selections: [MarketplaceMemberSelection]? = nil + ) + /// Drop one root and its selected recipients, using the installed graph. + case remove(String) +} + +public struct MarketplaceNodeVersions: Equatable, Sendable { + public let node: MarketplaceNodeID + public let locked: MarketplaceCoordinate? + /// The jointly eligible release selected by this resolution's lock and upgrade preferences. + public let eligible: MarketplaceCoordinate + /// Highest published precedence, including versions outside the incoming constraints. + public let latest: MarketplaceCoordinate? +} + +public struct MarketplaceResolutionNode: Sendable { + public let versions: MarketplaceNodeVersions + public let catalog: MarketplaceOrigin + public let dependencies: [MarketplaceResolvedEdge] + /// Available members of the selected release. Nil means its archive was unavailable or + /// the operation uses only the frozen installation. + public let availableMembers: [BundleComponent]? +} + +/// Read-only release and member discovery. Select members using their logical kind and name. +public struct MarketplaceResolution: Sendable { + public let roots: [MarketplaceResolvedRoot] + public let nodes: [MarketplaceResolutionNode] +} + +public struct MarketplaceResolutionPreview: Sendable { + public let resolution: MarketplaceResolution + public let report: CombinedUpdateReport + public let ownershipConflict: String? + fileprivate let request: MarketplaceResolutionRequest + fileprivate let environment: RuntimeEnvironment + fileprivate let replace: Bool + fileprivate let captured: MarketplacePreparation? + fileprivate let observationDigest: String + fileprivate let stateDigest: String + fileprivate let policyFingerprint: String + fileprivate let organization: OrganizationPolicySnapshot + fileprivate let routes: Set + fileprivate let installations: [String: SkillInstallationTarget] +} + +extension MarketplaceOperations { + /// Discovers the dependency graph and available members without preparing native outputs. + public static func resolve( + _ request: MarketplaceResolutionRequest = .reconcile, scope: InstallScope = .project, + environment: RuntimeEnvironment = RuntimeEnvironment(), + hostedAccess: HostedMarketplaceAccess? = nil + ) throws -> MarketplaceResolution { + try MarketplacePreparation( + request, store: StateStore(scope: scope, environment: environment), + usingPendingResolution: true, hostedAccess: hostedAccess + ).resolution + } + + /// Composes a scoped update for every selected member and root in the resolution. + public static func previewResolution( + _ request: MarketplaceResolutionRequest = .reconcile, scope: InstallScope = .project, + environment: RuntimeEnvironment = RuntimeEnvironment(), replace: Bool = false, + hostedAccess: HostedMarketplaceAccess? = nil + ) throws -> MarketplaceResolutionPreview { + let store = StateStore(scope: scope, environment: environment) + let plan = try MarketplacePreparation(request, store: store, hostedAccess: hostedAccess) + return try plan.withUpdateRequest(store: store, replace: replace) { update in + let (report, conflict, routes, installations) = try UpdateOperations.previewWithOwnership( + update, scope: scope, environment: environment, organizationPolicy: plan.organizationPolicy) + return MarketplaceResolutionPreview( + resolution: plan.resolution, report: report, ownershipConflict: conflict, + request: request, environment: environment, replace: replace, + captured: plan.usesHostedCatalog ? plan : nil, + observationDigest: plan.solution.observationDigest, stateDigest: plan.stateDigest, + policyFingerprint: plan.policyFingerprint, organization: plan.organizationPolicy, + routes: routes, + installations: installations) + } + } + + public static func previewResolutionLifecycle( + _ request: MarketplaceResolutionRequest = .reconcile, intent: LifecycleOperationIntent, + scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment(), + replace: Bool = false, hostedAccess: HostedMarketplaceAccess? = nil + ) throws -> LifecyclePackageReview { + let context = LifecycleContext(scope: scope, environment: environment) + let (discovery, root) = try context.capturePackageRoot() + let preview = try previewResolution( + request, scope: scope, environment: environment, replace: replace, hostedAccess: hostedAccess) + let plan = try context.packagePlan( + intent: intent, discovery: discovery, snapshot: preview.organization, + findings: preview.report.organizationPolicy, ownershipConflict: preview.ownershipConflict + ) { snapshot in + let current = try previewResolution( + request, scope: scope, environment: environment, replace: replace, + hostedAccess: hostedAccess) + try snapshot.requireSameLifecyclePolicy(as: current.organization) + if let conflict = current.ownershipConflict { throw CoreError.invalidState(conflict) } + } + return LifecyclePackageReview( + report: preview, lifecycle: plan.inspection, ownershipConflict: preview.ownershipConflict, + plan: plan + ) { provider in + performResolution(preview, bindingProvider: provider, existingRoot: root) { + try $0.apply(ifUnchangedFrom: preview.report.displayedFingerprint) + } + } + } + + /// Re-prepares the displayed candidate and runs the scope's recoverable transaction in + /// the same-thread closure. Hosted resolutions use the verified bytes captured by the preview. + public static func withPreparedResolution( + _ preview: MarketplaceResolutionPreview, bindingProvider: (any RuntimeBindingProvider)? = nil, + _ body: (PreparedUpdate) throws -> Result + ) throws -> Result { + try prepareResolution(preview, bindingProvider: bindingProvider, checkpoint: { _ in }, body) + } + + /// Reports the durable outcome after publication, recovery and scope cleanup have returned. + public static func performResolution( + _ preview: MarketplaceResolutionPreview, bindingProvider: (any RuntimeBindingProvider)? = nil, + _ body: (PreparedUpdate) throws -> Value + ) -> UpdateCompletion { + performResolution(preview, bindingProvider: bindingProvider, existingRoot: nil, body) + } + + static func performResolution( + _ preview: MarketplaceResolutionPreview, bindingProvider: (any RuntimeBindingProvider)?, + existingRoot: ExistingProjectRoot?, _ body: (PreparedUpdate) throws -> Value + ) -> UpdateCompletion { + var outcome = TransactionOutcome() + var delivered = false + let result = Result { + try prepareResolution( + preview, bindingProvider: bindingProvider, checkpoint: { _ in }, + completion: { outcome = $0 }, existingRoot: existingRoot + ) { update in + delivered = true + return try body(update) + } + } + var recovered = false + if !delivered, case .failure(let error) = result, + case CoreError.transactionRecovered = (error as? UpdateApplyError)?.underlyingError ?? error + { + recovered = true + } + return UpdateOperations.completion( + result, outcome: outcome, recovered: recovered, + store: StateStore(scope: preview.report.scope, environment: preview.environment)) + } + + package static func prepareResolution( + _ preview: MarketplaceResolutionPreview, bindingProvider: (any RuntimeBindingProvider)? = nil, + checkpoint: @escaping (String) throws -> Void, + completion: ((TransactionOutcome) -> Void)? = nil, existingRoot: ExistingProjectRoot? = nil, + _ body: (PreparedUpdate) throws -> Result + ) throws -> Result { + if let conflict = preview.ownershipConflict { throw CoreError.invalidState(conflict) } + let environment = preview.environment + let scope = preview.report.scope + let store = StateStore(scope: scope, environment: environment) + let plan: MarketplacePreparation + do { + if let captured = preview.captured { + plan = try captured.revalidating(in: store) + } else { + plan = try MarketplacePreparation(preview.request, store: store) + } + } catch let error as CoreError { + guard case .recoveryPending = error else { throw error } + try store.withLock(checkpoint: checkpoint, existingRoot: existingRoot) {} + throw error + } + guard plan.stateDigest == preview.stateDigest, + plan.policyFingerprint == preview.policyFingerprint + else { + throw CoreError.invalidState( + "marketplace scope or source policy changed; refresh the preview") + } + guard plan.solution.observationDigest == preview.observationDigest else { + throw CoreError.invalidState("marketplace catalog changed; refresh the preview") + } + return try plan.withUpdateRequest(store: store, replace: preview.replace) { update in + try UpdateOperations.prepare( + update, scope: scope, environment: environment, checkpoint: checkpoint, + provider: bindingProvider ?? RequiredBindingProvider(), completion: completion, + admittedRoutes: preview.routes, admittedInstallations: preview.installations, + admittedOrganizationPolicy: plan.organizationPolicy, existingRoot: existingRoot + ) { prepared in + guard prepared.report.displayedFingerprint == preview.report.displayedFingerprint else { + throw CoreError.invalidState("marketplace destination changed; refresh the preview") + } + return try body(prepared) + } + } + } +} + +struct MarketplacePreparation: Sendable { + let solution: MarketplaceSolution + let stateDigest: String + let policyFingerprint: String + let organizationPolicy: OrganizationPolicySnapshot + private let priorDesired: ResolvedLedger? + let usesHostedCatalog: Bool + private let generation: [TargetPrecondition] + + private init(captured: Self, organizationPolicy: OrganizationPolicySnapshot) { + priorDesired = captured.priorDesired + solution = captured.solution + stateDigest = captured.stateDigest + policyFingerprint = captured.policyFingerprint + usesHostedCatalog = captured.usesHostedCatalog + generation = captured.generation + self.organizationPolicy = organizationPolicy + } + + func revalidating(in store: StateStore) throws -> Self { + let organization = try OrganizationPolicySnapshot( + store: store, offlineObservations: organizationPolicy) + try organization.admit() + try store.withReadLock { + let baseline = try StatePrecondition(store: store) + let sourcePolicy = try SourcePolicySnapshot(store: store) + try MarketplaceGraphChange( + graph: nil, stateDigest: stateDigest, policyFingerprint: policyFingerprint, + directoryInputs: [], promotedLegacy: [], hostedArchives: [:], hostedGeneration: generation + ).validate(baseline, policy: sourcePolicy, organizationPolicy: organization, store: store) + try baseline.validate() + try sourcePolicy.validate() + } + return Self(captured: self, organizationPolicy: organization) + } + + init( + _ request: MarketplaceResolutionRequest, store: StateStore, + usingPendingResolution: Bool = false, hostedAccess: HostedMarketplaceAccess? = nil + ) throws { + organizationPolicy = try OrganizationPolicySnapshot(store: store) + try organizationPolicy.admit() + let (declaration, deployed, policy, starting, stateDigest, declarationBytes) = + try store.withReadLock { + let baseline = try StatePrecondition(store: store) + let declaration = try store.readDeclaration(prepared: baseline) + let previous = try store.readLedger(prepared: baseline) + if previous.pendingDeployment != nil, !usingPendingResolution { + throw MarketplaceError.pendingDeployment + } + try MarketplaceChanges.validate( + declaration, matching: previous.pendingDeployment?.desired(in: previous) ?? previous, + in: store, allowingGraphReconciliation: true) + let generation = try MarketplaceGraphChange.stateDigest(in: baseline, store: store) + let policy = try SourcePolicySnapshot(store: store) + try baseline.validate() + let starting = try [store.declarationURL, store.resolvedURL, store.watchURL].map { + try baseline.evidence(for: $0) + } + return ( + declaration, previous, policy, starting, generation, + try baseline.bytes(for: store.declarationURL) + ) + } + priorDesired = try deployed.pendingDeployment?.desired(in: deployed) + let previous = priorDesired ?? deployed + self.stateDigest = stateDigest + self.generation = starting + policyFingerprint = try ResolvedLedgerCodec.digest([ + policy.fingerprint, organizationPolicy.fingerprint, + ]) + + var roots = declaration.marketplaceRoots + var upgrading: String? + switch request { + case .install(let root): + if let index = roots.firstIndex(where: { $0.name == root.name }) { + roots[index] = root + } else { + roots.append(root) + } + case .upgrade(let name, let requirement, let selections): + let existing: MarketplaceRoot + let index = roots.firstIndex(where: { $0.name == name }) + if let index { + existing = roots[index] + } else if let pin = previous.marketplacePackages?.first(where: { $0.dependency.name == name }) + { + existing = try MarketplaceLegacyRoot(pin, store: store).intent( + in: declaration, ledger: previous, store: store) + } else { + throw MarketplaceError.missingPin(name) + } + let root = try MarketplaceRoot( + name: name, catalog: existing.catalog, package: existing.package, + requirement: requirement ?? existing.requirement, + selections: selections ?? existing.selections) + if let index { + roots[index] = root + } else { + roots.append(root) + } + upgrading = name + case .remove(let name): + try MarketplaceGraphChange.validate(declaration, matching: previous, store: store) + guard let graph = previous.marketplaceGraph, + graph.roots.contains(where: { $0.intent.name == name }) + else { throw MarketplaceError.missingPin(name) } + let roots = graph.roots.filter { $0.intent.name != name } + var retained = Set() + for root in roots { retained.formUnion(graph.reachable(from: root.node)) } + let remaining = MarketplaceGraph( + roots: roots, + nodes: graph.nodes.filter { + retained.contains($0.id) + }) + usesHostedCatalog = graph.nodes.contains { $0.hostedEvidence != nil } + solution = MarketplaceSolution( + graph: remaining, bundles: [:], + versions: remaining.nodes.map { + MarketplaceNodeVersions( + node: $0.id, locked: $0.coordinate, eligible: $0.coordinate, latest: nil) + }, observationDigest: "", + hostedArchives: Dictionary( + remaining.nodes.compactMap { node in + guard node.hostedEvidence != nil, + let bytes = previous.contentObjects[node.archiveDigest] + else { return nil } + return (node.archiveDigest, bytes) + }, uniquingKeysWith: { first, _ in first })) + return + case .reconcile: + break + } + + if organizationPolicy.evaluator.active { + var prospective = declaration + prospective.marketplaceRoots = roots + let bytes = try DeclarationEditPlan.bytes( + replacing: declaration, with: prospective, in: declarationBytes.map { Array($0) }, + identity: .init(store.declarationURL.path), environment: store.environment) + let evaluation = try OrganizationInstallEvaluation( + policy: organizationPolicy, store: store, declaration: prospective, + bytes: bytes.map { Data($0) } ?? declarationBytes) + try organizationPolicy.admit(evaluation.beforeAcquisition()) + } + solution = try MarketplaceSolver( + store: store, policy: policy, organizationPolicy: organizationPolicy, + declaration: declaration, previous: previous, + updatingRoot: upgrading, hostedAccess: hostedAccess + ).solve(roots, previous: previous.marketplaceGraph) + usesHostedCatalog = + !solution.hostedArchives.isEmpty + || previous.marketplaceGraph?.nodes.contains { $0.hostedEvidence != nil } == true + } + + var resolution: MarketplaceResolution { + let versions = Dictionary(uniqueKeysWithValues: solution.versions.map { ($0.node, $0) }) + return MarketplaceResolution( + roots: solution.graph.roots, + nodes: solution.graph.nodes.map { + MarketplaceResolutionNode( + versions: versions[$0.id]!, catalog: $0.catalog, dependencies: $0.dependencies, + availableMembers: solution.bundles[$0.id]?.components) + }) + } + + func withUpdateRequest( + store: StateStore, replace: Bool, _ body: (UpdateRequest) throws -> T + ) throws -> T { + if usesHostedCatalog { + _ = try MarketplaceGraphChange.admitHostedRegistrations( + solution.graph, environment: store.environment) + try MarketplaceGraphChange.validateHosted( + solution.graph, objects: solution.hostedArchives, + policy: SourcePolicySnapshot(store: store).effective, organizationPolicy: organizationPolicy + ) + } + let targets = try solution.graph.selectedTargets() + let inputs: [BundleInstallation.Input] = try solution.graph.nodes.compactMap { node in + let selected = targets[node.id] ?? [:] + let retained = Dictionary(uniqueKeysWithValues: node.members.map { ($0.key, $0) }) + guard + selected.contains(where: { key, targets in + guard let member = retained[key] else { return true } + // A skill or MCP producer that predates this selection may omit Antigravity. + return key.kind != .instructions && targets.contains(.antigravity) + && !member.targets.contains(.antigravity) + }) + else { return nil } + guard let bundle = solution.bundles[node.id] else { + throw MarketplaceError.releaseNotFound(node.coordinate.label) + } + let groups = Dictionary(grouping: bundle.components, by: \.marketplaceKey) + for member in selected.keys where groups[member]?.count != 1 { + let issue = groups[member] == nil ? "missing member" : "ambiguous member" + throw MarketplaceError.selectionMismatch( + node.coordinate.label + " / " + member.name + " (" + issue + ")") + } + let selections = bundle.components.compactMap { component -> BundleImportSelection? in + selected[component.marketplaceKey].map { + BundleImportSelection( + componentID: component.id, targets: $0.sorted { $0.rawValue < $1.rawValue }) + } + } + return BundleInstallation.Input(bundle: bundle, selections: selections, node: node) + } + return try BundleInstallation.withStagedSources( + inputs, store: store, organizationPolicy: organizationPolicy + ) { installation in + var graph = solution.graph + let members = Dictionary(grouping: installation.members, by: \.marketplaceNode) + graph.nodes = try graph.nodes.map { node in + var next = node + guard let staged = members[node.id] else { + next.members = node.members.compactMap { member in + targets[node.id]?[member.key].map { + MarketplaceResolvedMember( + key: member.key, componentID: member.componentID, sourceAlias: member.sourceAlias, + targets: $0.sorted { $0.rawValue < $1.rawValue }, + producerResource: member.producerResource) + } + } + return next + } + next.members = try staged.map { + MarketplaceResolvedMember( + key: MarketplaceMemberKey( + kind: DeclaredComponentKind(rawValue: $0.item.kind.rawValue)!, name: $0.item.name), + componentID: try $0.item.id, sourceAlias: $0.alias, + targets: $0.targets.sorted { $0.rawValue < $1.rawValue }) + } + return next + } + var request = UpdateRequest(replace: replace) + request.bundleInstallation = installation + request.marketplaceGraphChange = MarketplaceGraphChange( + graph: graph.roots.isEmpty ? nil : graph, stateDigest: stateDigest, + policyFingerprint: policyFingerprint, directoryInputs: solution.directoryInputs, + promotedLegacy: solution.promotedLegacy, hostedArchives: solution.hostedArchives, + hostedGeneration: usesHostedCatalog ? generation : []) + return try withFrozenProducers(for: graph, store: store) { retained in + request.marketplaceFrozenProducers = retained + return try body(request) + } + } + } + + private func withFrozenProducers( + for graph: MarketplaceGraph, store: StateStore, _ body: ([String: URL]) throws -> T + ) throws -> T { + guard let ledger = priorDesired else { return try body([:]) } + let members = graph.nodes.flatMap(\.members).filter { $0.producerResource != nil } + guard !members.isEmpty else { return try body([:]) } + let workspace = FileManager.default.temporaryDirectory.appendingPathComponent( + "agents-marketplace-lock-" + UUID().uuidString) + try FileSystem.createDirectory(at: workspace) + defer { try? FileManager.default.removeItem(at: workspace) } + var staged: [String: URL] = [:] + for member in members { + guard let id = member.producerResource, let resource = ledger.resources[id] else { + throw MarketplaceError.contributionMismatch(member.sourceAlias) + } + let source = MarketplaceGraphChange.source(for: member.sourceAlias, scope: store.scope) + let container = workspace.appendingPathComponent( + String(member.sourceAlias.dropFirst(MarketplaceResolvedNode.sourceAliasPrefix.count))) + try LedgerResources.materialize(resource, objects: ledger.contentObjects, at: container) + staged[try source.identity(environment: store.environment)] = container + } + return try body(staged) + } +} diff --git a/Sources/AgentsUpdates/Marketplace/MarketplaceSolver.swift b/Sources/AgentsUpdates/Marketplace/MarketplaceSolver.swift new file mode 100644 index 0000000..4641341 --- /dev/null +++ b/Sources/AgentsUpdates/Marketplace/MarketplaceSolver.swift @@ -0,0 +1,517 @@ +import AgentsCore +import AgentsManifest +import Foundation + +struct MarketplaceSolution { + let graph: MarketplaceGraph + let bundles: [MarketplaceNodeID: BundleInspection] + let versions: [MarketplaceNodeVersions] + let observationDigest: String + var directoryInputs: [MarketplaceCatalogInput] = [] + var promotedLegacy: Set = [] + var hostedArchives: [String: Data] = [:] +} + +/// Deterministic backtracking over candidate-specific constraints. Catalog handles and verified +/// archives are reused across branches, including branches failing before composition. +final class MarketplaceSolver { + private struct CatalogNeeded: Error { + let id: MarketplaceCatalogID + let origin: MarketplaceOrigin + } + + private struct Demand { + let requirement: SourceRequirement + let path: [MarketplaceNodeID] + let root: String + let updating: Bool + + var description: String { + ([root] + path.map(\.package)).joined(separator: " → ") + + " (" + requirement.marketplaceDescription + ")" + } + } + + private struct Choice { + let node: MarketplaceResolvedNode + let release: MarketplaceRelease? + } + + private struct ObservedRelease: Encodable { + let coordinate: MarketplaceCoordinate + let digest: String + let bytes: Int + let summary: String? + let commit: String? + } + + private struct Observation: Encodable { + let id: MarketplaceCatalogID + let origin: MarketplaceOrigin + let commit: String? + let releases: [ObservedRelease] + } + + private let store: StateStore + private let policy: SourcePolicySnapshot + private let organizationPolicy: OrganizationPolicySnapshot + private let preferred: [MarketplaceNodeID: MarketplaceResolvedNode] + private let updatingRoot: String? + private let legacy: [MarketplaceNodeID: [MarketplaceLegacyRoot]] + private let declaration: Declaration + private let previous: ResolvedLedger + private let hostedAccess: HostedMarketplaceAccess? + private var hostedTrust: (origins: Set, evidence: TargetPrecondition)? + private var hostedPackages: [MarketplaceReleaseKey: VerifiedMarketplacePackage] = [:] + + private struct MarketplaceReleaseKey: Hashable { + let node: MarketplaceNodeID + let version: String + } + private var observations: [MarketplaceCatalogID: ObservedMarketplaceCatalog] = [:] + private var observedOrigins: [MarketplaceCatalogID: MarketplaceOrigin] = [:] + private var bundles: [MarketplaceNodeID: [String: BundleInspection]] = [:] + private var packageCandidates: [MarketplaceNodeID: [MarketplaceRelease]] = [:] + private var archivedBytes = 0 + private var releaseCount = 0 + private var attempts = 0 + + private static let maximumCatalogs = 32 + static let maximumMetadataReleases = 4096 + private static let maximumAttempts = 8192 + + init( + store: StateStore, policy: SourcePolicySnapshot, organizationPolicy: OrganizationPolicySnapshot, + declaration: Declaration, + previous: ResolvedLedger, updatingRoot: String?, hostedAccess: HostedMarketplaceAccess? + ) throws { + self.store = store + self.policy = policy + self.organizationPolicy = organizationPolicy + self.declaration = declaration + self.previous = previous + self.hostedAccess = hostedAccess + preferred = Dictionary( + uniqueKeysWithValues: (previous.marketplaceGraph?.nodes ?? []).map { + ($0.id, $0) + }) + self.updatingRoot = updatingRoot + legacy = Dictionary( + grouping: try (previous.marketplacePackages ?? []).map { + try MarketplaceLegacyRoot($0, store: store) + }, + by: \.id) + } + + func solve(_ intents: [MarketplaceRoot], previous: MarketplaceGraph?) throws + -> MarketplaceSolution + { + guard intents.count <= MarketplaceGraph.maximumNodes else { + throw MarketplaceError.resolutionLimit("root count") + } + let oldRoots = Dictionary( + uniqueKeysWithValues: (previous?.roots ?? []).map { + ($0.intent.name, ($0.node, $0.intent.catalog.ref)) + } + + legacy.values.flatMap { $0.map { ($0.name, ($0.id, $0.pin.dependency.catalog.ref)) } }) + let roots = try intents.map { root in + try root.validate() + let id = try identifier(package: root.package, from: root.catalog) + if let (previousID, ref) = oldRoots[root.name], previousID != id || ref != root.catalog.ref { + throw MarketplaceError.originConflict(root.name) + } + return MarketplaceResolvedRoot(intent: root, node: id) + } + var locators: [MarketplaceCatalogID: MarketplaceOrigin] = [:] + var demands: [MarketplaceNodeID: [Demand]] = [:] + for root in roots { + try bind(root.intent.catalog, id: root.node.catalog, in: &locators) + demands[root.node, default: []].append( + Demand( + requirement: root.intent.requirement, path: [root.node], root: root.intent.name, + updating: root.intent.name == updatingRoot)) + } + return try observing { + let choices = try search(roots: roots, demands: demands, locators: locators, choices: [:]) + let promoted = promotedRoots(for: Set(choices.keys)) + let roots = try includingLegacy(in: roots, promoted: promoted) + let ordered = choices.keys.sorted(by: MarketplaceNodeID.ordered) + var selectedBundles: [MarketplaceNodeID: BundleInspection] = [:] + var hostedArchives: [String: Data] = [:] + for id in ordered { + let choice = choices[id]! + if let release = choice.release { + selectedBundles[id] = try bundle(for: release, id: id) + } + if choice.node.hostedEvidence != nil { + let key = MarketplaceReleaseKey(node: id, version: choice.node.coordinate.version) + guard + let bytes = hostedPackages[key]?.archive + ?? self.previous.contentObjects[choice.node.archiveDigest] + else { throw MarketplaceError.integrityMismatch(choice.node.coordinate.label) } + hostedArchives[choice.node.archiveDigest] = bytes + if selectedBundles[id] == nil { + selectedBundles[id] = try BundleOperations.inspect(bytes) + } + } + } + try hostedTrust?.evidence.validate() + let graph = MarketplaceGraph(roots: roots, nodes: ordered.map { choices[$0]!.node }) + let versions = ordered.map { id in + MarketplaceNodeVersions( + node: id, + locked: preferred[id]?.coordinate ?? legacy[id]?.first?.pin.dependency.coordinate, + eligible: choices[id]!.node.coordinate, + latest: packageCandidates[id]?.first?.coordinate) + } + let observed = observations.keys.sorted { $0.sortKey.lexicographicallyPrecedes($1.sortKey) } + let evidence = observed.map { id in + let catalog = observations[id]! + return Observation( + id: id, origin: observedOrigins[id]!, commit: catalog.commit, + releases: catalog.releases.map { + ObservedRelease( + coordinate: $0.coordinate, digest: $0.archiveDigest, bytes: $0.archiveByteCount, + summary: $0.summary, commit: $0.catalogCommit) + }) + } + let directories = observed.filter { $0.kind == .directory }.map { id in + let releases = observations[id]!.releases + return MarketplaceCatalogInput( + origin: observedOrigins[id]!, source: id.origin, releases: releases, + archives: Set( + releases.compactMap { release in + let node = MarketplaceNodeID(catalog: id, package: release.coordinate.package) + return bundles[node]?[release.coordinate.version] == nil ? nil : release.coordinate + })) + } + try policy.validate() + try organizationPolicy.validate() + return MarketplaceSolution( + graph: graph, bundles: selectedBundles, versions: versions, + observationDigest: try ResolvedLedgerCodec.digest(evidence), directoryInputs: directories, + promotedLegacy: Set(promoted.map(\.name)), hostedArchives: hostedArchives) + } + } + + private func observing(_ body: () throws -> T) throws -> T { + do { + return try body() + } catch let needed as CatalogNeeded { + guard observations.count < Self.maximumCatalogs else { + throw MarketplaceError.resolutionLimit("catalog count") + } + return try MarketplaceOperations.withObservedCatalog( + needed.origin, scope: store.scope, environment: catalogEnvironment, + maximumReleases: Self.maximumMetadataReleases - releaseCount, + expectedOrigin: needed.id.origin, + requireRecordedTransport: organizationPolicy.evaluator.requiresRecordedGitOrigin, + hostedAccess: hostedAccess, organizationPolicy: organizationPolicy, + trustedRegistration: hostedTrust?.evidence + ) { observation in + releaseCount += observation.releases.count + observations[needed.id] = observation + observedOrigins[needed.id] = needed.origin + for (package, releases) in Dictionary( + grouping: observation.releases, + by: { + $0.coordinate.package + }) + { + packageCandidates[MarketplaceNodeID(catalog: needed.id, package: package)] = releases + } + return try observing(body) + } + } + } + + private func search( + roots: [MarketplaceResolvedRoot], demands: [MarketplaceNodeID: [Demand]], + locators: [MarketplaceCatalogID: MarketplaceOrigin], choices: [MarketplaceNodeID: Choice] + ) throws -> [MarketplaceNodeID: Choice] { + try Task.checkCancellation() + guard demands.count <= MarketplaceGraph.maximumNodes else { + throw MarketplaceError.resolutionLimit("node count") + } + guard + let id = demands.keys.filter({ choices[$0] == nil }).sorted(by: { + let left = demands[$0]!.contains(where: \.updating) + let right = demands[$1]!.contains(where: \.updating) + return left == right ? MarketplaceNodeID.ordered($0, $1) : left + }).first + else { + try validateBranch(roots: roots, choices: choices) + try admitOrganizationPaths(roots: roots, choices: choices) + return choices + } + let evaluator = organizationPolicy.evaluator + try admitOrganizationPaths(roots: roots, choices: choices) + let origin = locators[id.catalog]! + guard observations[id.catalog] != nil else { + throw CatalogNeeded(id: id.catalog, origin: origin) + } + guard observedOrigins[id.catalog]?.ref == origin.ref else { + throw MarketplaceError.originConflict(id.description) + } + + let priorExact = legacy[id] ?? [] + let rootNames = Set(roots.map(\.intent.name)) + let incoming = + demands[id]! + + priorExact.filter { !rootNames.contains($0.name) }.map { + Demand( + requirement: .exact($0.pin.dependency.coordinate.version), path: [id], + root: $0.name, updating: false) + } + for leaf in priorExact where leaf.pin.dependency.catalog.ref != origin.ref { + throw MarketplaceError.originConflict(leaf.name) + } + let locked = preferred[id] + let published = packageCandidates[id] ?? [] + for leaf in priorExact { + if let release = published.first(where: { $0.coordinate == leaf.pin.dependency.coordinate }), + release.archiveDigest != leaf.pin.archiveDigest + { + throw MarketplaceError.integrityMismatch(release.coordinate.label) + } + } + let current = published.first { $0.coordinate == locked?.coordinate } + if let current, current.archiveDigest != locked?.archiveDigest { + throw MarketplaceError.integrityMismatch(current.coordinate.label) + } + let updating = incoming.contains(where: \.updating) + let fixed = updatingRoot != nil && !updating && locked != nil + let required = evaluator.marketplaceRequirements(for: id) + let authored = incoming.map(\.requirement) + let constraints = (required.overrides ? [] : authored) + required.constraints + func satisfies(_ version: String) -> Bool { + constraints.allSatisfy { $0.admitsMarketplaceVersion(version) } + } + func recordingOverride(_ node: MarketplaceResolvedNode) -> MarketplaceResolvedNode { + var node = node + node.organizationRequirements = required.overrides ? required.constraints : nil + return node + } + + let lockedChoice = locked.flatMap { node in + satisfies(node.coordinate.version) + ? Choice(node: recordingOverride(node), release: node.hostedEvidence == nil ? current : nil) + : nil + } + let releases = + fixed + ? [] + : published.filter { + $0.coordinate != locked?.coordinate && satisfies($0.coordinate.version) + } + var options: [(choice: Choice?, release: MarketplaceRelease?)] = [] + if let lockedChoice, !updating { options.append((lockedChoice, nil)) } + options += releases.map { (nil, $0) } + if let lockedChoice, updating { + let position = + options.firstIndex { + !MarketplaceCoordinate.newer($0.release!.coordinate, than: lockedChoice.node.coordinate) + } ?? options.endIndex + options.insert((lockedChoice, nil), at: position) + } + let conflict = MarketplaceError.unsatisfiable( + id.description + ": " + incoming.map(\.description).joined(separator: "; ")) + if options.isEmpty && !required.constraints.isEmpty { + try organizationPolicy.admit( + evaluator.version( + nil, identity: .init(id), authored: authored, available: false, + path: incoming[0].path.map { OrganizationPolicyIdentity($0).description })) + } + var failure: any Error = conflict + for option in options { + attempts += 1 + guard attempts <= Self.maximumAttempts else { + throw MarketplaceError.resolutionLimit("candidate attempts") + } + do { + var nextLocators = locators + let choice: Choice + if let locked = option.choice { + choice = locked + for edge in locked.node.dependencies { + let edgeOrigin = edge.requirement.catalog ?? origin + if edgeOrigin != origin { try requireTrustedHostedCatalog(edgeOrigin) } + try bind(edgeOrigin, id: edge.target.catalog, in: &nextLocators) + } + } else { + let release = option.release! + let archive = try bundle(for: release, id: id) + let edges = try (archive.package.dependencies ?? []).map { requirement in + let edgeOrigin = requirement.catalog ?? origin + if edgeOrigin != origin { try requireTrustedHostedCatalog(edgeOrigin) } + let target = try identifier(package: requirement.package, from: edgeOrigin) + try bind(edgeOrigin, id: target.catalog, in: &nextLocators) + return MarketplaceResolvedEdge(requirement: requirement, target: target) + } + choice = Choice( + node: MarketplaceResolvedNode( + id: id, catalog: release.origin, coordinate: release.coordinate, + archiveDigest: release.archiveDigest, + catalogCommit: priorExact.first(where: { + $0.pin.dependency.coordinate == release.coordinate + })?.pin.catalogCommit ?? release.catalogCommit, + dependencies: edges, + organizationRequirements: required.overrides ? required.constraints : nil, + hostedEvidence: hostedPackages[ + MarketplaceReleaseKey(node: id, version: release.coordinate.version) + ]?.hostedEvidence), + release: release) + } + var nextChoices = choices + nextChoices[id] = choice + guard + nextChoices.values.reduce(0, { $0 + $1.node.dependencies.count }) + <= MarketplaceGraph.maximumEdges + else { throw MarketplaceError.resolutionLimit("edge count") } + var nextDemands = demands + let parent = incoming.first(where: \.updating) ?? incoming[0] + for edge in choice.node.dependencies { + let path = parent.path + [edge.target] + if parent.path.contains(edge.target) { + throw MarketplaceError.dependencyCycle(path.map(\.description).joined(separator: " → ")) + } + guard path.count <= MarketplaceGraph.maximumDepth else { + throw MarketplaceError.resolutionLimit("graph depth") + } + let demand = Demand( + requirement: edge.requirement.requirement, path: path, + root: parent.root, updating: updating) + nextDemands[edge.target, default: []].append(demand) + if let existing = nextChoices[edge.target], + existing.node.organizationRequirements == nil, + !demand.requirement.admitsMarketplaceVersion(existing.node.coordinate.version) + { + let reasons = nextDemands[edge.target]!.map(\.description).joined(separator: "; ") + throw MarketplaceError.unsatisfiable(edge.target.description + ": " + reasons) + } + } + return try search( + roots: roots, demands: nextDemands, locators: nextLocators, choices: nextChoices) + } catch let error as MarketplaceError { + switch error { + case .unsatisfiable, .dependencyCycle: + if !(failure is OrganizationPolicyFailure) { failure = error } + default: throw error + } + } catch let error as OrganizationPolicyFailure { + failure = error + } + } + throw failure + } + + private func promotedRoots(for ids: Set) -> [MarketplaceLegacyRoot] { + ids.flatMap { legacy[$0] ?? [] }.sorted { $0.name < $1.name } + } + + private func includingLegacy( + in roots: [MarketplaceResolvedRoot], promoted: [MarketplaceLegacyRoot] + ) throws -> [MarketplaceResolvedRoot] { + let names = Set(roots.map(\.intent.name)) + return try roots + + promoted.filter { !names.contains($0.name) }.map { + MarketplaceResolvedRoot( + intent: try $0.intent(in: declaration, ledger: previous, store: store), node: $0.id) + } + } + + private func admitOrganizationPaths( + roots: [MarketplaceResolvedRoot], choices: [MarketplaceNodeID: Choice] + ) throws { + let evaluator = organizationPolicy.evaluator + guard evaluator.active else { return } + let partial = MarketplaceGraph(roots: roots, nodes: choices.values.map(\.node)) + let paths = partial.policyPaths() + let findings = paths.keys.sorted(by: MarketplaceNodeID.ordered).flatMap { node in + let path = paths[node]!.map { OrganizationPolicyIdentity($0).description } + return evaluator.depth(path.count, path: path) + evaluator.marketplace(node, path: path) + } + try organizationPolicy.admit(findings) + } + + private func validateBranch( + roots: [MarketplaceResolvedRoot], choices: [MarketplaceNodeID: Choice] + ) + throws + { + var heights: [MarketplaceNodeID: Int] = [:] + var path: [MarketplaceNodeID] = [] + var visiting = Set() + func walk(_ id: MarketplaceNodeID) throws -> Int { + if let height = heights[id] { return height } + guard visiting.insert(id).inserted else { + throw MarketplaceError.dependencyCycle( + (path + [id]).map(\.description).joined(separator: " → ")) + } + guard path.count < MarketplaceGraph.maximumDepth else { + throw MarketplaceError.resolutionLimit("graph depth") + } + path.append(id) + let height = try 1 + (choices[id]!.node.dependencies.map { try walk($0.target) }.max() ?? 0) + path.removeLast() + visiting.remove(id) + heights[id] = height + return height + } + for root in roots where try walk(root.node) > MarketplaceGraph.maximumDepth { + throw MarketplaceError.resolutionLimit("graph depth from " + root.intent.name) + } + } + + private var catalogEnvironment: RuntimeEnvironment { store.marketplaceEnvironment } + + private func identifier(package: String, from origin: MarketplaceOrigin) throws + -> MarketplaceNodeID + { + let source = try origin.policyOrigin(environment: catalogEnvironment) + try policy.effective.require(source, reference: package) + return MarketplaceNodeID( + catalog: MarketplaceCatalogID(origin, origin: source), package: package) + } + + private func bind( + _ locator: MarketplaceOrigin, id: MarketplaceCatalogID, + in locators: inout [MarketplaceCatalogID: MarketplaceOrigin] + ) throws { + try policy.effective.require(id.origin) + if let other = locators[id], other.ref != locator.ref { + throw MarketplaceError.originConflict(id.origin.description) + } + if locators[id] == nil { locators[id] = locator } + } + + private func requireTrustedHostedCatalog(_ origin: MarketplaceOrigin) throws { + guard origin.kind == .hosted else { return } + if hostedTrust == nil { + hostedTrust = try MarketplaceDirectory.trustedHostedOrigins(environment: store.environment) + } + guard let trust = hostedTrust, trust.origins.contains(origin) else { + throw HostedMarketplaceError.registrationRequired + } + try trust.evidence.validate() + } + + private func bundle(for release: MarketplaceRelease, id: MarketplaceNodeID) throws + -> BundleInspection + { + if let bundle = bundles[id]?[release.coordinate.version] { return bundle } + guard release.archiveByteCount <= LedgerLimits.standard.encodedBytes - archivedBytes else { + throw MarketplaceError.resolutionLimit("verified archive bytes") + } + archivedBytes += release.archiveByteCount + try hostedTrust?.evidence.validate() + let verified = try observations[id.catalog]!.acquire(release) + let bundle = try verified.inspectBundle() + if verified.hostedEvidence != nil { + hostedPackages[MarketplaceReleaseKey(node: id, version: release.coordinate.version)] = + verified + } + bundles[id, default: [:]][release.coordinate.version] = bundle + return bundle + } +} diff --git a/Sources/AgentsUpdates/Marketplace/MarketplaceUpdate.swift b/Sources/AgentsUpdates/Marketplace/MarketplaceUpdate.swift new file mode 100644 index 0000000..811e95c --- /dev/null +++ b/Sources/AgentsUpdates/Marketplace/MarketplaceUpdate.swift @@ -0,0 +1,392 @@ +import AgentsCore +import AgentsManifest +import Foundation + +extension VerifiedMarketplacePackage { + /// Binds the verified release to the producer aliases created by its archive importer. + /// The importer must check the archive's own package coordinates before building the request. + /// Pass its full-scope update request so the transaction can replace prior package targets. + public func bindingImport( + _ request: UpdateRequest, as name: String, sourceAliases: [String] + ) throws -> UpdateRequest { + switch request.operation { + case .update, .declaration: break + default: throw MarketplaceError.selectionMismatch("package import requires an update") + } + let dependency = try MarketplaceDependency( + name: name, catalog: release.origin, coordinate: release.coordinate) + guard !sourceAliases.isEmpty, sourceAliases.count == Set(sourceAliases).count, + request.marketplaceChange == nil + else { throw MarketplaceError.contributionMismatch(name) } + let origin = try release.policyOrigin() + var request = request + var aliases = sourceAliases + if let installation = request.bundleInstallation { + guard installation.archiveDigest == release.archiveDigest, + Set(aliases) == Set(installation.members.map(\.alias)) + else { + throw MarketplaceError.contributionMismatch(dependency.name) + } + let catalog = try BundlePackageProvenance.release( + release.coordinate, origin: origin, root: release.origin.policyPath, + digest: release.archiveDigest, catalogCommit: release.catalogCommit) + let sealed = try installation.recordingCatalog(catalog, observedOrigin: origin) + request.bundleInstallation = sealed + aliases = sealed.members.map(\.alias) + } + request.marketplaceChange = .install( + dependency, digest: release.archiveDigest, commit: release.catalogCommit, + aliases: aliases.sorted(), origin: origin) + return request + } +} + +extension MarketplaceOperations { + /// Removes one dependency and its importer-owned source and group contributions. + public static func removalRequest(for name: String) -> UpdateRequest { + var request = UpdateRequest() + request.marketplaceChange = .remove(name) + return request + } + + /// Reads package pins under the scope lock and diagnoses missing or changed intent. + public static func installed( + scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> [MarketplacePin] { + let store = StateStore(scope: scope, environment: environment) + return try store.withReadLock { + let baseline = try StatePrecondition(store: store) + let declaration = try store.readDeclaration(prepared: baseline) + let ledger = try store.readLedger(prepared: baseline) + try MarketplaceChanges.validateInspection( + declaration, bytes: baseline.bytes(for: store.declarationURL), ledger: ledger, store: store) + try baseline.validate() + return ledger.marketplacePackages ?? [] + } + } +} + +package enum MarketplaceChange: Sendable { + case install( + MarketplaceDependency, digest: String, commit: String?, aliases: [String], origin: SourceOrigin) + case remove(String) +} + +enum MarketplaceChanges { + static func validateInspection( + _ declaration: Declaration, bytes: Data?, ledger: ResolvedLedger, store: StateStore + ) throws { + try ledger.pendingDeployment?.requireDeclaration(bytes) + try validate( + declaration, matching: ledger.pendingDeployment?.desired(in: ledger) ?? ledger, + in: store) + } + + static func validate( + _ declaration: Declaration, matching ledger: ResolvedLedger, in store: StateStore, + allowingGraphReconciliation: Bool = false + ) + throws + { + try MarketplaceGraphChange.validate( + declaration, matching: ledger, store: store, allowingIntentDrift: allowingGraphReconciliation) + let pins = ledger.marketplacePackages ?? [] + guard !declaration.packages.isEmpty || !pins.isEmpty else { return } + let dependencies = Dictionary(uniqueKeysWithValues: declaration.packages.map { ($0.name, $0) }) + let installed = Dictionary(uniqueKeysWithValues: pins.map { ($0.dependency.name, $0) }) + for dependency in declaration.packages { + guard let pin = installed[dependency.name] else { + throw MarketplaceError.missingPin(dependency.name) + } + guard pin.dependency == dependency else { + throw MarketplaceError.selectionMismatch(dependency.name) + } + } + let closure = try PackageClosure(ledger, store: store) + for pin in pins { + guard dependencies[pin.dependency.name] != nil else { + throw MarketplaceError.selectionMismatch(pin.dependency.name) + } + try closure.validate(pin, declaration: declaration) + } + } + + static func candidate( + _ candidate: Declaration, original: Declaration, previous: ResolvedLedger, + request: UpdateRequest, store: StateStore + ) throws -> Declaration { + guard candidate.packages == original.packages, + candidate.marketplaceRoots == original.marketplaceRoots + else { + throw MarketplaceError.selectionMismatch("use a verified package installation or removal") + } + if let graph = request.marketplaceGraphChange { + return try graph.compose(candidate, previous: previous, store: store) + } + guard let change = request.marketplaceChange else { + for pin in previous.marketplacePackages ?? [] { + if PackageClosure.intentDigest(candidate, aliases: Set(pin.sourceAliases)) + != PackageClosure.intentDigest(original, aliases: Set(pin.sourceAliases)) + { + throw MarketplaceError.contributionMismatch(pin.dependency.name) + } + } + return candidate + } + guard request.kinds == nil, request.names.isEmpty, request.selections.isEmpty, + request.selectedIdentities == nil + else { throw MarketplaceError.selectionMismatch("package changes require a full-scope update") } + + var candidate = candidate + let pins = previous.marketplacePackages ?? [] + switch change { + case .install(let dependency, let digest, _, let aliases, let origin): + guard try dependency.catalog.policyOrigin(environment: store.environment) == origin else { + throw MarketplaceError.originConflict(dependency.name) + } + let id = MarketplaceNodeID( + catalog: MarketplaceCatalogID(dependency.catalog, origin: origin), + package: dependency.coordinate.package) + if previous.marketplaceGraph?.nodes.contains(where: { $0.id == id }) == true { + throw MarketplaceError.selectionMismatch(dependency.name + " is in a resolved graph") + } + let existing = pins.first { $0.dependency.name == dependency.name } + if let existing { + guard existing.dependency.catalog == dependency.catalog, + existing.dependency.coordinate.package == dependency.coordinate.package + else { throw MarketplaceError.originConflict(dependency.name) } + if existing.dependency.coordinate == dependency.coordinate, existing.archiveDigest != digest + { + throw MarketplaceError.integrityMismatch(dependency.coordinate.label) + } + } + let ownedAliases = Set(existing?.sourceAliases ?? []) + let newAliases = Set(aliases) + for alias in newAliases { + guard candidate.sources[alias] != nil, + original.sources[alias] == nil || ownedAliases.contains(alias) + else { throw MarketplaceError.contributionMismatch(dependency.name) } + } + dropAliases(ownedAliases.subtracting(newAliases), from: &candidate) + if let index = candidate.packages.firstIndex(where: { $0.name == dependency.name }) { + candidate.packages[index] = dependency + } else { + candidate.packages.append(dependency) + } + case .remove(let name): + guard let pin = pins.first(where: { $0.dependency.name == name }) else { + throw MarketplaceError.missingPin(name) + } + dropAliases(Set(pin.sourceAliases), from: &candidate) + candidate.packages.removeAll { $0.name == name } + } + return candidate + } + + static func requirePolicy( + _ policy: EffectiveSourcePolicy, candidate: Declaration, previous: ResolvedLedger, + change: MarketplaceChange?, graph: MarketplaceGraph?, store: StateStore + ) throws { + guard policy.isConfigured else { return } + for node in graph?.nodes ?? [] { + try policy.require(node.id.catalog.origin, reference: node.id.description) + } + guard !candidate.packages.isEmpty else { return } + let installed = Dictionary( + uniqueKeysWithValues: (previous.marketplacePackages ?? []).map { ($0.dependency.name, $0) }) + let sources = candidate.sources + for dependency in candidate.packages { + let origin: SourceOrigin + let aliases: [String] + if case .install(let selected, _, _, let selectedAliases, let selectedOrigin) = change, + selected == dependency + { + origin = selectedOrigin + aliases = selectedAliases + } else { + guard let pin = installed[dependency.name] else { + throw MarketplaceError.missingPin(dependency.name) + } + origin = try pin.policyOrigin(environment: store.environment) + aliases = pin.sourceAliases + } + try policy.require(origin, reference: dependency.name) + // Custom importers can supply portable producer seals. A directory generated by an + // untyped importer establishes no original producer coordinates by itself. + for alias in aliases { + guard let source = sources[alias], source.kind == .local, + BundleSourceLocation.container( + of: source.localURL(environment: store.environment), in: store) != nil + else { + try policy.require(.missing, reference: dependency.name + ":" + alias) + continue + } + } + } + } + + static func pin( + _ ledger: ResolvedLedger, declaration: Declaration, previous: ResolvedLedger, + request: UpdateRequest, store: StateStore, sourceIDs: [SourceSnapshotID: String], + producers: [String: BundleSourceInputs.Producer] + ) throws -> ResolvedLedger { + let graph: MarketplaceGraph? + if let change = request.marketplaceGraphChange { + graph = change.graph + } else { + graph = previous.marketplaceGraph + } + var ledger = try MarketplaceGraphChange.freeze( + graph, in: ledger, sourceIDs: sourceIDs, producers: producers, declaration: declaration, + store: store, + hostedArchives: request.marketplaceGraphChange?.hostedArchives ?? previous.contentObjects) + if request.marketplaceGraphChange == nil, ledger.marketplaceGraph != previous.marketplaceGraph { + throw MarketplaceError.contributionMismatch( + "use a marketplace resolution to edit package contributions") + } + guard !declaration.packages.isEmpty else { return ledger } + let previous = Dictionary( + uniqueKeysWithValues: (previous.marketplacePackages ?? []).map { ($0.dependency.name, $0) }) + let closure = try PackageClosure(ledger, store: store) + ledger.marketplacePackages = try declaration.packages.map { dependency in + let existing = previous[dependency.name] + if case .install(let selected, let digest, let commit, let aliases, let origin) = request + .marketplaceChange, + dependency == selected + { + let pinnedCommit = existing?.dependency == dependency ? existing?.catalogCommit : commit + let evidence = try closure.evidence( + for: dependency, archiveDigest: digest, catalogCommit: pinnedCommit, + catalogOrigin: origin, aliases: aliases, in: declaration) + return MarketplacePin( + dependency: dependency, archiveDigest: digest, catalogCommit: pinnedCommit, + sourceAliases: aliases, componentRecords: evidence.components, + contributionDigest: evidence.digest, catalogOrigin: origin) + } + guard let existing else { throw MarketplaceError.missingPin(dependency.name) } + try closure.validate(existing, declaration: declaration) + return existing + } + return ledger + } + + private static func dropAliases(_ aliases: Set, from declaration: inout Declaration) { + declaration.sourceDeclarations.removeAll { aliases.contains($0.name) } + declaration.uses.removeAll { $0.source.map(aliases.contains) ?? false } + } +} + +struct PackageClosure { + private let ledger: ResolvedLedger + private let store: StateStore + private let sourceRecords: [String: [String]] + private let groups: [String: [LedgerGroup]] + private let byGroup: [Int: LedgerGroup] + private let byOccurrence: [Int: LedgerOccurrence] + + init(_ ledger: ResolvedLedger, store: StateStore) throws { + self.ledger = ledger + self.store = store + let roots = store.ledgerRoots(recordedIn: ledger) + let rootGroups = ledger.groups.filter { $0.parent == nil } + let records = Set(rootGroups.map(\.source)) + var sourceRecords: [String: [String]] = [:] + for id in records { + sourceRecords[try ledger.sourceIdentity(id, roots: roots), default: []].append(id) + } + self.sourceRecords = sourceRecords + groups = Dictionary(grouping: rootGroups, by: \.source) + byGroup = Dictionary(uniqueKeysWithValues: ledger.groups.map { ($0.id, $0) }) + byOccurrence = Dictionary(uniqueKeysWithValues: ledger.occurrences.map { ($0.id, $0) }) + } + + func validate(_ pin: MarketplacePin, declaration: Declaration) throws { + let evidence = try evidence( + for: pin.dependency, archiveDigest: pin.archiveDigest, catalogCommit: pin.catalogCommit, + catalogOrigin: pin.catalogOrigin, aliases: pin.sourceAliases, in: declaration) + guard evidence.digest == pin.contributionDigest, evidence.components == pin.componentRecords + else { throw MarketplaceError.contributionMismatch(pin.dependency.name) } + } + + func evidence( + for dependency: MarketplaceDependency, archiveDigest: String, catalogCommit: String?, + catalogOrigin: SourceOrigin?, aliases: [String], in declaration: Declaration + ) throws -> (components: [String], digest: String) { + let name = dependency.name + var selectedGroups: [LedgerGroup] = [] + let sources = declaration.sources + let uses = Dictionary( + grouping: declaration.uses.compactMap { use in + use.source.map { ($0, use.name) } + }, by: { $0.0 }) + for alias in aliases { + guard let source = sources[alias], source.kind == .local, source.requirement == nil, + let selectedUses = uses[alias], !selectedUses.isEmpty, + let records = sourceRecords[try source.identity(environment: store.environment)] + else { throw MarketplaceError.contributionMismatch(name) } + for (_, selected) in selectedUses { + let matching = records.flatMap { groups[$0] ?? [] }.filter { $0.name == selected } + guard !matching.isEmpty else { throw MarketplaceError.contributionMismatch(name) } + selectedGroups.append(contentsOf: matching) + } + } + + var pending = selectedGroups.map(\.id) + var visited = Set() + var components = Set() + var manifests = Set() + var usedSources = Set() + while let id = pending.popLast() { + guard visited.insert(id).inserted else { continue } + if let group = byGroup[id] { + manifests.insert(group.manifestHash) + usedSources.insert(group.source) + pending.append(contentsOf: group.children) + } else if let occurrence = byOccurrence[id] { + components.insert(occurrence.component) + usedSources.formUnion(occurrence.dependencies) + } + } + guard !components.isEmpty else { throw MarketplaceError.contributionMismatch(name) } + for id in components { + guard let component = ledger.components[id], try ResolvedLedgerCodec.digest(component) == id + else { throw MarketplaceError.contributionMismatch(name) } + for resourceID in component.resources { + guard let resource = ledger.resources[resourceID], + resource.kind == .embedded || resource.kind == .artifact, + try ResolvedLedgerCodec.digest(resource) == resourceID + else { throw MarketplaceError.contributionMismatch(name) } + } + } + for id in usedSources { + guard let source = ledger.sources[id], try ResolvedLedgerCodec.digest(source) == id else { + throw MarketplaceError.contributionMismatch(name) + } + } + struct Evidence: Encodable { + let dependency: MarketplaceDependency + let archiveDigest: String + let catalogCommit: String? + let catalogOrigin: SourceOrigin? + let intent: String + let components: [String] + let manifests: [String] + let sources: [String] + } + let ordered = components.sorted() + return ( + ordered, + try ResolvedLedgerCodec.digest( + Evidence( + dependency: dependency, archiveDigest: archiveDigest, catalogCommit: catalogCommit, + catalogOrigin: catalogOrigin, + intent: Self.intentDigest(declaration, aliases: Set(aliases)), + components: ordered, manifests: manifests.sorted(), sources: usedSources.sorted())) + ) + } + + static func intentDigest(_ declaration: Declaration, aliases: Set) -> String { + let bytes = ManifestProjection.marketplaceContributionBytes(declaration, aliases: aliases) + return "sha256:" + FileHash.sha256Hex(data: Data(bytes)) + } +} diff --git a/Sources/AgentsUpdates/MarketplaceBundles.swift b/Sources/AgentsUpdates/MarketplaceBundles.swift new file mode 100644 index 0000000..6ab211a --- /dev/null +++ b/Sources/AgentsUpdates/MarketplaceBundles.swift @@ -0,0 +1,146 @@ +import AgentsCore +import Foundation + +extension MarketplaceOperations { + /// Verifies metadata, byte length, digest and embedded coordinates of every published archive. + /// Git releases are read from a single checkout of the selected ref. + public static func verifyCatalog( + _ registration: MarketplaceRegistration, scope: InstallScope = .project, + environment: RuntimeEnvironment = RuntimeEnvironment(), + hostedAccess: HostedMarketplaceAccess? = nil + ) throws -> MarketplaceCatalog { + let origin = registration.origin + let source = try origin.policyOrigin(environment: environment) + let policy = try OrganizationPolicySnapshot( + store: StateStore(scope: scope, environment: environment)) + try policy.admit(policy.evaluator.catalogAdmission(.init(source, root: origin.policyPath))) + return try withObservedCatalog( + origin, scope: scope, environment: environment, + maximumReleases: LedgerLimits.standard.entries, + expectedOrigin: source, requireRecordedTransport: policy.evaluator.requiresRecordedGitOrigin, + hostedAccess: hostedAccess, organizationPolicy: policy + ) { observed in + for release in observed.releases { + try Task.checkCancellation() + try policy.admit( + policy.evaluator.packageIdentity( + .init(source, suffix: release.coordinate.package, root: origin.policyPath), + catalog: .init(source, root: origin.policyPath))) + let package = try observed.acquire(release) + if origin.kind != .hosted { _ = try package.inspectBundle() } + } + try policy.validate() + return MarketplaceCatalog( + registration: registration, catalogCommit: observed.commit, releases: observed.releases, + indexDigest: observed.indexDigest) + } + } + + /// Lists newer releases from the catalog recorded by this installed dependency. + public static func availableUpdates( + for pin: MarketplacePin, scope: InstallScope, + environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> [MarketplaceRelease] { + let registration = try MarketplaceRegistration( + name: pin.dependency.name, origin: pin.dependency.catalog) + return try browse(registration, scope: scope, environment: environment).updates(for: pin) + } + + /// Rechecks the selected scope's policies for the exact bundle and directory before publication. + @discardableResult + public static func publishBundle( + _ archive: Data, to directory: URL, summary: String? = nil, scope: InstallScope = .project, + environment: RuntimeEnvironment = RuntimeEnvironment(), + registrySchemas: [MCPRegistryServer] = [] + ) throws -> MarketplaceRelease { + try publishAdmitted( + archive, inspection: BundleOperations.inspect(archive), to: directory, summary: summary, + scope: scope, environment: environment, registrySchemas: registrySchemas) + } + + static func publishAdmitted( + _ archive: Data, inspection: BundleInspection, to directory: URL, summary: String?, + scope: InstallScope, environment: RuntimeEnvironment, registrySchemas: [MCPRegistryServer] + ) throws -> MarketplaceRelease { + let package = inspection.package + let coordinate = try MarketplaceCoordinate(package: package.name, version: package.version) + let policy = try AuthorPackagePolicy( + environment, scope: scope, registrySchemas: registrySchemas) + try AuthorPackageOperations.requireLocalFileURL(directory) + let destination = try PathIdentity(directory) + _ = try policy.admit(inspection.archive) + try policy.admitCatalog(directory, package: package) + return try publish(archive, coordinate: coordinate, to: directory, summary: summary) { + try policy.validate() + try destination.validate() + } + } +} + +extension VerifiedMarketplacePackage { + /// Inspects a selected release and checks that its archive declares the catalogued coordinate. + public func inspectBundle() throws -> BundleInspection { + let bundle = try BundleOperations.inspect(archive) + guard bundle.package.name == release.coordinate.package, + bundle.package.version == release.coordinate.version, + bundle.archiveDigest == release.archiveDigest + else { + throw MarketplaceError.integrityMismatch(release.coordinate.releasePath) + } + return bundle + } +} + +extension VerifiedMarketplacePackage { + /// Previews installing or upgrading this release under the given dependency name. + public func previewImport( + as name: String, selections: [BundleImportSelection], scope: InstallScope, + environment: RuntimeEnvironment = RuntimeEnvironment(), replace: Bool = false + ) throws -> BundleImportPreview { + guard release.origin.kind != .hosted else { + throw MarketplaceError.dependenciesRequireResolution(release.coordinate.label) + } + return try BundleOperations.makeImportPreview( + inspectBundle(), selections: selections, scope: scope, environment: environment, + replace: replace, marketplace: (self, name)) + } + + public func previewImportLifecycle( + as name: String, selections: [BundleImportSelection], intent: LifecycleOperationIntent, + scope: InstallScope, environment: RuntimeEnvironment = RuntimeEnvironment(), + replace: Bool = false + ) throws -> LifecyclePackageReview { + try BundleOperations.reviewImportLifecycle( + intent: intent, scope: scope, environment: environment + ) { + try previewImport( + as: name, selections: selections, scope: scope, environment: environment, replace: replace) + } + } +} + +extension BundleInspection { + /// Carries selected clients to uniquely matching members of a new release. Members added or + /// renamed by the publisher require explicit selection. + public func retainedSelections(for pin: MarketplacePin, in scope: ScopeInspection) throws + -> [BundleImportSelection] + { + guard scope.marketplacePackages.contains(pin), package.name == pin.dependency.coordinate.package + else { + throw MarketplaceError.selectionMismatch(pin.dependency.name) + } + let records = Set(pin.componentRecords) + let installed = scope.components.filter { records.contains($0.record) } + var result: [BundleImportSelection] = [] + for item in components { + let matches = installed.filter { $0.kind == item.kind && $0.name == item.name } + guard !matches.isEmpty else { continue } + guard matches.count == 1, let match = matches.first, + components.filter({ $0.kind == item.kind && $0.name == item.name }).count == 1 + else { throw MarketplaceError.selectionMismatch(pin.dependency.name + " / " + item.name) } + let targets = item.supportedTargets(in: scope.scope).filter(match.recipients.contains) + if !targets.isEmpty { result.append(.init(componentID: item.id, targets: targets)) } + } + return result + } +} diff --git a/Sources/AgentsUpdates/OrganizationInstallEvaluation.swift b/Sources/AgentsUpdates/OrganizationInstallEvaluation.swift new file mode 100644 index 0000000..daafd73 --- /dev/null +++ b/Sources/AgentsUpdates/OrganizationInstallEvaluation.swift @@ -0,0 +1,510 @@ +import AgentsCore +import AgentsManifest +import Foundation + +struct OrganizationInstallEvaluation { + private struct DeclaredPackage { + let identity: OrganizationPolicyIdentity + let reference: String + let requirement: SourceRequirement? + let catalog: OrganizationPolicyIdentity? + } + + private struct DeclaredMCP { + let identity: OrganizationPolicyIdentity + let transport: String? + let registry: MCPRegistryEvidence? + let reference: String + } + + let policy: OrganizationPolicySnapshot + let store: StateStore + let declaration: Declaration + private let manifestFields: Set + private let authored: [DeclaredPackage] + private let authoredMCP: [DeclaredMCP] + private let components: [ComponentDeclaration] + var evaluator: OrganizationPolicyEvaluator { policy.evaluator } + + init( + policy: OrganizationPolicySnapshot, store: StateStore, declaration: Declaration, bytes: Data? + ) throws { + self.policy = policy + self.store = store + self.declaration = declaration + guard policy.evaluator.active else { + manifestFields = [] + authored = [] + authoredMCP = [] + components = [] + return + } + if let bytes { + let reader = try YAMLReader(bytes: Array(bytes), identity: .init(store.declarationURL.path)) + manifestFields = Set(reader.root.pairs?.compactMap { $0.key.text } ?? []) + } else { + manifestFields = [] + } + + let directSources = try declaration.sourceDeclarations.compactMap { entry -> DeclaredPackage? in + let source = entry.source + if source.kind == .local, + BundleSourceLocation.container( + of: source.localURL(environment: store.environment), in: store) != nil + { + return nil + } + let origin = try SourceOrigin.declared(source, in: store.environment) + return DeclaredPackage( + identity: .init(origin, root: source.path), reference: entry.name, + requirement: source.requirement, catalog: nil) + } + let graphRoots = try declaration.marketplaceRoots.map { root in + let origin = try root.catalog.policyOrigin(environment: store.marketplaceEnvironment) + return DeclaredPackage( + identity: .init(origin, suffix: root.package, root: root.catalog.policyPath), + reference: root.name, requirement: root.requirement, + catalog: .init(origin, root: root.catalog.policyPath)) + } + let legacy = try declaration.packages.map { package in + let origin = try package.catalog.policyOrigin(environment: store.marketplaceEnvironment) + return DeclaredPackage( + identity: .init( + origin, suffix: package.coordinate.package, root: package.catalog.policyPath), + reference: package.name, requirement: .exact(package.coordinate.version), + catalog: .init(origin, root: package.catalog.policyPath)) + } + authored = directSources + graphRoots + legacy + let groups = Dictionary(uniqueKeysWithValues: declaration.groups.map { ($0.name, $0) }) + var pending = declaration.uses.filter { $0.source == nil || $0.source == "." }.map(\.name) + var visited = Set() + var rootComponents = declaration.components + while let name = pending.popLast() { + guard visited.insert(name).inserted, let group = groups[name] else { continue } + rootComponents += group.components + pending += group.uses.filter { $0.source == nil || $0.source == "." }.map(\.name) + } + components = rootComponents + authoredMCP = rootComponents.compactMap { component in + guard case .mcpServer(let name, let transport, _, _, _, let registry) = component else { + return nil + } + return DeclaredMCP( + identity: registry?.organizationPolicyIdentity ?? .init(.inline, suffix: name), + transport: transport.organizationPolicyName, registry: registry, reference: name) + } + } + + func beforeAcquisition() -> [OrganizationPolicyFinding] { + var findings = authored.flatMap { item in + guard let catalog = item.catalog else { + return evaluator.directSource( + item.identity.origin, root: item.identity.root, requirement: item.requirement, + reference: item.reference) + } + let path = [item.reference] + return evaluator.packageIdentity(item.identity, catalog: catalog, path: path) + + evaluator.pinned( + item.requirement, identity: item.identity, name: item.identity.suffix ?? item.reference, + path: path) + } + for mcp in authoredMCP { + findings += evaluator.mcp( + mcp.identity, transport: mcp.transport, selfDefined: mcp.registry == nil, + transitive: false, path: [mcp.reference], + legacyRegistry: mcp.registry.map { $0.invocationDigest == nil } ?? false) + for origin in mcp.registry?.origins ?? [] { + findings += evaluator.source(origin, path: [mcp.reference]) + } + } + findings += evaluator.findings { rules, context in + var results: [OrganizationPolicyFinding] = [] + for field in rules.requiredFields where !manifestFields.contains(field) { + results.append( + context.finding( + .manifest, field, "manifest-required-field", + "The consumer manifest does not declare this field.")) + } + if rules.scriptsDenied, manifestFields.contains("scripts") || declaration.lifecycle != nil { + results.append( + context.finding( + .manifest, "scripts", "manifest-scripts", "The consumer manifest declares scripts.")) + } + if rules.explicitIncludes { + for case .skills(let alias, let selection) in components { + if case .all = selection.select { + results.append( + context.finding( + .manifest, alias, "manifest-explicit-includes", + "Skill selection needs explicit names.")) + } + } + } + for required in rules.dependencyRequire + where !authored.contains(where: { $0.identity.matches(required.identity, exact: true) }) { + results.append( + context.finding( + .package, required.identity, "dependency-required-declaration", + "Required package is absent from the consumer declaration.", pattern: required.identity) + ) + } + for required in rules.mcpRequire + where !authoredMCP.contains(where: { $0.identity.matches(required, exact: true) }) + && !declaration.marketplaceRoots.contains(where: { root in + root.selections.contains { $0.member.kind == .mcpServer } + }) && !declaration.uses.contains(where: { $0.source != nil && $0.source != "." }) + { + results.append( + context.finding( + .mcp, required, "mcp-required-declaration", + "Required MCP server is absent from the consumer declaration.", pattern: required)) + } + return results + } + return findings + } + + func closure(_ ledger: ResolvedLedger?, roots: [String: URL]) throws + -> [OrganizationPolicyFinding] + { + guard let ledger else { + return evaluator.findings { rules, context in + guard needsClosure(rules), + !authored.isEmpty || !components.isEmpty + || !declaration.uses.isEmpty || !rules.dependencyRequire.isEmpty + || !rules.mcpRequire.isEmpty || !rules.executableRequire.isEmpty + else { return [] } + return [ + context.finding( + .package, "agents.resolved", "dependency-closure-unavailable", + "No resolved lock is available to verify mandatory deployment evidence.") + ] + } + } + let findings = try evaluateClosure(ledger, roots: roots) + return findings.content + findings.workspaceRequirements + } + + func instructionPreviewClosure( + _ candidate: ResolvedLedger, previous: ResolvedLedger, roots: [String: URL] + ) throws -> [OrganizationPolicyFinding] { + let candidateFindings = try evaluateClosure(candidate, roots: roots) + let deployedFindings = try evaluateClosure(previous, roots: roots) + return candidateFindings.content + deployedFindings.workspaceRequirements + } + + private func evaluateClosure(_ ledger: ResolvedLedger, roots: [String: URL]) throws + -> (content: [OrganizationPolicyFinding], workspaceRequirements: [OrganizationPolicyFinding]) + { + let graph = ledger.marketplaceGraph + var results = try checkOverrides(ledger, roots: roots) + guard evaluator.active else { return (results, []) } + let deployed = Set(ledger.deployments.flatMap(\.owners)) + let copyInputs = Set( + ledger.lowerings.filter { $0.instructionCopyRecipient != nil }.flatMap(\.inputs)) + let selectedComponents = deployed.union( + ledger.components.compactMap { $0.value.chatGPT ? $0.key : nil }) + let deployedSources = Set(selectedComponents.compactMap { ledger.components[$0]?.source }) + .union(selectedComponents.compactMap { ledger.components[$0]?.declaringSource }) + .union( + ledger.occurrences.filter { selectedComponents.contains($0.component) }.flatMap( + \.dependencies)) + let graphPaths = graph?.policyPaths() ?? [:] + var packageIdentities: [(OrganizationPolicyIdentity, String?)] = [] + var marketplaceByComponent: [String: MarketplaceNodeID] = [:] + for node in graph?.nodes ?? [] { + let path = (graphPaths[node.id] ?? [node.id]).map { + OrganizationPolicyIdentity($0).description + } + results += evaluator.marketplace(node.id, path: path) + for request in node.hostedEvidence?.requests ?? [] { + let location = try HostedMarketplaceLocation(request.absoluteString) + results += evaluator.source(location.origin, root: location.policyPath, path: path) + } + results += evaluator.depth(path.count, path: path) + let incoming = + (graph?.roots.filter { $0.node == node.id }.map(\.intent.requirement) ?? []) + + (graph?.incoming(to: node.id).map(\.requirement.requirement) ?? []) + results += evaluator.version( + node.coordinate.version, identity: .init(node.id), authored: incoming, path: path) + if node.componentRecords.contains(where: selectedComponents.contains) { + packageIdentities.append((.init(node.id), node.coordinate.version)) + } + for component in node.componentRecords { marketplaceByComponent[component] = node.id } + } + var legacyByComponent: [String: OrganizationPolicyIdentity] = [:] + var catalogProducerSources = Set( + marketplaceByComponent.keys.compactMap { ledger.components[$0]?.declaringSource }) + for pin in ledger.marketplacePackages ?? [] { + let origin = try pin.policyOrigin(environment: store.marketplaceEnvironment) + let identity = OrganizationPolicyIdentity( + origin, suffix: pin.dependency.coordinate.package, root: pin.dependency.catalog.policyPath) + if pin.componentRecords.contains(where: selectedComponents.contains) { + packageIdentities.append((identity, pin.dependency.coordinate.version)) + } + results += evaluator.packageIdentity( + identity, catalog: .init(origin, root: pin.dependency.catalog.policyPath), + path: [pin.dependency.name]) + results += evaluator.version( + pin.dependency.coordinate.version, identity: identity, + authored: [.exact(pin.dependency.coordinate.version)], path: [pin.dependency.name]) + for component in pin.componentRecords { + legacyByComponent[component] = identity + if let source = ledger.components[component]?.declaringSource { + catalogProducerSources.insert(source) + } + } + } + + let origins = try ledger.sources.mapValues { source -> SourceOrigin in + switch source.kind { + case .git: return source.transport.flatMap { try? .git($0) } ?? .missing + case .wellKnown: return source.transport.flatMap { try? .http($0) } ?? .missing + case .local: + guard let location = source.location else { return .missing } + return .local(at: try location.resolve(roots: roots)) + } + } + let implicitRoot = LedgerLocation( + kind: .registered, root: store.scope == .project ? "project" : "state", path: ".") + func sourceIdentity(_ id: String, root: String? = nil) -> OrganizationPolicyIdentity { + var current = id + while let parent = ledger.sources[current]?.container { current = parent } + return .init(origins[current] ?? .missing, root: root) + } + for use in ledger.sourceUses { + let identity = sourceIdentity(use.source, root: use.root) + if let bundle = ledger.sources[use.source]?.bundleSources { + let standalone = !catalogProducerSources.contains(use.source) + if standalone { + let bundleIdentity = + ledger.sources[use.source]?.bundlePackageName.map( + OrganizationPolicyIdentity.localBundle) + ?? .init(.missing) + results += evaluator.packageIdentity( + bundleIdentity, path: [use.source], requireAllow: false) + } + for evidence in bundle { + results += evaluator.source( + evidence.policyOrigin, root: evidence.root, path: [use.source]) + if evidence.packageName != nil { + results += evaluator.recordedBundlePackage(evidence, path: [use.source]) + } else if standalone, evidence.policyOrigin != .inline { + results += evaluator.packageIdentity( + .init(evidence.policyOrigin, root: evidence.root), path: [use.source]) + } + } + } else if let source = ledger.sources[use.source], source.location != implicitRoot { + results += evaluator.source(identity.origin, root: identity.root, path: [use.source]) + results += evaluator.packageIdentity(identity, path: [use.source]) + if deployedSources.contains(use.source) { + packageIdentities.append((identity, source.version)) + } + results += evaluator.version( + source.version, identity: identity, authored: [use.requirement].compactMap { $0 }, + path: [use.source]) + } + } + var groupPaths: [Int: [String]] = [:] + var groupSources: [Int: String] = [:] + for group in ledger.groups { + var path = group.parent.flatMap { groupPaths[$0] } ?? [] + let previous = group.parent.flatMap { groupSources[$0] } + if group.source != previous, ledger.sources[group.source]?.location != implicitRoot, + ledger.sources[group.source]?.bundleSources == nil, + ledger.sources[group.source]?.container == nil + { + path.append(sourceIdentity(group.source, root: group.root).description) + results += evaluator.depth(path.count, path: path) + } + groupPaths[group.id] = path + groupSources[group.id] = group.source + } + for resource in ledger.resources.sorted(by: { $0.key < $1.key }).map(\.value) { + if let artifact = resource.artifact { + for origin in EffectiveSourcePolicy.artifactOrigins(artifact) { + results += evaluator.source(origin, path: [resource.path]) + } + } + } + + let authoredRoots = Set( + (graph?.roots ?? []).filter { declaration.marketplaceRoots.contains($0.intent) } + .map(\.intent.name)) + var declaredMCP = authoredMCP.map(\.identity) + var deployedMCP: [OrganizationPolicyIdentity] = [] + var deployedExecutables: [OrganizationPolicyIdentity] = [] + for (id, component) in ledger.components.sorted(by: { $0.key < $1.key }) { + let node = marketplaceByComponent[id] + let registry = component.mcpRegistry + let legacyRegistry = registry.map { $0.invocationDigest == nil } ?? false + let declaringSource = ledger.sources[component.declaringSource] + let identity = + node.map(OrganizationPolicyIdentity.init) ?? legacyByComponent[id] + ?? declaringSource?.bundlePackageName.map(OrganizationPolicyIdentity.localBundle) + ?? (declaringSource?.location == implicitRoot + ? .init(.inline, suffix: component.name) + : sourceIdentity(component.declaringSource, root: component.root)) + if component.kind == DeclaredComponentKind.mcpServer.rawValue { + let origin = + ledger.sources[component.declaringSource]?.location == implicitRoot + ? SourceOrigin.inline : identity.origin + let suffix = + origin == .inline + ? component.name + : identity.suffix.map { $0 + "/" + component.name } ?? component.name + let server = + registry?.organizationPolicyIdentity + ?? .init(origin, suffix: suffix, root: identity.root) + if let node, let graph { + let member = MarketplaceMemberKey(kind: .mcpServer, name: component.name) + let owners = graph.recipientsByRoot(for: member, in: node).keys + if owners.contains(where: authoredRoots.contains) { declaredMCP.append(server) } + } else if let identity = legacyByComponent[id], + authored.contains(where: { $0.identity == identity }) + { + declaredMCP.append(server) + } else if component.group != nil, origin != .inline, + authored.contains(where: { $0.catalog == nil && $0.identity.origin == origin }) + { + declaredMCP.append(server) + } + let transport = component.payload.object?["transport"]?.object?["kind"]?.text + results += evaluator.mcp( + server, transport: transport == "streamableHTTP" ? "streamable-http" : transport, + selfDefined: registry == nil, + transitive: node.map { node in !(graph?.roots.contains { $0.node == node } ?? false) } + ?? (component.group != nil && origin != .inline), path: [component.name], + legacyRegistry: legacyRegistry) + if deployed.contains(id) { deployedMCP.append(server) } + for origin in registry?.origins ?? [] { + results += evaluator.source(origin, path: [component.name]) + } + } + if deployed.contains(id) || copyInputs.contains(id) { + results += evaluator.findings { rules, context in + guard let allow = rules.contentTypes, !allow.contains(component.kind) else { return [] } + return [ + context.finding( + .manifest, component.name, "manifest-content-types", + "Component type \(component.kind) is outside the allow list.") + ] + } + } + guard deployed.contains(id) else { continue } + let entries = component.resources.compactMap { ledger.resources[$0] }.flatMap(\.entries) + let plugin = + component.kind == DeclaredComponentKind.plugin.rawValue + && component.payload.object?["mode"]?.text == PluginModeDeclaration.native.rawValue + let executable = + component.kind == DeclaredComponentKind.hook.rawValue + || component.kind == DeclaredComponentKind.lspServer.rawValue + || (component.kind == DeclaredComponentKind.mcpServer.rawValue + && (registry == nil || (legacyRegistry && registry?.package != nil))) + || entries.contains { entry in + entry.executable + || (plugin && [".mcp.json", ".lsp.json", "hooks/hooks.json"].contains(entry.path)) + } + if executable { + if !legacyRegistry { deployedExecutables.append(identity) } + results += evaluator.executable( + identity, name: component.name, legacyRegistry: legacyRegistry) + } else if plugin + || component.resources.contains(where: { ledger.resources[$0]?.kind == .liveEdit }) + { + results += evaluator.executable(identity, name: component.name, unknown: true) + } + } + results += evaluator.findings { rules, context in + guard rules.requireHashes else { return [] } + return ledger.resources.values.compactMap { resource in + guard resource.kind != .liveEdit, !resource.hash.hasPrefix("sha256:") else { return nil } + return context.finding( + .package, resource.path, "integrity-required-hash", "The resource has no content hash.") + } + } + let workspaceRequirements = evaluator.findings { rules, context in + var findings: [OrganizationPolicyFinding] = [] + for required in rules.dependencyRequire + where !packageIdentities.contains(where: { $0.0.matches(required.identity, exact: true) }) { + findings.append( + context.finding( + .package, required.identity, "dependency-required-deployment", + "Required package is absent from the resolved deployment.", pattern: required.identity)) + } + for required in rules.mcpRequire { + if !declaredMCP.contains(where: { $0.matches(required, exact: true) }) { + findings.append( + context.finding( + .mcp, required, "mcp-required-declaration", + "Required MCP server is absent from the consumer declaration.", pattern: required)) + } + if !deployedMCP.contains(where: { $0.matches(required, exact: true) }) { + findings.append( + context.finding( + .mcp, required, "mcp-required-deployment", + "Required MCP server is absent from the resolved deployment.", pattern: required)) + } + } + for required in rules.executableRequire + where !deployedExecutables.contains(where: { $0.matches(required, exact: true) }) { + findings.append( + context.finding( + .executable, required, "executables-required-deployment", + "No admitted executable deployment is recorded for the required package.", + pattern: required)) + } + return findings + } + return (results, workspaceRequirements) + } + + private func needsClosure(_ rules: OrganizationRules) -> Bool { + rules.dependencyAllow != nil || !rules.dependencyDeny.isEmpty + || !rules.dependencyRequire.isEmpty + || rules.maximumDepth != nil || rules.mcpAllow != nil || !rules.mcpDeny.isEmpty + || !rules.mcpRequire.isEmpty || rules.mcpTransportAllow != nil || rules.mcpSelfDefined != nil + || rules.mcpTrustTransitive == false || rules.executableDenyAll + || !rules.executableDeny.isEmpty + || !rules.executableRequire.isEmpty || rules.sourceAllow != nil || !rules.sourceDeny.isEmpty + || rules.marketplaceAllow != nil || rules.requireHashes || rules.contentTypes != nil + || rules.failOnDrift || rules.unmanagedAction != .ignore + } + + private func checkOverrides(_ ledger: ResolvedLedger, roots: [String: URL]) throws + -> [OrganizationPolicyFinding] + { + let chain = policy.chains.first(where: { $0.mode == .block }) + func finding(_ identity: OrganizationPolicyIdentity) -> OrganizationPolicyFinding { + .init( + subject: .package, identity: identity.description, rule: "dependency-policy-override", + authority: chain?.scope ?? store.scope, document: chain?.layers.last?.evidence.url, + documentDigest: chain?.layers.last?.evidence.digest, outcome: .block, + message: "The lock’s version override needs matching active organization policy.") + } + var findings: [OrganizationPolicyFinding] = [] + for node in ledger.marketplaceGraph?.nodes ?? [] { + guard let stored = node.organizationRequirements else { continue } + let required = evaluator.marketplaceRequirements(for: node.id) + if !required.overrides || stored != required.constraints { + findings.append(finding(.init(node.id))) + } + } + for use in ledger.sourceUses { + guard let stored = use.organizationRequirements else { continue } + let source = ledger.sources[use.source] + let origin: SourceOrigin + if source?.kind == .local, let location = source?.location { + origin = .local(at: try location.resolve(roots: roots)) + } else { + origin = source?.transport.flatMap { try? SourceOrigin.git($0) } ?? .missing + } + let identity = OrganizationPolicyIdentity(origin, root: use.root) + let required = evaluator.requirements(for: identity) + if !required.overrides || stored != required.constraints { + findings.append(finding(identity)) + } + } + return findings + } +} diff --git a/Sources/AgentsUpdates/OrganizationPolicyLoader.swift b/Sources/AgentsUpdates/OrganizationPolicyLoader.swift new file mode 100644 index 0000000..f90427b --- /dev/null +++ b/Sources/AgentsUpdates/OrganizationPolicyLoader.swift @@ -0,0 +1,645 @@ +import AgentsCore +import AgentsManifest +import Foundation +import Synchronization + +#if canImport(FoundationNetworking) + import FoundationNetworking +#endif + +package struct OrganizationPolicySnapshot: PreparedEvidence, Sendable { + let chains: [OrganizationPolicyChain] + let statuses: [OrganizationPolicyStatus] + let loadFindings: [OrganizationPolicyFinding] + let readDependencies: [ReadDependency] + let fingerprint: String + private let fileInputs: [TargetPrecondition] + private let cacheUpdates: [URL: OrganizationPolicyLoader.Cached] + private let absentRemoteURLs: Set + private let observedAt: Date + + static func configured(_ store: StateStore) -> Bool { + store.environment.userOrganizationPolicy != nil + || (store.scope == .project && store.environment.projectOrganizationPolicy != nil) + } + + init( + store: StateStore, now: Date = Date(), offline: Bool = false, + offlineObservations: OrganizationPolicySnapshot? = nil, + fetch: @escaping (URL) throws -> OrganizationPolicyLoader.Response = OrganizationPolicyHTTP + .fetch + ) throws { + let selections: [(InstallScope, OrganizationPolicySelection?)] = [ + (.user, store.environment.userOrganizationPolicy), + (.project, store.scope == .project ? store.environment.projectOrganizationPolicy : nil), + ] + var loader = OrganizationPolicyLoader( + store: store, now: now, + fetch: offline ? { _ in throw OrganizationPolicyLoader.Offline() } : fetch) + if let offlineObservations { + let absences = offlineObservations.absentRemoteURLs + let absenceAge = now.timeIntervalSince(offlineObservations.observedAt) + loader = OrganizationPolicyLoader( + store: store, now: now, + fetch: { url in + if (0...3600).contains(absenceAge), absences.contains(url) { + return .init(status: 404, url: url, bytes: Data()) + } + throw OrganizationPolicyLoader.Offline() + }, previewCache: offlineObservations.cacheUpdates) + } + var chains: [OrganizationPolicyChain] = [] + var statuses: [OrganizationPolicyStatus] = [] + var findings: [OrganizationPolicyFinding] = [] + var fingerprints: [String] = [] + for (scope, optional) in selections { + guard let selection = optional else { continue } + try Task.checkCancellation() + fingerprints.append(try ResolvedLedgerCodec.digest(selection)) + do { + let chain = try loader.load(selection, scope: scope) + if chain.layers.isEmpty { + statuses.append(.init(authority: scope, outcome: .absent)) + } else { + chains.append(chain) + statuses.append( + .init( + authority: scope, outcome: .loaded, mode: chain.mode, + documents: chain.layers.map(\.evidence))) + for layer in chain.layers { + fingerprints += [layer.evidence.url.absoluteString, layer.evidence.digest] + for warning in layer.rules.warnings { + findings.append( + .init( + subject: .policy, identity: "organization policy", rule: "policy-field", + authority: scope, document: layer.evidence.url, + documentDigest: layer.evidence.digest, outcome: .warn, message: warning)) + } + if layer.evidence.stale { + findings.append( + .init( + subject: .policy, identity: "organization policy", rule: "policy-stale", + authority: scope, document: layer.evidence.url, + documentDigest: layer.evidence.digest, outcome: .warn, + message: "Using previously verified policy bytes outside the freshness window.")) + } + } + } + } catch let error as OrganizationPolicyLoader.Failure { + statuses.append(.init(authority: scope, outcome: error.absent ? .absent : .unavailable)) + fingerprints += [error.absent ? "absent" : "unavailable", error.message] + findings.append( + .init( + subject: .policy, identity: "organization policy", rule: "policy-unavailable", + authority: scope, document: error.url, documentDigest: nil, + outcome: selection.required || error.block ? .block : .warn, message: error.message)) + } + } + self.chains = chains + self.statuses = statuses + loadFindings = findings + fileInputs = loader.fileInputs + cacheUpdates = loader.cacheUpdates + absentRemoteURLs = loader.absentRemoteURLs + observedAt = now + readDependencies = loader.readLocations.map { .entry($0) } + fingerprint = try ResolvedLedgerCodec.digest(fingerprints) + try validate() + } + + package func validate(excludingTargets targets: Set = []) throws { + for input in fileInputs { + if targets.isEmpty { + try input.validate() + } else { + try input.validateDuringPublication() + } + } + } + + func report(_ findings: [OrganizationPolicyFinding] = []) -> OrganizationPolicyReport { + var seen = Set() + return .init( + policies: statuses, findings: (loadFindings + findings).filter { seen.insert($0).inserted }) + } + + /// A read or a refused install never changes the cache. Cached documents are disposable. + func rememberVerifiedPolicies() { + for (url, entry) in cacheUpdates { + do { + try FileManager.default.createDirectory( + at: url.deletingLastPathComponent(), withIntermediateDirectories: true, + attributes: [.posixPermissions: 0o700]) + let bytes = try JSONEncoder().encode(entry) + try bytes.write(to: url, options: .atomic) + } catch { + continue + } + } + } +} + +struct OrganizationPolicyLoader { + static let maximumBytes = 256 * 1024 + static let offlineLifetime: TimeInterval = 7 * 86_400 + private static let maximumDocuments = 5 + + struct Response { + let status: Int + let url: URL + let bytes: Data + } + + struct Cached: Codable, Sendable { + let requested: URL + let effective: URL + let timestamp: Date + let digest: String + let bytes: Data + var ttl: Int + var fetchFailure: OrganizationPolicyMode + } + + struct Failure: Error { + let url: URL? + let message: String + var absent = false + var block = false + } + + struct Offline: Error { var block = false } + + private struct Loaded { + let url: URL + let bytes: Data + let age: Int? + let stale: Bool + let cached: Cached? + } + + let store: StateStore + let now: Date + let fetch: (URL) throws -> Response + var fileInputs: [TargetPrecondition] = [] + var readLocations: [URL] = [] + var cacheUpdates: [URL: Cached] = [:] + var absentRemoteURLs: Set = [] + var previewCache: [URL: Cached] = [:] + + mutating func load(_ selection: OrganizationPolicySelection, scope: InstallScope) throws + -> OrganizationPolicyChain + { + let urls: [URL] + let discovery: [URL] + switch selection.source { + case .invalidLocation: + throw Failure( + url: nil, + message: "Choose an absolute policy file path, an HTTPS URL, or github:OWNER/REPO.", + block: true) + case .local(let url): + guard url.isFileURL else { throw Failure(url: nil, message: "Expected a local policy file.") } + urls = [url.standardizedFileURL] + discovery = [] + case .https(let url): + urls = [try Self.https(url)] + discovery = [] + case .organization(let remote): + discovery = try Self.discoveryURLs(remote) + urls = discovery + } + var earlierOffline = false + for url in urls { + do { + let (layers, updates) = try chain( + at: url, discovery: discovery, earlierOffline: earlierOffline) + for (key, entry) in updates { + var admitted = entry + if let same = cacheUpdates[key], same.digest == admitted.digest { + admitted.ttl = min(same.ttl, admitted.ttl) + admitted.fetchFailure = max(same.fetchFailure, admitted.fetchFailure) + } + cacheUpdates[key] = admitted + } + return OrganizationPolicyChain(scope: scope, layers: layers.reversed()) + } catch let error as Offline { + if discovery.isEmpty || error.block { + throw Failure( + url: url, message: "The policy is unreachable and has no eligible cache.", + block: error.block) + } + earlierOffline = true + } catch let failure as Failure where failure.absent && !failure.block && !discovery.isEmpty { + continue + } + } + if earlierOffline { + throw Failure(url: urls.first, message: "Organization discovery is incomplete offline.") + } + if selection.required { + throw Failure( + url: urls.first, message: "The required organization policy is absent.", absent: true) + } + return OrganizationPolicyChain(scope: scope, layers: []) + } + + private mutating func chain(at url: URL, discovery: [URL], earlierOffline: Bool) throws + -> ([OrganizationPolicyLayer], [URL: Cached]) + { + for refresh in [false, true] { + let leaf = try read(url, ttl: nil, forceRefresh: refresh) + // An earlier unavailable candidate may own stronger policy. Offline discovery can + // fall back only to a later candidate whose bytes were already verified. + if earlierOffline && leaf.cached != nil { + throw Failure(url: url, message: "An earlier organization policy source is unavailable.") + } + var layers: [OrganizationPolicyLayer] = [] + var pending: [URL: Cached] = [:] + try append( + leaf, request: url, discovery: discovery, authority: leaf.url, visited: [], + layers: &layers, pendingCache: &pending, forceRefresh: refresh) + let ttl = layers.map(\.rules.ttl).min()! + if !refresh, + layers.contains(where: { + !$0.evidence.stale && ($0.evidence.ageSeconds ?? 0) > ttl + }) + { + continue + } + let failure = layers.map(\.rules.fetchFailure).max()! + return ( + layers, + pending.mapValues { item in + var item = item + item.ttl = ttl + item.fetchFailure = failure + return item + } + ) + } + preconditionFailure("remote refresh terminates") + } + + private mutating func append( + _ loaded: Loaded, request: URL, discovery: [URL], authority: URL, visited: Set, + layers: inout [OrganizationPolicyLayer], pendingCache: inout [URL: Cached], forceRefresh: Bool + ) throws { + guard layers.count < Self.maximumDocuments, + !visited.contains(request), !visited.contains(loaded.url) + else { + throw Failure( + url: loaded.url, message: "Organization policy inheritance cycle or depth limit.", + block: true) + } + let rules: OrganizationRules + do { + rules = try OrganizationPolicyDocument.parse(loaded.bytes, url: loaded.url) + } catch is CancellationError { + throw CancellationError() + } catch { + let known = try request.isFileURL ? nil : cachedEntry(request) + throw Failure( + url: loaded.url, message: "Invalid organization policy. \(error)", + block: known?.fetchFailure == .block) + } + let digest = "sha256:" + FileHash.sha256Hex(data: loaded.bytes) + layers.append( + .init( + rules: rules, + evidence: .init( + url: loaded.url, digest: digest, name: rules.name, version: rules.version, + ageSeconds: loaded.age, stale: loaded.stale))) + if let cached = loaded.cached { pendingCache[cacheURL(request)] = cached } + guard let reference = rules.parent else { return } + let parents: [URL] + do { + parents = try parentURLs( + reference, child: loaded.url, authority: authority, discovery: discovery) + } catch { + throw Failure( + url: loaded.url, message: "Invalid organization policy parent location.", block: true) + } + let ttl = layers.map(\.rules.ttl).min() + for parent in parents { + do { + guard !visited.contains(parent), parent != loaded.url, parent != request, + layers.count < Self.maximumDocuments + else { + throw Failure( + url: parent, message: "Organization policy inheritance cycle or depth limit.", + block: true) + } + let document = try read(parent, ttl: ttl, forceRefresh: forceRefresh) + let inheritedAuthority = authority.isFileURL && !parent.isFileURL ? parent : authority + try append( + document, request: parent, discovery: discovery, authority: inheritedAuthority, + visited: visited.union([request, loaded.url]), layers: &layers, + pendingCache: &pendingCache, forceRefresh: forceRefresh) + return + } catch let error as Failure where error.absent && parents.count > 1 { + continue + } catch is CancellationError { + throw CancellationError() + } catch { + let reason = (error as? Failure).map { " " + $0.message } ?? "" + throw Failure( + url: parent, message: "Organization policy parent could not be admitted." + reason, + block: true) + } + } + throw Failure( + url: loaded.url, message: "The organization policy parent is absent.", block: true) + } + + private func parentURLs(_ reference: String, child: URL, authority: URL, discovery: [URL]) + throws -> [URL] + { + if child.isFileURL { + if reference.hasPrefix("https://"), let remote = URL(string: reference) { + return [try Self.https(remote)] + } + guard !reference.contains("://"), reference != "org" else { + throw Failure(url: child, message: "Expected a local path or an HTTPS policy parent.") + } + return [ + URL(fileURLWithPath: reference, relativeTo: child.deletingLastPathComponent()) + .standardizedFileURL + ] + } + if reference == "org" { + if !discovery.isEmpty { return discovery } + if authority.host == "raw.githubusercontent.com" { + let parts = authority.path.split(separator: "/") + if parts.count >= 2 { + return try Self.discoveryURLs("github.com/" + parts.prefix(2).joined(separator: "/")) + } + } + } + let qualified: URL? + if reference.hasPrefix("https://") { + qualified = URL(string: reference) + } else if child.host == "raw.githubusercontent.com" { + let segments = reference.split(separator: "/", omittingEmptySubsequences: false) + qualified = + segments.count == 2 && segments.allSatisfy(Self.repositorySegment) + ? Self.githubURL(owner: String(segments[0]), repository: String(segments[1])) : nil + } else { + qualified = nil + } + guard let qualified else { + throw Failure(url: child, message: "Expected a same-origin HTTPS parent.") + } + let parent = try Self.https(qualified) + guard + try SourceOrigin.http(parent.absoluteString) == SourceOrigin.http(authority.absoluteString) + else { throw Failure(url: child, message: "Organization policy parent crosses HTTPS origins.") } + return [parent] + } + + private mutating func read(_ url: URL, ttl: Int?, forceRefresh: Bool) throws -> Loaded { + if url.isFileURL { + do { + readLocations.append(url) + let captured = try TargetPrecondition.readingFile(url, maximumFileBytes: Self.maximumBytes) + fileInputs.append(captured.evidence) + guard let bytes = captured.bytes else { + throw Failure(url: url, message: "Organization policy file is absent.", absent: true) + } + guard bytes.count <= Self.maximumBytes else { + throw Failure(url: url, message: "Organization policy exceeds the byte limit.") + } + return Loaded(url: url, bytes: bytes, age: nil, stale: false, cached: nil) + } catch let error as Failure { + throw error + } catch { + throw Failure(url: url, message: "Organization policy file cannot be read.") + } + } + let persisted = try cachedEntry(url) + let captured = previewCache[cacheURL(url)] + let useCapture = captured.map { $0.timestamp > (persisted?.timestamp ?? .distantPast) } ?? false + let cached = useCapture ? captured : persisted + if let cached { + let age = now.timeIntervalSince(cached.timestamp) + if !forceRefresh, age <= Double(min(ttl ?? cached.ttl, cached.ttl)) { + return Loaded( + url: cached.effective, bytes: cached.bytes, age: Int(age), stale: false, + cached: useCapture ? captured : nil) + } + } + let response: Response + do { + response = try fetch(url) + } catch is Offline { + guard let cached, now.timeIntervalSince(cached.timestamp) <= Self.offlineLifetime else { + throw Offline(block: cached?.fetchFailure == .block) + } + return Loaded( + url: cached.effective, bytes: cached.bytes, + age: Int(now.timeIntervalSince(cached.timestamp)), stale: true, cached: nil) + } catch is CancellationError { + throw CancellationError() + } catch { + throw Failure(url: url, message: "Organization policy HTTPS request failed.", block: true) + } + do { + try Self.requireSameOrigin(response.url, as: url) + } catch { + throw Failure( + url: url, message: "Organization policy redirected outside its HTTPS origin.", block: true) + } + guard (200..<300).contains(response.status) else { + if response.status == 404 { absentRemoteURLs.insert(url) } + throw Failure( + url: url, message: "Organization policy server returned HTTP \(response.status).", + absent: response.status == 404, + block: [401, 403].contains(response.status) || cached?.fetchFailure == .block) + } + guard response.bytes.count <= Self.maximumBytes else { + throw Failure(url: url, message: "Organization policy exceeds the byte limit.") + } + let entry = Cached( + requested: url, effective: response.url, timestamp: now, + digest: FileHash.sha256Hex(data: response.bytes), bytes: response.bytes, + ttl: 3600, fetchFailure: .warn) + return Loaded(url: response.url, bytes: response.bytes, age: 0, stale: false, cached: entry) + } + + private func cacheURL(_ url: URL) -> URL { + let root = store.environment.homeDirectory.appendingPathComponent( + ".cache/agents/organization-policies") + let key = FileHash.sha256Hex(data: Data(url.absoluteString.utf8)) + return root.appendingPathComponent(key + ".json") + } + + private mutating func cachedEntry(_ url: URL) throws -> Cached? { + let location = cacheURL(url) + readLocations.append(location) + guard + let captured = try? TargetPrecondition.readingFile( + location, maximumFileBytes: Self.maximumBytes * 2) + else { return nil } + fileInputs.append(captured.evidence) + guard let bytes = captured.bytes, bytes.count <= Self.maximumBytes * 2, + let entry = try? JSONDecoder().decode(Cached.self, from: bytes), + entry.requested == url, (try? Self.requireSameOrigin(entry.effective, as: url)) != nil, + entry.bytes.count <= Self.maximumBytes, + entry.digest == FileHash.sha256Hex(data: entry.bytes), + now.timeIntervalSince(entry.timestamp) >= 0, (1...86_400).contains(entry.ttl), + entry.fetchFailure != .off, + (try? OrganizationPolicyDocument.parse(entry.bytes, url: entry.effective)) != nil + else { return nil } + return entry + } + + static func https(_ url: URL) throws -> URL { + guard url.scheme?.lowercased() == "https", + let parts = URLComponents(url: url, resolvingAgainstBaseURL: true), + parts.user == nil, parts.password == nil, parts.query == nil, parts.fragment == nil, + let canonical = parts.url, (try? SourceOrigin.http(canonical.absoluteString)) != nil + else { + throw Failure( + url: nil, message: "Policy URLs must use HTTPS without credentials, query or fragment.") + } + return canonical + } + + static func requireSameOrigin(_ destination: URL, as reference: URL) throws { + let destination = try https(destination) + guard + try SourceOrigin.http(destination.absoluteString) + == SourceOrigin.http(reference.absoluteString) + else { throw Failure(url: reference, message: "Cross-origin policy redirect.") } + } + + private static func repositorySegment(_ value: Substring) -> Bool { + !value.isEmpty && value != "." && value != ".." + && value.utf8.allSatisfy { + (48...57).contains($0) || (65...90).contains($0) || (97...122).contains($0) + || [45, 46, 95].contains($0) + } + } + + private static func githubURL(owner: String, repository: String) -> URL { + URL(string: "https://raw.githubusercontent.com/\(owner)/\(repository)/HEAD/agents-policy.yaml")! + } + + private static func discoveryURLs(_ remote: String) throws -> [URL] { + guard let origin = try? SourceOrigin.git(remote), let identity = origin.identity, + identity.hasPrefix("github.com/") + else { throw Failure(url: nil, message: "Organization discovery requires a GitHub remote.") } + let parts = identity.split(separator: "/", omittingEmptySubsequences: false) + guard parts.count == 3, parts.dropFirst().allSatisfy(repositorySegment) else { + throw Failure( + url: nil, message: "Organization discovery requires a GitHub repository remote.") + } + return [".github-private", ".github", ".apm", "_apm"].map { + githubURL(owner: String(parts[1]), repository: $0) + } + } +} + +final class OrganizationPolicyHTTP: NSObject, URLSessionDataDelegate { + private struct State: Sendable { + var response: HTTPURLResponse? + var bytes = Data() + var rejected = false + var redirects = 0 + } + + private let origin: URL + private let state = Mutex(State()) + private let finished = DispatchSemaphore(value: 0) + private let result = Mutex?>(nil) + + private init(origin: URL) { self.origin = origin } + + static func fetch(_ url: URL) throws -> OrganizationPolicyLoader.Response { + let delegate = Self(origin: url) + let config = URLSessionConfiguration.ephemeral + config.timeoutIntervalForRequest = 10 + config.timeoutIntervalForResource = 20 + config.httpCookieStorage = nil + config.urlCredentialStorage = nil + let session = URLSession(configuration: config, delegate: delegate, delegateQueue: nil) + defer { session.finishTasksAndInvalidate() } + let task = session.dataTask(with: url) + task.resume() + while delegate.finished.wait(timeout: .now() + .milliseconds(100)) == .timedOut { + if Task.isCancelled { + task.cancel() + throw CancellationError() + } + } + return try delegate.result.withLock { try $0!.get() } + } + + func urlSession( + _ session: URLSession, task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, + completionHandler: @escaping @Sendable (URLRequest?) -> Void + ) { + let allowed = state.withLock { state in + state.redirects += 1 + guard state.redirects <= 5, let url = request.url, + (try? OrganizationPolicyLoader.requireSameOrigin(url, as: origin)) != nil + else { + state.rejected = true + return false + } + return true + } + completionHandler(allowed ? request : nil) + } + + func urlSession( + _ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, + completionHandler: @escaping @Sendable (URLSession.ResponseDisposition) -> Void + ) { + let allowed = state.withLock { state in + state.response = response as? HTTPURLResponse + if response.expectedContentLength > Int64(OrganizationPolicyLoader.maximumBytes) { + state.rejected = true + } + return state.response != nil && !state.rejected + } + completionHandler(allowed ? .allow : .cancel) + } + + func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + let cancel = state.withLock { state in + guard data.count <= OrganizationPolicyLoader.maximumBytes - state.bytes.count else { + state.rejected = true + return true + } + state.bytes.append(data) + return false + } + if cancel { dataTask.cancel() } + } + + func urlSession( + _ session: URLSession, task: URLSessionTask, didCompleteWithError error: (any Error)? + ) { + let output = state.withLock { state -> Result in + if state.rejected { + return .failure(CoreError.invalidSource("organization policy HTTPS boundary")) + } + if let code = (error as? URLError)?.code, + [ + .notConnectedToInternet, .timedOut, .networkConnectionLost, .cannotFindHost, + .cannotConnectToHost, .dnsLookupFailed, + ].contains(code) + { + return .failure(OrganizationPolicyLoader.Offline()) + } + if let error { return .failure(error) } + guard let response = state.response, let url = response.url else { + return .failure(CoreError.invalidSource("missing organization policy HTTP response")) + } + return .success(.init(status: response.statusCode, url: url, bytes: state.bytes)) + } + result.withLock { $0 = output } + finished.signal() + } +} diff --git a/Sources/AgentsUpdates/OrganizationPolicyOperations.swift b/Sources/AgentsUpdates/OrganizationPolicyOperations.swift new file mode 100644 index 0000000..03073f6 --- /dev/null +++ b/Sources/AgentsUpdates/OrganizationPolicyOperations.swift @@ -0,0 +1,162 @@ +import AgentsCore +import AgentsManifest +import AgentsSkills +import Components +import Foundation + +/// Read-only policy and CI evaluation. Only the selected policy transport may be consulted. +public enum OrganizationPolicyOperations { + public static func status( + scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> OrganizationPolicyReport { + let snapshot = try OrganizationPolicySnapshot( + store: StateStore(scope: scope, environment: environment)) + let report = snapshot.report() + return report.policies.isEmpty + ? .init(policies: [.init(authority: scope, outcome: .absent)], findings: []) + : report + } + + public static func audit( + scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment(), + requireOrganizationPolicy: Bool = false + ) throws -> OrganizationPolicyAudit { + let store = StateStore(scope: scope, environment: environment) + let policy = try OrganizationPolicySnapshot(store: store) + var routes = Set() + var installations: [String: SkillInstallationTarget] = [:] + while true { + do { + return try store.withReadLock(footprint: routes, installations: Array(installations.values)) + { + let hard = try SourcePolicySnapshot(store: store) + let baseline = try StatePrecondition(store: store) + let document = try store.declarationBytes(prepared: baseline) + let declaration = try store.readDeclaration(prepared: baseline) + let ledger = try store.readLedger(prepared: baseline) + try environment.requireMCPRegistryRoutes(in: ledger) + let hasLock = try baseline.bytes(for: store.resolvedURL) != nil + let roots = store.ledgerRoots(recordedIn: ledger) + let evaluation = try OrganizationInstallEvaluation( + policy: policy, store: store, declaration: declaration, bytes: document) + if evaluation.evaluator.chains.contains(where: { chain in + chain.mode != .off && chain.layers.contains { $0.rules.failOnDrift } + }) { + let footprint = try DeploymentConstruction.routes(ledger) + let targets = try SkillLifecycle.installationTargets(ledger, store: store) + guard footprint.isSubset(of: routes), + Set(targets.keys).isSubset(of: Set(installations.keys)) + else { throw RequiredRoutes(routes: footprint, installations: targets) } + } + let managed = try OrganizationWorkspaceInspection( + evaluator: evaluation.evaluator, store: store, ledger: ledger, roots: roots, + inspectDrift: true) + var findings = + try evaluation.beforeAcquisition() + + evaluation.closure(hasLock ? ledger : nil, roots: roots) + managed.findings + if requireOrganizationPolicy && policy.chains.isEmpty { + findings.append( + .init( + subject: .policy, identity: "organization policy", rule: "policy-required", + authority: scope, document: nil, documentDigest: nil, outcome: .block, + message: "CI requires an admitted organization policy.")) + } + var sourceViolations = try sourceViolations( + hard.effective, declaration: declaration, ledger: ledger, store: store, roots: roots) + let pendingPolicy: OrganizationPolicyReport? + if let pending = ledger.pendingDeployment { + let desired = try pending.desired(in: ledger) + try environment.requireMCPRegistryRoutes(in: desired) + let pendingViolations = try hard.effective.violations( + in: desired, store: store, roots: roots) + sourceViolations.append( + contentsOf: pendingViolations.filter { violation in + !sourceViolations.contains(violation) + }) + pendingPolicy = try policy.report( + evaluation.beforeAcquisition() + evaluation.closure(desired, roots: roots)) + } else { + pendingPolicy = nil + } + let closureIssue: String? + do { + try MarketplaceChanges.validateInspection( + declaration, bytes: document, ledger: ledger, store: store) + closureIssue = nil + } catch let error as MarketplaceError { + closureIssue = error.description + } + try baseline.validate() + try hard.validate() + try policy.validate() + try managed.validate() + return OrganizationPolicyAudit( + scope: scope, hasLock: hasLock, organization: policy.report(findings), + sourceViolations: sourceViolations, closureIssue: closureIssue, + pendingMarketplaceDeployment: ledger.pendingDeployment != nil, + pendingMarketplacePolicy: pendingPolicy) + } + } catch let required as RequiredRoutes { + routes.formUnion(required.routes) + installations.merge(required.installations, uniquingKeysWith: { _, next in next }) + } + } + } + + private static func sourceViolations( + _ policy: EffectiveSourcePolicy, declaration: Declaration, ledger: ResolvedLedger, + store: StateStore, roots: [String: URL] + ) throws -> [SourcePolicyViolation] { + guard policy.isConfigured else { return [] } + let recorded = try policy.violations(in: ledger, store: store, roots: roots) + let authored = try declaration.sourceDeclarations.flatMap { entry -> [SourcePolicyViolation] in + if entry.source.kind == .local, + BundleSourceLocation.container( + of: entry.source.localURL(environment: store.environment), in: store) != nil + { + return [] + } + let origin = try SourceOrigin.declared(entry.source, in: store.environment) + return policy.violations(for: origin, reference: entry.name) + } + return recorded + + authored.filter { violation in + !recorded.contains { + $0.scope == violation.scope && $0.origin == violation.origin + && $0.reason == violation.reason + } + } + } +} + +public struct OrganizationPolicyAudit: Encodable, Sendable { + public let scope: InstallScope + public let hasLock: Bool + public let organization: OrganizationPolicyReport + public let sourceViolations: [SourcePolicyViolation] + public let closureIssue: String? + public let pendingMarketplaceDeployment: Bool + /// Policy findings for the requested closure. Workspace drift lives in `organization`. + public let pendingMarketplacePolicy: OrganizationPolicyReport? + public var isBlocked: Bool { + organization.isBlocked || !sourceViolations.isEmpty || closureIssue != nil + || pendingMarketplaceDeployment + } +} + +extension OrganizationPolicySnapshot { + var evaluator: OrganizationPolicyEvaluator { .init(chains: chains) } + + func admit(_ findings: [OrganizationPolicyFinding] = []) throws { + try report(findings).requireAdmission() + } + + func requireSource(_ source: SourceDeclaration, reference: String, in store: StateStore) throws { + try admit() + guard evaluator.active else { return } + try admit( + evaluator.directSource( + .declared(source, in: store.environment), root: source.path, + requirement: source.requirement, reference: reference)) + } +} diff --git a/Sources/AgentsUpdates/OrganizationWorkspaceInspection.swift b/Sources/AgentsUpdates/OrganizationWorkspaceInspection.swift new file mode 100644 index 0000000..34b4f09 --- /dev/null +++ b/Sources/AgentsUpdates/OrganizationWorkspaceInspection.swift @@ -0,0 +1,215 @@ +import AgentsCore +import Components +import Foundation + +/// Reads native target evidence without repairing targets, resolving sources or materializing a lock. +struct OrganizationWorkspaceInspection: PreparedEvidence { + let findings: [OrganizationPolicyFinding] + private let reassess: () throws -> [OrganizationPolicyFinding] + + init( + evaluator: OrganizationPolicyEvaluator, store: StateStore, ledger: ResolvedLedger, + previous: ResolvedLedger? = nil, roots: [String: URL], inspectDrift: Bool + ) throws { + reassess = { + try Self.inspect( + evaluator, store: store, ledger: ledger, previous: previous, roots: roots, + inspectDrift: inspectDrift) + } + findings = try reassess() + } + + func validate(excludingTargets targets: Set = []) throws { + // During publication the transaction owns changes to admitted target paths. + if targets.isEmpty, try reassess() != findings { + throw CoreError.invalidState( + "organization workspace observations changed; refresh the preview") + } + } + + private struct Inventory { + let files: [String] + let incomplete: Bool + } + + private static func inspect( + _ evaluator: OrganizationPolicyEvaluator, store: StateStore, ledger: ResolvedLedger, + previous: ResolvedLedger?, roots: [String: URL], inspectDrift: Bool + ) throws -> [OrganizationPolicyFinding] { + let layers = evaluator.chains.filter { $0.mode != .off }.flatMap(\.layers) + let checkDrift = inspectDrift && layers.contains { $0.rules.failOnDrift } + let checkUnmanaged = layers.contains { $0.rules.unmanagedAction != .ignore } + guard checkDrift || checkUnmanaged else { return [] } + var drift: [(String, String)] = [] + if checkDrift { + for deployment in ledger.deployments { + try Task.checkCancellation() + let observed = try ArtifactAggregation.inspectDeployment( + deployment, ledger: ledger, store: store, roots: roots, permitReplay: false) + if observed.status != "current" { + drift.append((deployment.target.path, observed.diagnostic ?? observed.status)) + } + } + } + let defaults = checkUnmanaged ? defaultDirectories(store) : [:] + let managed = + checkUnmanaged + ? try ownedPaths([ledger, previous].compactMap { $0 }, store: store, roots: roots) + : Ownership() + var inventories: [String: Inventory] = [:] + for layer in layers where layer.rules.unmanagedAction != .ignore { + let directories = + layer.rules.unmanagedDirectories.isEmpty + ? Array(defaults.keys) : layer.rules.unmanagedDirectories + for path in directories where inventories[path] == nil { + let base = + store.scope == .project + ? store.environment.projectDirectory : store.environment.homeDirectory + let directory = defaults[path] ?? base.appendingPathComponent(path) + inventories[path] = try inventory( + directory, displayPath: path, owned: managed) + } + } + return evaluator.findings { rules, context in + var findings: [OrganizationPolicyFinding] = [] + if checkDrift && rules.failOnDrift { + findings += drift.map { path, reason in + context.finding(.workspace, path, "workspace-drift", reason) + } + } + guard rules.unmanagedAction != .ignore else { return findings } + let exclusions = context.chain.layers.flatMap(\.rules.unmanagedExclude) + let directories = + rules.unmanagedDirectories.isEmpty + ? Array(defaults.keys).sorted() : rules.unmanagedDirectories + var seen = Set() + for path in directories { + guard let inventory = inventories[path] else { continue } + for file in inventory.files + where seen.insert(file).inserted + && !exclusions.contains(where: { OrganizationPolicyEvaluator.glob($0, matches: file) }) + { + findings.append( + context.finding( + .workspace, file, "workspace-unmanaged", "No lock deployment owns this path.", + advisory: rules.unmanagedAction == .warn)) + } + if inventory.incomplete { + findings.append( + context.finding( + .workspace, path, "workspace-unmanaged-unverified", + "Could not inspect the entire directory.", + advisory: rules.unmanagedAction == .warn)) + } + } + return findings + } + } + + private static func defaultDirectories(_ store: StateStore) -> [String: URL] { + let base = + store.scope == .project + ? store.environment.projectDirectory : store.environment.homeDirectory + var directories: [String: URL] = [:] + for agent in AgentRegistry.skillAgents { + let url = AgentRegistry.installSkillsDirectory( + for: agent, scope: store.scope, environment: store.environment + ).standardizedFileURL + let relative = + url.path.hasPrefix(base.path + "/") + ? String(url.path.dropFirst(base.path.count + 1)) : url.path + directories[relative] = url + } + let rules = store.scope == .project ? ".agents/rules" : ".gemini/config/rules" + directories[rules] = base.appendingPathComponent(rules) + return directories + } + + private struct Ownership { + var whole = Set() + var copiedSkills = Set() + } + + private static func ownedPaths( + _ ledgers: [ResolvedLedger], store: StateStore, roots: [String: URL] + ) throws -> Ownership { + var result = Ownership() + let metadata = [ + store.declarationURL, store.resolvedURL, store.watchURL, store.cacheDirectory, + store.directory.appendingPathComponent(".agents.lock"), + store.directory.appendingPathComponent(BundleSourceLocation.directory), + ] + result.whole.formUnion( + metadata.map { url in + url.deletingLastPathComponent().resolvingSymlinksInPath() + .appendingPathComponent(url.lastPathComponent).path + }) + for ledger in ledgers { + for deployment in ledger.deployments { + let target = try deployment.target.resolve(roots: roots) + let parent = target.deletingLastPathComponent().resolvingSymlinksInPath() + let path = parent.appendingPathComponent(target.lastPathComponent).path + if deployment.route == "agents/skill@1", + let component = deployment.owners.first.flatMap({ ledger.components[$0] }), + component.payload.object?["mode"]?.text == InstallMode.copy.rawValue, + let resource = component.resources.first.flatMap({ ledger.resources[$0] }), + !resource.entries.isEmpty + { + result.copiedSkills.insert(path) + for entry in resource.entries where entry.kind != .directory { + result.whole.insert(entry.path == "." ? path : path + "/" + entry.path) + } + } else { + result.whole.insert(path) + } + } + } + return result + } + + private static func inventory( + _ directory: URL, displayPath: String, owned: Ownership + ) throws -> Inventory { + let governed = directory.resolvingSymlinksInPath().path + var pending: [(URL, String)] = [(directory, displayPath)] + var files: [String] = [] + var seen = 0 + var incomplete = false + let keys: [URLResourceKey] = [.isDirectoryKey, .isSymbolicLinkKey] + while let (url, display) = pending.popLast() { + try Task.checkCancellation() + seen += 1 + guard seen <= 16_384 else { return .init(files: files.sorted(), incomplete: true) } + let path = url.deletingLastPathComponent().resolvingSymlinksInPath() + .appendingPathComponent(url.lastPathComponent).path + if owned.whole.contains(path) { continue } + do { + let info = try url.resourceValues(forKeys: Set(keys)) + if info.isDirectory == true && info.isSymbolicLink != true { + let contents = try FileManager.default.contentsOfDirectory( + at: url, includingPropertiesForKeys: keys) + if contents.count > 16_384 - seen - pending.count { + incomplete = true + } else { + pending += contents.reversed().map { ($0, display + "/" + $0.lastPathComponent) } + } + } else if owned.copiedSkills.contains(path) { + continue + } else if url != directory || info.isSymbolicLink == true { + files.append(display) + } else { + incomplete = true + } + } catch let error as NSError + where error.domain == NSCocoaErrorDomain && error.code == NSFileReadNoSuchFileError + { + if url != directory || FileManager.default.fileExists(atPath: governed) { + incomplete = true + } + } catch { + incomplete = true + } + } + return .init(files: files.sorted(), incomplete: incomplete) + } +} diff --git a/Sources/AgentsUpdates/PreparedUpdate.swift b/Sources/AgentsUpdates/PreparedUpdate.swift index 61d7d7f..f1d4a15 100644 --- a/Sources/AgentsUpdates/PreparedUpdate.swift +++ b/Sources/AgentsUpdates/PreparedUpdate.swift @@ -1,12 +1,7 @@ import AgentsCore +import CPlatform import Foundation -#if canImport(Darwin) - import Darwin -#else - import Glibc -#endif - /// Valid only on the preparing thread, inside `withPreparedUpdate`. Any apply attempt consumes it. /// Render `report` directly; re-entering scope operations while this handle is active can deadlock. public final class PreparedUpdate { @@ -24,7 +19,7 @@ public final class PreparedUpdate { self.outcome = outcome } - public func apply() throws -> UpdateApplyResult { + public func apply(ifUnchangedFrom fingerprint: String? = nil) throws -> UpdateApplyResult { let pending = try gate.withLock { guard active, !attempted, let plan else { throw CoreError.invalidState("prepared update is inactive, consumed or on another thread") @@ -36,6 +31,9 @@ public final class PreparedUpdate { return plan } do { + if let fingerprint, fingerprint != report.displayedFingerprint { + throw CoreError.invalidState("displayed update candidate changed; refresh the report") + } return try pending.apply(outcome: outcome) } catch { pending.recover(outcome: outcome) diff --git a/Sources/AgentsUpdates/ProducerPatchDestination.swift b/Sources/AgentsUpdates/ProducerPatchDestination.swift new file mode 100644 index 0000000..55b4eb6 --- /dev/null +++ b/Sources/AgentsUpdates/ProducerPatchDestination.swift @@ -0,0 +1,220 @@ +import AgentsCore +import Foundation + +struct ProducerPatchDestination { + private let url: URL + private let anchor: DirectoryHandle + private let ancestry: PathIdentity + private let missing: [String] + private let protected: [URL] + + init(_ output: URL, excluding protected: [URL]) throws { + guard output.isFileURL, output.path.hasPrefix("/"), !output.path.utf8.contains(0), + output.host == nil || output.host == "" || output.host == "localhost", + !output.path.split(separator: "/").contains(".."), + output.query == nil, output.fragment == nil + else { throw ProducerPatchError.unsafeDestination(output) } + let url = output.standardizedFileURL + self.url = url + self.protected = protected + do { + var path = url + var missing: [String] = [] + while true { + if let directory = try DirectoryHandle.readDirectoryIfPresent(at: path) { + anchor = directory + break + } + missing.append(path.lastPathComponent) + path.deleteLastPathComponent() + } + self.missing = missing.reversed() + ancestry = try PathIdentity(anchor.url) + try validateAnchor() + try validateProtection() + } catch { + throw ProducerPatchError.unsafeDestination(output) + } + } + + private func validateProtection() throws { + let excluded = protected.flatMap { [$0.standardizedFileURL, $0.resolvingSymlinksInPath()] } + let protectedIDs = Set( + excluded.compactMap { + try? DirectoryHandle.readDirectoryIfPresent(at: $0)?.objectIdentity + }) + guard !excluded.contains(where: { $0.path == "/" || PathSafety.isContained(url, in: $0) }) + else { + throw ProducerPatchError.unsafeDestination(url) + } + var parent = anchor.url + while true { + let identity = try DirectoryHandle.readDirectory(at: parent).objectIdentity + guard !protectedIDs.contains(identity) else { + throw ProducerPatchError.unsafeDestination(url) + } + if parent.path == "/" { break } + parent.deleteLastPathComponent() + } + } + + private func validateAnchor() throws { + do { + try ancestry.validate() + guard + try DirectoryHandle.readDirectory(at: anchor.url).objectIdentity == anchor.objectIdentity + else { throw ProducerPatchError.unsafeDestination(url) } + } catch { + throw ProducerPatchError.unsafeDestination(url) + } + } + + func publish(_ patches: [ProducerPatchFile], validate: () throws -> Void) throws + -> ProducerPatchExport + { + func file(_ patch: ProducerPatchFile) -> URL { url.appendingPathComponent(patch.filename) } + if let first = missing.first { + // Publish the missing directory chain together. A stale preview or a competing directory + // leaves the entire selected path unmodified. + var committed = false + do { + guard + try anchor.publishDirectory( + named: first, + beforeCommit: { + try validate() + try validateAnchor() + try validateProtection() + }, + afterCommit: { committed = true }, + populate: { staging in + let directory = try missing.dropFirst().reduce(staging) { + try $0.createDirectoryExclusively($1) + } + for patch in patches { + guard + try directory.publishRegularFile( + named: patch.filename, bytes: Data(patch.content.utf8)) + else { throw CoreError.invalidState("duplicate staged patch filename") } + } + } + ) + else { throw ProducerPatchError.unsafeDestination(url) } + return .init(directory: url, written: patches.map(file), reused: [], failures: []) + } catch { + if committed { + return .init( + directory: url, written: patches.map(file), reused: [], + failures: patches.map { .init(file: file($0), reason: .publicationFailed) }) + } + if let known = error as? ProducerPatchError { throw known } + if error is CancellationError { throw CancellationError() } + return .init( + directory: url, written: [], reused: [], + failures: patches.map { .init(file: file($0), reason: .publicationFailed) }) + } + } + + var written: [URL] = [] + var reused: [URL] = [] + var failures: [ProducerPatchExport.Failure] = [] + var validated = false + for patch in patches { + let location = file(patch) + let bytes = Data(patch.content.utf8) + var committed = false + do { + try Task.checkCancellation() + try validateAnchor() + let published = try anchor.publishRegularFile( + named: patch.filename, bytes: bytes, afterCommit: { committed = true }, + beforeCommit: { + try validateAnchor() + if !validated { + try validate() + try validateProtection() + } + try validateAnchor() + validated = true + }) + if published { + try validateAnchor() + written.append(location) + } else if case .regular(_, _, let existing) = try? anchor.observeRegularFile( + patch.filename, maximumBytes: bytes.count), bytes == existing + { + try validateAnchor() + reused.append(location) + } else { + failures.append(.init(file: location, reason: .occupied)) + } + } catch ProducerPatchError.stale { + throw ProducerPatchError.stale + } catch { + if committed, (try? validateAnchor()) != nil { written.append(location) } + let reason: ProducerPatchExport.Failure.Reason + if error is CancellationError { + reason = .cancelled + } else if error is ProducerPatchError || (try? validateAnchor()) == nil { + reason = .destinationChanged + } else { + reason = .publicationFailed + } + failures.append(.init(file: location, reason: reason)) + } + } + return .init(directory: url, written: written, reused: reused, failures: failures) + } +} + +extension ProducerPatchInputs { + func protectedLocations() throws -> [URL] { + let environment = store.environment + let packageRoot = store.scope == .project ? environment.projectDirectory : store.directory + let implicit = LedgerLocation( + kind: .registered, root: store.scope == .project ? "project" : "state", path: ".") + var result = [ + StateStore(scope: .project, environment: environment).directory, + StateStore(scope: .user, environment: environment).directory, + environment.projectDirectory.appendingPathComponent(".git"), + ] + for scope in [InstallScope.project, .user] { + result += AgentRegistry.skillAgents.map { + AgentRegistry.installSkillsDirectory(for: $0, scope: scope, environment: environment) + } + result += AgentID.allCases.compactMap { + InstructionLocations.file(for: $0, scope: scope, environment: environment) + } + result += NativeTargetRoute.clientLocations(scope: scope, environment: environment).compactMap + { + try? $0.location.get() + } + } + result += roots[InstructionLocations.ruleRoot(in: store.scope)].map { [$0] } ?? [] + result += try ledger.deployments.map { try $0.target.resolve(roots: roots) } + result += sourcePolicy.readDependencies.map(\.url) + organization.readDependencies.map(\.url) + result += try declared.sourceDeclarations.compactMap { entry in + guard entry.source.kind == .local else { return nil } + let local = entry.source.localURL(environment: environment) + let directory = try PathSafety.resolvedChild(base: local, subpath: entry.source.path ?? ".") + return directory == packageRoot ? nil : directory + } + let catalogs = + (ledger.marketplaceGraph?.nodes.map(\.catalog) ?? []) + + (ledger.marketplacePackages?.map(\.dependency.catalog) ?? []) + result += catalogs.compactMap { $0.fileURL(environment: store.marketplaceEnvironment) } + for (id, source) in ledger.sources where source.kind == .local { + guard let location = source.location else { continue } + let local = try location.resolve(roots: roots) + if location == implicit || local.standardizedFileURL == packageRoot.standardizedFileURL { + for resource in ledger.resources.values where resource.source == id && resource.path != "." + { + result.append(try PathSafety.resolvedChild(base: local, subpath: resource.path)) + } + } else { + result.append(local) + } + } + return result.filter(\.isFileURL) + } +} diff --git a/Sources/AgentsUpdates/ProducerPatchDiff.swift b/Sources/AgentsUpdates/ProducerPatchDiff.swift new file mode 100644 index 0000000..14c674d --- /dev/null +++ b/Sources/AgentsUpdates/ProducerPatchDiff.swift @@ -0,0 +1,99 @@ +import AgentsCore +import Foundation + +enum ProducerPatchDiff { + static func files(for edits: [ProducerPatchPlan.Edit], in workspace: URL?) throws + -> [ProducerPatchFile] + { + guard !edits.isEmpty else { return [] } + guard let workspace else { throw CoreError.invalidState("missing producer patch workspace") } + let before = workspace.appendingPathComponent("before") + let after = workspace.appendingPathComponent("after") + let scratch = try DirectoryHandle.readDirectory(at: workspace) + var remaining = ProducerPatchInputs.limits.resourceBytes + var names = Set() + var files: [ProducerPatchFile] = [] + for (producer, edits) in Dictionary(grouping: edits, by: \.producer) { + let digest = try ResolvedLedgerCodec.digest(producer).dropFirst(7).prefix(32) + let base: String + let reference: String + switch producer.base { + case .git(let commit): + base = "commit " + commit + reference = String(commit.prefix(12)) + case .release(let version, let digest): + base = "version " + version + " (" + digest + ")" + reference = version + } + let label = + producer.package + ?? String(producer.source.split(separator: "/").last ?? "producer") + let name = String(PathSafety.sanitizeName(label).prefix(80)) + let ref = String(PathSafety.sanitizeName(reference).prefix(32)) + let filename = "\(name)@\(ref)-\(digest).patch" + guard names.insert(filename).inserted else { + throw CoreError.invalidState("producer patch filename collision") + } + let sorted = edits.sorted { $0.path.utf8.lexicographicallyPrecedes($1.path.utf8) } + let selectors = Array(Set(sorted.flatMap(\.selectors))).sorted() + var patch = Data() + func append(_ text: String) throws { + guard text.utf8.count <= remaining else { + throw CoreError.invalidState("producer patch output byte budget") + } + remaining -= text.utf8.count + patch.append(contentsOf: text.utf8) + } + try append("# Source: " + header(producer.source) + "\n") + if let package = producer.package { try append("# Package: " + header(package) + "\n") } + try append("# Root: " + header(producer.root) + "\n# Base: " + header(base) + "\n") + for selector in selectors { try append("# Selector: " + header(selector) + "\n") } + try append("\n") + for edit in sorted { + try Task.checkCancellation() + try edit.before.write(to: before) + try edit.after.write(to: after) + let diff = try ProcessRunner.isolatedGit( + [ + "diff", "--no-index", "--no-ext-diff", "--no-textconv", "--no-color", "--no-renames", + "--text", "--diff-algorithm=myers", "--no-indent-heuristic", "--unified=3", + "--output=diff", "--", "before", "after", + ], in: workspace) + guard diff.exitCode == 1 else { + throw CoreError.invalidState("cannot generate producer patch") + } + // Git's fixed scratch names bound the preamble separately from the hunk budget. + let bytes = try scratch.readRegularFile("diff", maximumBytes: remaining + 1024) + guard let output = String(data: bytes, encoding: .utf8), + let start = output.range(of: "\n@@ -", options: .literal) + else { throw CoreError.invalidState("cannot generate producer patch hunks") } + let a = quote("a/" + edit.path) + let b = quote("b/" + edit.path) + try append("diff --git \(a) \(b)\n--- \(a)\n+++ \(b)\n") + try append(String(output[start.lowerBound...].dropFirst())) + } + files.append( + .init( + filename: filename, producer: producer, selectors: selectors, + paths: sorted.map(\.path), content: String(decoding: patch, as: UTF8.self))) + } + return files.sorted { $0.filename < $1.filename } + } + + private static func header(_ text: String) -> String { + text.unicodeScalars.map { CharacterSet.controlCharacters.contains($0) ? " " : String($0) } + .joined() + } + + private static func quote(_ path: String) -> String { + var result = "\"" + for byte in path.utf8 { + switch byte { + case 34, 92: result += "\\" + String(UnicodeScalar(byte)) + case 32...126: result += String(UnicodeScalar(byte)) + default: result += String(format: "\\%03o", Int(byte)) + } + } + return result + "\"" + } +} diff --git a/Sources/AgentsUpdates/ProducerPatchLineage.swift b/Sources/AgentsUpdates/ProducerPatchLineage.swift new file mode 100644 index 0000000..3a4a0e0 --- /dev/null +++ b/Sources/AgentsUpdates/ProducerPatchLineage.swift @@ -0,0 +1,234 @@ +import AgentsCore +import Foundation + +final class ProducerPatchLineage { + struct Context { + let producer: ProducerPatchProducer + let selectors: [String] + let gitSource: String? + let releaseEntries: [Data: LedgerEntry]? + } + + enum Decision { + case owned(Context) + case skip(ProducerPatchSkip.Reason) + } + + private let inputs: ProducerPatchInputs + private let members: [String: [(MarketplaceResolvedNode, MarketplaceResolvedMember)]] + private let sourceRoots: [String: [String]] + private var archives: [MarketplaceNodeID: [String: BundleItem]] = [:] + + init(_ inputs: ProducerPatchInputs) { + self.inputs = inputs + let ledger = inputs.ledger + var members: [String: [(MarketplaceResolvedNode, MarketplaceResolvedMember)]] = [:] + for node in ledger.marketplaceGraph?.nodes ?? [] where node.catalog.kind == .hosted { + for member in node.members { + if let id = member.producerResource, let resource = ledger.resources[id] { + members[resource.source, default: []].append((node, member)) + } + } + } + self.members = members + self.sourceRoots = Dictionary(grouping: ledger.sourceUses, by: \.source).mapValues { + $0.map(\.root) + } + } + + private func rootSource(_ id: String) -> String { + var root = id + while let parent = inputs.ledger.sources[root]?.container { root = parent } + return root + } + + func isLocallyOwned(_ id: String) -> Bool { + let root = rootSource(id) + let source = inputs.ledger.sources[root]! + guard source.kind == .local, members[root] == nil else { return false } + if let evidence = source.bundleSources { + return evidence.allSatisfy(Self.localClaim) + } + guard let location = source.location, let url = try? location.resolve(roots: inputs.roots) + else { + return false + } + return BundleSourceLocation.container(of: url, in: inputs.store) == nil + } + + private static func localClaim(_ evidence: PortableSourceEvidence) -> Bool { + evidence.kind == .local && evidence.packageName == nil && evidence.origin?.kind != .missing + } + + func hostedProducerResources(for resources: Set) -> Set { + Set( + resources.flatMap { id in + let source = rootSource(inputs.ledger.resources[id]!.source) + return (members[source] ?? []).compactMap { $0.1.producerResource } + }) + } + + func resource(_ id: String) -> LedgerResource { inputs.ledger.resources[id]! } + + /// Claims without a resource-to-source mapping can be classified before any replay. + func unattributed(_ resource: LedgerResource) -> ProducerPatchSkip.Reason? { + let id = rootSource(resource.source) + let source = inputs.ledger.sources[id]! + if isLocallyOwned(resource.source) { return .locallyOwned } + if source.kind == .git { + guard let transport = source.transport, (try? SourceOrigin.git(transport)) != nil else { + return .missingProducerIdentity + } + return resource.kind == .git ? nil : .missingPathAttribution + } + if members[id] != nil { return nil } + if let claims = source.bundleSources { + let origins = Set(claims.filter { !Self.localClaim($0) }.map(\.policyOrigin)) + if origins.count > 1 { return .ambiguousProducer } + if let origin = origins.first, origin != .missing { return .missingPathAttribution } + } + return source.kind == .wellKnown ? .missingPathAttribution : .missingProducerIdentity + } + + func verifyGit( + _ source: String, commit: String, _ body: ((String, Data, Bool) throws -> Bool) throws -> Void + ) throws { + try SourceCache(store: inputs.store).withPinnedGitBlobCheck( + sourceID: source, revision: commit, body) + } + + func origin( + for copy: ProducerPatchRoutes.Copy, replayed: [String: URL] + ) throws -> Decision { + let ledger = inputs.ledger + let resource = ledger.resources[copy.resource]! + let id = rootSource(resource.source) + let source = ledger.sources[id]! + let owners = copy.owners.compactMap { ledger.components[$0] } + if let reason = unattributed(resource) { return .skip(reason) } + if source.kind == .git, let transport = source.transport, + let origin = try? SourceOrigin.git(transport), let identity = origin.identity + { + guard resource.kind == .git, SourceCache.isObjectID(source.revision) else { + return .skip(.missingPathAttribution) + } + let declaredRoots = sourceRoots[id] ?? [] + let matchingRoots = declaredRoots.filter { Self.contains(resource.path, in: $0) } + let ownerRoots = owners.compactMap { component -> String? in + guard rootSource(component.declaringSource) == id, + Self.contains(resource.path, in: component.root) + else { return nil } + return component.root + } + let roots = ownerRoots.isEmpty ? matchingRoots : ownerRoots + let root = roots.min(by: Self.ordered) ?? "." + let selectors = owners.map { Self.selector($0, root: $0.root) } + return .owned( + .init( + producer: .init( + source: identity, package: nil, root: root, base: .git(commit: source.revision)), + selectors: selectors, gitSource: try ledger.sourceIdentity(id, roots: inputs.roots), + releaseEntries: nil)) + } + + if let hosted = members[id] { + let candidates = hosted.filter { node, member in + let records = Set(node.componentRecords) + return zip(copy.owners, owners).contains { ownerID, component in + records.contains(ownerID) && component.declaringSource == id + && component.kind == member.key.kind.rawValue + && PathSafety.sanitizeName(member.key.name) == component.name + && !Set(copy.recipients).isDisjoint(with: member.targets) + } + } + guard let (node, member) = candidates.first else { return .skip(.missingPathAttribution) } + guard candidates.count == 1 else { return .skip(.ambiguousProducer) } + return try hostedOrigin( + node, member: member, source: source, resource: resource, + recipients: copy.recipients, replayed: replayed) + } + + return .skip(.missingProducerIdentity) + } + + private func hostedOrigin( + _ node: MarketplaceResolvedNode, member: MarketplaceResolvedMember, source: LedgerSource, + resource: LedgerResource, recipients: [AgentID], replayed: [String: URL] + ) throws -> Decision { + let ledger = inputs.ledger + let index = try HostedMarketplaceLocation(node.catalog.location) + guard let id = member.producerResource, let container = replayed[id], + let location = try source.location?.resolve(roots: inputs.roots), + let registered = BundleSourceLocation.container(of: location, in: inputs.store), + registered.lastPathComponent + == String(member.sourceAlias.dropFirst(MarketplaceResolvedNode.sourceAliasPrefix.count)) + else { throw ProducerPatchError.lockedInputUnavailable } + let seal = try BundleStoredSource.read(container, expectedKey: registered.lastPathComponent) + guard seal.marketplaceNode == node.id, seal.componentID == member.componentID, + seal.package.name == node.coordinate.package, seal.package.version == node.coordinate.version, + seal.sources == source.bundleSources + else { throw ProducerPatchError.lockedInputUnavailable } + + let items: [String: BundleItem] + if let known = archives[node.id] { + items = known + } else { + guard let evidence = node.hostedEvidence, + let bytes = ledger.contentObjects[node.archiveDigest], + bytes.count == evidence.archiveByteCount, BundleArchive.digest(bytes) == node.archiveDigest + else { throw ProducerPatchError.lockedInputUnavailable } + try evidence.validate(index: node.catalog.location) + try HostedMarketplaceReader.requireRequests( + evidence.requests, index: index, coordinate: node.coordinate, + policy: inputs.sourcePolicy.effective, organization: inputs.organization) + let archive = try BundleArchive.read(bytes) + guard archive.manifest.package.name == node.coordinate.package, + archive.manifest.package.version == node.coordinate.version, + archive.manifest.package.dependencies ?? [] == node.dependencies.map(\.requirement) + else { throw ProducerPatchError.lockedInputUnavailable } + items = try Dictionary( + uniqueKeysWithValues: archive.manifest.components.map { (try $0.id, $0) }) + archives[node.id] = items + } + + guard let item = items[member.componentID], + item.kind.rawValue == member.key.kind.rawValue, item.name == member.key.name + else { throw ProducerPatchError.lockedInputUnavailable } + // The archive's path can establish the release's own contents. A forwarded dependency's + // provenance does not identify that dependency's original file or authorize relabeling it. + let external = item.sources.filter { !Self.localClaim($0) } + guard external.isEmpty else { + return .skip(external.count > 1 ? .ambiguousProducer : .missingPathAttribution) + } + guard item.kind == .skills, item.discovery?.utf8.elementsEqual(resource.path.utf8) == true + else { return .skip(.missingPathAttribution) } + let selectors = ledger.marketplaceGraph?.recipientsByRoot(for: member.key, in: node.id) ?? [:] + let labels = selectors.keys.sorted().filter { + !Set(selectors[$0] ?? []).isDisjoint(with: recipients) + }.map { $0 + ":" + member.key.kind.rawValue + "/" + member.key.name } + guard !labels.isEmpty else { return .skip(.missingPathAttribution) } + return .owned( + .init( + producer: .init( + source: index.url.absoluteString, package: node.coordinate.package, root: ".", + base: .release(version: node.coordinate.version, contentDigest: node.archiveDigest)), + selectors: labels, gitSource: nil, + releaseEntries: Dictionary( + uniqueKeysWithValues: item.entries.map { + (Data($0.path.utf8), $0) + }))) + } + + private static func contains(_ path: String, in root: String) -> Bool { + root == "." || path.utf8.elementsEqual(root.utf8) || path.utf8.starts(with: (root + "/").utf8) + } + + private static func ordered(_ first: String, _ second: String) -> Bool { + first.utf8.lexicographicallyPrecedes(second.utf8) + } + + private static func selector(_ component: LedgerComponent, root: String) -> String { + [root, component.group, component.kind + "/" + component.name].compactMap { $0 } + .joined(separator: ":") + } +} diff --git a/Sources/AgentsUpdates/ProducerPatchOperations.swift b/Sources/AgentsUpdates/ProducerPatchOperations.swift new file mode 100644 index 0000000..a9492a9 --- /dev/null +++ b/Sources/AgentsUpdates/ProducerPatchOperations.swift @@ -0,0 +1,276 @@ +import AgentsCore +import AgentsManifest +import Components +import Foundation + +/// The immutable input to which a patch applies. +public enum ProducerPatchBase: Hashable, Sendable, Encodable { + case git(commit: String) + case release(version: String, contentDigest: String) +} + +public struct ProducerPatchProducer: Hashable, Sendable, Encodable { + /// Canonical repository or catalog identity, without transport credentials. + public let source: String + public let package: String? + /// Repository-relative package root, or "." for the entire repository or release. + public let root: String + public let base: ProducerPatchBase +} + +public struct ProducerPatchFile: Sendable, Encodable { + public let filename: String + public let producer: ProducerPatchProducer + public let selectors: [String] + public let paths: [String] + /// The exact UTF-8 content used by export. + public let content: String +} + +public struct ProducerPatchSkip: Equatable, Sendable, Encodable { + public enum Reason: String, Sendable, Encodable { + case locallyOwned, linkedDeployment, transformed, missingProducerIdentity + case missingPathAttribution, ambiguousProducer + case deleted, nonRegular, binary, uncleanSource, modeChanged, conflictingEdits + } + + public let path: URL + public let reason: Reason +} + +/// Captures a reviewable generation. Use a fresh preview after a stale export. +public struct ProducerPatchPreview: Sendable, Encodable, CustomReflectable { + public let patches: [ProducerPatchFile] + public let skipped: [ProducerPatchSkip] + fileprivate let store: StateStore + fileprivate let generation: ProducerPatchGeneration + + private enum CodingKeys: String, CodingKey { case patches, skipped } + + public var customMirror: Mirror { + Mirror(self, children: ["patches": patches, "skipped": skipped], displayStyle: .struct) + } +} + +public enum ProducerPatchError: Error, Equatable, Sendable, LocalizedError { + case missingLock + case lockedInputUnavailable + case stale + case unsafeDestination(URL) + + public var errorDescription: String? { + switch self { + case .missingLock: "Producer patches require a deployed agents.resolved lock." + case .lockedInputUnavailable: + "A required locked producer input is missing or failed verification." + case .stale: "Producer patch inputs changed. Preview the edits again before exporting." + case .unsafeDestination(let url): "Unsafe producer patch destination: " + url.path + } + } +} + +public struct ProducerPatchExport: Sendable, Encodable { + public struct Failure: Sendable, Encodable { + public enum Reason: String, Sendable, Encodable { + case occupied, destinationChanged, publicationFailed, cancelled + } + + public let file: URL + public let reason: Reason + } + + /// The common destination for every producer, nil for an empty preview. + public let directory: URL? + public let written: [URL] + public let reused: [URL] + public let failures: [Failure] +} + +extension UpdateOperations { + /// Previews edits to qualifying copies using only deployed state and offline producer evidence. + public static func previewProducerPatches( + scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> ProducerPatchPreview { + let store = StateStore(scope: scope, environment: environment) + return try withProducerPatchInputs(store: store) { inputs, plan, workspace in + let patches = try ProducerPatchDiff.files(for: plan.edits, in: workspace) + try inputs.validateState() + try plan.native.validate() + return ProducerPatchPreview( + patches: patches, skipped: plan.skipped, store: store, + generation: inputs.generation(native: plan.native)) + } finish: { _, preview in + preview + } + } + + /// Exports the reviewed bytes to one directory, defaulting to the project's patches directory. + /// The selected URL is used synchronously, including its security scope on macOS. + public static func exportProducerPatches( + _ preview: ProducerPatchPreview, to directory: URL? = nil + ) throws -> ProducerPatchExport { + let store = preview.store + let output = directory ?? store.environment.projectDirectory.appendingPathComponent("patches") + #if os(macOS) + let accessing = output.startAccessingSecurityScopedResource() + defer { if accessing { output.stopAccessingSecurityScopedResource() } } + #endif + var published: ProducerPatchExport? + do { + return try withProducerPatchInputs(store: store, expecting: preview.generation) { + inputs, plan, _ in + guard inputs.generation(native: plan.native) == preview.generation, + plan.skipped == preview.skipped + else { throw ProducerPatchError.stale } + return plan.native + } finish: { inputs, native in + if let published { return published } + func validate() throws { + do { + try inputs.validateState() + try native.validate() + if !preview.patches.isEmpty { try store.validateHeldScope() } + } catch is CancellationError { + throw CancellationError() + } catch { + throw ProducerPatchError.stale + } + } + try validate() + guard !preview.patches.isEmpty else { + return .init(directory: nil, written: [], reused: [], failures: []) + } + let destination = try ProducerPatchDestination( + output, excluding: inputs.protectedLocations()) + let result = try destination.publish(preview.patches, validate: validate) + published = result + return result + } + } catch { + if let published { return published } + if error is ProducerPatchError || error is SourcePolicyFailure + || error is OrganizationPolicyFailure || error is CancellationError + { + throw error + } + throw ProducerPatchError.stale + } + } + + private static func withProducerPatchInputs( + store: StateStore, expecting generation: ProducerPatchGeneration? = nil, + prepare: (ProducerPatchInputs, ProducerPatchPlan, URL?) throws -> Prepared, + finish: (ProducerPatchInputs, Prepared) throws -> Result + ) throws -> Result { + try withReadPlan(store: store) { admitted, installations in + let inputs: ProducerPatchInputs + do { + inputs = try ProducerPatchInputs(store: store) + } catch is CancellationError { + throw CancellationError() + } catch let error as SourcePolicyFailure { + throw error + } catch let error as OrganizationPolicyFailure { + throw error + } catch { + if generation != nil { throw ProducerPatchError.stale } + throw error + } + if let generation, inputs.fingerprint != generation.fingerprint { + throw ProducerPatchError.stale + } + + let projections = try ProducerPatchRoutes(inputs: inputs) + let additional = projections.routes.subtracting(admitted) + let targets = projections.installations.filter { installations[$0.key] == nil } + guard additional.isEmpty, targets.isEmpty else { + throw RequiredRoutes(routes: additional, installations: targets) + } + let prepared = try projections.withPlan(inputs: inputs, revalidating: generation != nil) { + plan, workspace in + try prepare(inputs, plan, workspace) + } + return try finish(inputs, prepared) + } + } +} + +struct ProducerPatchGeneration: Equatable, Sendable { + let fingerprint: String + let scopeDirectory: FileObjectIdentity + let native: ProducerPatchNativeInputs +} + +struct ProducerPatchInputs { + static let limits = LedgerLimits.standard + + let store: StateStore + let ledger: ResolvedLedger + let roots: [String: URL] + let sourcePolicy: SourcePolicySnapshot + let organization: OrganizationPolicySnapshot + let fingerprint: String + let declared: Declaration + private let scopeDirectory: FileObjectIdentity + private let declaration: Data + private let ledgerDigest: String + + init(store: StateStore) throws { + self.store = store + guard let directory = try DirectoryHandle.readDirectoryIfPresent(at: store.directory), + let lock = try directory.readRegularFileIfPresent( + StateStore.resolvedFileName, maximumBytes: Self.limits.encodedBytes) + else { throw ProducerPatchError.missingLock } + guard + let declaration = try directory.readRegularFileIfPresent( + StateStore.declarationFileName, maximumBytes: Self.limits.encodedBytes) + else { throw CoreError.missingDeclaration(store.declarationURL.path) } + self.declaration = declaration + scopeDirectory = try directory.objectIdentity + var ledger = try ResolvedLedgerCodec.decode(lock, limits: Self.limits) + ledger.pendingDeployment = nil + self.ledger = ledger + ledgerDigest = try ResolvedLedgerCodec.digest(ledger) + roots = store.ledgerRoots(recordedIn: ledger) + sourcePolicy = try SourcePolicySnapshot(store: store) + try sourcePolicy.effective.require(ledger, store: store, roots: roots) + organization = try OrganizationPolicySnapshot(store: store, offline: true) + try organization.admit() + let document = try DeclarationDocument( + bytes: Array(declaration), identity: .init(store.declarationURL.path)) + declared = try ManifestProjection.declaration(of: document, environment: store.environment) + var deployedDeclaration = declared + deployedDeclaration.marketplaceRoots = ledger.marketplaceGraph?.roots.map(\.intent) ?? [] + deployedDeclaration.packages = ledger.marketplacePackages?.map(\.dependency) ?? [] + let evaluation = try OrganizationInstallEvaluation( + policy: organization, store: store, declaration: deployedDeclaration, bytes: declaration) + let findings = try evaluation.closure(ledger, roots: roots) + try organization.admit(findings) + fingerprint = try ResolvedLedgerCodec.digest([ + ledgerDigest, sourcePolicy.fingerprint, organization.fingerprint, + ResolvedLedgerCodec.digest(findings.map { try ResolvedLedgerCodec.digest($0) }.sorted()), + ]) + } + + func generation(native: ProducerPatchNativeInputs) -> ProducerPatchGeneration { + .init(fingerprint: fingerprint, scopeDirectory: scopeDirectory, native: native) + } + + func validateState() throws { + try Task.checkCancellation() + try sourcePolicy.validate() + try organization.validate() + let directory = try DirectoryHandle.readDirectory(at: store.directory) + guard try directory.objectIdentity == scopeDirectory, + try directory.readRegularFile( + StateStore.declarationFileName, maximumBytes: Self.limits.encodedBytes) == declaration, + let lock = try directory.readRegularFileIfPresent( + StateStore.resolvedFileName, maximumBytes: Self.limits.encodedBytes) + else { throw ProducerPatchError.stale } + var current = try ResolvedLedgerCodec.decode(lock, limits: Self.limits) + current.pendingDeployment = nil + guard try ResolvedLedgerCodec.digest(current) == ledgerDigest else { + throw ProducerPatchError.stale + } + } +} diff --git a/Sources/AgentsUpdates/ProducerPatchPlan.swift b/Sources/AgentsUpdates/ProducerPatchPlan.swift new file mode 100644 index 0000000..3fcc92b --- /dev/null +++ b/Sources/AgentsUpdates/ProducerPatchPlan.swift @@ -0,0 +1,254 @@ +import AgentsCore +import Foundation + +struct ProducerPatchNativeInputs: Equatable, Sendable { + private enum Observation: Equatable, Sendable { + case missing(FileObjectIdentity?) + case blocked + case other(FileObjectIdentity, FileObjectIdentity) + case regular(FileObjectIdentity, FileObjectIdentity, executable: Bool, digest: String) + } + + private var files: [URL: Observation] = [:] + private var remaining = ProducerPatchInputs.limits.resourceBytes + + mutating func read(_ path: URL) throws -> RegularFileObservation? { + let (observation, file) = try Self.observe(path, maximumBytes: remaining) + if let known = files[path], known != observation { throw ProducerPatchError.stale } + if files.updateValue(observation, forKey: path) == nil, + case .regular(_, _, let bytes) = file + { + remaining -= bytes.count + } + return file + } + + func validate() throws { + var remaining = ProducerPatchInputs.limits.resourceBytes + for (path, expected) in files { + try Task.checkCancellation() + let (actual, file) = try Self.observe(path, maximumBytes: remaining) + guard actual == expected else { throw ProducerPatchError.stale } + if case .regular(_, _, let bytes) = file { remaining -= bytes.count } + } + } + + private static func observe(_ path: URL, maximumBytes: Int) throws + -> (Observation, RegularFileObservation?) + { + let parent: DirectoryHandle? + do { + parent = try DirectoryHandle.readDirectoryIfPresent(at: path.deletingLastPathComponent()) + } catch CoreError.unsafePath { + return (.blocked, nil) + } + guard let parent else { return (.missing(nil), .missing) } + let directory = try parent.objectIdentity + let file = try parent.observeRegularFile( + path.lastPathComponent, maximumBytes: maximumBytes, requireUnshared: true) + switch file { + case .missing: return (.missing(directory), file) + case .other(let identity): return (.other(directory, identity), file) + case .regular(let identity, let executable, let bytes): + return ( + .regular( + directory, identity, executable: executable, digest: FileHash.sha256Hex(data: bytes)), + file + ) + } + } +} + +struct ProducerPatchPlan { + struct Edit { + let producer: ProducerPatchProducer + let selectors: [String] + let path: String + let native: URL + let before: Data + let after: Data + let executable: Bool + } + + private(set) var native = ProducerPatchNativeInputs() + private(set) var edits: [Edit] = [] + private var findings: [ProducerPatchSkip] + private var remaining = ProducerPatchInputs.limits.entries + var skipped: [ProducerPatchSkip] { + findings.sorted { + if !$0.path.path.utf8.elementsEqual($1.path.path.utf8) { + return $0.path.path.utf8.lexicographicallyPrecedes($1.path.path.utf8) + } + return $0.reason.rawValue < $1.reason.rawValue + } + } + + init(skipped: [ProducerPatchSkip]) { + findings = skipped + remaining -= skipped.count + } + + mutating func skip(_ path: URL, _ reason: ProducerPatchSkip.Reason) throws { + try charge() + findings.append(.init(path: path, reason: reason)) + } + + private mutating func charge() throws { + guard remaining > 0 else { throw CoreError.invalidState("producer patch entry budget") } + remaining -= 1 + } + + mutating func compare( + _ copy: ProducerPatchRoutes.Copy, resources: [String: URL], lineage: ProducerPatchLineage + ) throws { + let origin = try lineage.origin(for: copy, replayed: resources) + 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 { + throw ProducerPatchError.lockedInputUnavailable + } + var pending: [Edit] = [] + try scan( + 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() + } + try scan( + record.support, source: root, target: support, prefix: ".", + context: context, pending: &pending) + } + if let git = context.gitSource, case .git(let commit) = context.producer.base { + try lineage.verifyGit(git, commit: commit) { matches in + for edit in pending { + if try matches(edit.path, edit.before, edit.executable) { + edits.append(edit) + } else { + findings.append(.init(path: edit.native, reason: .transformed)) + } + } + } + } else { + edits += pending + } + } + + private mutating func scan( + _ entries: [LedgerEntry], source: URL, target: URL, prefix: String, + context: ProducerPatchLineage.Context, pending: inout [Edit] + ) throws { + for entry in entries where entry.kind != .directory { + try Task.checkCancellation() + try charge() + let targetFile = Self.child(target, entry.path) + guard entry.kind == .file else { + findings.append(.init(path: targetFile, reason: .nonRegular)) + continue + } + let path = prefix == "." ? entry.path : entry.path == "." ? prefix : prefix + "/" + entry.path + guard path != "." else { + findings.append(.init(path: targetFile, reason: .missingPathAttribution)) + continue + } + guard let captured = try native.read(targetFile) else { + findings.append(.init(path: targetFile, reason: .nonRegular)) + continue + } + switch captured { + case .missing: findings.append(.init(path: targetFile, reason: .deleted)) + case .other: findings.append(.init(path: targetFile, reason: .nonRegular)) + case .regular(_, let mode, let bytes): + guard mode == entry.executable else { + findings.append(.init(path: targetFile, reason: .modeChanged)) + continue + } + let baseFile = Self.child(source, entry.path) + let parent = try DirectoryHandle.readDirectory(at: baseFile.deletingLastPathComponent()) + guard let count = entry.byteCount, + case .regular(_, let executable, let base) = try parent.observeRegularFile( + baseFile.lastPathComponent, maximumBytes: count), + base.count == count, executable == entry.executable + else { throw ProducerPatchError.lockedInputUnavailable } + if let entries = context.releaseEntries { + guard let archived = entries[Data(path.utf8)], archived.kind == .file, + archived.executable == entry.executable, archived.byteCount == count, + archived.object == "sha256:" + FileHash.sha256Hex(data: base) + else { + findings.append(.init(path: targetFile, reason: .missingPathAttribution)) + continue + } + } + guard Self.isText(base), Self.isText(bytes) else { + findings.append(.init(path: targetFile, reason: .binary)) + continue + } + guard base == Self.normalized(base) else { + findings.append(.init(path: targetFile, reason: .uncleanSource)) + continue + } + let edited = Self.normalized(bytes) + guard edited != base else { continue } + pending.append( + .init( + producer: context.producer, selectors: context.selectors, + path: path, native: targetFile, before: base, after: edited, executable: executable)) + } + } + } + + /// Compare modified copies before assigning edits to a package, including overlapping roots. + mutating func coalesce() { + struct File: Hashable { + let source: String + let package: String? + let base: ProducerPatchBase + let path: Data + } + let files = Dictionary(grouping: edits) { + File( + source: $0.producer.source, package: $0.producer.package, base: $0.producer.base, + path: Data($0.path.utf8)) + } + edits = files.values.compactMap { copies in + let owner = copies.min { + $0.producer.root.utf8.lexicographicallyPrecedes($1.producer.root.utf8) + }! + guard copies.allSatisfy({ $0.before == owner.before && $0.after == owner.after }) else { + for copy in Set(copies.map(\.native)) { + findings.append(.init(path: copy, reason: .conflictingEdits)) + } + return nil + } + return .init( + producer: owner.producer, selectors: Array(Set(copies.flatMap(\.selectors))).sorted(), + path: owner.path, native: owner.native, before: owner.before, after: owner.after, + executable: owner.executable) + } + } + + private static func child(_ directory: URL, _ path: String) -> URL { + path == "." ? directory : directory.appendingPathComponent(path) + } + + private static func isText(_ bytes: Data) -> Bool { + !bytes.contains(0) && String(data: bytes, encoding: .utf8) != nil + } + + private static func normalized(_ bytes: Data) -> Data { + let start = bytes.starts(with: [239, 187, 191]) ? bytes.startIndex + 3 : bytes.startIndex + let body = bytes[start...] + guard body.contains(13) else { return body } + var result = Data() + result.reserveCapacity(body.count) + for index in body.indices { + if body[index] == 13, index + 1 < body.endIndex, body[index + 1] == 10 { continue } + result.append(body[index]) + } + return result + } +} diff --git a/Sources/AgentsUpdates/ProducerPatchRoutes.swift b/Sources/AgentsUpdates/ProducerPatchRoutes.swift new file mode 100644 index 0000000..f292ad5 --- /dev/null +++ b/Sources/AgentsUpdates/ProducerPatchRoutes.swift @@ -0,0 +1,224 @@ +import AgentsCore +import Components +import Foundation + +struct ProducerPatchRoutes { + struct Deployment { + let record: LedgerDeployment + let lowering: LockedLowering + let path: URL + } + + struct Copy { + let resource: String + let owners: [String] + let target: URL + let support: URL? + let recipients: [AgentID] + } + + let deployments: [Deployment] + let skipped: [ProducerPatchSkip] + let routes: Set + let installations: [String: SkillInstallationTarget] + + init(inputs: ProducerPatchInputs) throws { + let ledger = inputs.ledger + guard ledger.deployments.count <= ProducerPatchInputs.limits.entries else { + throw CoreError.invalidState("producer patch deployment budget") + } + let lineage = ProducerPatchLineage(inputs) + var byDeployment: [String: [LockedLowering]] = [:] + for lowering in ledger.lowerings { + for id in lowering.deployments { byDeployment[id, default: []].append(lowering) } + } + var deployments: [Deployment] = [] + var skipped: [ProducerPatchSkip] = [] + var routes = Set() + var installations: [String: SkillInstallationTarget] = [:] + for record in ledger.deployments { + let resolved = try record.target.resolve(roots: inputs.roots) + func skip(_ reason: ProducerPatchSkip.Reason) { + skipped.append(.init(path: resolved, reason: reason)) + } + guard let lowerings = byDeployment[record.id], lowerings.count == 1, + let lowering = lowerings.first + else { + skip(.ambiguousProducer) + continue + } + let resources = lowering.resources.map { ledger.resources[$0]! } + let sources = + resources.isEmpty + ? lowering.inputs.map { ledger.components[$0]!.source } : resources.map(\.source) + if !sources.isEmpty, sources.allSatisfy(lineage.isLocallyOwned) { + skip(.locallyOwned) + continue + } + guard record.ownership == .generated, record.owners.count == 1 else { + skip(.transformed) + continue + } + let path: URL + if lowering.format == "agents/skill@1" { + guard lowering.layout.object?["mode"]?.text == InstallMode.copy.rawValue else { + skip(.linkedDeployment) + continue + } + guard let agent = record.recipients.first, record.recipients == [agent], + record.target.kind == .registered, record.target.root == "skills-" + agent.rawValue, + lowering.inputs == record.owners, lowering.resources.count == 1, + let owner = ledger.components[record.owners[0]], owner.kind == "skills", + owner.recipients.contains(agent), owner.resources == lowering.resources, + owner.payload.object?["mode"]?.text == InstallMode.copy.rawValue, + record.target.path == PathSafety.sanitizeName(owner.name), + lowering.layout.object?["name"]?.text == lowering.artifacts.first?.name, + lowering.artifacts.map(\.kind) == [.tree], + record.expectedHash == resources[0].hash + else { + skip(.missingPathAttribution) + continue + } + if let reason = lineage.unattributed(resources[0]) { + skip(reason) + continue + } + let target = try inputs.store.skillInstallationTarget(for: agent, named: record.target.path) + installations[target.url.path] = target + routes.formUnion(target.footprint) + // The recorded loader spelling is read with no-follow even if it has a coordination alias. + path = resolved + } else { + let route: NativeTargetRoute + if lowering.format.hasSuffix("-generated-plugin@1") { + route = try DeploymentConstruction.generatedRoute(lowering, ledger: ledger) + } else if lowering.format.hasSuffix("-components@1"), + lowering.artifacts.contains(where: { $0.kind == .tree }), + let root = record.target.root, let registered = NativeTargetRoute.targetRoute(root) + { + route = registered + } else { + skip(.transformed) + continue + } + guard record.target.kind == .registered, record.target.root == route.root, + record.target.path.utf8.elementsEqual(route.basename.utf8), + lowering.artifacts.first?.hash == record.expectedHash, + !resources.contains(where: { + $0.kind == .liveEdit || ($0.kind == .git && lineage.isLocallyOwned($0.source)) + }) + else { + skip(.missingPathAttribution) + continue + } + routes.insert(route) + path = try route.logicalDirectory(inputs.store.environment) + .appendingPathComponent(route.basename) + } + deployments.append(.init(record: record, lowering: lowering, path: path)) + } + self.deployments = deployments + self.skipped = skipped + self.routes = routes + self.installations = installations + } + + func withPlan( + inputs: ProducerPatchInputs, revalidating: Bool, + _ body: (ProducerPatchPlan, URL?) throws -> Result + ) throws -> Result { + guard !deployments.isEmpty else { + return try body(.init(skipped: skipped), nil) + } + let ledger = inputs.ledger + let lineage = ProducerPatchLineage(inputs) + let lowerings = Set(deployments.map(\.lowering.id)) + let resources = Set(deployments.flatMap(\.lowering.resources)) + let extra = lineage.hostedProducerResources(for: resources) + var entered = false + do { + return try LedgerReplay.withLockedResources( + ledger, store: inputs.store, roots: inputs.roots, limits: ProducerPatchInputs.limits, + lowerings: lowerings, offline: true, sourcePolicy: inputs.sourcePolicy.effective, + requireRecordedTransport: true, additionalResources: extra, anchorLockedGit: true + ) { artifacts, resources, workspace in + let outputs = Dictionary(uniqueKeysWithValues: artifacts.map { ($0.name, $0) }) + var plan = ProducerPatchPlan(skipped: skipped) + for deployment in deployments { + try Task.checkCancellation() + for copy in try copies(deployment, outputs: outputs, ledger: ledger, plan: &plan) { + try plan.compare(copy, resources: resources, lineage: lineage) + } + } + plan.coalesce() + entered = true + return try body(plan, workspace) + } + } catch is CancellationError { + throw CancellationError() + } catch let error as SourcePolicyFailure { + throw error + } catch let error as OrganizationPolicyFailure { + throw error + } catch { + if entered { throw error } + throw revalidating ? ProducerPatchError.stale : ProducerPatchError.lockedInputUnavailable + } + } + + private func copies( + _ deployment: Deployment, outputs: [String: ReplayedArtifact], + ledger: ResolvedLedger, plan: inout ProducerPatchPlan + ) throws -> [Copy] { + let record = deployment.record + let lowering = deployment.lowering + let artifacts = lowering.artifacts.map { outputs[$0.name]! } + if lowering.format == "agents/skill@1" { + guard artifacts.first?.tree != nil else { throw ProducerPatchError.lockedInputUnavailable } + return [ + .init( + resource: lowering.resources[0], owners: record.owners, + target: deployment.path, support: nil, recipients: record.recipients) + ] + } + if lowering.format.hasSuffix("-generated-plugin@1") { + let plugin = try NativeGeneratedPluginContribution.decode( + lowering, ledger: ledger, artifacts: artifacts, limits: ProducerPatchInputs.limits) + try plan.skip(deployment.path.appendingPathComponent(plugin.manifestPath), .transformed) + let owners = Dictionary( + grouping: plugin.members.flatMap { member in + ledger.components[member.component]!.resources.map { ($0, member.component) } + }, by: { $0.0 }) + return plugin.resourcePlacements.compactMap { placement in + guard let resource = plugin.resources[placement.resource], + let records = owners[placement.resource]?.map({ $0.1 }) + else { return nil } + let primary = ArtifactAggregation.generatedResourcePath(placement, resource: resource) + let supporting = ArtifactAggregation.generatedResourceBase(placement, resource: resource) + return .init( + resource: placement.resource, owners: records, + target: deployment.path.appendingPathComponent(primary), + support: resource.support.isEmpty + ? nil : deployment.path.appendingPathComponent(supporting), + recipients: record.recipients) + } + } + let contribution = try NativeComponentLayoutsV1.contribution( + lowering, ledger: ledger, artifacts: artifacts, limits: ProducerPatchInputs.limits) + for (index, output) in contribution.outputs.enumerated() + where record.id == lowering.id + ":" + String(index) { + guard case .nativePlugin(_, let resource, _) = output.content else { break } + let route = try DeploymentConstruction.route(output, request: contribution.request) + guard route.root == record.target.root, route.basename == record.target.path, + record.owners == [contribution.component], record.recipients == contribution.recipients + else { break } + return [ + .init( + resource: resource, owners: record.owners, target: deployment.path, + support: nil, recipients: record.recipients) + ] + } + try plan.skip(deployment.path, .missingPathAttribution) + return [] + } +} diff --git a/Sources/AgentsUpdates/RegistryAcquisition.swift b/Sources/AgentsUpdates/RegistryAcquisition.swift new file mode 100644 index 0000000..05fe021 --- /dev/null +++ b/Sources/AgentsUpdates/RegistryAcquisition.swift @@ -0,0 +1,250 @@ +import AgentsCore +import Foundation + +#if canImport(FoundationNetworking) + import FoundationNetworking +#endif + +struct RegistryAcquisition { + private struct Metadata: Codable { + let control: String? + let vary: Set + let etag: String? + let modified: String? + let expires: Date + } + + @TaskLocal static var transport: (@Sendable (URLRequest) async throws -> RegistryHTTP.Response)? + + let environment: RuntimeEnvironment + let endpoint: URL + + func read( + _ request: URLRequest, anonymous: Bool, refresh: Bool, validate: (Data) throws -> T + ) async throws -> T { + let cache = AcquisitionCache(environment: environment) + guard anonymous, let key = Self.identity(request) else { + return try validate(fullResponse(await fetch(request), for: request).body) + } + var stored = try? cache.read( + .http, key: key, maximumBytes: RegistryHTTP.responseLimit, touching: !refresh + ) { value in + let metadata = try JSONDecoder().decode(Metadata.self, from: value.metadata) + guard metadata.vary.isSubset(of: ["accept"]), + metadata.expires.timeIntervalSinceReferenceDate.isFinite, + Self.validator(metadata.etag) == metadata.etag, + Self.validator(metadata.modified) == metadata.modified, + !Self.forbidsStorage(Self.directives(metadata.control)) + else { throw AcquisitionCacheError.invalidEntry } + return (value, metadata) + } + if let (value, metadata) = stored, !refresh, metadata.expires > Date() { + do { return try validate(value.data) } catch MCPRegistryError.invalidResponse { + try cache.invalidate(.http, key: key, publication: value.publication) + stored = nil + } + } + let publication = stored?.0.publication ?? (try? cache.publication(.http, key: key)) + + var conditional = request + if let (_, metadata) = stored, !refresh, metadata.expires <= Date() { + conditional.setValue(metadata.etag, forHTTPHeaderField: "If-None-Match") + conditional.setValue(metadata.modified, forHTTPHeaderField: "If-Modified-Since") + } + + let received = try await fetch(conditional) + try requireRequestedURL(received, for: request) + if received.status == 304 { + guard let (value, old) = stored, + conditional.value(forHTTPHeaderField: "If-None-Match") != nil + || conditional.value(forHTTPHeaderField: "If-Modified-Since") != nil + else { throw MCPRegistryError.httpStatus(304) } + let vary = Self.vary(received.headers["vary"], old: old.vary) + let admissible = + vary == old.vary + && Self.sameValidator(received.headers["etag"], as: old.etag) + && (old.etag != nil + || Self.sameValidator(received.headers["last-modified"], as: old.modified)) + && received.headers["set-cookie"] == nil && received.headers["set-cookie2"] == nil + && received.headers["content-location"] == nil + if admissible { + let metadata = Self.metadata(received.headers, old: old, now: Date()) + if metadata == nil { + try cache.invalidate(.http, key: key, publication: value.publication) + } + let result = try validate(value.data) + if let metadata { + save( + value.data, metadata: metadata, cache: cache, key: key, + condition: .publication(value.publication)) + } + return result + } + + try cache.invalidate(.http, key: key, publication: value.publication) + let response = try fullResponse(await fetch(request), for: request) + return try consume(response, cache: cache, key: key, stored: nil, validate: validate) + } + return try consume( + fullResponse(received, for: request), cache: cache, key: key, + stored: publication, validate: validate) + } + + private func consume( + _ response: RegistryHTTP.Response, cache: AcquisitionCache, key: String, stored: UUID?, + validate: (Data) throws -> T + ) throws -> T { + let metadata = Self.metadata(response.headers, old: nil, now: Date()) + if metadata == nil, let stored { + try cache.invalidate(.http, key: key, publication: stored) + } + let result = try validate(response.body) + if let metadata { + save( + response.body, metadata: metadata, cache: cache, key: key, + condition: stored.map(AcquisitionCache.WriteCondition.publication) ?? .absent) + } + return result + } + + private func save( + _ data: Data, metadata: Metadata, cache: AcquisitionCache, key: String, + condition: AcquisitionCache.WriteCondition + ) { + guard let encoded = try? JSONEncoder().encode(metadata) else { return } + _ = try? cache.write( + data, store: .http, key: key, object: FileHash.sha256Hex(data: data), + metadata: encoded, condition: condition) + } + + private func fetch(_ request: URLRequest) async throws -> RegistryHTTP.Response { + try environment.requireMCPRegistry(endpoint) + if let transport = Self.transport { return try await transport(request) } + return try await RegistryHTTP().read(request) + } + + private func requireRequestedURL(_ response: RegistryHTTP.Response, for request: URLRequest) + throws + { + guard let url = request.url, + url.absoluteString.utf8.elementsEqual(response.url.absoluteString.utf8) + else { throw MCPRegistryError.redirectRejected } + } + + private func fullResponse( + _ response: RegistryHTTP.Response, for request: URLRequest + ) throws -> RegistryHTTP.Response { + try requireRequestedURL(response, for: request) + guard response.status == 200 else { throw MCPRegistryError.httpStatus(response.status) } + guard response.body.count <= RegistryHTTP.responseLimit else { + throw MCPRegistryError.responseTooLarge + } + return response + } + + private static func identity(_ request: URLRequest) -> String? { + guard request.httpMethod == "GET", let url = request.url, + let components = URLComponents(url: url, resolvingAgainstBaseURL: true), + RegistryHTTP.validURL(components), components.scheme?.lowercased() == "https", + (components.queryItems ?? []).allSatisfy({ field in + !RegistryInput.isCredentialName(field.name) + && !["x-amz-", "x-goog-"].contains(where: field.name.lowercased().hasPrefix) + }), + !request.httpShouldHandleCookies, + let headers = request.allHTTPHeaderFields, headers.count == 1, + let accept = request.value(forHTTPHeaderField: "Accept") + else { return nil } + return AcquisitionCache.key([ + ("method", Data("GET".utf8)), ("url", Data(url.absoluteString.utf8)), + ("accept", Data(accept.utf8)), + ]) + } + + private static func vary(_ value: String?, old: Set = []) -> Set? { + guard let value else { return old } + let fields = Set( + value.split(separator: ",", omittingEmptySubsequences: false).map { + $0.trimmingCharacters(in: .whitespaces).lowercased() + }) + return fields.isSubset(of: ["accept"]) ? fields : nil + } + + private static func sameValidator(_ new: String?, as old: String?) -> Bool { + guard let new, let old else { return true } + return new.utf8.elementsEqual(old.utf8) + } + + private static func metadata( + _ headers: [String: String], old: Metadata?, now: Date + ) -> Metadata? { + guard headers["set-cookie"] == nil, headers["set-cookie2"] == nil, + headers["content-location"] == nil, + let vary = vary(headers["vary"], old: old?.vary ?? []) + else { return nil } + let control = headers["cache-control"] ?? old?.control + let fields = + control?.split(separator: ",").map { + $0.trimmingCharacters(in: .whitespaces).split(separator: "=", maxSplits: 1).map { + $0.trimmingCharacters(in: .whitespaces) + } + } ?? [] + guard + !fields.contains(where: { field in + field.first.map { ["private", "no-store", "no-cache"].contains($0.lowercased()) } ?? false + }), headers["pragma"]?.lowercased().contains("no-cache") != true + else { return nil } + + let date = headers["date"].flatMap(Self.httpDate) + let suppliedAge = headers["age"].flatMap(Int.init) + if headers["age"] != nil, suppliedAge == nil || suppliedAge! < 0 { return nil } + let age = max(Double(suppliedAge ?? 0), date.map { now.timeIntervalSince($0) } ?? 0) + let ages = fields.filter { $0.first?.lowercased() == "max-age" } + let expires: Date + if !ages.isEmpty { + guard ages.count == 1, ages[0].count == 2, + let seconds = Int(ages[0][1].trimmingCharacters(in: CharacterSet(charactersIn: "\""))), + seconds >= 0 + else { return nil } + expires = now.addingTimeInterval(Double(seconds) - age) + } else if let until = headers["expires"].flatMap(Self.httpDate) { + expires = now.addingTimeInterval(until.timeIntervalSince(date ?? now) - age) + } else { + expires = now + } + let etag = validator(headers["etag"]) ?? old?.etag + let modified = + validator(headers["last-modified"]).flatMap { httpDate($0) == nil ? nil : $0 } + ?? old?.modified + guard expires > now || etag != nil || modified != nil else { return nil } + return Metadata(control: control, vary: vary, etag: etag, modified: modified, expires: expires) + } + + private static func directives(_ control: String?) -> [[String]] { + control?.split(separator: ",").map { + $0.trimmingCharacters(in: .whitespaces).split(separator: "=", maxSplits: 1).map { + $0.trimmingCharacters(in: .whitespaces) + } + } ?? [] + } + + private static func forbidsStorage(_ fields: [[String]]) -> Bool { + fields.contains { field in + field.first.map { ["private", "no-store", "no-cache"].contains($0.lowercased()) } ?? false + } + } + + private static func validator(_ header: String?) -> String? { + guard let header, !header.isEmpty, header.utf8.count <= 1024, + RegistryHTTP.isHeaderValue(header) + else { return nil } + return header + } + + private static func httpDate(_ value: String) -> Date? { + let formatter = DateFormatter() + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.timeZone = TimeZone(secondsFromGMT: 0) + formatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss 'GMT'" + return formatter.date(from: value) + } +} diff --git a/Sources/AgentsUpdates/ScopeInspection.swift b/Sources/AgentsUpdates/ScopeInspection.swift new file mode 100644 index 0000000..7503407 --- /dev/null +++ b/Sources/AgentsUpdates/ScopeInspection.swift @@ -0,0 +1,367 @@ +import AgentsCore +import AgentsInstructions +import AgentsManifest +import AgentsSkills +import Components +import Foundation + +/// A logical identity independent of revision, resources and temporary extraction paths. +public struct ComponentSelection: Hashable, Sendable { + public let identity: String + /// An occurrence selection is checked against the inspection generation before use. + public let occurrence: Int? + public let generation: String +} + +public struct ComponentInspection: Sendable { + public let record: String + public let sourceRecord: String + public let declaringSourceRecord: String + public let selection: ComponentSelection + public let kind: DeclaredComponentKind + public let name: String + public let source: String + public let declaringSource: String + public let root: String + public let group: String? + public let revision: String? + public let version: String? + public let mcpRegistry: MCPRegistryEvidence? + /// Frozen symbolic configuration. Binding slots are objects with `environment` or `secret` keys. + public let configuration: NativeValue + public let conditions: [DeclarationCondition] + public let recipients: [AgentID] + /// Active copy destinations recorded in the resolved instruction lowerings. + public let copyRecipients: [InstructionRecipient] + public let chatGPT: Bool + public let resources: [String] + public let occurrences: [OccurrenceInspection] +} + +public struct OccurrenceInspection: Sendable { + public let declaringSourceRecord: String + public let dependencyRecords: [String] + public let selection: ComponentSelection + public let declaringSource: String + public let manifestPath: String + public let reference: Int? + public let dependencies: [String] + public let condition: DeclarationCondition + public let recipients: [AgentID] + public let consumerEditable: Bool +} + +public struct SourceInspection: Sendable { + public let record: String + public let identity: String + public let kind: SourceKind + public let revision: String + public let version: String? + public let container: String? + public let namespace: String? + public let location: URL? + public let uses: [SourceInspectionUse] +} + +public struct SourceInspectionUse: Sendable { + public let root: String + public let requirement: SourceRequirement? +} + +public struct GroupInspection: Sendable { + public let sourceRecord: String + public let id: Int + public let parent: Int? + public let source: String + public let root: String + public let name: String + public let requirement: SourceRequirement? + public let manifestHash: String + public let children: [Int] +} + +public struct ResourceInspection: Sendable { + public let sourceRecord: String + public let identity: String + public let source: String + public let path: String + public let hash: String + public let kind: String + public let location: URL? + public let entries: [ResourceEntryInspection] + public let support: [ResourceEntryInspection] +} + +public struct ResourceEntryInspection: Sendable { + public let path: String + public let kind: String + public let executable: Bool + public let link: String? + public let byteCount: Int? +} + +public struct DeploymentInspection: Sendable { + public enum Status: String, Sendable { case current, missing, drifted, unverified } + public let identity: String + public let location: URL + public let format: String + public let owners: [String] + public let ownerRecords: [String] + public let recipients: [AgentID] + public let ownership: String + public let effectiveReaders: [AgentID]? + public let privateMaterialization: Bool + public let status: Status + /// Fixed diagnostics never contain native sibling bytes or provider values. + public let diagnostic: String? +} + +public struct RecoveryInspection: Sendable { + public let pending: Bool + public let requiresOwner: Bool + public let diagnostic: String? +} + +/// One read generation. No native bytes, retained content objects, provider calls or recovery. +public struct ScopeInspection: Sendable { + package let additionDestination: AdditionDestination? + public let scope: InstallScope + public let document: DeclarationDocument? + public let declaration: Declaration? + public let generation: String? + public let sources: [SourceInspection] + public let components: [ComponentInspection] + public let groups: [GroupInspection] + public let marketplacePackages: [MarketplacePin] + public let marketplaceGraph: MarketplaceGraph? + public let marketplaceIssue: MarketplaceError? + /// The reviewed desired graph, independent of the scope's deployed graph and statuses. + public let pendingMarketplaceDeployment: MarketplacePendingDeployment? + public let resources: [ResourceInspection] + public let deployments: [DeploymentInspection] + public let watch: WatchState? + public let recovery: RecoveryInspection + /// Actual state, source and deployment paths, including absent leaves for directory watching. + public let readLocations: [URL] +} + +public struct MarketplaceFileOwnership: Equatable, Sendable { + public let node: MarketplaceNodeID + public let member: MarketplaceMemberKey + public let root: String + public let recipients: [AgentID] +} + +extension ScopeInspection { + /// Looks up root-specific contributions to the native deployment in this inspection. + public func marketplaceOwners(of deployment: DeploymentInspection) -> [MarketplaceFileOwnership] { + guard let graph = marketplaceGraph else { return [] } + let resourcesByID = Dictionary(uniqueKeysWithValues: resources.map { ($0.identity, $0) }) + let owners = Set(deployment.ownerRecords) + let owned = Dictionary( + grouping: components.filter { owners.contains($0.record) }, + by: \.declaringSourceRecord) + return graph.nodes.flatMap { node in + node.members.flatMap { member -> [MarketplaceFileOwnership] in + guard let resource = member.producerResource.flatMap({ resourcesByID[$0] }), + let components = owned[resource.sourceRecord] + else { return [] } + let recipients = Set(components.flatMap(\.recipients)).intersection(deployment.recipients) + let attribution = graph.recipientsByRoot(for: member.key, in: node.id) + return attribution.keys.sorted().compactMap { root in + let selected = attribution[root]!.filter(recipients.contains) + guard !selected.isEmpty else { return nil } + return MarketplaceFileOwnership( + node: node.id, member: member.key, root: root, recipients: selected) + } + } + } + } +} + +extension UpdateOperations { + public static func inspect( + scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> ScopeInspection { + let store = StateStore(scope: scope, environment: environment) + var admitted = Set() + var installations: [String: SkillInstallationTarget] = [:] + let stateLocations = + [store.declarationURL, store.resolvedURL, store.watchURL] + + [store.configurationJSONURL].compactMap { $0 } + + SourcePolicySnapshot.locations(in: store).map { $0.1 } + + [SourceAccessSettingsEditor.settingsURL(environment: environment)] + while true { + do { + return try store.withReadLock( + onPendingRecovery: { + let diagnostic = FileTransaction.recoveryDiagnostic(store: store) + return ScopeInspection( + additionDestination: nil, scope: scope, document: nil, declaration: nil, + generation: nil, + sources: [], components: [], groups: [], marketplacePackages: [], + marketplaceGraph: nil, marketplaceIssue: nil, pendingMarketplaceDeployment: nil, + resources: [], deployments: [], watch: nil, + recovery: .init( + pending: true, requiresOwner: diagnostic.requiresOwner, + diagnostic: diagnostic.message), + readLocations: stateLocations) + }, footprint: admitted, installations: Array(installations.values), + { + let baseline = try StatePrecondition(store: store) + let document = try store.declarationDocument(prepared: baseline) + let declaration = try store.readDeclaration(prepared: baseline) + let ledger = try store.readLedger(prepared: baseline) + let routes = try DeploymentConstruction.routes(ledger) + let required = try SkillLifecycle.installationTargets(ledger, store: store) + guard routes.isSubset(of: admitted), + Set(required.keys).isSubset(of: Set(installations.keys)) + else { throw RequiredRoutes(routes: routes, installations: required) } + let watch = try store.readWatch(prepared: baseline) + let generation = try ResolvedLedgerCodec.digest([ + ResolvedLedgerCodec.digest(ledger), document?.digest ?? "absent", + ]) + let roots = store.ledgerRoots(recordedIn: ledger) + func source(_ id: String) throws -> String { + try ledger.sourceIdentity(id, roots: roots) + } + let sources = try ledger.sources.keys.sorted().map { id in + let s = ledger.sources[id]! + return SourceInspection( + record: id, identity: try source(id), kind: s.kind, revision: s.revision, + version: s.version, + container: try s.container.map(source), namespace: s.namespace, + location: try s.location?.resolve(roots: roots), + uses: ledger.sourceUses.filter { $0.source == id }.map { + .init(root: $0.root, requirement: $0.requirement) + }) + } + let components = try componentInspections(ledger, roots: roots, generation: generation) + func entry(_ e: LedgerEntry) -> ResourceEntryInspection { + .init( + path: e.path, kind: e.kind.rawValue, executable: e.executable, + link: e.link, byteCount: e.byteCount) + } + let resources = try ledger.resources.keys.sorted().map { id in + let r = ledger.resources[id]! + return ResourceInspection( + sourceRecord: r.source, identity: id, source: try source(r.source), path: r.path, + hash: r.hash, + kind: r.kind.rawValue, + location: try ArtifactAggregation.resourceDestination( + id, ledger: ledger, store: store, roots: roots), + entries: r.entries.map(entry), support: r.support.map(entry)) + } + let deployments = try ledger.deployments.map { d in + let url = try d.target.resolve(roots: roots) + let observed = try ArtifactAggregation.inspectDeployment( + d, ledger: ledger, store: store, roots: roots) + let exposure = try ArtifactAggregation.nativeExposure( + d, ledger: ledger, store: store, roots: roots) + return DeploymentInspection( + identity: d.id, location: url, format: d.route, + owners: try d.owners.map { + try LedgerImpact.identity(ledger.components[$0]!, ledger: ledger, roots: roots) + }, + ownerRecords: d.owners, recipients: d.recipients, ownership: d.ownership.rawValue, + effectiveReaders: exposure.readers, privateMaterialization: exposure.sensitive, + status: DeploymentInspection.Status(rawValue: observed.status)!, + diagnostic: observed.diagnostic) + } + let groups = try ledger.groups.map { g in + GroupInspection( + sourceRecord: g.source, id: g.id, parent: g.parent, source: try source(g.source), + root: g.root, + name: g.name, requirement: g.requirement, manifestHash: g.manifestHash, + children: g.children) + } + let paths = + try readLocations( + declarations: [declaration], ledgers: [ledger], store: store, roots: roots) + + installations.values.map(\.url) + stateLocations + let marketplaceIssue: MarketplaceError? + do { + try MarketplaceChanges.validateInspection( + declaration, bytes: baseline.bytes(for: store.declarationURL), ledger: ledger, + store: store) + marketplaceIssue = nil + } catch let issue as MarketplaceError { + marketplaceIssue = issue + } + try baseline.validate() + return ScopeInspection( + additionDestination: try AdditionDestination( + store: store, declaration: declaration, baseline: baseline), + scope: scope, document: document, declaration: declaration, generation: generation, + sources: sources, components: components, groups: groups, + marketplacePackages: ledger.marketplacePackages ?? [], + marketplaceGraph: ledger.marketplaceGraph, marketplaceIssue: marketplaceIssue, + pendingMarketplaceDeployment: ledger.pendingMarketplaceDeployment, + resources: resources, + deployments: deployments, watch: watch, + recovery: .init(pending: false, requiresOwner: false, diagnostic: nil), + readLocations: Array(Set(paths)).sorted { $0.path < $1.path }) + }) + } catch let required as RequiredRoutes { + admitted.formUnion(required.routes) + installations.merge(required.installations, uniquingKeysWith: { _, next in next }) + } + } + } + + static func componentInspections( + _ ledger: ResolvedLedger, roots: [String: URL], generation: String + ) throws -> [ComponentInspection] { + func source(_ id: String) throws -> String { try ledger.sourceIdentity(id, roots: roots) } + func condition(_ c: LedgerCondition) -> DeclarationCondition { + .init( + agents: c.agents, scopes: c.scopes, + platforms: c.platforms?.compactMap(DeclarationPlatform.init(rawValue:))) + } + var copyMemberships: [String: Set] = [:] + for lowering in ledger.lowerings { + guard let recipient = lowering.instructionCopyRecipient else { continue } + for input in lowering.inputs { + copyMemberships[input, default: []].insert(recipient) + } + } + return try ledger.components.keys.sorted().map { id in + let c = ledger.components[id]! + let identity = try LedgerImpact.identity(c, ledger: ledger, roots: roots) + return ComponentInspection( + record: id, sourceRecord: c.source, declaringSourceRecord: c.declaringSource, + selection: .init(identity: identity, occurrence: nil, generation: generation), + kind: DeclaredComponentKind(rawValue: c.kind)!, name: c.name, + source: try source(c.source), declaringSource: try source(c.declaringSource), + root: c.root, group: c.group, revision: c.revision, version: c.version, + mcpRegistry: c.mcpRegistry, + configuration: symbolicValue(c.payload), conditions: c.conditions.map(condition), + recipients: c.recipients, + copyRecipients: (copyMemberships[id] ?? []).sorted { $0.rawValue < $1.rawValue }, + chatGPT: c.chatGPT, resources: c.resources, + occurrences: try ledger.occurrences.filter { $0.component == id }.map { o in + .init( + declaringSourceRecord: o.declaringSource, dependencyRecords: o.dependencies, + selection: .init(identity: identity, occurrence: o.id, generation: generation), + declaringSource: try source(o.declaringSource), manifestPath: o.manifestPath, + reference: o.reference, dependencies: try o.dependencies.map(source), + condition: condition(o.condition), recipients: o.recipients, + consumerEditable: o.consumerEditable) + }) + } + } + + static func symbolicValue(_ value: LedgerValue) -> NativeValue { + switch value.kind { + case .environment: return .object(["environment": .string(value.text!)]) + case .secret: return .object(["secret": .string(value.text!)]) + case .string, .literal: return .string(value.text!) + case .integer: return .integer(value.integer!) + case .decimal: return .decimal(value.text!) + case .boolean: return .boolean(value.boolean!) + case .null: return .null + case .array: return .array(value.array!.map(symbolicValue)) + case .object: return .object(value.object!.mapValues(symbolicValue)) + } + } +} diff --git a/Sources/AgentsUpdates/SkillOperations.swift b/Sources/AgentsUpdates/SkillOperations.swift new file mode 100644 index 0000000..0195ffc --- /dev/null +++ b/Sources/AgentsUpdates/SkillOperations.swift @@ -0,0 +1,187 @@ +import AgentsCore +import AgentsManifest +import AgentsSkills +import Components +import Foundation + +extension SkillOperations { + public static func add(_ options: AddOptions) throws -> AddOutcome { + try add(options, checkpoint: { _ in }) + } + + package static func add(_ supplied: AddOptions, checkpoint: @escaping (String) throws -> Void) + throws -> AddOutcome + { + var options = supplied + let argument = try SourceArgument(options.source) + if let name = argument.name { + guard !options.all else { + throw CoreError.invalidSource("a named skill cannot be combined with all") + } + if !options.skillNames.contains(name) { options.skillNames.append(name) } + } + let store = StateStore(scope: options.scope, environment: options.environment) + let organization = try OrganizationPolicySnapshot(store: store) + let (declaration, digest, ledger, source, id, available) = try store.withReadLock { + let declaration = try store.readDeclaration() + let digest = try store.declarationDocument(prepared: nil)?.digest ?? "absent" + if OrganizationPolicySnapshot.configured(store) { + let selection = try argument.selection( + in: declaration, requirement: options.sourceRequirement, path: options.path, + environment: options.environment) + try organization.requireSource( + selection.applied(to: selection.source), reference: options.alias ?? "skill source", + in: store) + } + let (source, id, available) = try SkillOperations.inspect(options, declaration: declaration) + try organization.validate() + return (declaration, digest, try store.readLedger(), source, id, available) + } + if options.listOnly || (options.skillNames.isEmpty && !options.all && available.count > 1) { + return AddOutcome(source: source, sourceID: id, availableSkills: available, installed: []) + } + guard !available.isEmpty else { + throw CoreError.notFound("no skills found in " + source.location) + } + var next = declaration + let existing = try argument.existingAlias( + in: declaration, sourceID: id, path: source.path, environment: options.environment) + let alias = options.alias ?? existing ?? declaration.derivedAlias(for: source.location) + if let prior = declaration.sources[alias], + try prior.identity(environment: options.environment) != id + { + throw CoreError.invalidSource("source alias already refers to another source") + } + let names = available.map { PathSafety.sanitizeName($0.name) } + let recipients = options.agents ?? declaration.defaultAgents + for deployment in ledger.deployments.sorted(by: { $0.id < $1.id }) + where deployment.route == "agents/skill@1" { + let target = InstructionLocations.physical( + try deployment.target.resolve(roots: store.ledgerRoots)) + guard let owner = deployment.owners.first.flatMap({ ledger.components[$0] }), + names.contains(PathSafety.sanitizeName(owner.name)) + else { continue } + let ownerID = try ledger.sourceIdentity(owner.source, roots: store.ledgerRoots) + guard ownerID != id else { continue } + let paths = names.flatMap { name in + recipients.map { agent in + ( + agent, + InstructionLocations.physical( + SkillLifecycle.target(name: name, agent: agent, store: store)) + ) + } + } + guard paths.contains(where: { $0.1 == target }) else { continue } + let ownerAlias = + try declaration.sources.keys.sorted().first { + try declaration.sources[$0]!.identity(environment: options.environment) == ownerID + } ?? owner.group ?? ownerID + let destinations = paths.map { "\($0.0.rawValue) at \($0.1.path)" }.joined(separator: ", ") + throw CoreError.invalidSkill( + "skill '\(PathSafety.sanitizeName(owner.name))' in \(options.scope.rawValue) scope is owned by '\(ownerAlias)' (\(ownerID)); '\(alias)' (\(id)) requests the same installation: \(destinations)" + ) + } + next.sources[alias] = source + var updated = false + for index in next.components.indices { + guard case .skills(let selectedAlias, var selection) = next.components[index], + selectedAlias == alias + else { continue } + guard !updated else { + throw CoreError.invalidState( + "skill selection is ambiguous; edit the specific YAML occurrence") + } + updated = true + if options.all { + selection.select = .all + } else if case .names(let old) = selection.select { + selection.select = .names(Array(Set(old + names)).sorted()) + } + selection.exclude = selection.exclude?.filter { !names.contains($0) } + var overrides = selection.overrides ?? [:] + for name in names { + overrides[name] = SkillOverride( + agents: options.agents ?? overrides[name]?.agents ?? selection.agents, mode: options.mode) + } + selection.overrides = overrides + next.components[index] = .skills(source: alias, selection) + } + if !updated { + next.components.append( + .skills( + source: alias, + SkillDeclaration( + select: options.all ? .all : .names(names), agents: options.agents, mode: options.mode)) + ) + } + var request = UpdateRequest( + operation: .declaration(next), kinds: [.skills], names: names, + expectedDeclarationDigest: digest) + if options.skillNames.isEmpty && !options.all { + request.automaticSkill = (id, available[0].name) + } + return try UpdateOperations.withDomainUpdate( + request, scope: options.scope, environment: options.environment, checkpoint: checkpoint + ) { prepared in + let result = try prepared.apply() + return AddOutcome( + source: source, sourceID: id, availableSkills: available, installed: result.installedSkills) + } + } + + public static func updateInstalled( + scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment(), + skillNames: [String] = [], apply: Bool = false, + beforeApply: (([UpdateResult]) throws -> Void)? = nil + ) throws -> [UpdateResult] { + do { + let request = UpdateRequest(kinds: [.skills], names: skillNames) + if !apply { + return try UpdateOperations.preview(request, scope: scope, environment: environment).skills + } + return try UpdateOperations.withDomainUpdate(request, scope: scope, environment: environment) + { + prepared in + try beforeApply?(prepared.report.skills) + let applied = try prepared.apply() + return applied.report.skills.map { item in + var item = item + item.installed = applied.installedSkills.filter { $0.skill == item.skill } + return item + } + } + } catch let error as LinkError { + if case .missing = error { throw CoreError.notFound(error.description) } + throw error + } + } + + public static func installResolvedReport( + scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> ResolvedInstallReport { + try UpdateOperations.withDomainUpdate( + UpdateRequest(operation: .restore, kinds: [.skills]), scope: scope, environment: environment + ) { + ResolvedInstallReport(installed: try $0.apply().installedSkills) + } + } + + @discardableResult + public static func remove( + skillNames: [String], scope: InstallScope = .project, agents: [AgentID]? = nil, + environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> [String] { + let names = skillNames.map(PathSafety.sanitizeName) + return try UpdateOperations.withDomainUpdate( + UpdateRequest(operation: .remove, kinds: [.skills], names: names, agents: agents), + scope: scope, environment: environment + ) { + guard Set(names).isSubset(of: Set($0.report.skills.map(\.skill))) else { + throw CoreError.notFound("skill is not installed") + } + _ = try $0.apply() + return names.sorted() + } + } +} diff --git a/Sources/AgentsUpdates/SourceCatalogInspection.swift b/Sources/AgentsUpdates/SourceCatalogInspection.swift new file mode 100644 index 0000000..6d8eaa0 --- /dev/null +++ b/Sources/AgentsUpdates/SourceCatalogInspection.swift @@ -0,0 +1,568 @@ +import AgentsCore +import AgentsManifest +import Components +import Foundation + +/// A handle from one immutable source inspection; labels are never selection keys. +public struct SourceCatalogChoiceID: Hashable, Sendable { + fileprivate let owner: UUID + fileprivate let index: Int +} + +public struct SourceCatalogInputID: Hashable, Sendable { + fileprivate let owner: UUID + fileprivate let index: Int +} + +public enum SourceCatalogUnit: Sendable { + case skill, instruction, group, nativePlugin, componentsPlugin + case pluginMember(ComponentReferenceDeclaration) + case importer +} + +public struct SourceCatalogOccurrenceEffect: Sendable { + public let provenance: SourceProvenance + public let condition: DeclarationCondition + public let recipients: [AgentID] + public let dependencies: [String] +} + +public struct SourceCatalogConstraintInspection: Sendable { + public let source: String + public let root: String + public let requirement: SourceRequirement? + public let referenceChain: [SourceSpan] +} + +public struct SourceCatalogEffect: Sendable { + public let kind: DeclaredComponentKind + public let name: String + public let source: String + public let revision: String + public let conditions: [DeclarationCondition] + public let recipients: [AgentID] + public let chatGPT: Bool + public let resources: [String] + public let declaration: ComponentDeclaration? + public let occurrences: [SourceCatalogOccurrenceEffect] +} + +public struct SourceCatalogChoiceInspection: Sendable { + public let id: SourceCatalogChoiceID + public let label: String + public let origin: ImportLocationInspection + public let unit: SourceCatalogUnit + public let effects: [SourceCatalogEffect] + public let importedEffects: ImportSelectionEffects? + public let constraints: [SourceCatalogConstraintInspection] + public let artifactDigest: String? + public let unavailableReason: String? +} + +public struct SourceCatalogRequiredInput: Sendable { + public let id: SourceCatalogInputID + public let kind: ImportInputKind + public let location: ImportLocationInspection + public let suggestedReference: ImportBindingReference? +} + +public struct SourceCatalogInputResolution: Sendable { + public let id: SourceCatalogInputID + public let value: ImportInputValue + public init(id: SourceCatalogInputID, value: ImportInputValue) { + self.id = id + self.value = value + } +} + +/// The explicit adapter and document within the selected discovery root. Omission and an +/// empty producer selection retain their adapter-defined meanings during inspection. +public struct SourceCatalogImportOptions: Sendable { + public let format: String + public let document: String + public let selection: Set? + public init(format: String, document: String, selection: Set? = nil) { + self.format = format + self.document = document + self.selection = selection + } +} + +public struct SourceCatalogSelectionOptions: Sendable { + public var agents: [AgentID]? + public var condition: DeclarationCondition? + public var skillMode: InstallMode? + public init( + agents: [AgentID]? = nil, condition: DeclarationCondition? = nil, skillMode: InstallMode? = nil + ) { + self.agents = agents + self.condition = condition + self.skillMode = skillMode + } +} + +/// Explicit source choices and their full linked or adapter-issued effects. Source sessions and +/// private freshness observations are retained only as opaque preparation authority. +public struct SourceCatalogInspection: Sendable, CustomReflectable { + public let alias: String + public let sourceIdentity: String + public let revision: String + public let availableChoices: [SourceCatalogChoiceInspection] + public let fixedEffects: ImportSelectionEffects? + public let requiredInputs: [SourceCatalogRequiredInput] + public let bindings: [ImportBindingInspection] + public let producerSelections: [ImportSelectionInspection] + private let capture: CatalogCapture + public var customMirror: Mirror { + Mirror(self, children: ["alias": alias, "choices": availableChoices]) + } + + /// Empty selection returns nil before opening sources or initializing a request. Every other + /// selection revalidates this inspection and composes only the selected finite additions. + public func select( + _ choices: [SourceCatalogChoiceID], options: SourceCatalogSelectionOptions = .init(), + inputs: [SourceCatalogInputResolution] = [] + ) throws -> ComponentDiscovery? { + guard !choices.isEmpty else { return nil } + guard Set(choices).count == choices.count, + choices.allSatisfy({ + $0.owner == capture.owner && capture.catalog.choices.indices.contains($0.index) + }), + Set(inputs.map(\.id)).count == inputs.count, + inputs.allSatisfy({ + $0.id.owner == capture.owner && capture.targets.indices.contains($0.id.index) + }) + else { throw CoreError.invalidState("catalog handles belong to another inspection") } + let preparation = CatalogPreparation( + capture: capture, choices: choices.map(\.index), options: options, inputs: inputs) + let additions = try preparation.additions() + guard + var discovery = try UpdateOperations.captureAddition( + additions, in: capture.destination, catalogExpectation: preparation.compositionExpectation) + else { return nil } + discovery.catalogPreparation = preparation + return discovery + } + + fileprivate init(capture: CatalogCapture) { + self.capture = capture + let catalog = capture.catalog + alias = catalog.alias + sourceIdentity = catalog.snapshot.source + revision = catalog.snapshot.revision + availableChoices = catalog.choices.enumerated().map { index, choice in + let unit: SourceCatalogUnit + switch choice.unit { + case .skill: unit = .skill + case .instruction: unit = .instruction + case .group: unit = .group + case .nativePlugin: unit = .nativePlugin + case .componentsPlugin: unit = .componentsPlugin + case .pluginMember(_, let selector): unit = .pluginMember(selector) + case .importer: unit = .importer + } + return .init( + id: .init(owner: capture.owner, index: index), label: choice.label, + origin: location(choice.origin), unit: unit, + effects: choice.graph?.components.map { component in + .init( + kind: component.key.kind, name: component.key.name, source: component.snapshot.source, + revision: component.snapshot.revision, conditions: component.conditions, + recipients: component.recipients.sorted { $0.rawValue < $1.rawValue }, + chatGPT: component.chatGPT, + resources: component.resources.map(\.path), + declaration: { + if case .declaration(let declaration) = component.payload { return declaration } + return nil + }(), + occurrences: component.origins.map { origin in + .init( + provenance: origin.provenance, + condition: origin.condition, + recipients: origin.recipients.sorted { $0.rawValue < $1.rawValue }, + dependencies: origin.dependencies.map { $0.source + "@" + $0.revision }) + }) + } ?? [], importedEffects: choice.imported.map(effects), + constraints: choice.graph?.constraints.map { + .init( + source: $0.source, root: $0.root, requirement: $0.requirement, + referenceChain: $0.referenceChain) + } ?? [], + artifactDigest: choice.artifact?.digest, unavailableReason: choice.unavailableReason) + } + fixedEffects = catalog.fixedEffects.map(effects) + requiredInputs = capture.targets.enumerated().map { index, target in + let kind: ImportInputKind + let origin: ImportLocation + let suggested: ImportBindingReference? + switch target { + case .adapter(let input): + kind = input.kind == .gitSource ? .sourceCoordinates : .explicitContent + origin = input.location + suggested = nil + case .binding(let binding): + kind = .bindingReference + origin = binding.location + suggested = binding.environmentVariable.map(ImportBindingReference.environment) + } + return .init( + id: .init(owner: capture.owner, index: index), kind: kind, + location: location(origin), suggestedReference: suggested) + } + bindings = catalog.bindings.map { + .init( + document: $0.location.document, pointer: $0.location.pointer, + reason: $0.reason, environmentVariable: $0.environmentVariable, + canResolveCanonicalSlot: $0.canonicalSlot) + } + producerSelections = catalog.producerSelections.map { + .init( + document: $0.origin.document, pointer: $0.origin.pointer, + sourceAlias: $0.sourceAlias, kind: $0.kind.rawValue, values: $0.values, + automatic: $0.automatic, + developmentOnly: $0.developmentOnly) + } + } +} + +extension UpdateOperations { + /// Enumerates only the explicit source/root. Inspection neither publishes state nor retains + /// a source extraction. Selection remains bound to this destination and source generation. + public static func inspectSource( + alias: String, source: SourceDeclaration, importing: SourceCatalogImportOptions? = nil, + scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> SourceCatalogInspection { + let store = StateStore(scope: scope, environment: environment) + let policy = try SourcePolicySnapshot(store: store) + try policy.effective.require(source, environment: environment) + let organization = try OrganizationPolicySnapshot(store: store) + try organization.requireSource(source, reference: alias, in: store) + let destination = try inspect(scope: scope, environment: environment) + let imported: SourceCatalogImport? + if let importing { + guard let profile = SourceImportProfile(rawValue: importing.format) else { + throw CoreError.invalidSource("unknown source import profile") + } + imported = .init( + profile: profile, document: importing.document, selection: importing.selection) + } else { + imported = nil + } + #if os(macOS) + let platform = DeclarationPlatform.macOS + #else + let platform = DeclarationPlatform.linux + #endif + let localGit = + try source.kind == .local + && SourceResolutionSession.withTemporaryRead(store: store) { try $0.isGitSource(source) } + let original = + try source.kind == .local && !localGit + ? TargetPrecondition(source.localURL(environment: environment)) : nil + let catalog = try SourceCatalog.inspect( + alias: alias, source: source, store: store, platform: platform, importing: imported, + sourcePolicy: policy.effective, organization: organization.evaluator, + admitOrganization: { try organization.admit($0) }) + let liveOriginal = catalog.snapshot.revision.hasPrefix("sha256:") ? original : nil + try liveOriginal?.validate() + try policy.validate() + try organization.validate() + return SourceCatalogInspection( + capture: .init( + catalog: catalog, store: store, + destination: destination, platform: platform, original: liveOriginal)) + } +} + +private enum CatalogInputTarget: Sendable { + case adapter(ImportInputMetadata) + case binding(ImportBindingRequirement) +} + +private final class CatalogCapture: @unchecked Sendable, CustomReflectable { + let owner = UUID() + let catalog: SourceCatalog + let store: StateStore + let destination: ScopeInspection + let platform: DeclarationPlatform + let original: TargetPrecondition? + let targets: [CatalogInputTarget] + var customMirror: Mirror { Mirror(self, children: [Mirror.Child]()) } + init( + catalog: SourceCatalog, store: StateStore, destination: ScopeInspection, + platform: DeclarationPlatform, original: TargetPrecondition? + ) { + self.catalog = catalog + self.store = store + self.destination = destination + self.platform = platform + self.original = original + targets = + catalog.requiredInputs.map(CatalogInputTarget.adapter) + + catalog.bindings.filter { $0.canonicalSlot && $0.key != nil }.map( + CatalogInputTarget.binding) + } +} + +/// Concrete catalog evidence, rechecked at selection and ordinary request preparation. +package final class CatalogPreparation: @unchecked Sendable, CustomReflectable { + private let capture: CatalogCapture + private let choices: [Int] + private let options: SourceCatalogSelectionOptions + private let inputs: [SourceCatalogInputResolution] + package var customMirror: Mirror { Mirror(self, children: [Mirror.Child]()) } + fileprivate init( + capture: CatalogCapture, choices: [Int], options: SourceCatalogSelectionOptions, + inputs: [SourceCatalogInputResolution] + ) { + self.capture = capture + self.choices = choices + self.options = options + self.inputs = inputs + } + package func validate() throws -> [TargetPrecondition] { + _ = try additions() + return capture.original.map { [$0] } ?? [] + } + package func validateStandalone(replacing targets: [URL]) throws { + guard capture.catalog.importDocument != nil else { return } + let (_, proposal) = try conversion() + for resource in proposal.resources where resource.selected && resource.requiresStandaloneSource + { + guard + let source = proposal.sources.first(where: { $0.alias == resource.sourceAlias })? + .declaration, + source.kind == .local + else { continue } + let root = source.localURL(environment: capture.store.environment) + if targets.contains(where: { + PathSafety.isContained(root, in: $0) || PathSafety.isContained($0, in: root) + }) { + throw CoreError.invalidState( + "import requires an independent authoring source before replacing its installed content") + } + } + } + fileprivate func additions() throws -> Declaration { + let policy = try SourcePolicySnapshot(store: capture.store) + try capture.original?.validate() + let catalog = capture.catalog + let organization = try OrganizationPolicySnapshot(store: capture.store) + try organization.requireSource(catalog.source, reference: catalog.alias, in: capture.store) + let fresh = try SourceCatalog.inspect( + alias: catalog.alias, source: catalog.source, store: capture.store, + platform: capture.platform, importing: catalog.importDocument, + sourcePolicy: policy.effective, organization: organization.evaluator, + admitOrganization: { try organization.admit($0) }) + guard fresh.snapshot == catalog.snapshot, fresh.root.utf8.elementsEqual(catalog.root.utf8), + fresh.contentHash == catalog.contentHash + else { throw CoreError.invalidState("catalog source changed; refresh inspection") } + for index in choices { + guard fresh.choices.indices.contains(index), + fresh.choices[index].graph == catalog.choices[index].graph, + fresh.choices[index].artifact == catalog.choices[index].artifact, + fresh.choices[index].unavailableReason == catalog.choices[index].unavailableReason + else { throw CoreError.invalidState("catalog dependency changed; refresh inspection") } + } + try capture.original?.validate() + try policy.validate() + try organization.validate() + let selected = try catalog.selected(choices.map { catalog.choices[$0].id }) ?? [] + if catalog.importDocument == nil { + guard inputs.isEmpty else { throw CoreError.invalidState("catalog has no adapter input") } + return try catalog.additions( + selected.map(\.id), agents: options.agents, condition: options.condition, + mode: options.skillMode) + } + guard options.agents == nil, options.condition == nil, options.skillMode == nil else { + throw CoreError.invalidState( + "import recipients and restrictions belong to the adapter conversion") + } + return try conversion().0 + } + fileprivate var compositionExpectation: CatalogCompositionExpectation { + .init( + choices: choices.map { capture.catalog.choices[$0] }, skillMode: options.skillMode) + } + + private func conversion() throws -> (Declaration, SourceImportProposal) { + let catalog = capture.catalog + let selected = try catalog.selected(choices.map { catalog.choices[$0].id }) ?? [] + var bindings: [String: RuntimeBinding] = [:] + var sources: [String: SourceDeclaration] = [:] + var content: [String: String] = [:] + for input in inputs { + switch (capture.targets[input.id.index], input.value) { + case (.adapter(let target), .source(let source)) where target.kind == .gitSource: + guard SourceImport.admitsSourceCoordinates(source) else { + throw CoreError.invalidSource("import requires Git coordinates") + } + sources[target.key] = source + case (.adapter(let target), .content(let path)) where target.kind == .installedContent: + _ = try PathSafety.sanitizeSubpath(path) + content[target.key] = path + case (.binding(let target), .binding(let reference)): + switch reference { + case .environment(let name): + guard name.range(of: #"^[A-Za-z_][A-Za-z0-9_]*$"#, options: .regularExpression) != nil + else { throw CoreError.invalidState("invalid symbolic environment reference") } + bindings[target.key!] = .environment(name) + case .secret(let name): + guard !name.isEmpty, + !name.unicodeScalars.contains(where: { CharacterSet.controlCharacters.contains($0) }) + else { throw CoreError.invalidState("invalid symbolic secret reference") } + bindings[target.key!] = .secret(name) + } + default: throw CoreError.invalidState("wrong catalog input kind") + } + } + let keys = Set( + selected.compactMap { choice -> String? in + if case .importer(let metadata) = choice.unit { return metadata.key } + return nil + }) + let result = try catalog.conversion( + keys: keys, bindings: bindings, sources: sources, content: content, store: capture.store) + try capture.original?.validate() + return result + } +} + +private func location(_ value: ImportLocation) -> ImportLocationInspection { + .init(document: value.document, pointer: value.pointer, span: value.span) +} + +private func effects(_ value: SourceCatalog.ImportEffects) -> ImportSelectionEffects { + .init( + sources: value.sources.map { s in + .init( + alias: s.alias, document: s.origin.document, pointer: s.origin.pointer, + declaration: s.declaration, commit: s.pin.commit, version: s.pin.version, + integrityKind: s.pin.integrity?.kind.rawValue, integrity: s.pin.integrity?.value, + requestedRef: s.requestedRef, resolvedRef: s.resolvedRef, resolvedURL: s.resolvedURL, + developmentOnly: s.developmentOnly, producerPath: s.producerPath, + producerIdentity: s.producerIdentity, registry: s.registry) + }, + components: value.components.map { + .init(document: $0.origin.document, pointer: $0.origin.pointer, declaration: $0.declaration) + }, + resources: value.resources.map { + .init( + sourceAlias: $0.sourceAlias, producerName: $0.producerName, path: $0.path, + hash: $0.observedHash, integrityKind: $0.producerIntegrity?.kind.rawValue, + integrity: $0.producerIntegrity?.value, + executableFlags: $0.executableFlags, requiresStandaloneSource: $0.requiresStandaloneSource, + selected: $0.selected, requiresBindingRewrite: $0.requiresBindingRewrite) + }, + diagnostics: value.diagnostics.map { + .init( + code: $0.code.rawValue, document: $0.location.document, + pointer: $0.location.pointer, span: $0.location.span, message: $0.message) + }) +} + +/// Selected producer evidence is checked against the composed graph before it is frozen. +/// Consumer restrictions, recipients, modes and container filters remain authored composition. +package struct CatalogCompositionExpectation { + private let components: [LinkedComponent] + private let references: [LinkedReference] + private let liveEditKeys: Set + + init(choices: [SourceCatalog.Choice], skillMode: InstallMode?) { + components = choices.flatMap { $0.graph?.components ?? [] } + references = choices.flatMap { $0.graph?.references ?? [] } + liveEditKeys = Set( + choices.flatMap { choice -> [ComponentKey] in + guard skillMode == .edit, case .skill = choice.unit else { return [] } + return choice.graph?.components.map(\.key) ?? [] + }) + } + + func validate(_ linked: LinkedComponents) throws { + for reference in references { + let candidates = linked.references.filter { + $0.group.utf8.elementsEqual(reference.group.utf8) + && $0.root.utf8.elementsEqual(reference.root.utf8) + && $0.snapshot.source.utf8.elementsEqual(reference.snapshot.source.utf8) + } + guard !candidates.isEmpty, + candidates.allSatisfy({ + $0.snapshot.revision.utf8.elementsEqual(reference.snapshot.revision.utf8) + && $0.manifestHash.utf8.elementsEqual(reference.manifestHash.utf8) + }) + else { throw CoreError.invalidState("catalog group changed dependency; refresh inspection") } + } + let expected = Dictionary(grouping: components, by: \.key) + let actual = Dictionary(grouping: linked.components, by: \.key) + for (key, requirements) in expected { + let candidates = actual[key] ?? [] + if liveEditKeys.contains(key) { + guard + candidates.allSatisfy({ + if case .skill(_, .edit, _) = $0.payload { return true } + return false + }) + else { + throw CoreError.invalidState("catalog live edit changed mode; refresh inspection") + } + } + // Choosing Antigravity can derive additional inputs from the captured section snapshot. + // The composed discovery fingerprint binds those inputs for preview and publication. + let allowsDerivedIncludes = requirements.allSatisfy { + !$0.resources.contains(where: \.antigravityInclude) + } + guard !candidates.isEmpty, + try Set(requirements.map { try evidence($0) }) + == Set( + candidates.map { + try evidence($0, allowsDerivedIncludes: allowsDerivedIncludes) + }) + else { + throw CoreError.invalidState("catalog addition changed dependency; refresh inspection") + } + } + } + + private func evidence( + _ component: LinkedComponent, allowsDerivedIncludes: Bool = false + ) throws -> Data { + let editing = liveEditKeys.contains(component.key) + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys] + func snapshot(_ value: SourceSnapshotID) throws -> Data { + try encoder.encode([ + value.source, + editing && value.source.utf8.elementsEqual(component.snapshot.source.utf8) + ? "live" : value.revision, + ]) + } + var fields = try [snapshot(component.snapshot), snapshot(component.declaringSnapshot)] + for resource in component.resources { + if allowsDerivedIncludes, resource.antigravityInclude, + case .instruction(_, nil, _) = component.payload, + component.recipients.contains(.antigravity), resource.snapshot == component.snapshot + { + continue + } + fields.append( + try encoder.encode([ + snapshot(resource.snapshot), Data(resource.path.utf8), Data(resource.hash.utf8), + encoder.encode(resource.executableFlags), encoder.encode(resource.artifact), + ])) + } + // Root occurrence numbers and declaration positions differ after finite composition. + // Complete producer dependency clauses remain distinct; their collection order is incidental. + let dependencies = try Set( + component.origins.map { origin in + try encoder.encode( + Set( + origin.dependencies.filter { + $0.revision != "live" + && !(editing && $0.source.utf8.elementsEqual(component.snapshot.source.utf8)) + }.map(snapshot) + ).sorted { $0.lexicographicallyPrecedes($1) }) + }) + fields.append(try encoder.encode(dependencies.sorted { $0.lexicographicallyPrecedes($1) })) + return try encoder.encode(fields) + } +} diff --git a/Sources/AgentsUpdates/SourceImportOperations.swift b/Sources/AgentsUpdates/SourceImportOperations.swift new file mode 100644 index 0000000..b740f43 --- /dev/null +++ b/Sources/AgentsUpdates/SourceImportOperations.swift @@ -0,0 +1,509 @@ +import AgentsCore +import Components +import Foundation + +public struct ImportSourceInspection: Sendable { + public let alias: String + public let document: String + public let pointer: String + public let declaration: SourceDeclaration? + public let commit: String? + public let version: String? + public let integrityKind: String? + public let integrity: String? + public let requestedRef: String? + public let resolvedRef: String? + public let resolvedURL: String? + public let developmentOnly: Bool + public let producerPath: String? + public let producerIdentity: String? + public let registry: String? +} + +public struct ImportComponentInspection: Sendable { + public let document: String + public let pointer: String + public let declaration: ComponentDeclaration +} + +public struct ImportDiagnosticInspection: Sendable { + public let code: String + public let document: String + public let pointer: String + public let span: SourceSpan? + public let message: String +} + +public struct ImportResourceInspection: Sendable { + public let sourceAlias: String + public let producerName: String + public let path: String? + public let hash: String? + public let integrityKind: String? + public let integrity: String? + public let executableFlags: [String: Bool] + public let requiresStandaloneSource: Bool + public let selected: Bool + public let requiresBindingRewrite: Bool +} + +/// Producer claims remain evidence; they never grant ownership of an existing target. +public struct ImportDeploymentInspection: Sendable { + public let document: String + public let pointer: String + public let sourceAlias: String? + public let agent: String? + public let scope: String? + public let directory: String? + public let files: [String] +} + +public struct ImportBindingInspection: Sendable { + public let document: String + public let pointer: String + public let reason: String + public let environmentVariable: String? + /// False means the explicit source/content must be corrected and inspected again. + public let canResolveCanonicalSlot: Bool +} + +public struct ImportSelectionInspection: Sendable { + public let document: String + public let pointer: String + public let sourceAlias: String? + public let kind: String + public let values: [String] + public let automatic: Bool + public let developmentOnly: Bool +} + +public struct ImportOrderedSourceInspection: Sendable { + public let document: String + public let pointer: String + public let alias: String + public let identity: String + public let transport: String + public let registry: String? + public let requestedRef: String? + public let skillsPath: String + public let rulesPath: String + public let skills: [String]? + public let rules: [String]? +} + +/// Handles are issued by one immutable inspection and cannot be constructed by consumers. +public struct ImportChoiceID: Hashable, Sendable { + fileprivate let owner: UUID + fileprivate let index: Int +} + +public struct ImportInputID: Hashable, Sendable { + fileprivate let owner: UUID + fileprivate let index: Int +} + +public struct ImportLocationInspection: Sendable { + public let document: String + public let pointer: String + public let span: SourceSpan? +} + +/// Effects from the adapter enumeration. Fixed contributions and unresolved inspection +/// requirements remain relevant when choosing any producer key. +public struct ImportSelectionEffects: Sendable { + public let sources: [ImportSourceInspection] + public let components: [ImportComponentInspection] + public let resources: [ImportResourceInspection] + public let diagnostics: [ImportDiagnosticInspection] +} + +public struct ImportChoiceInspection: Sendable { + public let id: ImportChoiceID + public let label: String + public let locations: [ImportLocationInspection] + public let effects: ImportSelectionEffects + /// Diagnostics emitted by this producer key. Fixed effects and global requirements also + /// participate in admission; an empty list is not permission to publish preserved bytes. + public var hasConversionDiagnostics: Bool { !effects.diagnostics.isEmpty } +} + +public enum ImportInputKind: Sendable { + case sourceCoordinates, explicitContent, bindingReference +} + +/// A binding resolution carries a reference, never the credential value. +public enum ImportBindingReference: Sendable { + case environment(String) + case secret(String) +} + +public struct ImportRequiredInput: Sendable { + public let id: ImportInputID + public let kind: ImportInputKind + public let location: ImportLocationInspection + public let suggestedReference: ImportBindingReference? +} + +/// Source coordinates are accepted only for Git-coordinate requirements. Content paths +/// stay relative to the explicit input root and are re-read by the owning adapter. +public enum ImportInputValue: Sendable { + case source(SourceDeclaration) + case content(path: String) + case binding(ImportBindingReference) +} + +public struct ImportInputResolution: Sendable { + public let id: ImportInputID + public let value: ImportInputValue + public init(id: ImportInputID, value: ImportInputValue) { + self.id = id + self.value = value + } +} + +private enum ImportResolutionTarget: Sendable { + case adapter(ImportInputMetadata) + case binding(String) +} + +public struct SourceImportInspection: Sendable { + public let format: String + public let producerRevision: String? + public let specificationStatus: String + public let sources: [ImportSourceInspection] + public let components: [ImportComponentInspection] + public let diagnostics: [ImportDiagnosticInspection] + public let resources: [ImportResourceInspection] + public let deployments: [ImportDeploymentInspection] + public let bindings: [ImportBindingInspection] + public let selections: [ImportSelectionInspection] + public let orderedSources: [ImportOrderedSourceInspection] + public let readLocations: [URL] + /// Actual adapter selection units; several component families can share one choice. + public let availableChoices: [ImportChoiceInspection] + /// Only supported missing inputs receive handles. Other requirements remain in bindings + /// or diagnostics and require a corrected explicit input, followed by reinspection. + public let requiredInputs: [ImportRequiredInput] + /// Contributions emitted independently of the adapter selection, including preserved inputs. + public let fixedEffects: ImportSelectionEffects + private let owner: UUID + private let choiceKeys: [String] + private let resolutionTargets: [ImportResolutionTarget] + private let preparation: ImportPreparation + + /// Merges selected canonical intent into the same captured full declaration. Unconverted + /// semantics and required bindings must be resolved through supported inputs. Preserved + /// resources requiring a binding rewrite need corrected content, even after slot resolution. + public func updateRequest(in inspection: ScopeInspection) throws -> UpdateRequest { + try preparation.validateConversion() + var additions = Declaration() + for source in preparation.proposal.sources { + guard var imported = source.declaration else { + throw CoreError.invalidState("import lacks exact canonical source coordinates") + } + if imported.kind == .local { + let identity = try imported.identity( + environment: RuntimeEnvironment( + projectDirectory: preparation.input.root, homeDirectory: preparation.input.root, + environment: [:])) + imported.location = String(identity.dropFirst("local:".count)) + imported.environment = nil + } + additions.sourceDeclarations.append(.init(name: source.alias, source: imported)) + } + additions.components = preparation.proposal.components.map(\.declaration) + guard + let discovery = try UpdateOperations.captureAddition( + additions, in: inspection, importPreparation: preparation) + else { throw CoreError.invalidState("import selection contains no new additions") } + return discovery.updateRequest() + } + + /// Revalidates the captured inputs, then reruns the same adapter with owner-issued choices. + /// Nil choices preserve the current selection; an empty list uses the adapter's empty semantics. + public func resolving( + choices: [ImportChoiceID]? = nil, inputs: [ImportInputResolution] = [] + ) throws -> SourceImportInspection { + _ = try preparation.capture(admitConversion: false) + var input = preparation.input + if let choices { + guard Set(choices).count == choices.count, + choices.allSatisfy({ $0.owner == owner && choiceKeys.indices.contains($0.index) }) + else { throw CoreError.invalidState("import choices belong to another inspection") } + input.selection = Set(choices.map { choiceKeys[$0.index] }) + } + guard Set(inputs.map(\.id)).count == inputs.count else { + throw CoreError.invalidState("import input was supplied more than once") + } + for resolution in inputs { + guard resolution.id.owner == owner, resolutionTargets.indices.contains(resolution.id.index) + else { throw CoreError.invalidState("import input belongs to another inspection") } + switch (resolutionTargets[resolution.id.index], resolution.value) { + case (.adapter(let requirement), .source(let declaration)) + where requirement.kind == .gitSource: + guard SourceImport.admitsSourceCoordinates(declaration) else { + throw CoreError.invalidSource("import requires Git source coordinates") + } + input.sourceDeclarations[requirement.key] = declaration + case (.adapter(let requirement), .content(let path)) + where requirement.kind == .installedContent: + _ = try PathSafety.resolvedChild(base: input.root, subpath: path) + input.installedSkills[requirement.key] = path + case (.binding(let key), .binding(let reference)): + let value: RuntimeBinding + switch reference { + case .environment(let name): + guard !name.isEmpty, + name.range(of: #"^[A-Za-z_][A-Za-z0-9_]*$"#, options: .regularExpression) != nil + else { throw CoreError.invalidState("invalid symbolic environment reference") } + value = .environment(name) + case .secret(let name): + guard !name.isEmpty, + !name.unicodeScalars.contains(where: { CharacterSet.controlCharacters.contains($0) }) + else { throw CoreError.invalidState("invalid symbolic secret reference") } + value = .secret(name) + } + input.bindingReferences[key] = value + default: throw CoreError.invalidState("import input value has the wrong supported kind") + } + } + return try SourceImportOperations.inspect(input) + } + + init( + _ proposal: SourceImportProposal, preparation: ImportPreparation, + catalog: SourceImportProposal? = nil + ) { + self.preparation = preparation + format = proposal.profile.rawValue + producerRevision = proposal.profile.producerRevision + specificationStatus = proposal.profile.specificationStatus + sources = proposal.sources.map { s in + .init( + alias: s.alias, document: s.origin.document, pointer: s.origin.pointer, + declaration: s.declaration, commit: s.pin.commit, version: s.pin.version, + integrityKind: s.pin.integrity?.kind.rawValue, integrity: s.pin.integrity?.value, + requestedRef: s.requestedRef, resolvedRef: s.resolvedRef, resolvedURL: s.resolvedURL, + developmentOnly: s.developmentOnly, producerPath: s.producerPath, + producerIdentity: s.producerIdentity, registry: s.registry) + } + components = proposal.components.map { + .init( + document: $0.origin.document, + pointer: $0.origin.pointer, declaration: $0.declaration) + } + diagnostics = proposal.diagnostics.map { + .init( + code: $0.code.rawValue, + document: $0.location.document, pointer: $0.location.pointer, span: $0.location.span, + message: $0.message) + } + resources = proposal.resources.map { + .init( + sourceAlias: $0.sourceAlias, + producerName: $0.producerName, path: $0.path, hash: $0.observedHash, + integrityKind: $0.producerIntegrity?.kind.rawValue, integrity: $0.producerIntegrity?.value, + executableFlags: $0.executableFlags, requiresStandaloneSource: $0.requiresStandaloneSource, + selected: $0.selected, requiresBindingRewrite: $0.requiresBindingRewrite) + } + deployments = proposal.deployments.map { + .init( + document: $0.origin.document, + pointer: $0.origin.pointer, sourceAlias: $0.sourceAlias, agent: $0.agent, scope: $0.scope, + directory: $0.installDirectory, files: $0.files) + } + bindings = proposal.bindings.map { + .init( + document: $0.location.document, + pointer: $0.location.pointer, reason: $0.reason, + environmentVariable: $0.environmentVariable, + canResolveCanonicalSlot: $0.canonicalSlot + ) + } + selections = proposal.selections.map { + .init( + document: $0.origin.document, + pointer: $0.origin.pointer, sourceAlias: $0.sourceAlias, kind: $0.kind.rawValue, + values: $0.values, automatic: $0.automatic, developmentOnly: $0.developmentOnly) + } + orderedSources = proposal.orderedSources.map { + .init( + document: $0.origin.document, + pointer: $0.origin.pointer, alias: $0.alias, identity: $0.identity, transport: $0.transport, + registry: $0.registry, requestedRef: $0.requestedRef, skillsPath: $0.skillsPath, + rulesPath: $0.rulesPath, skills: $0.skills, rules: $0.rules) + } + readLocations = preparation.locations + let issued = UUID() + owner = issued + choiceKeys = catalog?.choices.map(\.key) ?? [] + var targets: [ImportResolutionTarget] = [] + var requirements: [ImportRequiredInput] = [] + for item in proposal.requiredInputs { + let index = targets.count + targets.append(.adapter(item)) + requirements.append( + .init( + id: .init(owner: issued, index: index), + kind: item.kind == .gitSource ? .sourceCoordinates : .explicitContent, + location: .init( + document: item.location.document, pointer: item.location.pointer, + span: item.location.span), + suggestedReference: nil)) + } + for item in proposal.bindings { + guard item.canonicalSlot, let key = item.key else { continue } + let index = targets.count + targets.append(.binding(key)) + requirements.append( + .init( + id: .init(owner: issued, index: index), kind: .bindingReference, + location: .init( + document: item.location.document, pointer: item.location.pointer, + span: item.location.span), + suggestedReference: item.environmentVariable.map(ImportBindingReference.environment))) + } + resolutionTargets = targets + requiredInputs = requirements + if let catalog { + let view = SourceImportInspection(catalog, preparation: preparation) + func effects(_ component: [Int], _ source: [Int], _ resource: [Int], _ diagnostic: [Int]) + -> ImportSelectionEffects + { + .init( + sources: source.map { view.sources[$0] }, + components: component.map { view.components[$0] }, + resources: resource.map { view.resources[$0] }, + diagnostics: diagnostic.map { view.diagnostics[$0] }) + } + availableChoices = catalog.choices.enumerated().map { index, choice in + .init( + id: .init(owner: issued, index: index), label: "Producer selection \(index + 1)", + locations: choice.locations.map { + .init(document: $0.document, pointer: $0.pointer, span: $0.span) + }, + effects: effects(choice.components, choice.sources, choice.resources, choice.diagnostics)) + } + let assignedComponents = Set(catalog.choices.flatMap(\.components)) + let assignedSources = Set(catalog.choices.flatMap(\.sources)) + let assignedResources = Set(catalog.choices.flatMap(\.resources)) + let assignedDiagnostics = Set(catalog.choices.flatMap(\.diagnostics)) + fixedEffects = effects( + catalog.components.indices.filter { !assignedComponents.contains($0) }, + catalog.sources.indices.filter { !assignedSources.contains($0) }, + catalog.resources.indices.filter { !assignedResources.contains($0) }, + catalog.diagnostics.indices.filter { !assignedDiagnostics.contains($0) }) + } else { + availableChoices = [] + fixedEffects = .init( + sources: sources, components: components, resources: resources, diagnostics: diagnostics) + } + } +} + +package struct ImportPreparation: Sendable { + let input: SourceImportInput + let proposal: SourceImportProposal + let catalog: SourceImportProposal + let locations: [URL] + private let originalInputs: [TargetPrecondition] + + init( + input: SourceImportInput, proposal: SourceImportProposal, catalog: SourceImportProposal, + locations: [URL] + ) throws { + self.input = input + self.proposal = proposal + self.catalog = catalog + self.locations = locations + originalInputs = try locations.map { try TargetPrecondition($0) } + } + + func requireSourcePolicy(_ policy: EffectiveSourcePolicy) throws { + guard policy.isConfigured else { return } + try policy.require(.local(at: input.root), reference: "import input") + } + + func validateConversion() throws { + guard proposal.diagnostics.isEmpty, proposal.bindings.isEmpty else { + throw CoreError.invalidState( + "import has unresolved conversion diagnostics or binding requirements") + } + guard !proposal.resources.contains(where: { $0.selected && $0.requiresBindingRewrite }) else { + throw CoreError.invalidState( + "import preserved resources require corrected explicit content before publication") + } + guard + !proposal.resources.contains(where: { + $0.selected && $0.producerIntegrity != nil && $0.observedHash == nil + }) + else { + throw CoreError.invalidState( + "import requires verified captured content for the producer integrity claim") + } + } + + func capture(admitConversion: Bool = true) throws -> [TargetPrecondition] { + for original in originalInputs { try original.validate() } + var enumeration = input + enumeration.enumerateChoices = true + enumeration.selection = nil + guard try SourceImport.preview(input) == proposal, + try SourceImport.preview(enumeration) == catalog + else { throw CoreError.invalidState("import inputs changed; refresh the import inspection") } + if admitConversion { try validateConversion() } + for original in originalInputs { try original.validate() } + return originalInputs + } +} + +public enum SourceImportOperations { + /// Explicit pinned profile names are the importer owner's existing raw values. No ambient + /// config discovery, execution, network access, deployment adoption or write occurs. + public static func inspect( + format: String, root: URL, document: String, selection: Set? = nil, + sourceDeclarations: [String: SourceDeclaration] = [:], installedSkills: [String: String] = [:] + ) throws -> SourceImportInspection { + guard let profile = SourceImportProfile(rawValue: format) else { + throw CoreError.invalidSource("unknown source import profile") + } + let input = SourceImportInput( + profile: profile, root: root, document: document, + selection: selection, sourceDeclarations: sourceDeclarations, installedSkills: installedSkills + ) + return try inspect(input) + } + + static func inspect(_ input: SourceImportInput) throws -> SourceImportInspection { + guard input.sourceDeclarations.values.allSatisfy(SourceImport.admitsSourceCoordinates) else { + throw CoreError.invalidSource("import source coordinates are not admitted") + } + let root = input.root + let document = input.document + let installedSkills = input.installedSkills + let url = try PathSafety.resolvedChild(base: root, subpath: document) + let proposal = try SourceImport.preview(input) + var enumeration = input + enumeration.selection = nil + enumeration.enumerateChoices = true + let catalog = try SourceImport.preview(enumeration) + var locations = [url] + for path in installedSkills.values { + locations.append(try PathSafety.resolvedChild(base: root, subpath: path)) + } + for source in (proposal.sources + catalog.sources).compactMap(\.declaration) + where source.kind == .local { + let environment = + source.environment?.runtime ?? RuntimeEnvironment(projectDirectory: root, environment: [:]) + let identity = try source.identity(environment: environment) + if identity.hasPrefix("local:") { + locations.append(URL(fileURLWithPath: String(identity.dropFirst(6)))) + } + } + let preparation = try ImportPreparation( + input: input, proposal: proposal, catalog: catalog, + locations: Array(Set(locations)).sorted { $0.path < $1.path }) + _ = try preparation.capture(admitConversion: false) + return SourceImportInspection(proposal, preparation: preparation, catalog: catalog) + } +} diff --git a/Sources/AgentsUpdates/SourcePolicyEditing.swift b/Sources/AgentsUpdates/SourcePolicyEditing.swift new file mode 100644 index 0000000..872ab56 --- /dev/null +++ b/Sources/AgentsUpdates/SourcePolicyEditing.swift @@ -0,0 +1,44 @@ +import AgentsCore +import AgentsManifest +import Foundation + +/// A single editable scope policy captured when the editor opened. +public struct SourcePolicyEditor: Sendable { + public let url: URL + public let original: Data? + private let scope: InstallScope + private let environment: RuntimeEnvironment + private let projectRoot: ExistingProjectRoot? + + public init(scope: InstallScope, environment: RuntimeEnvironment = RuntimeEnvironment()) throws { + self.scope = scope + self.environment = environment + let store = StateStore(scope: scope, environment: environment) + projectRoot = scope == .project ? try store.captureExistingProjectRoot() : nil + let location = SourcePolicyOperations.policyURL(scope: scope, environment: environment) + url = location + original = try store.withReadLock { try TargetPrecondition.readingFile(location).bytes } + } + + /// Parses the exact proposed bytes, then publishes only if the displayed policy still matches. + public func save(_ bytes: Data) throws { + _ = try SourcePolicyDocument.parse(bytes, identity: DocumentIdentity(url.path)) + if let managed = environment.organizationSourcePolicyURL, + managed.resolvingSymlinksInPath().standardizedFileURL + == url.resolvingSymlinksInPath().standardizedFileURL + { + throw CoreError.invalidState("this policy is managed by the organization") + } + let store = StateStore(scope: scope, environment: environment) + try store.withLock(existingRoot: projectRoot) { + let observed = try TargetPrecondition.readingFile(url) + guard observed.bytes == original else { + throw CoreError.invalidState("the source policy changed; reopen it before saving") + } + guard observed.bytes != bytes else { return } + let transaction = FileTransaction(store: store) + try transaction.replace(url, with: .data(bytes), expecting: observed.evidence) + try transaction.commit() + } + } +} diff --git a/Sources/AgentsUpdates/SourcePolicyOperations.swift b/Sources/AgentsUpdates/SourcePolicyOperations.swift new file mode 100644 index 0000000..3c248c0 --- /dev/null +++ b/Sources/AgentsUpdates/SourcePolicyOperations.swift @@ -0,0 +1,61 @@ +import AgentsCore +import AgentsManifest +import Foundation + +public struct SourcePolicyInspection: Sendable, Encodable { + public let effective: EffectiveSourcePolicy + public let readDependencies: [ReadDependency] +} + +public struct SourcePolicyAudit: Sendable, Encodable { + public let scope: InstallScope + public let hasLock: Bool + public let policy: SourcePolicyInspection + public let violations: [SourcePolicyViolation] +} + +/// Source policy can be inspected and audited without acquisition, recovery or writes. +public enum SourcePolicyOperations { + public static func policyURL( + scope: InstallScope, environment: RuntimeEnvironment = RuntimeEnvironment() + ) -> URL { + SourcePolicySnapshot.policyURL(in: StateStore(scope: scope, environment: environment)) + } + + public static func inspect( + scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> SourcePolicyInspection { + let snapshot = try SourcePolicySnapshot( + store: StateStore(scope: scope, environment: environment)) + return .init(effective: snapshot.effective, readDependencies: snapshot.readDependencies) + } + + /// Evaluates the complete committed provenance. `hasLock` indicates whether an exact closure + /// was available for the audit. Unresolved declarations require an ordinary install preview. + public static func audit( + scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> SourcePolicyAudit { + let store = StateStore(scope: scope, environment: environment) + return try store.withReadLock { + let snapshot = try SourcePolicySnapshot(store: store) + let baseline = try StatePrecondition(store: store) + _ = try store.declarationBytes(prepared: baseline) + let ledger = try store.readLedger(prepared: baseline) + try environment.requireMCPRegistryRoutes(in: ledger) + if let pending = ledger.pendingDeployment { + try environment.requireMCPRegistryRoutes(in: pending.desired(in: ledger)) + } + let failures = try snapshot.effective.violations( + in: ledger, store: store, roots: store.ledgerRoots(recordedIn: ledger)) + try baseline.validate() + try snapshot.validate() + return .init( + scope: scope, hasLock: try baseline.bytes(for: store.resolvedURL) != nil, + policy: .init( + effective: snapshot.effective, + readDependencies: snapshot.readDependencies + + [.entry(store.declarationURL), .entry(store.resolvedURL)]), + violations: failures) + } + } +} diff --git a/Sources/AgentsUpdates/UpdateCompletion.swift b/Sources/AgentsUpdates/UpdateCompletion.swift new file mode 100644 index 0000000..7afb985 --- /dev/null +++ b/Sources/AgentsUpdates/UpdateCompletion.swift @@ -0,0 +1,98 @@ +import AgentsCore + +/// The outer operation's disposition after writer-lock recovery and cleanup have returned. +public enum UpdateTerminalDisposition: String, Sendable { + case unchanged, rolledBack, committed, recoveryRequired +} + +public struct UpdateCompletion { + public let result: Result + public let disposition: UpdateTerminalDisposition + public let recoveredBeforePreparation: Bool + public let recovery: RecoveryInspection +} + +extension UpdateCompletion: Sendable where Value: Sendable {} + +extension UpdateOperations { + /// Returns only after the synchronous closure, source lifetime and outer scope cleanup end. + /// UI consumers reprepare and compare the displayed fingerprint inside this closure. + public static func perform( + _ request: UpdateRequest = UpdateRequest(), scope: InstallScope = .project, + environment: RuntimeEnvironment = RuntimeEnvironment(), + bindingProvider: (any RuntimeBindingProvider)? = nil, + _ body: (PreparedUpdate) throws -> Value + ) -> UpdateCompletion { + perform( + request, scope: scope, environment: environment, bindingProvider: bindingProvider, + checkpoint: { _ in }, body) + } + + package static func perform( + _ request: UpdateRequest = UpdateRequest(), scope: InstallScope = .project, + environment: RuntimeEnvironment = RuntimeEnvironment(), + bindingProvider: (any RuntimeBindingProvider)? = nil, + checkpoint: @escaping (String) throws -> Void, + existingRoot: ExistingProjectRoot? = nil, expectedFingerprint: String? = nil, + _ body: (PreparedUpdate) throws -> Value + ) -> UpdateCompletion { + var capturedOutcome = TransactionOutcome() + var delivered = false + var recovered = false + let result = Result { + do { + return try prepare( + request, scope: scope, environment: environment, checkpoint: checkpoint, + provider: bindingProvider ?? RequiredBindingProvider(), + completion: { capturedOutcome = $0 }, expectedFingerprint: expectedFingerprint, + existingRoot: existingRoot + ) { update in + delivered = true + return try body(update) + } + } catch { + let underlying = (error as? UpdateApplyError)?.underlyingError ?? error + if !delivered, case CoreError.transactionRecovered = underlying { recovered = true } + throw error + } + } + return completion( + result, outcome: capturedOutcome, recovered: recovered, + store: StateStore(scope: scope, environment: environment)) + } + + static func completion( + _ result: Result, outcome: TransactionOutcome, recovered: Bool, + store: StateStore + ) -> UpdateCompletion { + let disposition: UpdateTerminalDisposition + switch outcome.terminal { + case .committed: disposition = .committed + case .rolledBack: disposition = outcome.publicationStarted ? .rolledBack : .unchanged + case nil: + disposition = + outcome.publicationStarted && outcome.recoveryPending ? .recoveryRequired : .unchanged + } + var recovery: RecoveryInspection + do { + recovery = try store.withReadLock( + onPendingRecovery: { + let diagnostic = FileTransaction.recoveryDiagnostic(store: store) + return .init( + pending: true, requiresOwner: diagnostic.requiresOwner, diagnostic: diagnostic.message) + }, { .init(pending: false, requiresOwner: false, diagnostic: nil) }) + } catch { + recovery = .init( + pending: true, requiresOwner: true, + diagnostic: "recovery or cleanup could not be verified; retain this scope for diagnosis") + } + if outcome.recoveryPending && !recovery.pending { + recovery = .init( + pending: true, requiresOwner: true, + diagnostic: "transaction recovery or cleanup remains pending at the captured scope") + } + return UpdateCompletion( + result: result, disposition: disposition, + recoveredBeforePreparation: recovered, recovery: recovery) + } +} diff --git a/Sources/AgentsUpdates/UpdateInputs.swift b/Sources/AgentsUpdates/UpdateInputs.swift new file mode 100644 index 0000000..2cf18dd --- /dev/null +++ b/Sources/AgentsUpdates/UpdateInputs.swift @@ -0,0 +1,51 @@ +import AgentsCore +import AgentsSkills +import Foundation + +/// Live skill content remains live; its authored directory identity and valid metadata cannot change. +final class UpdateInputs: PreparedEvidence { + private struct LiveSkill { + let resource: LedgerResource + let name: String + let logical: PathIdentity + let physical: PathIdentity + } + private let frozen: [TargetPrecondition] + private let live: [LiveSkill] + private let ledger: ResolvedLedger + private let roots: [String: URL] + + init( + ledger: ResolvedLedger, roots: [String: URL], resources: [String: URL], + decisions: [TargetPrecondition], + originals: [TargetPrecondition] + ) throws { + frozen = decisions + originals + self.ledger = ledger + self.roots = roots + live = try ledger.components.values.compactMap { component in + guard component.kind == "skills", let id = component.resources.first, + let resource = ledger.resources[id], resource.kind == .liveEdit, let url = resources[id] + else { return nil } + return try LiveSkill( + resource: resource, name: component.payload.object?["name"]?.text ?? component.name, + logical: PathIdentity(url), physical: PathIdentity(url.resolvingSymlinksInPath())) + } + } + + func validate(excludingTargets targets: Set = []) throws { + for evidence in frozen where !targets.contains(evidence.url.path) { + if targets.isEmpty { + try evidence.validate() + } else { + try evidence.validateDuringPublication() + } + } + for item in live { + let edit = try LedgerResources.liveEditSource(item.resource, ledger: ledger, roots: roots) + try item.logical.validate() + try item.physical.validate() + try SkillOperations.validateLiveMetadata(at: edit.directory, name: item.name) + } + } +} diff --git a/Sources/AgentsUpdates/UpdateModels.swift b/Sources/AgentsUpdates/UpdateModels.swift index 056a950..0d15cef 100644 --- a/Sources/AgentsUpdates/UpdateModels.swift +++ b/Sources/AgentsUpdates/UpdateModels.swift @@ -1,14 +1,99 @@ import AgentsCore import AgentsInstructions import AgentsSkills +import Components +import Foundation -public struct CombinedUpdateReport: Sendable, Equatable { +public struct CombinedUpdateReport: Codable, Sendable, Equatable { public let scope: InstallScope public let skills: [UpdateResult] public let instructions: InstructionUpdateReport public let lockMissing: Bool - /// Includes normalized state changes and missing-lock reconstruction, even without file diffs. + /// Includes changes to declaration bytes, normalized state and missing-lock reconstruction. public let hasChanges: Bool + public let displayedFingerprint: String + /// Exact package pin changes included in this preview, when present. + public let marketplaceChanges: [MarketplacePackageUpdate]? + public let marketplaceGraphChange: MarketplaceGraphUpdate? + public let organizationPolicy: OrganizationPolicyReport? + /// Explicit re-resolution observed different ZIP bytes for the same normalized tree. + public let archiveRepresentationChanges: [SourceArchiveRepresentationChange]? + /// Durable inputs and absent leaves used to invalidate this exact preview. + public let readLocations: [URL] + public let components: [ComponentUpdateChange] +} + +public struct SourceArchiveRepresentationChange: Codable, Sendable, Equatable { + public let source: String + public let treeDigest: String + public let before: String + public let after: String + + static func between( + _ previous: ResolvedLedger, _ next: ResolvedLedger + ) -> [Self]? { + let changes = next.sources.values.compactMap { source -> Self? in + guard let archive = source.archive, let transport = source.transport, + let old = previous.sources.values.first(where: { + $0.transport == transport && $0.archive?.effectiveURL == archive.effectiveURL + && $0.archive?.treeDigest == archive.treeDigest + })?.archive, old.observedArchiveDigest != archive.observedArchiveDigest + else { return nil } + return .init( + source: transport, treeDigest: archive.treeDigest, + before: old.observedArchiveDigest, after: archive.observedArchiveDigest) + }.sorted { ($0.source, $0.treeDigest, $0.after) < ($1.source, $1.treeDigest, $1.after) } + return changes.isEmpty ? nil : changes + } +} + +public struct MarketplacePackageUpdate: Codable, Sendable, Equatable { + public let before: MarketplacePin? + public let after: MarketplacePin? + + static func between(_ previous: ResolvedLedger, _ next: ResolvedLedger) -> [Self]? { + let before = Dictionary( + uniqueKeysWithValues: (previous.marketplacePackages ?? []).map { ($0.dependency.name, $0) }) + let after = Dictionary( + uniqueKeysWithValues: (next.marketplacePackages ?? []).map { ($0.dependency.name, $0) }) + let changes = Set(before.keys).union(after.keys).sorted().compactMap { name in + before[name] == after[name] ? nil : Self(before: before[name], after: after[name]) + } + return changes.isEmpty ? nil : changes + } +} + +public struct MarketplaceGraphUpdate: Codable, Sendable, Equatable { + public let before: MarketplaceGraph? + public let after: MarketplaceGraph? + + /// Roots whose intent changes or whose reachable package changes release or edges. + public var affectedRoots: [String] { + let oldRoots = Dictionary( + uniqueKeysWithValues: (before?.roots ?? []).map { ($0.intent.name, $0) }) + let newRoots = Dictionary( + uniqueKeysWithValues: (after?.roots ?? []).map { ($0.intent.name, $0) }) + let oldNodes = Dictionary(uniqueKeysWithValues: (before?.nodes ?? []).map { ($0.id, $0) }) + let newNodes = Dictionary(uniqueKeysWithValues: (after?.nodes ?? []).map { ($0.id, $0) }) + var changed = Set(oldRoots.keys).union(newRoots.keys).filter { oldRoots[$0] != newRoots[$0] } + for id in Set(oldNodes.keys).union(newNodes.keys) { + let old = oldNodes[id] + let new = newNodes[id] + if old?.coordinate != new?.coordinate || old?.archiveDigest != new?.archiveDigest + || old?.catalogCommit != new?.catalogCommit || old?.dependencies != new?.dependencies + { + changed.formUnion(before?.rootsRequiring(id) ?? []) + changed.formUnion(after?.rootsRequiring(id) ?? []) + } + } + return changed.sorted() + } + + static func between(_ previous: ResolvedLedger, _ next: ResolvedLedger) -> Self? { + let before = previous.marketplaceGraph + let after = next.marketplaceGraph + return before == after ? nil : Self(before: before, after: after) + } } public struct UpdateApplyResult: Sendable { @@ -37,3 +122,58 @@ public struct UpdateApplyError: Error { (underlyingError as? UpdateApplyError)?.underlyingError ?? underlyingError } } + +public struct ComponentUpdateChange: Codable, Sendable, Equatable { + public let sourceIdentity: String + public let revision: String? + public let version: String? + public let format: String + public let ownership: String + public let resources: [ComponentResourceInfo] + public let requiredBindings: [String] + public let effectiveReaders: [AgentID] + public let privateMaterialization: Bool + public let permissionChange: ComponentPermissionChange? + /// Readable selected native configuration/files with symbolic environment/secret references. + /// Nil means the old selected value is unavailable; native sibling values are never included. + public let symbolicBefore: String? + /// Readable selected native configuration/files, including generated member content and targets. + public let symbolicAfter: String? + public let kind: String + public let name: String + public let path: String + public let agents: [AgentID] + public let changed: Bool +} + +public struct ComponentResourceInfo: Codable, Sendable, Equatable { + public let path: String + public let hash: String + public let executableFiles: [String: Bool] +} + +public struct ComponentPermissionChange: Codable, Sendable, Equatable { + public let beforeOwner: UInt32 + public let beforeGroup: UInt32 + public let beforeMode: UInt32 + public let afterOwner: UInt32 + public let afterMode: UInt32 + public let ownerOnly: Bool + public let members: [ComponentMemberPermissionChange] +} + +public struct ComponentMemberPermissionChange: Codable, Sendable, Equatable { + public let path: String + public let beforeOwner: UInt32 + public let beforeGroup: UInt32 + public let beforeMode: UInt32 + public let afterOwner: UInt32 + public let afterMode: UInt32 +} + +// Public preview text uses the inspection projection, never the ledger wire representation. +extension UpdateOperations { + static func symbolicConfigurationText(_ value: LedgerValue) throws -> String { + try ArtifactAggregation.configurationPreview(symbolicValue(value)) + } +} diff --git a/Sources/AgentsUpdates/UpdateOperations.swift b/Sources/AgentsUpdates/UpdateOperations.swift index 4cd1383..537fa2f 100644 --- a/Sources/AgentsUpdates/UpdateOperations.swift +++ b/Sources/AgentsUpdates/UpdateOperations.swift @@ -1,54 +1,258 @@ import AgentsCore +import AgentsInstructions +import AgentsManifest import Foundation +struct RequiredBindingProvider: RuntimeBindingProvider { + func value(for binding: String, environment: RuntimeEnvironment) throws -> Data { + throw CoreError.invalidState("this materialization requires a runtime binding provider") + } +} + public enum UpdateOperations { - /// Resolves a fresh, read-only report under one shared scope lock. Pending recovery stops inspection. public static func preview( - scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment() + _ request: UpdateRequest = UpdateRequest(), scope: InstallScope = .project, + environment: RuntimeEnvironment = RuntimeEnvironment() ) throws -> CombinedUpdateReport { - try preview(scope: scope, environment: environment, checkpoint: { _ in }) + try preview(request, scope: scope, environment: environment, checkpoint: { _ in }) } package static func preview( - scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment(), + _ request: UpdateRequest = UpdateRequest(), scope: InstallScope = .project, + environment: RuntimeEnvironment = RuntimeEnvironment(), checkpoint: @escaping (String) throws -> Void ) throws -> CombinedUpdateReport { + try withPreview(request, scope: scope, environment: environment, checkpoint: checkpoint) { + plan, _, _ in plan.report + } + } + + static func previewInstructionOutputs( + scope: InstallScope, environment: RuntimeEnvironment + ) throws -> CombinedUpdateReport { + let store = StateStore(scope: scope, environment: environment) + let organization = try OrganizationPolicySnapshot(store: store) + let acquisitions = GitAcquisitionCaptures() + return try withReadPlan(store: store) { admitted, installations in + try UpdatePlan.withPlan( + request: UpdateRequest(kinds: [.instructions]), store: store, admitted: admitted, + installations: installations, checkpoint: { _ in }, provider: RequiredBindingProvider(), + organizationPolicy: organization, acquisitions: acquisitions, + instructionPreview: { $0 }, + { _ in throw CoreError.invalidState("instruction output preview requires compilation") }) + } + } + + static func previewWithOwnership( + _ request: UpdateRequest, scope: InstallScope, environment: RuntimeEnvironment, + organizationPolicy: OrganizationPolicySnapshot? = nil + ) throws -> ( + CombinedUpdateReport, String?, Set, [String: SkillInstallationTarget] + ) { + try withPreview( + request, scope: scope, environment: environment, organizationPolicy: organizationPolicy + ) { plan, routes, installations in + do { + try plan.requireOwnership() + return (plan.report, nil, routes, installations) + } catch { + return (plan.report, String(describing: error), routes, installations) + } + } + } + + private static func withPreview( + _ request: UpdateRequest, scope: InstallScope, environment: RuntimeEnvironment, + checkpoint: @escaping (String) throws -> Void = { _ in }, + organizationPolicy: OrganizationPolicySnapshot? = nil, + acquisitions: GitAcquisitionCaptures = .init(), + _ body: (UpdatePlan, Set, [String: SkillInstallationTarget]) throws -> Result + ) throws -> Result { let store = StateStore(scope: scope, environment: environment) - return try store.withReadLock { try UpdatePlan(store: store, checkpoint: checkpoint).report } + try request.capturedAddition?.validate(request, in: store) + let organization = + try organizationPolicy + ?? OrganizationPolicySnapshot( + store: store, offline: request.restoresOffline) + return try withReadPlan(store: store) { admitted, installations in + try UpdatePlan.withPlan( + request: request, store: store, admitted: admitted, installations: installations, + checkpoint: checkpoint, provider: RequiredBindingProvider(), + organizationPolicy: organization, acquisitions: acquisitions + ) { try body($0, admitted, installations) } + } } - /// Holds the writer lock through preparation, synchronous rendering and optional application. - /// Returning or throwing before apply cancels. A caller error after apply does not undo the commit. + static func marketplaceLockPlan( + _ request: UpdateRequest, store: StateStore, organizationPolicy: OrganizationPolicySnapshot + ) throws -> MarketplaceLockPlan { + let acquisitions = GitAcquisitionCaptures() + return try withReadPlan(store: store) { admitted, installations in + try UpdatePlan.withPlan( + request: request, store: store, admitted: admitted, installations: installations, + checkpoint: { _ in }, provider: RequiredBindingProvider(), + organizationPolicy: organizationPolicy, acquisitions: acquisitions, marketplaceLock: { $0 } + ) { _ in throw CoreError.invalidState("a lock-only write requires a marketplace resolution") } + } + } + + static func withReadPlan( + store: StateStore, + _ body: (Set, [String: SkillInstallationTarget]) throws -> Result + ) throws -> Result { + var admitted = Set() + var installations: [String: SkillInstallationTarget] = [:] + while true { + do { + return try store.withReadLock( + footprint: admitted, installations: Array(installations.values) + ) { + try body(admitted, installations) + } + } catch let required as RequiredRoutes { + admitted.formUnion(required.routes) + installations.merge(required.installations, uniquingKeysWith: { _, next in next }) + } + } + } + + /// Holds admitted locks and borrowed resources through this synchronous, same-thread closure. public static func withPreparedUpdate( - scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment(), + _ request: UpdateRequest = UpdateRequest(), scope: InstallScope = .project, + environment: RuntimeEnvironment = RuntimeEnvironment(), + bindingProvider: (any RuntimeBindingProvider)? = nil, _ body: (PreparedUpdate) throws -> Result ) throws -> Result { - try withPreparedUpdate(scope: scope, environment: environment, checkpoint: { _ in }, body) + try prepare( + request, scope: scope, environment: environment, checkpoint: { _ in }, + provider: bindingProvider ?? RequiredBindingProvider(), body) } package static func withPreparedUpdate( - scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment(), + _ request: UpdateRequest = UpdateRequest(), scope: InstallScope = .project, + environment: RuntimeEnvironment = RuntimeEnvironment(), checkpoint: @escaping (String) throws -> Void, _ body: (PreparedUpdate) throws -> Result + ) throws -> Result { + try prepare( + request, scope: scope, environment: environment, checkpoint: checkpoint, + provider: RequiredBindingProvider(), body) + } + + package static func prepare( + _ request: UpdateRequest, scope: InstallScope, environment: RuntimeEnvironment, + checkpoint: @escaping (String) throws -> Void, provider: any RuntimeBindingProvider, + completion: ((TransactionOutcome) -> Void)? = nil, + admittedRoutes: Set = [], + admittedInstallations: [String: SkillInstallationTarget] = [:], + admittedOrganizationPolicy: OrganizationPolicySnapshot? = nil, + expectedFingerprint: String? = nil, + existingRoot: ExistingProjectRoot? = nil, + _ body: (PreparedUpdate) throws -> Result ) throws -> Result { let store = StateStore(scope: scope, environment: environment) + try request.capturedAddition?.validate(request, in: store) let outcome = TransactionOutcome() + defer { completion?(outcome) } + var delivered = false var returned = false - do { - return try store.withLock(checkpoint: checkpoint, outcome: outcome) { - let plan = try UpdatePlan(store: store, checkpoint: checkpoint) - try plan.validateOwnership() - let update = PreparedUpdate(plan: plan, outcome: outcome) - defer { update.invalidate() } - let result = try body(update) - returned = true - return result + var admitted = admittedRoutes + var installations = admittedInstallations + let organization = + try admittedOrganizationPolicy + ?? OrganizationPolicySnapshot( + store: store, offline: request.restoresOffline) + let acquisitions = GitAcquisitionCaptures() + var preflight: UpdatePlan.Admission? + if expectedFingerprint != nil || OrganizationPolicySnapshot.configured(store) { + do { + preflight = try withPreview( + request, scope: scope, environment: environment, organizationPolicy: organization, + acquisitions: acquisitions + ) { plan, routes, targets in + admitted.formUnion(routes) + installations.merge(targets, uniquingKeysWith: { _, selected in selected }) + return plan.admission + } + } catch let error as CoreError { + guard case .recoveryPending = error, expectedFingerprint == nil else { throw error } + // The ordinary writer owns pending recovery and reports that the command must be retried. } - } catch { - if returned || error is UpdateApplyError { - throw UpdateApplyError(outcome: outcome, underlyingError: error) + } + if let expectedFingerprint, preflight?.fingerprint != expectedFingerprint { + throw CoreError.invalidState("marketplace deployment changed; refresh the preview") + } + let validatePreflight: () throws -> Void = { try preflight?.validate() } + while true { + do { + try validatePreflight() + return try store.withLock( + checkpoint: checkpoint, outcome: outcome, footprint: admitted, + installations: Array(installations.values), existingRoot: existingRoot, + beforeScopeLock: validatePreflight + ) { + try UpdatePlan.withPlan( + request: request, store: store, admitted: admitted, installations: installations, + checkpoint: checkpoint, provider: provider, organizationPolicy: organization, + acquisitions: acquisitions + ) { plan in + if let preflight, plan.report.displayedFingerprint != preflight.fingerprint { + throw CoreError.invalidState( + "update inputs changed after organization policy admission") + } + do { + try plan.requireOwnership() + } catch let error as InstructionError { + throw UpdateApplyError(outcome: outcome, underlyingError: error) + } + let update = PreparedUpdate(plan: plan, outcome: outcome) + defer { update.invalidate() } + delivered = true + let result = try body(update) + returned = true + return result + } + } + } catch let required as RequiredRoutes where !delivered { + admitted.formUnion(required.routes) + installations.merge(required.installations, uniquingKeysWith: { _, next in next }) + } catch { + if returned || error is UpdateApplyError { + throw UpdateApplyError(outcome: outcome, underlyingError: error) + } + throw error } + } + } + + static func withDomainUpdate( + _ request: UpdateRequest, scope: InstallScope, environment: RuntimeEnvironment, + checkpoint: @escaping (String) throws -> Void = { _ in }, + _ body: (PreparedUpdate) throws -> Result + ) throws -> Result { + do { + return try withPreparedUpdate( + request, scope: scope, environment: environment, checkpoint: checkpoint, body) + } catch let error as UpdateApplyError { + if case .unchanged = error.disposition { throw error.underlyingError } throw error } } + + static func declarationSnapshot(_ store: StateStore) throws -> (Declaration, String) { + try store.withReadLock { + let document = try store.declarationDocument(prepared: nil) + return (try store.readDeclaration(), document?.digest ?? "absent") + } + } + + public static func restore( + scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment(), + bindingProvider: (any RuntimeBindingProvider)? = nil, offline: Bool = false + ) throws -> UpdateApplyResult { + try withPreparedUpdate( + UpdateRequest(operation: .restore, offline: offline), scope: scope, environment: environment, + bindingProvider: bindingProvider + ) { try $0.apply() } + } } diff --git a/Sources/AgentsUpdates/UpdatePlan.swift b/Sources/AgentsUpdates/UpdatePlan.swift index 8873eb8..ef88f70 100644 --- a/Sources/AgentsUpdates/UpdatePlan.swift +++ b/Sources/AgentsUpdates/UpdatePlan.swift @@ -1,108 +1,1251 @@ import AgentsCore import AgentsInstructions +import AgentsManifest import AgentsSkills +import Components import Foundation -/// Domain plans share resolution, but contribute only their owned records to the next generation. +struct RequiredRoutes: Error { + let routes: Set + var installations: [String: SkillInstallationTarget] = [:] +} + +/// The composition plan borrows both source/replay resources and the admitted writer scope. final class UpdatePlan { + func requireOwnership() throws { try aggregation.requireOwnership() } + let report: CombinedUpdateReport private let store: StateStore private let baseline: StatePrecondition - private let declaration: Declaration - private let previous: ResolvedState - private let next: ResolvedState + private let sourcePolicy: SourcePolicySnapshot + private let organization: OrganizationInstallEvaluation + private let workspacePolicy: OrganizationWorkspaceInspection + + struct Admission { + let fingerprint: String + let baseline: StatePrecondition + let sourcePolicy: SourcePolicySnapshot + let organizationPolicy: OrganizationPolicySnapshot + let workspacePolicy: OrganizationWorkspaceInspection + + func validate() throws { + try baseline.validate() + try sourcePolicy.validate() + try organizationPolicy.validate() + try workspacePolicy.validate() + } + } + + var admission: Admission { + .init( + fingerprint: report.displayedFingerprint, baseline: baseline, sourcePolicy: sourcePolicy, + organizationPolicy: organization.policy, + workspacePolicy: workspacePolicy) + } + private let previous: ResolvedLedger + private let next: ResolvedLedger private let watch: WatchState - private let skills: SkillUpdatePlan - private let instructions: InstructionUpdatePlan - private let resolutions: SourceResolutionSession + private let declarationChange: DeclarationChange? + private let aggregation: ArtifactAggregation private let checkpoint: (String) throws -> Void + private let provider: any RuntimeBindingProvider + private let inputs: UpdateInputs + private let receipts: [InstallResult] + private let bundlePublications: [BundleSourceInputs.Publication] + private let bundleRemovals: [TargetPrecondition] + private let marketplaceGraphChange: MarketplaceGraphChange? + private let deployPendingMarketplace: Bool + private let restoresOffline: Bool + private let acquisitions: GitAcquisitionCaptures + private let resources: [String: URL] + + static func withPlan( + request: UpdateRequest, store: StateStore, admitted: Set, + installations: [String: SkillInstallationTarget], + checkpoint: @escaping (String) throws -> Void, provider: any RuntimeBindingProvider, + organizationPolicy: OrganizationPolicySnapshot, acquisitions: GitAcquisitionCaptures, + marketplaceLock: ((MarketplaceLockPlan) throws -> T)? = nil, + instructionPreview: ((CombinedUpdateReport) throws -> T)? = nil, + _ body: (UpdatePlan) throws -> T + ) throws -> T { + var request = request + let sourcePolicy = try SourcePolicySnapshot(store: store) + try organizationPolicy.admit() + try organizationPolicy.validate() + try request.capturedAddition?.validate(request, in: store) + try request.importPreparation?.requireSourcePolicy(sourcePolicy.effective) + let catalogInputs = try request.catalogPreparation?.validate() ?? [] + var importInputs = try (request.importPreparation?.capture() ?? []) + catalogInputs + let baseline = try StatePrecondition(store: store) + let previous = try store.readLedger(prepared: baseline) + let roots = store.ledgerRoots(recordedIn: previous) + let instructionReferences = try resolveSelection( + &request, ledger: previous, store: store, roots: roots, baseline: baseline) + let restoringRequest: Bool + if case .restore = request.operation { + restoringRequest = true + } else { + restoringRequest = false + } + let declaration: Declaration + do { + declaration = try store.readDeclaration(prepared: baseline) + } catch is ManifestFailure + where restoringRequest + && previous.pendingDeployment == nil && previous.marketplaceGraph == nil + && (previous.marketplacePackages ?? []).isEmpty && !organizationPolicy.evaluator.active + { + // Standalone components restore from their locked inputs. Package and + // organization admission still require a readable declaration. + declaration = Declaration() + } + let pending = previous.pendingDeployment + if pending != nil, !request.deployPendingMarketplace, marketplaceLock == nil { + throw MarketplaceError.pendingDeployment + } + let lockedIntent = try pending?.desired(in: previous) ?? previous + try request.marketplaceGraphChange?.validate( + baseline, policy: sourcePolicy, organizationPolicy: organizationPolicy, store: store) + try MarketplaceChanges.validate( + declaration, matching: lockedIntent, in: store, + allowingGraphReconciliation: request.marketplaceGraphChange != nil) + if restoringRequest, request.marketplaceChange != nil || request.marketplaceGraphChange != nil { + throw MarketplaceError.selectionMismatch("package change requires an update") + } + let watch = try store.readWatch(prepared: baseline) + let original = try restoringRequest ? nil : store.declarationDocument(prepared: baseline) + if request.declarationYAML != nil, request.expectedDeclarationDigest == nil { + throw CoreError.invalidState("a YAML edit requires an expected declaration digest") + } + if let expected = request.expectedDeclarationDigest, expected != (original?.digest ?? "absent") + { + throw CoreError.invalidState("declaration changed during discovery; retry the command") + } + if let installation = request.bundleInstallation, request.marketplaceGraphChange == nil { + request.operation = try .declaration(installation.adding(to: declaration, store: store)) + } + var candidate = declaration + var change: DeclarationChange? + var addedInstructions: (paths: Set, requested: Set)? + #if os(macOS) + let platform = DeclarationPlatform.macOS + #else + let platform = DeclarationPlatform.linux + #endif + let restoring: Bool + switch request.operation { + case .restore: restoring = true + case .update: restoring = false + case .edit(let edits): + restoring = false + let bytes: [UInt8] + if let yaml = request.declarationYAML { + bytes = yaml + } else { + guard let original else { throw CoreError.notFound("declaration document") } + bytes = try original.preparing(edits).bytes + } + candidate = try ManifestProjection.declaration( + of: DeclarationDocument( + bytes: bytes, identity: DocumentIdentity(store.declarationURL.path)), + environment: store.environment) + change = bytes == original?.bytes ? nil : DeclarationChange(bytes: Data(bytes)) + case .declaration(let replacement): + restoring = false + candidate = replacement + if let addition = request.instructionAddition { + let hasUses = !candidate.uses.isEmpty + let groups = + try hasUses + ? instructionGroups( + addition, candidate: candidate, original: declaration, document: original, + store: store, baseline: baseline, previous: previous, roots: roots, platform: platform, + sourcePolicy: sourcePolicy, organizationPolicy: organizationPolicy, + acquisitions: acquisitions) : [] + let selection = InstructionOperations.addLocalRecipients( + addition, scope: store.scope, platform: platform, groups: groups, to: &candidate) + if hasUses { + addedInstructions = selection + if selection.paths.isEmpty, let alias = addition.alias, declaration.sources[alias] == nil + { + candidate.sources[alias] = nil + } + } + } + if request.marketplaceChange == nil { + change = try store.planDeclaration(candidate, replacing: declaration, prepared: baseline) + } + case .remove: + restoring = false + try LedgerImpact.requireEditable( + previous, kinds: request.kinds ?? Set(DeclaredComponentKind.allCases), + names: Set(request.names), roots: roots, + selectedIdentities: request.selectedIdentities) + candidate = try removing( + request, from: declaration, ledger: previous, store: store, roots: roots, + selectedInstructionReferences: instructionReferences) + change = try store.planDeclaration(candidate, replacing: declaration, prepared: baseline) + } + if !restoring { + candidate = try MarketplaceChanges.candidate( + candidate, original: declaration, previous: lockedIntent, request: request, store: store) + if request.marketplaceChange != nil || request.marketplaceGraphChange != nil { + change = try store.planDeclaration(candidate, replacing: declaration, prepared: baseline) + } + } + let retargetedInstructions: Set + if case .remove = request.operation, request.agents != nil, + request.kinds?.contains(.instructions) ?? true + { + retargetedInstructions = try Set( + previous.occurrences.filter { $0.consumerEditable }.compactMap { + guard let component = previous.components[$0.component], component.kind == "instructions", + component.group == nil + else { return nil } + return try LedgerImpact.identity(component, ledger: previous, roots: roots) + }) + } else { + retargetedInstructions = [] + } + let organization = try OrganizationInstallEvaluation( + policy: organizationPolicy, store: store, declaration: candidate, + bytes: change?.bytes ?? baseline.bytes(for: store.declarationURL)) + let initialFindings = + organization.beforeAcquisition() + (request.bundleInstallation?.policyFindings ?? []) + try organizationPolicy.admit(initialFindings) + if restoring { + let next: ResolvedLedger + if request.deployPendingMarketplace { + guard let pending else { throw CoreError.notFound("pending marketplace deployment") } + try pending.requireDeclaration(baseline.bytes(for: store.declarationURL)) + next = lockedIntent + request.selectedIdentities = try MarketplaceGraphChange.deploymentIdentities( + from: previous, to: next, roots: roots) + } else { + next = previous + } + try MarketplaceGraphChange.validateHosted( + next.marketplaceGraph, objects: next.contentObjects, policy: sourcePolicy.effective, + organizationPolicy: organizationPolicy) + try sourcePolicy.effective.require(next, store: store, roots: roots) + try organizationPolicy.admit( + initialFindings + + organization.closure( + baseline.bytes(for: store.resolvedURL) == nil ? nil : next, roots: roots)) + let routes = try DeploymentConstruction.routes(previous).union( + DeploymentConstruction.routes(next)) + let required = try SkillLifecycle.installationTargets(previous, store: store).merging( + SkillLifecycle.installationTargets(next, store: store), + uniquingKeysWith: { _, next in next }) + guard routes.isSubset(of: admitted), Set(required.keys).isSubset(of: Set(installations.keys)) + else { throw RequiredRoutes(routes: routes, installations: required) } + return try LedgerReplay.withLockedResources( + next, store: store, roots: roots, limits: .standard, + offline: request.restoresOffline, + sourcePolicy: sourcePolicy.effective, + requireRecordedTransport: organization.evaluator.requiresRecordedGitOrigin, + acquisitions: acquisitions + ) { artifacts, resources, workspace in + let publications = try MarketplaceGraphChange.restoreProducers( + next.marketplaceGraph, replayed: resources, store: store) + let removals = + try request.deployPendingMarketplace + ? MarketplaceGraphChange.pruneProducers( + previous: previous, next: next, store: store, roots: roots, + declaration: declaration, 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: nil, artifacts: artifacts, resources: resources, + workspace: workspace, + decisionInputs: [], originalInputs: [], + checkpoint: checkpoint, provider: provider, installations: Array(installations.values), + retargetedInstructions: retargetedInstructions, bundlePublications: publications, + bundleRemovals: removals, acquisitions: acquisitions)) + } + } + var document: DeclarationDocument + if let change { + document = try DeclarationDocument( + bytes: Array(change.bytes), identity: DocumentIdentity(store.declarationURL.path)) + } else if let original { + document = original + } else { + document = try DeclarationDocument( + bytes: Array("version: 1\n".utf8), identity: DocumentIdentity(store.declarationURL.path)) + } + let updating: Bool + if case .update = request.operation { + updating = request.marketplaceGraphChange == nil + } else { + updating = request.expectedDiscoveryFingerprint != nil && request.capturedAddition == nil + } + let removing: Bool + if case .remove = request.operation { removing = true } else { removing = false } + if removing || (updating && !request.names.isEmpty), request.kinds?.contains(.skills) ?? true { + var linkingDeclaration = candidate + for index in linkingDeclaration.components.indices { + guard case .skills(let alias, var selection) = linkingDeclaration.components[index], + case .all = selection.select, let source = linkingDeclaration.sources[alias] + else { continue } + let identity = try source.identity(environment: store.environment) + let existing = try previous.components.values.filter { component in + guard component.kind == "skills", component.group == nil else { return false } + return try previous.sourceIdentity(component.source, roots: roots) == identity + }.map { PathSafety.sanitizeName($0.name) }.sorted() + let selected = request.names.filter { name in + !previous.components.values.contains { $0.kind == "skills" && $0.name == name } + || existing.contains(name) + } + selection.select = .names( + removing + ? existing.filter { !(selection.exclude ?? []).contains($0) } + : Array(Set(existing + selected)).sorted()) + linkingDeclaration.components[index] = .skills(source: alias, selection) + } + if removing { + linkingDeclaration.components.removeAll { + if case .skills(_, let selection) = $0, case .names(let names) = selection.select { + return names.isEmpty + } + return false + } + } + if let bytes = try store.planDeclaration( + linkingDeclaration, replacing: declaration, prepared: baseline)?.bytes + { + document = try DeclarationDocument( + bytes: Array(bytes), identity: DocumentIdentity(store.declarationURL.path)) + } + } + let impact = try LedgerImpact( + ledger: previous, roots: roots, + kinds: request.kinds ?? Set(DeclaredComponentKind.allCases), names: Set(request.names), + updating: updating, selectedIdentities: request.selectedIdentities) + let marketplace = request.marketplaceGraphChange + if let registration = try MarketplaceGraphChange.admitHostedRegistrations( + marketplace?.graph, environment: store.environment) + { + importInputs.append(registration) + } + try MarketplaceGraphChange.validateHosted( + marketplace.map(\.graph) ?? previous.marketplaceGraph, + objects: marketplace?.hostedArchives ?? previous.contentObjects, + policy: sourcePolicy.effective, + organizationPolicy: organizationPolicy) + try MarketplaceChanges.requirePolicy( + sourcePolicy.effective, candidate: candidate, previous: previous, + change: request.marketplaceChange, + graph: request.marketplaceGraphChange.map(\.graph) ?? previous.marketplaceGraph, + store: store) + let admitOrganization: @Sendable ([OrganizationPolicyFinding]) throws -> Void = { + try organizationPolicy.admit(initialFindings + $0) + } + let staged = request.marketplaceFrozenProducers.merging( + request.bundleInstallation?.stagedContainers ?? [:], uniquingKeysWith: { _, new in new }) + return try ComponentLinker.withLinkedComponents( + document: document, store: store, platform: platform, + preserving: impact.pins, directPins: impact.directPins, retaining: previous, + sourcePolicy: sourcePolicy.effective, organization: organization.evaluator, + admitOrganization: admitOrganization, + stagedLocalSources: staged.mapValues { $0.appendingPathComponent(BundleSourceLocation.tree) }, + acquisitions: acquisitions, instructionsOnly: instructionPreview != nil + ) { linked, session in + let bundleSources = try BundleSourceInputs.capture( + linked, session: session, store: store, staged: staged) + if let expected = request.automaticSkill { + guard + linked.components.contains(where: { component in + if case .skill(let skill, _, _) = component.payload { + return skill.name == expected.name && component.snapshot.source == expected.source + } + return false + }) + else { + throw CoreError.invalidState( + "automatic skill selection changed during discovery; retry the command") + } + } + let locations = try sourceLocations(linked, declaration: candidate, store: store) + for component in linked.components { + if case .skill(let skill, .copy, _) = component.payload { + try DeploymentConstruction.validateCopiedSkill( + session.resource(snapshot: component.snapshot, path: skill.path)) + } + } + let frozen = try LedgerFreeze.freezeWithSources( + linked, session: session, locations: .init(sources: locations), limits: .standard) + try sourcePolicy.effective.require(frozen.ledger, store: store, roots: roots) + if let instructionPreview { + let complete = try DeploymentConstruction.complete( + frozen.ledger, linked: linked, store: store, previous: previous, platform: platform, + roots: roots, session: session) + return try instructionPreview( + InstructionOutputPreview.report( + complete, previous: previous, store: store, baseline: baseline, roots: roots, + sourcePolicy: sourcePolicy, organization: organization, + initialFindings: initialFindings, + acquisitions: acquisitions)) + } + if let addition = request.instructionAddition, let selection = addedInstructions { + // A fresh scope can publish the requested group routes. An existing lock already + // owns those routes, so re-adding them leaves their deployed files alone. + let initialGroupPaths = + try baseline.bytes(for: store.resolvedURL) == nil + ? Set(addition.units.map { $0.record.path }) : [] + var selected = Set() + var unrequested = Set() + for item in frozen.ledger.components.values where item.kind == "instructions" { + guard item.payload.object?["prompt"] == nil, + let resource = item.resources.first.flatMap({ frozen.ledger.resources[$0] }), + try frozen.ledger.sourceIdentity(item.source, roots: roots) == addition.source + else { continue } + if item.group == nil, selection.paths.contains(resource.path) { + selected.insert(try LedgerImpact.identity(item, ledger: frozen.ledger, roots: roots)) + } else if item.group != nil, initialGroupPaths.contains(resource.path), + !item.recipients.isEmpty + { + let identity = try LedgerImpact.identity(item, ledger: frozen.ledger, roots: roots) + if selection.requested.isSuperset(of: item.recipients) { + selected.insert(identity) + } else { + unrequested.insert(identity) + } + } + } + // Several conditioned occurrences can share an identity. + request.selectedIdentities = selected.subtracting(unrequested) + } + if let expected = request.expectedDiscoveryFingerprint, + expected != (try LedgerImpact.discoveryFingerprint(frozen.ledger, roots: roots)) + { + throw CoreError.invalidState("discovered source content changed; refresh discovery") + } + let lowered = try DeploymentConstruction.lowerNative( + linked: linked, frozen: frozen, scope: store.scope, platform: platform) + let native = try MarketplaceChanges.pin( + lowered, declaration: candidate, previous: previous, request: request, store: store, + sourceIDs: frozen.sources, producers: bundleSources.producers) + 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), + roots: roots, + selectedIdentities: identities) + } + if let installation = request.bundleInstallation { + let selected = try installation.selectedIdentities(native, roots: roots) + if request.marketplaceChange == nil, request.marketplaceGraphChange == nil { + request.selectedIdentities = selected + } + } + 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 kinds = request.kinds ?? Set(DeclaredComponentKind.allCases) + try LedgerImpact.requireProtected( + previous: previous, next: native, kinds: kinds, names: Set(request.names), + roots: roots, selectedIdentities: request.selectedIdentities, + retargetedInstructions: retargetedInstructions) + } + let complete = try DeploymentConstruction.complete( + native, linked: linked, store: store, previous: previous, platform: platform, roots: roots, + session: session) + if marketplaceLock == nil { + let required = try SkillLifecycle.installationTargets(previous, store: store).merging( + SkillLifecycle.installationTargets(complete.ledger, store: store), + uniquingKeysWith: { _, next in next }) + guard Set(required.keys).isSubset(of: Set(installations.keys)) else { + throw RequiredRoutes(routes: routes, installations: required) + } + } + let originals = try linked.components.flatMap { c -> [TargetPrecondition] in + if case .skill(_, .edit, _) = c.payload { return [] } + return try c.resources.filter { $0.snapshot.revision == "live" }.map { + try TargetPrecondition(session.resource(snapshot: $0.snapshot, path: $0.path)) + } + } + try checkpoint("plan.skills") + let roots = store.ledgerRoots(recordedIn: previous) + return try LedgerReplay.withPreparedLowerings( + complete.ledger, 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) + 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, + 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)) + } + } + } + + private static func instructionGroups( + _ addition: InstructionAddition, candidate: Declaration, original: Declaration, + document originalDocument: DeclarationDocument?, store: StateStore, baseline: StatePrecondition, + previous: ResolvedLedger, roots: [String: URL], platform: DeclarationPlatform, + sourcePolicy: SourcePolicySnapshot, organizationPolicy: OrganizationPolicySnapshot, + acquisitions: GitAcquisitionCaptures + ) throws -> [LinkedComponent] { + let change = try store.planDeclaration(candidate, replacing: original, prepared: baseline) + let document: DeclarationDocument + if let change { + document = try DeclarationDocument( + bytes: Array(change.bytes), identity: DocumentIdentity(store.declarationURL.path)) + } else if let originalDocument { + document = originalDocument + } else { + throw CoreError.missingDeclaration(store.declarationURL.path) + } + let impact = try LedgerImpact( + ledger: previous, roots: roots, kinds: [.instructions], names: [], updating: false) + let organization = try OrganizationInstallEvaluation( + policy: organizationPolicy, store: store, declaration: candidate, bytes: Data(document.bytes)) + let initial = organization.beforeAcquisition() + try organizationPolicy.admit(initial) + let admitOrganization: @Sendable ([OrganizationPolicyFinding]) throws -> Void = { + try organizationPolicy.admit(initial + $0) + } + return try ComponentLinker.withLinkedComponents( + document: document, store: store, platform: platform, + preserving: impact.pins, directPins: impact.directPins, retaining: previous, + sourcePolicy: sourcePolicy.effective, organization: organization.evaluator, + admitOrganization: admitOrganization, + acquisitions: acquisitions + ) { linked, _ in + linked.components.filter { component in + guard component.key.group != nil, component.snapshot.source == addition.source, + case .instruction(_, prompt: nil, _) = component.payload + else { return false } + return true + } + } + } - init(store: StateStore, checkpoint: @escaping (String) throws -> Void = { _ in }) throws { + private init( + request: UpdateRequest, store: StateStore, roots: [String: URL], baseline: StatePrecondition, + sourcePolicy: SourcePolicySnapshot, organization: OrganizationInstallEvaluation, + initialFindings: [OrganizationPolicyFinding], previous: ResolvedLedger, next: ResolvedLedger, + watch: WatchState, + change: DeclarationChange?, artifacts: [ReplayedArtifact], resources: [String: URL], + workspace: URL, + decisionInputs: [TargetPrecondition], originalInputs: [TargetPrecondition], + checkpoint: @escaping (String) throws -> Void, provider: any RuntimeBindingProvider, + installations: [SkillInstallationTarget], retargetedInstructions: Set, + bundlePublications: [BundleSourceInputs.Publication] = [], + bundleRemovals: [TargetPrecondition] = [], acquisitions: GitAcquisitionCaptures + ) throws { self.store = store + self.baseline = baseline + self.sourcePolicy = sourcePolicy + self.organization = organization + self.previous = previous + self.watch = watch + declarationChange = change self.checkpoint = checkpoint - baseline = try StatePrecondition(store: store) - declaration = try store.readDeclaration() - previous = try store.readResolved() - watch = try store.readWatch() - resolutions = try SourceResolutionSession(store: store) - skills = try SkillOperations.prepareUpdate( - store: store, declaration: declaration, previous: previous, resolutions: resolutions) - try checkpoint("plan.skills") - instructions = try InstructionOperations.prepareUpdate( - store: store, declaration: declaration, previousDeclaration: declaration, - previous: previous, resolutions: resolutions) - var next = previous - next.skills = skills.next.skills - next.instructions = instructions.next.instructions - for (id, source) in skills.next.sources where source != previous.sources[id] { - next.sources[id] = source - } - for (id, source) in instructions.next.sources where source != previous.sources[id] { - if let other = skills.next.sources[id], other != previous.sources[id], other != source { - throw CoreError.invalidState("incompatible planned source records: \(id)") - } - next.sources[id] = source - } - try declaration.validate(environment: store.environment) - try next.validate() - self.next = next - let lockMissing = try store.existingData(store.resolvedURL) == nil + self.provider = provider + self.bundlePublications = bundlePublications + self.bundleRemovals = bundleRemovals + marketplaceGraphChange = request.marketplaceGraphChange + deployPendingMarketplace = request.deployPendingMarketplace + restoresOffline = request.restoresOffline + self.acquisitions = acquisitions + 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, + replace: request.replace, + changingAccess: request.changingAccess, kinds: request.kinds, + names: Set(request.names), selectedIdentities: request.selectedIdentities, + installations: installations, retargetedInstructions: retargetedInstructions, + offlineBaseline: restoresOffline || sourcePolicy.effective.isConfigured, + sourcePolicy: sourcePolicy.effective, verifyPriorSkillLinks: deployPendingMarketplace) + try request.catalogPreparation?.validateStandalone(replacing: aggregation.changes.map(\.url)) + if let imported = request.importPreparation { + for resource in imported.proposal.resources + where resource.selected && resource.requiresStandaloneSource { + guard + let source = imported.proposal.sources.first(where: { $0.alias == resource.sourceAlias })? + .declaration, + source.kind == .local + else { continue } + let sourceEnvironment = source.environment?.runtime ?? store.environment + let identity = try source.identity(environment: sourceEnvironment) + let root = URL(fileURLWithPath: String(identity.dropFirst(6))) + if aggregation.changes.contains(where: { + PathSafety.isContained(root, in: $0.url) || PathSafety.isContained($0.url, in: root) + }) { + throw CoreError.invalidState( + "import requires an independent authoring source before replacing its installed content" + ) + } + } + } + self.next = aggregation.ledger + try self.next.validate() + workspacePolicy = try OrganizationWorkspaceInspection( + evaluator: organization.evaluator, store: store, ledger: self.next, previous: previous, + roots: roots, inspectDrift: false) + 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 before = try previous.domainProjection(roots: roots) + let after = try self.next.domainProjection(roots: roots) + let allResults = try UpdateReporting.skills( + previous: previous, next: self.next, resources: resources, + changes: aggregation.changes, store: store, roots: roots, lockMissing: lockMissing, + included: request.kinds == nil || request.kinds!.contains(.skills), + selectedIdentities: request.selectedIdentities, names: Set(request.names)) + let results = + request.names.isEmpty ? allResults : allResults.filter { request.names.contains($0.skill) } + receipts = results.flatMap(\.installed) + let publicResults = results.map { + var result = $0 + result.installed = [] + return result + } + func instructionArtifacts(_ ledger: ResolvedLedger) -> [String: String] { + var result: [String: String] = [:] + for lowering in ledger.lowerings + where InstructionLocations.isInstructionFormat(lowering.format) + || lowering.format == "agents/chatgpt@1" + || lowering.format == LockedLowering.instructionCopyFormat + { + for artifact in lowering.artifacts { + result[lowering.format + ":" + artifact.name] = artifact.hash + } + } + return result + } + let instructions = try UpdateReporting.instructions( + before: before.instructions, after: after.instructions, + changes: aggregation.changes, ledger: self.next, artifacts: artifacts, + lockMissing: lockMissing, + included: request.kinds == nil || request.kinds!.contains(.instructions), store: store, + stateChanged: instructionArtifacts(previous) != instructionArtifacts(self.next) + || (change != nil && request.kinds == [.instructions]), + conflicts: aggregation.antigravityConflicts) + let operation: String + switch request.operation { + case .update: operation = "update" + case .restore: operation = deployPendingMarketplace ? "marketplace-frozen-deploy" : "restore" + case .remove: operation = "remove" + case .edit, .declaration: operation = "edit" + } + struct Fingerprint: Encodable { + let version = 1 + let operation: String + let scope: InstallScope + let kinds: [String]? + let names: [String] + let selectedIdentities: [String]? + let replace: Bool + let changingAccess: Bool + let candidate: ResolvedLedger + let baseline: ResolvedLedger + let declaration: String? + let marketplaceState: String? + let targets: [String] + let instructionOutputs: [String: String] + let sourcePolicy: String? + let organizationPolicy: String? + let organizationFindings: [OrganizationPolicyFinding]? + } + var semanticCandidate = self.next + semanticCandidate.nativeAuthorities = nil + var semanticBaseline = previous + semanticBaseline.nativeAuthorities = nil + let fingerprint = try ResolvedLedgerCodec.digest( + Fingerprint( + operation: operation, scope: store.scope, kinds: request.kinds?.map(\.rawValue).sorted(), + names: request.names.sorted(), selectedIdentities: request.selectedIdentities?.sorted(), + replace: request.replace, + changingAccess: request.changingAccess, + candidate: semanticCandidate, baseline: semanticBaseline, + declaration: try (change?.bytes ?? baseline.bytes(for: store.declarationURL)).map { + "sha256:" + FileHash.sha256Hex(data: $0) + }, + marketplaceState: deployPendingMarketplace + ? try MarketplaceGraphChange.stateDigest(in: baseline, store: store) : nil, + targets: (aggregation.fingerprints + + (try decisionInputs.map { try $0.displayEvidence(includeContent: false) })).sorted(), + instructionOutputs: Dictionary( + uniqueKeysWithValues: instructions.outputs.map { + ($0.id, FileHash.sha256Hex(data: $0.content)) + }), + sourcePolicy: sourcePolicy.isConfigured ? sourcePolicy.fingerprint : nil, + organizationPolicy: policyReport.policies.isEmpty ? nil : organization.policy.fingerprint, + organizationFindings: policyReport.findings.isEmpty ? nil : policyReport.findings)) + var readDeclarations: [Declaration] = [] + if case .restore = request.operation { + } else { + readDeclarations.append(try store.readDeclaration(prepared: baseline)) + } + if let change { + readDeclarations.append( + try ManifestProjection.declaration( + of: DeclarationDocument( + bytes: Array(change.bytes), identity: DocumentIdentity(store.declarationURL.path)), + environment: store.environment)) + } + let readPaths = + try UpdateOperations.readLocations( + declarations: readDeclarations, ledgers: [previous, self.next], store: store, roots: roots) + + decisionInputs.map(\.url) + installations.map(\.url) + + aggregation.instructionDecisionLocations + sourcePolicy.readDependencies.map(\.url) + + organization.policy.readDependencies.map(\.url) + + (marketplaceGraphChange?.directoryInputs.flatMap(\.readLocations) ?? []) + let finalNext = self.next report = CombinedUpdateReport( - scope: store.scope, skills: skills.results, instructions: instructions.report, + scope: store.scope, skills: publicResults, instructions: instructions, lockMissing: lockMissing, - hasChanges: next.normalized != previous.normalized - || skills.results.contains(where: \.changed) || instructions.report.hasChanges - || (lockMissing && declaration.normalized != Declaration().normalized)) - try baseline.validate() + hasChanges: self.next != previous || change != nil + || !bundlePublications.isEmpty || !bundleRemovals.isEmpty + || aggregation.needsRetainedArtifactPublication + || aggregation.changes.contains(where: \.changed), + displayedFingerprint: fingerprint, + marketplaceChanges: MarketplacePackageUpdate.between(previous, finalNext), + marketplaceGraphChange: MarketplaceGraphUpdate.between(previous, finalNext), + organizationPolicy: policyReport.policies.isEmpty ? nil : policyReport, + archiveRepresentationChanges: SourceArchiveRepresentationChange.between(previous, finalNext), + readLocations: Set(readPaths.map(\.path)).sorted().map { + URL(fileURLWithPath: $0, isDirectory: false) + }, + components: try aggregation.changes.filter { change in + guard change.native else { return false } + guard let identities = request.selectedIdentities else { return true } + return try change.deployment.owners.contains { owner in + let ledger = finalNext.components[owner] == nil ? previous : finalNext + return try identities.contains( + LedgerImpact.identity( + ledger.components[owner]!, ledger: ledger, roots: roots)) + } + }.map { change in + let owner = change.deployment.owners[0] + let ledger = finalNext.components[owner] == nil ? previous : finalNext + let component = ledger.components[owner]! + return ComponentUpdateChange( + sourceIdentity: try ledger.sourceIdentity(component.source, roots: roots), + revision: component.revision, version: component.version, + format: change.deployment.route, ownership: change.deployment.ownership.rawValue, + resources: component.resources.compactMap { ledger.resources[$0] }.map { resource in + ComponentResourceInfo( + path: resource.path, hash: resource.hash, + executableFiles: Dictionary( + uniqueKeysWithValues: resource.entries.filter { $0.kind == .file }.map { + ($0.path, $0.executable) + })) + }, requiredBindings: change.requiredBindings, effectiveReaders: change.effectiveReaders, + privateMaterialization: change.privateMaterialization, + permissionChange: change.accessChange.map { access in + ComponentPermissionChange( + beforeOwner: access.before.owner, beforeGroup: access.before.group, + beforeMode: UInt32(access.before.mode), afterOwner: access.owner, + afterMode: access.mode, ownerOnly: true, + members: change.memberAccessChanges.map { + ComponentMemberPermissionChange( + path: $0.path, beforeOwner: $0.before.owner, beforeGroup: $0.before.group, + beforeMode: UInt32($0.before.mode), afterOwner: $0.owner, afterMode: $0.mode) + }) + }, + symbolicBefore: try change.configurationBefore + ?? change.symbolicBefore.map { + try UpdateOperations.symbolicConfigurationText($0) + }, + symbolicAfter: try change.configurationAfter + ?? change.symbolicAfter.map { + try UpdateOperations.symbolicConfigurationText($0) + }, + kind: component.kind, name: component.name, path: change.url.path, + agents: change.deployment.recipients, changed: change.changed) + }) + try admission.validate() } - func validateOwnership() throws { - try skills.validateOwnership() - let paths = skills.targetPaths + instructions.report.targets.map(\.url) - for (index, path) in paths.enumerated() { - guard - !paths.prefix(index).contains(where: { - PathSafety.isContained(path, in: $0) || PathSafety.isContained($0, in: path) - }) - else { throw CoreError.invalidState("overlapping update targets") } + func apply(outcome: TransactionOutcome) throws -> UpdateApplyResult { + try admission.validate() + let roots = store.ledgerRoots(recordedIn: previous) + try sourcePolicy.effective.require(next, store: store, roots: roots) + try baseline.validate() + try aggregation.validate() + try aggregation.requireOwnership() + try inputs.validate() + if report.hasChanges { + let ledgerReferences = try RetentionReferences(ledger: next, roots: roots) + var references = ledgerReferences + try references.include(watch: watch) + let cache = SourceCache( + store: store, sourcePolicy: sourcePolicy.effective, + requireRecordedTransport: organization.evaluator.requiresRecordedGitOrigin, + acquisitions: acquisitions, checkpoint: checkpoint) + let priorReferences = try RetentionReferences(ledger: previous, roots: roots) + try cache.withArchivePublication( + previous: priorReferences, next: ledgerReferences, offline: restoresOffline + ) { + // A watch subscription is independent from install policy and already owns its own pins. + if !deployPendingMarketplace { + try cache.retain( + references: sourcePolicy.effective.isConfigured ? ledgerReferences : references, + offline: restoresOffline) + } + try checkpoint("apply.retained") + try admission.validate() + try aggregation.validate() + try inputs.validate() + try marketplaceGraphChange?.validateCatalogs(in: store) + let transaction = FileTransaction(store: store, outcome: outcome, checkpoint: checkpoint) + transaction.requireUnchanged( + since: baseline, aggregation, inputs, sourcePolicy, organization.policy, workspacePolicy) + for publication in bundlePublications { try publication.stage(in: transaction) } + for removal in bundleRemovals { try transaction.delete(removal.url, expecting: removal) } + try aggregation.stage( + transaction: transaction, provider: provider, + roots: store.ledgerRoots(recordedIn: previous) + ) + try store.stageDeclaration(declarationChange, in: transaction, prepared: baseline) + // Empty scopes need no lock file; a declaration edit always accompanies first deployment. + if try store.declarationBytes(prepared: baseline) != nil || declarationChange != nil { + try store.stageLedger( + producing: { self.aggregation.ledger }, limits: .standard, transaction: transaction, + prepared: baseline) + } + try cache.prune(references: references, transaction: transaction) + try transaction.commit() + } + rememberDeployedBytes(roots: roots) } - try skills.validate() - try instructions.validate() + organization.policy.rememberVerifiedPolicies() + return UpdateApplyResult(report: report, installedSkills: receipts) } - func apply(outcome: TransactionOutcome) throws -> UpdateApplyResult { - try validate() - if report.hasChanges { - let retained = try skills.retain() - try instructions.retain() - try checkpoint("apply.retained") - try validate() - let transaction = FileTransaction(store: store, outcome: outcome, checkpoint: checkpoint) - try skills.stage(retained: retained, transaction: transaction) - try instructions.stage(transaction: transaction) - try store.stageDeclaration(declaration, in: transaction) - let resolvedBytes = try StateStore.encodeState(next.normalized) - if try store.existingData(store.resolvedURL) != resolvedBytes { - try transaction.replace(store.resolvedURL, content: nil, data: resolvedBytes) - } - try SourceCache(store: store).prune( - referencedBy: next, watch: watch, transaction: transaction) - try transaction.commit() - } - return UpdateApplyResult(report: report, installedSkills: skills.receipts) + /// Only direct Git skill payloads are eligible. Whole-file configuration rewrites, + /// renderer-generated bytes and runtime bindings do not carry this provenance. + private func rememberDeployedBytes(roots: [String: URL]) { + let cache = AcquisitionCache(environment: store.environment) + let ledger = aggregation.ledger + for change in aggregation.changes + where change.changed + && change.deployment.route == "agents/skill@1" + { + for owner in change.deployment.owners { + guard let component = ledger.components[owner] else { continue } + for id in component.resources { + guard let resource = ledger.resources[id], resource.kind == .git, + let source = ledger.sources[resource.source], let transport = source.transport, + source.container == nil, source.kind == .git, + acquisitions.containsAnonymousCommit( + .init(kind: .git, location: transport), revision: source.revision, + environment: store.environment), + let verifiedRoot = resources[id] + else { continue } + let installed: URL + if change.afterLink != nil { + guard + let expected = try? ArtifactAggregation.resourceDestination( + id, ledger: ledger, store: store, roots: roots), + let retained = PathSafety.realPath(expected.path), + let target = PathSafety.realPath(change.url.path), + retained.utf8.elementsEqual(target.utf8) + else { continue } + installed = URL(fileURLWithPath: retained) + } else { + installed = change.url + } + for file in resource.entries + where file.kind == .file + && file.byteCount.map({ $0 <= AcquisitionCache.deployedFileLimit }) == true + { + guard let expected = try? readDeployedFile(at: verifiedRoot, path: file.path), + let bytes = try? readDeployedFile(at: installed, path: file.path), + bytes.count == file.byteCount, bytes == expected + else { continue } + try? cache.rememberDeployedBytes(bytes) + } + } + } + } } - private func validate() throws { - try baseline.validate() - try skills.validate() - try instructions.validate() + private func readDeployedFile(at root: URL, path: String) throws -> Data { + if path == "." { + let directory = try DirectoryHandle.readDirectory(at: root.deletingLastPathComponent()) + return try directory.readRegularFile( + root.lastPathComponent, maximumBytes: AcquisitionCache.deployedFileLimit) + } + let components = path.split(separator: "/") + guard let file = components.last else { throw AcquisitionCacheError.invalidEntry } + var directory = try DirectoryHandle.readDirectory(at: root) + for name in components.dropLast() { + guard let child = try directory.directory(String(name)) else { + throw AcquisitionCacheError.invalidEntry + } + directory = child + } + return try directory.readRegularFile( + String(file), maximumBytes: AcquisitionCache.deployedFileLimit) } func recover(outcome: TransactionOutcome) { - do { - _ = try FileTransaction.recover(store: store, outcome: outcome) - } catch { + do { _ = try FileTransaction.recover(store: store, outcome: outcome) } catch { outcome.disposition = .recoveryRequired } } + + static func sourceLocations( + _ linked: LinkedComponents, declaration: Declaration, store: StateStore + ) throws -> [String: LedgerLocation] { + var locations: [String: LedgerLocation] = [:] + let packageRoot = + store.scope == .project ? store.environment.projectDirectory : store.directory + for evidence in linked.sourceSnapshots + linked.declaringSnapshots + where evidence.container == nil && evidence.snapshot.source.hasPrefix("local:") { + let path = String(evidence.snapshot.source.dropFirst(6)) + if path == packageRoot.path { + locations[evidence.snapshot.source] = .init( + kind: .registered, root: store.scope == .project ? "project" : "state", path: ".") + } else if let authored = try declaration.sources.values.first(where: { + try $0.identity(environment: store.environment) == evidence.snapshot.source + }), + !authored.location.hasPrefix("/") + { + if authored.location == "~" || authored.location.hasPrefix("~/") { + locations[evidence.snapshot.source] = .init( + kind: .authoringRelative, root: "home", + path: authored.location == "~" ? "." : String(authored.location.dropFirst(2))) + } else if authored.environment?.projectDirectory.path + == store.environment.projectDirectory.path || authored.environment == nil + { + locations[evidence.snapshot.source] = .init( + kind: .authoringRelative, root: "project", path: authored.location) + } else { + locations[evidence.snapshot.source] = .init(kind: .absolute, path: path) + } + } else { + locations[evidence.snapshot.source] = .init(kind: .absolute, path: path) + } + } + return locations + } + + private static func resolveSelection( + _ request: inout UpdateRequest, ledger: ResolvedLedger, store: StateStore, + roots: [String: URL], baseline: StatePrecondition + ) throws -> Set? { + let kinds = request.kinds ?? Set(DeclaredComponentKind.allCases) + func name(_ c: LedgerComponent) -> String { + c.kind == "skills" ? PathSafety.sanitizeName(c.name) : c.name + } + if request.selections.isEmpty { + if case .remove = request.operation, request.kinds == [.instructions] { + let declaration = try store.readDeclaration(prepared: baseline) + let references = try selectedInstructionReferences(Set(request.names), in: declaration) + let sections = declaration.components.flatMap { component -> [SectionDeclaration] in + guard case .instructions(let selection) = component else { return [] } + return selection.sectionReferences + + selection.prompts.flatMap { $0.prompt.sectionReferences } + } + var selected = Set() + for section in sections where references.contains(section.reference) { + let source: String + if let alias = section.source, alias != "." { + guard let sourceDeclaration = declaration.sources[alias] else { continue } + source = try sourceDeclaration.identity(environment: store.environment) + } else { + source = "local:" + store.environment.projectDirectory.resolvingSymlinksInPath().path + } + for component in ledger.components.values + where component.kind == "instructions" && component.group == nil + && component.name == section.name + { + if try ledger.sourceIdentity(component.source, roots: roots) == source { + selected.insert( + try LedgerImpact.identity(component, ledger: ledger, roots: roots)) + } + } + } + request.selectedIdentities = selected + return references + } + for requested in request.names { + let matches = try ledger.components.values.filter { + kinds.contains(DeclaredComponentKind(rawValue: $0.kind)!) && name($0) == requested + }.map { try LedgerImpact.identity($0, ledger: ledger, roots: roots) } + guard Set(matches).count <= 1 else { + throw CoreError.invalidState( + "component name is ambiguous; select a component from inspection: " + requested) + } + } + return nil + } + guard request.names.isEmpty else { + throw CoreError.invalidState("use names or precise selections, not both") + } + switch request.operation { + case .update, .remove: break + default: throw CoreError.invalidState("precise selection applies to update or removal") + } + let documentDigest = + try baseline.bytes(for: store.declarationURL).map { "sha256:" + FileHash.sha256Hex(data: $0) } + ?? "absent" + let generation = try ResolvedLedgerCodec.digest([ + ResolvedLedgerCodec.digest(ledger), documentDigest, + ]) + var selected = Set() + var names = Set() + var selectedKinds = Set() + for selection in request.selections { + guard selection.generation == generation else { + throw CoreError.invalidState("inspection changed; refresh component selection") + } + let entries = try ledger.components.filter { + try LedgerImpact.identity($0.value, ledger: ledger, roots: roots) + == selection.identity + } + guard let entry = entries.first, + kinds.contains(DeclaredComponentKind(rawValue: entry.value.kind)!) + else { + throw CoreError.notFound("selected component") + } + if let occurrence = selection.occurrence { + let occurrences = ledger.occurrences.filter { entries[$0.component] != nil } + guard occurrences.contains(where: { $0.id == occurrence }) else { + throw CoreError.notFound("selected occurrence") + } + guard occurrences.count == 1 else { + throw CoreError.invalidState( + "this component has multiple contributions; select the complete component or edit its declaration reference" + ) + } + } + selected.insert(selection.identity) + names.insert(name(entry.value)) + selectedKinds.insert(DeclaredComponentKind(rawValue: entry.value.kind)!) + } + request.selectedIdentities = selected + request.names = names.sorted() + request.kinds = selectedKinds + return nil + } + + private static func selectedInstructionReferences( + _ names: Set, in declaration: Declaration + ) throws -> Set { + let references = Set( + declaration.components.flatMap { component -> [String] in + guard case .instructions(let selection) = component else { return [] } + return selection.sectionReferences.map(\.reference) + + selection.prompts.flatMap { $0.prompt.sectionReferences.map(\.reference) } + }) + var selected = Set() + for name in names { + let exact = references.filter { $0 == name } + let matches = + exact.isEmpty + ? references.filter { $0.split(separator: ":").last.map(String.init) == name } : exact + guard matches.count == 1, let reference = matches.first else { + throw CoreError.notFound("instruction name is missing or ambiguous: " + name) + } + selected.insert(reference) + } + return selected + } + + private static func removing( + _ request: UpdateRequest, from declaration: Declaration, ledger: ResolvedLedger, + store: StateStore, roots: [String: URL], selectedInstructionReferences: Set? + ) throws -> Declaration { + var result = declaration + let names = Set(request.names) + let kinds = request.kinds ?? Set(DeclaredComponentKind.allCases) + var instructionReferences = Set() + if let selectedInstructionReferences { + instructionReferences = selectedInstructionReferences + } else if kinds.contains(.instructions), let identities = request.selectedIdentities { + let sections = declaration.components.flatMap { component -> [SectionDeclaration] in + guard case .instructions(let selection) = component else { return [] } + return selection.sectionReferences + + selection.prompts.flatMap { $0.prompt.sectionReferences } + } + for section in sections { + let source: String + if let alias = section.source, alias != "." { + guard let declaration = declaration.sources[alias] else { continue } + source = try declaration.identity(environment: store.environment) + } else { + source = "local:" + store.environment.projectDirectory.resolvingSymlinksInPath().path + } + if try ledger.components.values.contains(where: { c in + try c.kind == "instructions" && c.name == section.name + && ledger.sourceIdentity(c.source, roots: roots) == source + && identities.contains( + LedgerImpact.identity(c, ledger: ledger, roots: roots)) + }) { + instructionReferences.insert(section.reference) + } + } + } else if kinds.contains(.instructions) { + instructionReferences = try Self.selectedInstructionReferences(names, in: declaration) + } + result.components = declaration.components.compactMap { component in + switch component { + case .skills(let alias, var selection) where kinds.contains(.skills): + if let identities = request.selectedIdentities { + let source = try? declaration.sources[alias]?.identity(environment: store.environment) + let matches = ledger.components.values.contains { c in + c.kind == "skills" + && (try? ledger.sourceIdentity(c.source, roots: roots)) == source + && (try? LedgerImpact.identity(c, ledger: ledger, roots: roots)).map( + identities.contains) == true + } + if !matches { return component } + } + if case .all = selection.select { + selection.exclude = Array(Set(selection.exclude ?? []).union(names)).sorted() + } else if case .names(let selected) = selection.select { + selection.select = .names(selected.filter { !names.contains($0) }) + } + if request.agents == nil { + selection.overrides = selection.overrides?.filter { !names.contains($0.key) } + } + if let agents = request.agents { + selection = { + var original = selection + for name in names { + let current = ledger.components.values.first { + $0.kind == "skills" && PathSafety.sanitizeName($0.name) == name + && (try? ledger.sourceIdentity($0.source, roots: roots)) + == (try? declaration.sources[alias]?.identity(environment: store.environment)) + } + var overrides = original.overrides ?? [:] + overrides[name] = SkillOverride( + agents: current?.recipients.filter { !agents.contains($0) } ?? [], + mode: original.overrides?[name]?.mode) + original.overrides = overrides + } + return original + }() + if let prior = declaration.components.first(where: { + if case .skills(let a, _) = $0 { a == alias } else { false } + }), case .skills(_, let original) = prior { + selection.select = original.select + selection.exclude = original.exclude + } + } + return .skills(source: alias, selection) + case .instructions(var selection) where kinds.contains(.instructions): + selection.sectionReferences.removeAll { + instructionReferences.contains($0.reference) + } + for index in selection.prompts.indices { + selection.prompts[index].prompt.sectionReferences.removeAll { + instructionReferences.contains($0.reference) + } + } + selection.prompts.removeAll { $0.prompt.sectionReferences.isEmpty } + if let agents = request.agents { selection.agents = agents } + return .instructions(selection) + default: + guard kinds.contains(component.kind), names.contains(component.name ?? "") else { + return component + } + if let agents = request.agents { + let recipients = (component.selectedAgents ?? declaration.defaultAgents).filter { + !agents.contains($0) + } + return component.replacingAgents(recipients) + } + return nil + } + } + return result + } +} + +extension ComponentDeclaration { + fileprivate var selectedAgents: [AgentID]? { + switch self { + case .skills(_, let s): s.agents + case .instructions(let s): s.agents + case .mcpServer(_, _, let a, _, _, _), .hook(_, _, _, _, _, let a, _, _), + .subagent(_, _, _, _, _, let a, _, _), .command(_, _, _, _, let a, _, _), + .lspServer(_, _, _, _, let a, _, _), .permissions(_, _, let a, _, _), + .ignore(_, _, _, let a, _, _), .plugin(_, _, _, _, _, _, let a, _, _): + a + } + } + + fileprivate func replacingAgents(_ agents: [AgentID]) -> ComponentDeclaration { + switch self { + case .skills(let source, var value): + value.agents = agents + return .skills(source: source, value) + case .instructions(var value): + value.agents = agents + return .instructions(value) + case .mcpServer(let n, let t, _, let c, let v, let registry): + return .mcpServer( + name: n, transport: t, agents: agents, condition: c, native: v, registry: registry) + case .hook(let n, let e, let r, let m, let t, _, let c, let v): + return .hook( + name: n, event: e, run: r, matcher: m, timeoutSeconds: t, agents: agents, condition: c, + native: v) + case .subagent(let n, let d, let p, let m, let t, _, let c, let v): + return .subagent( + name: n, description: d, prompt: p, model: m, tools: t, agents: agents, condition: c, + native: v) + case .command(let n, let d, let p, let args, _, let c, let v): + return .command( + name: n, description: d, prompt: p, parameters: args, agents: agents, condition: c, + native: v) + case .lspServer(let n, let r, let l, let o, _, let c, let v): + return .lspServer( + name: n, run: r, languages: l, initializationOptions: o, agents: agents, condition: c, + native: v) + case .permissions(let n, let r, _, let c, let v): + return .permissions(name: n, rules: r, agents: agents, condition: c, native: v) + case .ignore(let n, let p, let u, _, let c, let v): + return .ignore(name: n, patterns: p, purpose: u, agents: agents, condition: c, native: v) + case .plugin(let n, let p, let s, let m, let select, let exclude, _, let c, let v): + return .plugin( + name: n, path: p, source: s, mode: m, select: select, exclude: exclude, agents: agents, + condition: c, native: v) + } + } } diff --git a/Sources/AgentsUpdates/UpdateReadLocations.swift b/Sources/AgentsUpdates/UpdateReadLocations.swift new file mode 100644 index 0000000..4e4dde3 --- /dev/null +++ b/Sources/AgentsUpdates/UpdateReadLocations.swift @@ -0,0 +1,136 @@ +import AgentsCore +import AgentsInstructions +import Components +import Foundation + +extension UpdateOperations { + /// Only durable inputs are exposed; replay workspaces and borrowed source URLs stay private. + static func readLocations( + declarations: [Declaration], ledgers: [ResolvedLedger], store: StateStore, + roots admittedRoots: [String: URL]? = nil + ) throws -> [URL] { + var paths = [store.declarationURL, store.resolvedURL, store.watchURL] + let scopeRoot = store.scope == .user ? store.directory : store.environment.projectDirectory + for declaration in declarations { + for source in declaration.sources.values where source.kind == .local { + paths.append(source.localURL(environment: source.environment?.runtime ?? store.environment)) + } + func resourceRoot(_ alias: String?) throws -> URL? { + guard let alias, alias != "." else { return scopeRoot } + guard let source = declaration.sources[alias], source.kind == .local else { return nil } + return try PathSafety.resolvedChild( + base: source.localURL(environment: store.environment), subpath: source.path ?? ".") + } + func collect(_ components: [ComponentDeclaration]) throws { + for component in components { + for resource in component.resources { + if let root = try resourceRoot(resource.source) { + paths.append(try PathSafety.resolvedChild(base: root, subpath: resource.path)) + } + } + if case .skills(let alias, let selection) = component, let root = try resourceRoot(alias) + { + // Discovery reads the root even when it finds no selected members. + paths.append(try PathSafety.resolvedChild(base: root, subpath: selection.path ?? ".")) + } + guard case .instructions(let instructions) = component else { continue } + let sections = + instructions.sectionReferences + + instructions.prompts.flatMap { $0.prompt.sectionReferences } + let ownNames = sections.filter { $0.source == nil || $0.source == "." }.map(\.name) + if store.scope == .project { + paths += InstructionOperations.ownReadLocations( + names: ownNames, environment: store.environment) + } + let appendRoot = + store.scope == .user + ? store.environment.homeDirectory : store.environment.projectDirectory + for prompt in instructions.prompts { + if let appendix = prompt.prompt.append { + paths.append(try PathSafety.resolvedChild(base: appendRoot, subpath: appendix)) + } + } + } + } + try collect(declaration.components) + for group in declaration.groups { try collect(group.components) } + } + let roots = admittedRoots ?? store.ledgerRoots + for ledger in ledgers { + func localRoot(_ id: String) throws -> URL? { + guard let source = ledger.sources[id], source.kind == .local else { return nil } + if let location = source.location { return try location.resolve(roots: roots) } + if let container = source.container { return try localRoot(container) } + return nil + } + let explicitSources = Set(ledger.sourceUses.map(\.source)) + for (id, source) in ledger.sources { + if let location = source.location { + let root = try location.resolve(roots: roots) + // The linker's implicit live snapshot supplies provenance, not a whole-tree read. + // Explicit local declarations above retain their independent whole-tree interests. + let implicit = + source.kind == .local && source.revision == "live" + && source.container == nil + && root.resolvingSymlinksInPath().path == scopeRoot.resolvingSymlinksInPath().path + if !implicit || explicitSources.contains(id) { paths.append(root) } + } + } + for occurrence in ledger.occurrences { + if let root = try localRoot(occurrence.declaringSource) { + paths.append(try PathSafety.resolvedChild(base: root, subpath: occurrence.manifestPath)) + } + if let plugin = occurrence.pluginExpansion, let root = try localRoot(plugin.source) { + paths.append(try PathSafety.resolvedChild(base: root, subpath: plugin.containerRoot)) + paths.append(try PathSafety.resolvedChild(base: root, subpath: plugin.document)) + } + } + for group in ledger.groups { + if let root = try localRoot(group.source) { + let directory = try PathSafety.resolvedChild(base: root, subpath: group.root) + paths.append( + directory.appendingPathComponent( + directory.lastPathComponent == ".agent" ? "agents.yaml" : ".agent/agents.yaml")) + } + } + for component in ledger.components.values { + if component.kind == DeclaredComponentKind.skills.rawValue, + let root = try localRoot(component.source) + { + paths.append( + try PathSafety.resolvedChild( + base: root, subpath: component.containerRoot ?? component.root)) + } + if let value = component.payload.object?["localAppend"] { + paths.append(try LedgerLocation(ledgerValue: value).resolve(roots: roots)) + } + } + for deployment in ledger.deployments { + paths.append(try deployment.target.resolve(roots: roots)) + } + for (id, resource) in ledger.resources { + paths.append( + try ArtifactAggregation.resourceDestination( + id, ledger: ledger, store: store, roots: roots)) + if let root = try localRoot(resource.source) { + let selected = try PathSafety.resolvedChild(base: root, subpath: resource.path) + paths.append(selected) + // Support directories also contain structural ancestors. Only actual entries and + // link targets are recursive interests; those ancestors are not source-tree reads. + for entry in resource.support where entry.kind != .directory { + paths.append(try PathSafety.resolvedChild(base: root, subpath: entry.path)) + } + let links = + try resource.entries.filter { $0.kind == .symlink }.map { + try PathSafety.resolvedChild(base: selected, subpath: $0.path) + } + + resource.support.filter { $0.kind == .symlink }.map { + try PathSafety.resolvedChild(base: root, subpath: $0.path) + } + paths += links.map { $0.resolvingSymlinksInPath() } + } + } + } + return Array(Set(paths.map(\.standardizedFileURL))).sorted { $0.path < $1.path } + } +} diff --git a/Sources/AgentsUpdates/UpdateReporting.swift b/Sources/AgentsUpdates/UpdateReporting.swift new file mode 100644 index 0000000..b8f99df --- /dev/null +++ b/Sources/AgentsUpdates/UpdateReporting.swift @@ -0,0 +1,226 @@ +import AgentsCore +import AgentsInstructions +import AgentsSkills +import Components +import Foundation + +/// Public domain reports expose owned content. Shared native documents never enter these diffs. +enum UpdateReporting { + static func skills( + previous: ResolvedLedger, next: ResolvedLedger, resources: [String: URL], + changes: [AggregatedChange], store: StateStore, roots: [String: URL], lockMissing: Bool, + included: Bool, + selectedIdentities: Set? = nil, names: Set = [] + ) throws -> [UpdateResult] { + guard included else { return [] } + struct Item { + let name: String + var record: LockedSkill + let resource: String + } + func items(_ ledger: ResolvedLedger) throws -> [String: Item] { + var result: [String: Item] = [:] + for component in ledger.components.values + where component.kind == "skills" && !component.recipients.isEmpty { + if let selectedIdentities, + !selectedIdentities.contains( + try LedgerImpact.identity(component, ledger: ledger, roots: roots)) + { + continue + } + guard names.isEmpty || names.contains(PathSafety.sanitizeName(component.name)) else { + continue + } + guard let id = component.resources.first, let resource = ledger.resources[id] else { + continue + } + let source = try ledger.sourceIdentity(component.source, roots: roots) + let producer = try ledger.sourceIdentity( + component.declaringSource, roots: roots) + let identity = try ResolvedLedgerCodec.digest( + LedgerValue(object: [ + "producer": LedgerValue(producer), "source": .init(source), + "root": .init(component.root), + "group": component.group.map { .init($0) } ?? .init(), + "name": .init(PathSafety.sanitizeName(component.name)), + "path": .init(resource.path), + "conditions": .init(try ResolvedLedgerCodec.digest(component.conditions)), + ])) + let mode = + component.payload.object?["mode"]?.text.flatMap(InstallMode.init(rawValue:)) ?? .copy + var record = + result[identity]?.record + ?? LockedSkill( + source: source, revision: component.revision, + version: component.version, artifact: resource.artifact, path: resource.path, + hash: mode == .edit ? nil : resource.hash, installs: [:]) + for agent in component.recipients { record.installs[agent.rawValue] = mode } + result[identity] = Item( + name: PathSafety.sanitizeName(component.name), record: record, resource: id) + } + return result + } + let before = try items(previous) + let after = try items(next) + return try Set(before.keys).union(after.keys).sorted().map { identity in + let old = before[identity]?.record + let new = after[identity]?.record + let name = after[identity]?.name ?? before[identity]!.name + let membership = Set((old?.installs ?? [:]).keys).union((new?.installs ?? [:]).keys).sorted() + .compactMap { raw -> SkillMembershipChange? in + guard let agent = AgentID(rawValue: raw) else { return nil } + let path = SkillLifecycle.target(name: name, agent: agent, store: store).path + return SkillMembershipChange( + agent: agent, path: path, + before: old?.installs[raw].map { .installed(mode: $0) } ?? .absent, + after: new?.installs[raw].map { .installed(mode: $0) } ?? .absent) + } + let installed = (new?.installs ?? [:]).keys.sorted().compactMap { raw -> InstallResult? in + guard let agent = AgentID(rawValue: raw), let mode = new?.installs[raw] else { return nil } + return InstallResult( + skill: name, agent: agent, scope: store.scope, mode: mode, + path: SkillLifecycle.target(name: name, agent: agent, store: store).path) + } + let content = after[identity].flatMap { resources[$0.resource] } + var diffs: [SkillFileChange] = [] + let physicalMembers = Dictionary(grouping: membership) { + InstructionLocations.physical(URL(fileURLWithPath: $0.path)).path + } + for target in physicalMembers.keys.sorted() { + let members = physicalMembers[target]! + let retained = members.contains { new?.installs[$0.agent.rawValue] != nil } + let oldFiles = try entries(URL(fileURLWithPath: target)) + var newFiles = try retained ? content.map(entries) ?? [:] : [:] + if !retained, changes.contains(where: { $0.url.path == target && !$0.changed }) { + newFiles = oldFiles + } + if let change = changes.first(where: { $0.url.path == target }), + let destination = change.afterLink + { + newFiles["."] = .symbolicLink( + FileTransaction.linkDestination( + destination, parent: URL(fileURLWithPath: target).deletingLastPathComponent(), + store: store)) + } + for path in Set(oldFiles.keys).union(newFiles.keys).sorted() + where oldFiles[path] != newFiles[path] { + diffs.append( + SkillFileChange( + path: path == "." + ? target : URL(fileURLWithPath: target).appendingPathComponent(path).path, + 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, + oldRevision: old?.revision, newRevision: new?.revision, oldVersion: old?.version, + newVersion: new?.version, + oldHash: old?.hash, newHash: new?.hash, lockMissing: lockMissing, membership: membership, + changes: diffs, installed: installed) + }.sorted { + ($0.skill, $0.sourceIdentity, $0.membership.first?.path ?? "") < ( + $1.skill, $1.sourceIdentity, $1.membership.first?.path ?? "" + ) + } + } + + static func instructions( + before: LockedInstructions, after: LockedInstructions, changes: [AggregatedChange], + ledger: ResolvedLedger, artifacts: [ReplayedArtifact], + lockMissing: Bool, included: Bool, store: StateStore, stateChanged: Bool, + conflicts: [String] + ) throws -> InstructionUpdateReport { + guard included else { + return InstructionUpdateReport( + sections: [], targets: [], changedPrompts: [], lockMissing: lockMissing, hasChanges: false) + } + func identity(_ section: LockedSection) -> [String] { + [section.source, section.name, section.path] + } + let identities = Set((before.sections + after.sections).map(identity)) + .sorted { $0.lexicographicallyPrecedes($1) } + let sectionChanges = identities.compactMap { + id -> InstructionSectionChange? in + let old = before.sections.first { identity($0) == id } + let new = after.sections.first { identity($0) == id } + return old == new ? nil : InstructionSectionChange(before: old, after: new) + } + let targets = try changes.filter { !$0.native && $0.deployment.route != "agents/skill@1" }.map { + change in + let key = InstructionLocations.key(for: change.url, store: store) + let old = before.targets[key] + let drift = try old.map { old -> InstructionDrift in + guard let bytes = change.before else { return .missing } + if old.import != nil { + return try Instructions.detectDrift(in: bytes, lockedBlockHash: old.blockHash) + } + return ("sha256:" + FileHash.sha256Hex(data: bytes)) == old.blockHash ? .clean : .drifted + } + return InstructionTargetChange( + target: key, url: change.url, + before: try change.deployment.ownership == .importBlock + ? InstructionTargets.ownedImportBytes(change.before) : change.before, + after: try change.deployment.ownership == .importBlock + ? InstructionTargets.ownedImportBytes(change.after) : change.after, + beforeAgents: old?.agents, + afterAgents: after.targets[key]?.agents ?? [], + drift: drift, + foreign: change.instructionForeign + ?? (change.deployment.ownership != .importBlock + && change.before.map { $0 != change.after && !Instructions.isOwned($0) } ?? false)) + } + let prompts = Set(before.chatgpt.keys).union(after.chatgpt.keys).filter { + let old = before.chatgpt[$0] + let new = after.chatgpt[$0] + return old?.append != new?.append + || old?.sections.map { identity($0) + [$0.hash] } + != new?.sections.map { identity($0) + [$0.hash] } + }.sorted() + let advisories = + after.targets.values.contains(where: { $0.agents.contains(.antigravity) }) + ? [ + "Antigravity shares a 20,000-token budget across active global and always-on rules. " + + "When exceeded, the largest rules may be loaded as file pointers." + ] : [] + var outputs = changes.flatMap { change -> [InstructionBuildOutput] in + guard !change.native, InstructionLocations.isInstructionFormat(change.deployment.route), + let content = change.after + else { return [] } + let key = InstructionLocations.key(for: change.url, store: store) + return (after.targets[key]?.agents ?? []).map { agent in + InstructionBuildOutput( + id: "local:" + agent.rawValue + ":" + key, recipient: .local(agent), + displayName: key, fileURL: change.url, content: content) + } + } + let copyProducts = ledger.lowerings.compactMap { lowering in + lowering.instructionCopyRecipient.map { (lowering.id, $0) } + } + if !copyProducts.isEmpty { + let rendered = Dictionary(uniqueKeysWithValues: artifacts.map { ($0.name, $0) }) + for (id, recipient) in copyProducts { + guard let content = rendered[id]?.bytes else { + throw CoreError.invalidState("missing rendered instruction copy product") + } + outputs.append( + InstructionBuildOutput( + id: id, recipient: recipient, displayName: recipient.displayName, fileURL: nil, + content: content)) + } + } + return InstructionUpdateReport( + sections: sectionChanges, targets: targets, changedPrompts: prompts, + lockMissing: lockMissing, + hasChanges: stateChanged || before != after || targets.contains(where: \.changed), + outputs: outputs, advisories: advisories, conflicts: conflicts.sorted()) + } + + private static func entries(_ root: URL) throws -> [String: SkillFileEntry] { + try SkillLifecycle.entries(root) + } +} diff --git a/Sources/AgentsUpdates/UpdateRequest.swift b/Sources/AgentsUpdates/UpdateRequest.swift new file mode 100644 index 0000000..b973ddb --- /dev/null +++ b/Sources/AgentsUpdates/UpdateRequest.swift @@ -0,0 +1,71 @@ +import AgentsCore +import AgentsManifest +import Foundation + +public enum UpdateOperation: Sendable { + case update + case restore + case edit([ManifestEdit]) + case declaration(Declaration) + case remove +} + +/// Selection constrains application and protects the recorded semantics of every other domain. +public struct UpdateRequest: Sendable { + package var marketplaceChange: MarketplaceChange? + var marketplaceGraphChange: MarketplaceGraphChange? + var marketplaceFrozenProducers: [String: URL] = [:] + var deployPendingMarketplace = false + package var catalogPreparation: CatalogPreparation? + package var capturedAddition: CapturedAddition? + package var importPreparation: ImportPreparation? + var bundleInstallation: BundleInstallation? + package var expectedDiscoveryFingerprint: String? + package var automaticSkill: (source: String, name: String)? + var instructionAddition: InstructionAddition? + package var selectedIdentities: Set? + private(set) var declarationYAML: [UInt8]? + public var selections: [ComponentSelection] + public var operation: UpdateOperation { + didSet { declarationYAML = nil } + } + public var kinds: Set? + public var names: [String] + /// Recipient removal for skills and native components; replacement recipients for instruction removal. + public var agents: [AgentID]? + public var replace: Bool + public var expectedDeclarationDigest: String? + public var changingAccess: Bool + /// Restricts restore to existing scope state, local producers, and admitted exact acquisitions. + public var offline: Bool + + var restoresOffline: Bool { + if case .restore = operation { return offline || deployPendingMarketplace } + return false + } + + public init( + operation: UpdateOperation = .update, kinds: Set? = nil, + names: [String] = [], selections: [ComponentSelection] = [], agents: [AgentID]? = nil, + replace: Bool = false, + changingAccess: Bool = false, expectedDeclarationDigest: String? = nil, offline: Bool = false + ) { + self.selections = selections + self.operation = operation + self.kinds = kinds + self.names = names + self.agents = agents + self.replace = replace + self.changingAccess = changingAccess + self.offline = offline + self.expectedDeclarationDigest = expectedDeclarationDigest + } + + /// Previews and applies the complete UTF-8 declaration, preserving its exact bytes. + /// Supply the digest of the loaded document, or `"absent"` when the scope has no declaration. + /// Preview and preparation validate the YAML and its sources before publication. + public init(declarationYAML: Data, expectedDeclarationDigest: String) { + self.init(operation: .edit([]), expectedDeclarationDigest: expectedDeclarationDigest) + self.declarationYAML = Array(declarationYAML.prefix(ManifestLimits.Input.bytes + 1)) + } +} diff --git a/Sources/AgentsUpdates/WatchCompletion.swift b/Sources/AgentsUpdates/WatchCompletion.swift new file mode 100644 index 0000000..fd54d0e --- /dev/null +++ b/Sources/AgentsUpdates/WatchCompletion.swift @@ -0,0 +1,28 @@ +import AgentsCore +import AgentsSkills + +extension UpdateOperations { + /// Acknowledges exactly the displayed content in its captured scope and environment. + public static func performWatch( + _ status: WatchStatus, + operations: WatchOperations = SkillOperations.watchOperations() + ) -> UpdateCompletion { + performWatch(operations.previewSeen(status), operations: operations) + } + + /// Uses WatchOperations' single subscription writer, then reports its actual outer terminal. + public static func performWatch( + _ preview: WatchMutationPreview, + operations: WatchOperations = SkillOperations.watchOperations() + ) -> UpdateCompletion { + let outcome = TransactionOutcome() + var recovered = false + let result = Result { + do { return try operations.apply(preview, outcome: outcome) } catch { + if case CoreError.transactionRecovered = error { recovered = true } + throw error + } + } + return completion(result, outcome: outcome, recovered: recovered, store: preview.store) + } +} diff --git a/Sources/CPlatform/CPlatform.c b/Sources/CPlatform/CPlatform.c new file mode 100644 index 0000000..09be82c --- /dev/null +++ b/Sources/CPlatform/CPlatform.c @@ -0,0 +1,513 @@ +#define _GNU_SOURCE 1 +#include "CPlatform.h" + +#include +#include +#include +#include +#include +#include + +#if defined(__APPLE__) +#include +#include +#else +#include +#include +#endif + +bool platform_zip_member(const unsigned char *input, size_t inputSize, unsigned int method, + unsigned char *output, size_t outputSize, unsigned int expectedCRC) { + if (inputSize > UINT_MAX || outputSize > UINT_MAX) return false; + if (method == 0) { + if (inputSize != outputSize) return false; + if (outputSize) memcpy(output, input, outputSize); + } else if (method == 8) { + unsigned char empty; + z_stream stream = {0}; + stream.next_in = (Bytef *)input; + stream.avail_in = (uInt)inputSize; + stream.next_out = outputSize ? output : ∅ + stream.avail_out = outputSize ? (uInt)outputSize : 1; + if (inflateInit2(&stream, -MAX_WBITS) != Z_OK) return false; + int status = inflate(&stream, Z_FINISH); + bool valid = status == Z_STREAM_END && stream.total_in == inputSize && + stream.total_out == outputSize; + inflateEnd(&stream); + if (!valid) return false; + } else { + return false; + } + return crc32(0, output, (uInt)outputSize) == expectedCRC; +} + +int platform_flock(int descriptor, int operation) { + return flock(descriptor, operation); +} + +void platform_raise_open_file_limit(void) { + struct rlimit limit; + if (getrlimit(RLIMIT_NOFILE, &limit) != 0 || limit.rlim_cur >= limit.rlim_max) return; + rlim_t ceiling = limit.rlim_max; +#if defined(__APPLE__) + int maximum; + size_t size = sizeof(maximum); + if (sysctlbyname("kern.maxfilesperproc", &maximum, &size, NULL, 0) != 0 || + size != sizeof(maximum) || maximum <= 0) return; + if ((rlim_t)maximum < ceiling) ceiling = (rlim_t)maximum; +#endif + if (ceiling == RLIM_INFINITY || ceiling <= limit.rlim_cur) return; + limit.rlim_cur = ceiling; + (void)setrlimit(RLIMIT_NOFILE, &limit); +} + +int platform_access(int directory, const char *name, int mode) { + return faccessat(directory, name, mode, AT_EACCESS); +} + +const char *platform_entry_name(const struct dirent *entry) { + return entry->d_name; +} + +bool platform_system_alias(const char *name) { +#if defined(__APPLE__) + return strcmp(name, "var") == 0 || strcmp(name, "tmp") == 0 || strcmp(name, "etc") == 0; +#else + (void)name; + return false; +#endif +} + +int platform_exchange(int sourceDirectory, const char *name, int destinationDirectory, const char *destination) { +#if defined(__APPLE__) + return renameatx_np(sourceDirectory, name, destinationDirectory, destination, RENAME_SWAP); +#else + // Call the kernel primitive without relying on the libc Swift overlay. + return (int)syscall(SYS_renameat2, sourceDirectory, name, destinationDirectory, destination, 2 /* RENAME_EXCHANGE */); +#endif +} + +int platform_rename_exclusive(int sourceDirectory, const char *name, int destinationDirectory, const char *destination) { +#if defined(__APPLE__) + return renameatx_np(sourceDirectory, name, destinationDirectory, destination, RENAME_EXCL); +#else + return (int)syscall(SYS_renameat2, sourceDirectory, name, destinationDirectory, destination, 1 /* RENAME_NOREPLACE */); +#endif +} + +bool platform_same_generation(const struct stat *first, const struct stat *second) { +#if defined(__APPLE__) +#define MTIME st_mtimespec +#define CTIME st_ctimespec +#else +#define MTIME st_mtim +#define CTIME st_ctim +#endif + return first->st_dev == second->st_dev && first->st_ino == second->st_ino && + first->st_mode == second->st_mode && first->st_size == second->st_size && + first->MTIME.tv_sec == second->MTIME.tv_sec && first->MTIME.tv_nsec == second->MTIME.tv_nsec && + first->CTIME.tv_sec == second->CTIME.tv_sec && first->CTIME.tv_nsec == second->CTIME.tv_nsec; +#undef MTIME +#undef CTIME +} + +int platform_directory_birthtime(int descriptor, int64_t *seconds, int64_t *nanoseconds) { +#if defined(__APPLE__) + struct stat info; + if (fstat(descriptor, &info) != 0) return -1; + *seconds = info.st_birthtimespec.tv_sec; + *nanoseconds = info.st_birthtimespec.tv_nsec; +#else + struct statx info; + if (syscall(SYS_statx, descriptor, "", AT_EMPTY_PATH, STATX_BTIME, &info) != 0) return -1; + if (!(info.stx_mask & STATX_BTIME)) { errno = ENOTSUP; return -1; } + *seconds = info.stx_btime.tv_sec; + *nanoseconds = info.stx_btime.tv_nsec; +#endif + return 0; +} + +int platform_sync(int descriptor) { + int result; + do { result = fsync(descriptor); } while (result < 0 && errno == EINTR); +#if defined(__APPLE__) + if (result == 0) { + do { result = fcntl(descriptor, F_FULLFSYNC); } while (result < 0 && errno == EINTR); + } +#endif + return result; +} + +int platform_copy_data(int source, int destination) { +#if defined(__APPLE__) + return fcopyfile(source, destination, NULL, COPYFILE_DATA); +#else + char buffer[65536]; + for (;;) { + ssize_t count; + do { count = read(source, buffer, sizeof(buffer)); } while (count < 0 && errno == EINTR); + if (count < 0) return -1; + if (count == 0) return 0; + ssize_t offset = 0; + while (offset < count) { + ssize_t written = write(destination, buffer + offset, (size_t)(count - offset)); + if (written < 0 && errno == EINTR) continue; + if (written <= 0) { + if (written == 0) errno = EIO; + return -1; + } + offset += written; + } + } +#endif +} + +#if !defined(__APPLE__) +// POSIX ACLs are Linux system.posix_acl_* xattrs. Copy them along with all other +// attributes, without requiring libacl or an external executable. +static int copy_xattrs(int source, int destination, const char *sourceLink, + const char *destinationLink) { + ssize_t size = sourceLink ? llistxattr(sourceLink, NULL, 0) : flistxattr(source, NULL, 0); + if (size < 0) return errno == ENOTSUP ? 0 : -1; + char *names = malloc(size ? (size_t)size : 1); + if (!names) { errno = ENOMEM; return -1; } + ssize_t count = sourceLink ? llistxattr(sourceLink, names, (size_t)size) + : flistxattr(source, names, (size_t)size); + if (count < 0 || count > size) { + if (count > size) errno = ERANGE; + free(names); + return -1; + } + // A new entry may inherit a default ACL from its parent. Remove destination + // attributes absent from the source before restoring the source's metadata. + ssize_t targetSize = destinationLink ? llistxattr(destinationLink, NULL, 0) + : flistxattr(destination, NULL, 0); + if (targetSize < 0) { free(names); return -1; } + char *targetNames = malloc(targetSize ? (size_t)targetSize : 1); + if (!targetNames) { free(names); errno = ENOMEM; return -1; } + ssize_t targetCount = destinationLink ? llistxattr(destinationLink, targetNames, (size_t)targetSize) + : flistxattr(destination, targetNames, (size_t)targetSize); + if (targetCount < 0 || targetCount > targetSize) { + if (targetCount > targetSize) errno = ERANGE; + free(targetNames); + free(names); + return -1; + } + int result = 0; + for (ssize_t offset = 0; offset < targetCount;) { + const char *name = targetNames + offset; + offset += (ssize_t)strlen(name) + 1; + bool found = false; + for (ssize_t i = 0; i < count; i += (ssize_t)strlen(names + i) + 1) { + if (strcmp(name, names + i) == 0) { found = true; break; } + } + if (!found) { + result = destinationLink ? lremovexattr(destinationLink, name) + : fremovexattr(destination, name); + if (result < 0) break; + } + } + free(targetNames); + if (result < 0) { free(names); return -1; } + // Setting an access ACL may make the destination read-only. Install it only + // after every other xattr, while the staging file still has owner write access. + for (int pass = 0; pass < 2 && result == 0; ++pass) { + for (ssize_t offset = 0; offset < count;) { + const char *name = names + offset; + offset += (ssize_t)strlen(name) + 1; + bool accessACL = strcmp(name, "system.posix_acl_access") == 0; + if (accessACL != (pass == 1)) continue; + ssize_t length = sourceLink ? lgetxattr(sourceLink, name, NULL, 0) + : fgetxattr(source, name, NULL, 0); + if (length < 0) { result = -1; break; } + void *value = malloc(length ? (size_t)length : 1); + if (!value) { errno = ENOMEM; result = -1; break; } + ssize_t readCount = sourceLink ? lgetxattr(sourceLink, name, value, (size_t)length) + : fgetxattr(source, name, value, (size_t)length); + if (readCount < 0 || readCount > length) { + if (readCount > length) errno = ERANGE; + free(value); + result = -1; + break; + } + result = destinationLink ? lsetxattr(destinationLink, name, value, (size_t)readCount, 0) + : fsetxattr(destination, name, value, (size_t)readCount, 0); + free(value); + if (result < 0) break; + } + } + int error = errno; + free(names); + errno = error; + return result; +} +#endif + +int platform_copy_metadata(int source, int destination, mode_t mode) { +#if defined(__APPLE__) + if (fcopyfile(source, destination, NULL, COPYFILE_METADATA) < 0) return -1; +#else + struct stat info; + if (fstat(source, &info) < 0) return -1; + // Inherited default ACLs can restrict even a freshly created staging entry. + if (fchmod(destination, S_ISDIR(mode) ? 0700 : 0600) < 0) return -1; + if (copy_xattrs(source, destination, NULL, NULL) < 0) return -1; + const struct timespec times[2] = {info.st_atim, info.st_mtim}; + if (futimens(destination, times) < 0) return -1; +#endif + if (fchmod(destination, mode & 07777) < 0) return -1; + return platform_sync(destination); +} + +int platform_copy_link_metadata(int sourceDirectory, const char *source, + int destinationDirectory, const char *destination) { +#if defined(__APPLE__) + int origin = openat(sourceDirectory, source, O_RDONLY | O_SYMLINK | O_CLOEXEC); + if (origin < 0) return -1; + int target = openat(destinationDirectory, destination, O_RDONLY | O_SYMLINK | O_CLOEXEC); + int result = -1; + struct stat info; + if (target >= 0 && fstat(origin, &info) == 0) { + result = platform_copy_metadata(origin, target, info.st_mode); + } + int error = errno; + close(origin); + if (target >= 0) close(target); + errno = error; + return result; +#else + // /proc/self/fd keeps both parent paths anchored to the pinned descriptors; + // l*xattr and AT_SYMLINK_NOFOLLOW operate on the links, never their targets. + char origin[64 + NAME_MAX], target[64 + NAME_MAX]; + int n = snprintf(origin, sizeof(origin), "/proc/self/fd/%d/%s", sourceDirectory, source); + int m = snprintf(target, sizeof(target), "/proc/self/fd/%d/%s", destinationDirectory, destination); + if (n < 0 || m < 0 || (size_t)n >= sizeof(origin) || (size_t)m >= sizeof(target)) { + errno = ENAMETOOLONG; + return -1; + } + struct stat info; + if (fstatat(sourceDirectory, source, &info, AT_SYMLINK_NOFOLLOW) < 0) return -1; + if (!S_ISLNK(info.st_mode)) { errno = EINVAL; return -1; } + if (copy_xattrs(-1, -1, origin, target) < 0) return -1; + const struct timespec times[2] = {info.st_atim, info.st_mtim}; + return utimensat(destinationDirectory, destination, times, AT_SYMLINK_NOFOLLOW); +#endif +} + +void platform_dispose_file_access(struct platform_file_access *value) { + free(value->acl); + free(value->default_acl); + memset(value, 0, sizeof(*value)); +} + +static unsigned int access_permissions(unsigned int permissions) { + return ((permissions & 4) ? PLATFORM_ACCESS_EXTERNAL_READ : 0) | + ((permissions & 2) ? PLATFORM_ACCESS_EXTERNAL_WRITE : 0) | + ((permissions & 1) ? PLATFORM_ACCESS_EXTERNAL_SEARCH : 0); +} + +#if defined(__APPLE__) +static int read_access_acl(int descriptor, struct platform_file_access *value) { + acl_t acl = acl_get_fd_np(descriptor, ACL_TYPE_EXTENDED); + // Darwin reports ENOENT for an absent extended ACL even on a valid open fd. + // fstat brackets this read; unsupported/denied ACL queries still fail closed. + if (!acl) return errno == ENOENT ? 0 : -1; + int result = -1; + ssize_t size = acl_size(acl); + if (size < 0) goto done; + // acl_copy_ext uses the portable external representation, including ordered + // qualifiers, permissions and inheritance flags, without resolving UUIDs. + value->acl = calloc(size ? (size_t)size : 1, 1); + if (!value->acl) { errno = ENOMEM; goto done; } + ssize_t count = acl_copy_ext(value->acl, acl, size); + if (count < 0) goto done; + value->acl_size = (size_t)count; + acl_entry_t entry; + int status = acl_get_entry(acl, ACL_FIRST_ENTRY, &entry); + while (status == 0) { + acl_tag_t tag; + acl_flagset_t flags; + acl_permset_mask_t permissions; + if (acl_get_tag_type(entry, &tag) < 0 || acl_get_flagset_np(entry, &flags) < 0 || + acl_get_permset_mask_np(entry, &permissions) < 0) goto done; + if (tag != ACL_EXTENDED_ALLOW && tag != ACL_EXTENDED_DENY) { errno = ENOTSUP; goto done; } + const acl_permset_mask_t known = ACL_READ_DATA | ACL_WRITE_DATA | ACL_EXECUTE | + ACL_DELETE | ACL_APPEND_DATA | ACL_DELETE_CHILD | ACL_READ_ATTRIBUTES | + ACL_WRITE_ATTRIBUTES | ACL_READ_EXTATTRIBUTES | ACL_WRITE_EXTATTRIBUTES | + ACL_READ_SECURITY | ACL_WRITE_SECURITY | ACL_CHANGE_OWNER | ACL_SYNCHRONIZE; + if (permissions & ~known) { errno = ENOTSUP; goto done; } + int inheritOnly = acl_get_flag_np(flags, ACL_ENTRY_ONLY_INHERIT); + if (inheritOnly < 0) goto done; + if (!inheritOnly) { + const acl_permset_mask_t read = ACL_READ_DATA; + const acl_permset_mask_t write = ACL_WRITE_DATA | ACL_APPEND_DATA; + const acl_permset_mask_t control = ACL_DELETE | ACL_DELETE_CHILD | + ACL_WRITE_SECURITY | ACL_CHANGE_OWNER | ACL_WRITE_ATTRIBUTES | ACL_WRITE_EXTATTRIBUTES; + const acl_permset_mask_t required = read | write | control | + (S_ISDIR(value->info.st_mode) ? ACL_SEARCH : 0); + // Without identity-directory resolution a deny may apply to the owner. + // Reject that unprovable layout; do not reorder ACEs or guess membership. + if (tag == ACL_EXTENDED_DENY && (permissions & required)) { + value->assessment |= PLATFORM_ACCESS_OWNER_DENIED; + } + if (tag == ACL_EXTENDED_ALLOW) { + if (permissions & read) value->assessment |= PLATFORM_ACCESS_EXTERNAL_READ; + if (permissions & write) value->assessment |= PLATFORM_ACCESS_EXTERNAL_WRITE; + if (permissions & ACL_SEARCH) value->assessment |= PLATFORM_ACCESS_EXTERNAL_SEARCH; + if (permissions & control) value->assessment |= PLATFORM_ACCESS_EXTERNAL_CONTROL; + } + } + status = acl_get_entry(acl, ACL_NEXT_ENTRY, &entry); + } + // Darwin returns -1/EINVAL at the end of iteration, unlike the POSIX API. + if (errno != EINVAL) goto done; + result = 0; +done:; + int error = errno; + acl_free(acl); + errno = error; + return result; +} +#else +static int read_acl_xattr(int descriptor, const char *name, void **bytes, size_t *length) { + ssize_t size = fgetxattr(descriptor, name, NULL, 0); + if (size < 0) return errno == ENODATA ? 0 : -1; + *bytes = malloc(size ? (size_t)size : 1); + if (!*bytes) { errno = ENOMEM; return -1; } + ssize_t count = fgetxattr(descriptor, name, *bytes, (size_t)size); + if (count < 0) return -1; + if (count != size) { errno = EAGAIN; return -1; } + *length = (size_t)count; + return 0; +} + +static unsigned int acl_u16(const unsigned char *p) { + return (unsigned int)p[0] | ((unsigned int)p[1] << 8); +} + +static uint32_t acl_u32(const unsigned char *p) { + return (uint32_t)acl_u16(p) | ((uint32_t)acl_u16(p + 2) << 16); +} + +// The kernel validates installed ACLs. Validate the representation as well so an +// unrecognized format never becomes an empty/permissive guessed assessment. +static int posix_acl_permissions(const void *bytes, size_t size, uid_t owner, + unsigned int *ownerPermissions, unsigned int *external) { + const unsigned char *p = bytes; + if (size < 4 || (size - 4) % 8 != 0 || acl_u32(p) != 2) { errno = ENOTSUP; return -1; } + unsigned int seen = 0, group = 0, named = 0, other = 0, mask = 7; + bool hasNamed = false; + for (size_t offset = 4; offset < size; offset += 8) { + unsigned int tag = acl_u16(p + offset), permissions = acl_u16(p + offset + 2); + uint32_t identifier = acl_u32(p + offset + 4); + if (permissions > 7) { errno = ENOTSUP; return -1; } + if (tag == 2 || tag == 8) { + if (identifier == UINT32_MAX) { errno = ENOTSUP; return -1; } + hasNamed = true; + // The owning user's class always wins over a named entry for that uid. + if (tag == 8 || identifier != owner) named |= permissions; + continue; + } + if (identifier != UINT32_MAX || (seen & tag)) { errno = ENOTSUP; return -1; } + seen |= tag; + switch (tag) { + case 1: *ownerPermissions = permissions; break; + case 4: group = permissions; break; + case 16: mask = permissions; break; + case 32: other = permissions; break; + default: errno = ENOTSUP; return -1; + } + } + if ((seen & 37) != 37 || (hasNamed && !(seen & 16))) { errno = ENOTSUP; return -1; } + *external = ((group | named) & mask) | other; + return 0; +} + +static int read_access_acl(int descriptor, struct platform_file_access *value) { + if (read_acl_xattr(descriptor, "system.posix_acl_access", &value->acl, &value->acl_size) < 0) return -1; + unsigned int owner = (value->info.st_mode >> 6) & 7; + unsigned int external = (value->info.st_mode & 7) | ((value->info.st_mode >> 3) & 7); + if (value->acl && posix_acl_permissions(value->acl, value->acl_size, value->info.st_uid, + &owner, &external) < 0) return -1; + value->assessment = access_permissions(external); + unsigned int required = S_ISDIR(value->info.st_mode) ? 7 : 6; + if ((owner & required) != required) value->assessment |= PLATFORM_ACCESS_OWNER_DENIED; + if (S_ISDIR(value->info.st_mode)) { + if (read_acl_xattr(descriptor, "system.posix_acl_default", &value->default_acl, + &value->default_acl_size) < 0) return -1; + if (value->default_acl) { + unsigned int ignoredOwner, ignoredExternal; + if (posix_acl_permissions(value->default_acl, value->default_acl_size, value->info.st_uid, + &ignoredOwner, &ignoredExternal) < 0) return -1; + } + } + return 0; +} +#endif + +int platform_read_file_access(int descriptor, struct platform_file_access *result) { + memset(result, 0, sizeof(*result)); + if (fstat(descriptor, &result->info) < 0) return -1; + if (!S_ISREG(result->info.st_mode) && !S_ISDIR(result->info.st_mode)) { + errno = EINVAL; + return -1; + } + unsigned int owner = (result->info.st_mode >> 6) & 7; + unsigned int required = S_ISDIR(result->info.st_mode) ? 7 : 6; + result->assessment = access_permissions((result->info.st_mode & 7) | ((result->info.st_mode >> 3) & 7)); + if ((owner & required) != required) result->assessment |= PLATFORM_ACCESS_OWNER_DENIED; + if (read_access_acl(descriptor, result) < 0) goto failed; + struct stat after; + if (fstat(descriptor, &after) < 0) goto failed; + if (!platform_same_generation(&result->info, &after) || + result->info.st_uid != after.st_uid || result->info.st_gid != after.st_gid || + result->info.st_nlink != after.st_nlink) { errno = EAGAIN; goto failed; } + return 0; +failed:; + int error = errno; + platform_dispose_file_access(result); + errno = error; + return -1; +} + +int platform_spawn(pid_t *pid, const char *executable, char *const argv[], + char *const environment[], const char *directory, int lock, + bool inheritInput, int output, int error) { + posix_spawn_file_actions_t actions; + posix_spawnattr_t attributes; + int result = posix_spawn_file_actions_init(&actions); + if (result != 0) return result; + result = posix_spawnattr_init(&attributes); + if (result != 0) { posix_spawn_file_actions_destroy(&actions); return result; } +#define CHECK(call) do { result = (call); if (result != 0) goto done; } while (0) +#if defined(__APPLE__) + CHECK(posix_spawnattr_setflags(&attributes, POSIX_SPAWN_CLOEXEC_DEFAULT)); + if (inheritInput) CHECK(posix_spawn_file_actions_addinherit_np(&actions, STDIN_FILENO)); +#else + if (inheritInput) CHECK(posix_spawn_file_actions_adddup2(&actions, STDIN_FILENO, STDIN_FILENO)); +#endif + if (!inheritInput) { + CHECK(posix_spawn_file_actions_addopen(&actions, STDIN_FILENO, "/dev/null", O_RDONLY, 0)); + } + // The _np spelling is required on macOS 15 and glibc 2.34. +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + if (directory) CHECK(posix_spawn_file_actions_addchdir_np(&actions, directory)); +#pragma clang diagnostic pop + CHECK(posix_spawn_file_actions_adddup2(&actions, output, STDOUT_FILENO)); + CHECK(posix_spawn_file_actions_adddup2(&actions, error, STDERR_FILENO)); +#if defined(__APPLE__) + CHECK(posix_spawn_file_actions_addinherit_np(&actions, lock)); +#else + // All sources have been duplicated above fd 2 by the caller. Install the lock + // last at fd 3, then close everything higher without enumerating a racy fd list. + CHECK(posix_spawn_file_actions_adddup2(&actions, lock, 3)); + CHECK(posix_spawn_file_actions_addclosefrom_np(&actions, 4)); +#endif + result = posix_spawn(pid, executable, &actions, &attributes, argv, environment); +done: + posix_spawnattr_destroy(&attributes); + posix_spawn_file_actions_destroy(&actions); +#undef CHECK + return result; +} diff --git a/Sources/CPlatform/DuplexProcess.c b/Sources/CPlatform/DuplexProcess.c new file mode 100644 index 0000000..79d1a81 --- /dev/null +++ b/Sources/CPlatform/DuplexProcess.c @@ -0,0 +1,339 @@ +#define _GNU_SOURCE 1 +#include "CPlatform.h" +#include +#include +#if defined(__APPLE__) +#include +#include +#else +#include +#include +#include +#include +#include +#endif + +int platform_duplex_spawn(pid_t *pid, const char *executable, char *const argv[], + char *const environment[], const char *directory, + int directory_descriptor, int descriptors[3]) { + struct sigaction childAction; + if (sigaction(SIGCHLD, NULL, &childAction) < 0) return errno; + if (childAction.sa_handler == SIG_IGN || (childAction.sa_flags & SA_NOCLDWAIT)) return EINVAL; + int pipes[6] = {-1,-1,-1,-1,-1,-1}; + int result = 0; + for (int i = 0; i < 6; i += 2) { +#if defined(__APPLE__) + if (pipe(&pipes[i]) < 0) { result = errno; goto cleanup; } + for (int j = i; j < i + 2; j++) { + if (fcntl(pipes[j], F_SETFD, FD_CLOEXEC) < 0) { result = errno; goto cleanup; } + } +#else + if (pipe2(&pipes[i], O_CLOEXEC) < 0) { result = errno; goto cleanup; } +#endif + for (int j = i; j < i + 2; j++) { + if (pipes[j] < 3) { + int replacement = fcntl(pipes[j], F_DUPFD_CLOEXEC, 3); + if (replacement < 0) { result = errno; goto cleanup; } + close(pipes[j]); pipes[j] = replacement; + } + } + } + posix_spawn_file_actions_t actions; + posix_spawnattr_t attributes; + result = posix_spawn_file_actions_init(&actions); + if (result) goto cleanup; + result = posix_spawnattr_init(&attributes); + if (result) { posix_spawn_file_actions_destroy(&actions); goto cleanup; } +#define CHECK(call) do { result = (call); if (result) goto destroy; } while (0) + short flags = POSIX_SPAWN_SETPGROUP | POSIX_SPAWN_SETSIGMASK | POSIX_SPAWN_SETSIGDEF; +#if defined(__APPLE__) + flags |= POSIX_SPAWN_CLOEXEC_DEFAULT; +#endif + sigset_t mask, defaults; + sigemptyset(&mask); sigemptyset(&defaults); + sigaddset(&defaults, SIGPIPE); sigaddset(&defaults, SIGTERM); + sigaddset(&defaults, SIGINT); sigaddset(&defaults, SIGHUP); + CHECK(posix_spawnattr_setflags(&attributes, flags)); + CHECK(posix_spawnattr_setpgroup(&attributes, 0)); + CHECK(posix_spawnattr_setsigmask(&attributes, &mask)); + CHECK(posix_spawnattr_setsigdefault(&attributes, &defaults)); +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + if (directory_descriptor >= 0) { + CHECK(posix_spawn_file_actions_addfchdir_np(&actions, directory_descriptor)); + } else { + CHECK(posix_spawn_file_actions_addchdir_np(&actions, directory)); + } +#pragma clang diagnostic pop + CHECK(posix_spawn_file_actions_adddup2(&actions, pipes[0], 0)); + CHECK(posix_spawn_file_actions_adddup2(&actions, pipes[3], 1)); + CHECK(posix_spawn_file_actions_adddup2(&actions, pipes[5], 2)); +#if !defined(__APPLE__) + CHECK(posix_spawn_file_actions_addclosefrom_np(&actions, 3)); +#endif + // Parent ends are nonblocking; child standard streams retain ordinary blocking I/O. + for (int i = 0; i < 3; i++) { + int fd = pipes[(int[]){1,2,4}[i]]; + if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0) { result = errno; goto destroy; } + } +#if defined(__APPLE__) + // Native per-descriptor suppression also covers a child that exits before reading stdin. + if (fcntl(pipes[1], F_SETNOSIGPIPE, 1) < 0) { result = errno; goto destroy; } +#endif + result = posix_spawn(pid, executable, &actions, &attributes, argv, environment); + if (!result) { + descriptors[0] = pipes[1]; pipes[1] = -1; + descriptors[1] = pipes[2]; pipes[2] = -1; + descriptors[2] = pipes[4]; pipes[4] = -1; + } +destroy: + posix_spawnattr_destroy(&attributes); + posix_spawn_file_actions_destroy(&actions); +#undef CHECK +cleanup: + for (int i = 0; i < 6; i++) if (pipes[i] >= 0) close(pipes[i]); + return result; +} + +int platform_duplex_observe(pid_t pid, bool *exited) { + siginfo_t info; + memset(&info, 0, sizeof(info)); + int result; + do { result = waitid(P_PID, (id_t)pid, &info, WEXITED | WNOHANG | WNOWAIT); } + while (result < 0 && errno == EINTR); + if (result < 0) return errno; + *exited = info.si_pid == pid; + return 0; +} + +ssize_t platform_duplex_write(int descriptor, const void *bytes, size_t count) { +#if defined(__APPLE__) + ssize_t written; + do { written = write(descriptor, bytes, count); } while (written < 0 && errno == EINTR); + return written; +#else + sigset_t blocked, previous, pending; + sigemptyset(&blocked); sigaddset(&blocked, SIGPIPE); + int result = pthread_sigmask(SIG_BLOCK, &blocked, &previous); + if (result) { errno = result; return -1; } + sigpending(&pending); + bool wasPending = sigismember(&pending, SIGPIPE) == 1; + ssize_t written; + do { written = write(descriptor, bytes, count); } while (written < 0 && errno == EINTR); + int error = errno; + if (written < 0 && error == EPIPE && !wasPending) { + const struct timespec immediate = {0, 0}; + while (sigtimedwait(&blocked, NULL, &immediate) < 0 && errno == EINTR) {} + } + pthread_sigmask(SIG_SETMASK, &previous, NULL); + errno = error; + return written; +#endif +} + +#if !defined(__APPLE__) +static int duplex_proc_scan_budget(const struct timespec *start) { + struct timespec now; + if (clock_gettime(CLOCK_MONOTONIC, &now) < 0) return errno; + if ((now.tv_sec - start->tv_sec) * 1000000000LL + now.tv_nsec - start->tv_nsec >= 20000000) + return EAGAIN; + return 0; +} + +// Require a complete bounded kernel record; a short read is not an EOF proof. +static int duplex_proc_read_record(int fd, char *record, size_t capacity, + const struct timespec *start) { + size_t used = 0; + for (;;) { + int result = duplex_proc_scan_budget(start); + if (result) return result; + ssize_t count = read(fd, record + used, capacity - 1 - used); + if (count < 0) return errno; + if (count == 0) { + if (used == 0) return EINVAL; + record[used] = 0; + return 0; + } + used += (size_t)count; + if (used == capacity - 1) return EOVERFLOW; + } +} + +// mountinfo escapes whitespace in paths; its post-separator options are tokens. +static int duplex_proc_mount_options(char *line, unsigned long long mountID) { + char *end; + errno = 0; + unsigned long long identifier = strtoull(line, &end, 10); + if (errno || end == line || *end != ' ') return EINVAL; + if (identifier != mountID) return ENOENT; + char *separator = strstr(end, " - "); + char type[32], source[256], options[4096], extra; + if (!separator || sscanf(separator + 3, "%31s %255s %4095s %c", type, source, options, &extra) != 3) + return EINVAL; + if (strcmp(type, "proc") != 0) return ENOTSUP; + char *saved = NULL; + for (char *option = strtok_r(options, ",", &saved); option; option = strtok_r(NULL, ",", &saved)) { + if (strncmp(option, "hidepid", 7) == 0 && strcmp(option, "hidepid=0") != 0) return ENOTSUP; + } + return 0; +} + +static int duplex_proc_complete_view(int proc, const struct timespec *start) { + struct statfs filesystem; + if (fstatfs(proc, &filesystem) < 0) return errno; + if (filesystem.f_type != PROC_SUPER_MAGIC) return ENOTSUP; + // fdinfo identifies this open proc root, including bind mounts/overmounts. + char path[64], descriptorInfo[1024]; + int length = snprintf(path, sizeof(path), "self/fdinfo/%d", proc); + if (length < 0 || (size_t)length >= sizeof(path)) return EOVERFLOW; + int fd = openat(proc, path, O_RDONLY | O_CLOEXEC); + if (fd < 0) return errno; + int error = duplex_proc_read_record(fd, descriptorInfo, sizeof(descriptorInfo), start); + close(fd); + if (error) return error; + unsigned long long mountID = 0; + char *saved = NULL; + for (char *line = strtok_r(descriptorInfo, "\n", &saved); line; line = strtok_r(NULL, "\n", &saved)) { + if (strncmp(line, "mnt_id:", 7) == 0) { + char extra; + if (sscanf(line, "mnt_id: %llu %c", &mountID, &extra) != 1) return EINVAL; + break; + } + } + if (mountID == 0) return ENOTSUP; + fd = openat(proc, "self/mountinfo", O_RDONLY | O_CLOEXEC); + if (fd < 0) return errno; + char line[8192], chunk[4096]; + size_t used = 0, total = 0; + int result = ENOTSUP; + for (;;) { + result = duplex_proc_scan_budget(start); + if (result) break; + ssize_t count = read(fd, chunk, sizeof(chunk)); + if (count < 0) { result = errno; break; } + if (count == 0) { result = ENOTSUP; break; } + if ((size_t)count > 1024 * 1024 - total) { result = EOVERFLOW; break; } + total += (size_t)count; + for (ssize_t i = 0; i < count; i++) { + if (chunk[i] == '\n') { + line[used] = 0; + result = duplex_proc_mount_options(line, mountID); + if (result != ENOENT) goto complete; + used = 0; + } else { + if (used == sizeof(line) - 1) { result = EOVERFLOW; goto complete; } + line[used++] = chunk[i]; + } + } + } +complete: + close(fd); + return result; +} + +static int duplex_proc_state(char *stat, char *state, long *group, long *threads) { + // comm may contain spaces and ')'; the final ')' ends that field. + char *fields = strrchr(stat, ')'); + if (!fields) return EINVAL; + char *saved = NULL; + char *field = strtok_r(fields + 1, " \n", &saved); + for (int index = 0; index <= 17; index++, field = strtok_r(NULL, " \n", &saved)) { + if (!field) return EINVAL; + if (index == 0) { + if (strlen(field) != 1) return EINVAL; + *state = field[0]; + } else if (index == 2 || index == 17) { + char *end; + errno = 0; + long number = strtol(field, &end, 10); + if (errno || end == field || *end != 0 || (index == 17 ? number <= 0 : number < 0)) return EINVAL; + if (index == 2) *group = number; else *threads = number; + } + } + return 0; +} +#endif + +int platform_duplex_group_quiescent(pid_t pid, bool *quiescent) { + *quiescent = false; +#if defined(__APPLE__) + // Zombie-only groups need no signal. Inspect only this reserved group; + // an all-zombie group cannot fork. + int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PGRP, pid}; + size_t size = 0; + if (sysctl(mib, 4, NULL, &size, NULL, 0) < 0) return errno; + if (size > 1024 * 1024) return EOVERFLOW; // Bounded cleanup inspection bytes. + if (size == 0) { *quiescent = true; return 0; } + struct kinfo_proc *members = malloc(size); + if (!members) return ENOMEM; + int result = sysctl(mib, 4, members, &size, NULL, 0); + int error = errno; + bool live = false; + if (result == 0) { + for (size_t i = 0; i < size / sizeof(*members); i++) { + if (members[i].kp_proc.p_stat != SZOMB) { live = true; break; } + } + } + free(members); + if (result < 0) return error; + *quiescent = !live; + return 0; +#else + // /proc is a runtime prerequisite. Bound both scan work and elapsed inspection; + // an unreadable or incomplete snapshot cannot establish group quiescence. + DIR *processes = opendir("/proc"); + if (!processes) return errno; + struct timespec start; + if (clock_gettime(CLOCK_MONOTONIC, &start) < 0) { + int error = errno; closedir(processes); return error; + } + int result = duplex_proc_complete_view(dirfd(processes), &start); + if (result) { closedir(processes); return result; } + bool leaderSeen = false; + size_t entries = 0; + for (;;) { + if (++entries > 65536) { result = EOVERFLOW; break; } + result = duplex_proc_scan_budget(&start); + if (result) break; + errno = 0; + struct dirent *entry = readdir(processes); + if (!entry) { + result = errno; + if (!result && !leaderSeen) result = ESRCH; + if (!result) *quiescent = true; + break; + } + if (!entry->d_name[0] || strspn(entry->d_name, "0123456789") != strlen(entry->d_name)) continue; + char path[sizeof(entry->d_name) + 6]; + int length = snprintf(path, sizeof(path), "%s/stat", entry->d_name); + if (length < 0 || (size_t)length >= sizeof(path)) { result = EOVERFLOW; break; } + int fd = openat(dirfd(processes), path, O_RDONLY | O_CLOEXEC | O_NOFOLLOW); + if (fd < 0) { result = errno; break; } + char stat[4096]; + result = duplex_proc_read_record(fd, stat, sizeof(stat), &start); + close(fd); + if (result) break; + char state; + long group, threads; + result = duplex_proc_state(stat, &state, &group, &threads); + if (result) break; + if (group != pid) continue; + if (strtol(entry->d_name, NULL, 10) == pid) leaderSeen = true; + // A zombie main thread can still have live workers after pthread_exit. + // num_threads includes the leader: exactly one zombie task proves no worker. + if (state != 'Z' || threads != 1) break; + } + closedir(processes); + return result; +#endif +} + +int platform_duplex_signal(pid_t pid, int signal) { +#if defined(__APPLE__) + bool quiescent = false; + int result = platform_duplex_group_quiescent(pid, &quiescent); + if (result || quiescent) return result; +#endif + if (kill(-pid, signal) == 0 || errno == ESRCH) return 0; + return errno; +} diff --git a/Sources/CPlatform/include/CPlatform.h b/Sources/CPlatform/include/CPlatform.h new file mode 100644 index 0000000..3f05e21 --- /dev/null +++ b/Sources/CPlatform/include/CPlatform.h @@ -0,0 +1,73 @@ +#ifndef CORE_CPLATFORM_H +#define CORE_CPLATFORM_H + +#include "DuplexProcess.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(__APPLE__) +#include +#endif + +// Decodes a bounded ZIP member and verifies its CRC. Supports stored and raw-deflate members. +bool platform_zip_member(const unsigned char *input, size_t inputSize, unsigned int method, + unsigned char *output, size_t outputSize, unsigned int expectedCRC); +int platform_flock(int descriptor, int operation); +void platform_raise_open_file_limit(void); +int platform_access(int directory, const char *name, int mode); +const char *platform_entry_name(const struct dirent *entry); +bool platform_system_alias(const char *name); +int platform_exchange(int sourceDirectory, const char *name, int destinationDirectory, const char *destination); +int platform_rename_exclusive(int sourceDirectory, const char *name, int destinationDirectory, const char *destination); +bool platform_same_generation(const struct stat *first, const struct stat *second); +int platform_sync(int descriptor); +int platform_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_link_metadata(int sourceDirectory, const char *source, + int destinationDirectory, const char *destination); + +// ACL bytes are descriptor-derived, ordered, and platform-specific: Darwin's +// external ACL representation or Linux's POSIX ACL xattr format. No names or +// directory-service lookups participate in capture or evaluation. +enum { + PLATFORM_ACCESS_OWNER_DENIED = 1, + PLATFORM_ACCESS_EXTERNAL_READ = 2, + PLATFORM_ACCESS_EXTERNAL_WRITE = 4, + PLATFORM_ACCESS_EXTERNAL_SEARCH = 8, + PLATFORM_ACCESS_EXTERNAL_CONTROL = 16 +}; +struct platform_file_access { + struct stat info; + void *acl; + size_t acl_size; + void *default_acl; + size_t default_acl_size; + unsigned int assessment; +}; +// Failure never changes the object. Success owns allocations released by dispose. +int platform_read_file_access(int descriptor, struct platform_file_access *result); +void platform_dispose_file_access(struct platform_file_access *value); + +// Returns a POSIX error number, as posix_spawn does. The caller owns all fds. +// In the child only stdin, stdout, stderr and the specified lock survive exec. +int platform_spawn(pid_t *pid, const char *executable, char *const argv[], + char *const environment[], const char *directory, int lock, + bool inheritInput, int output, int error); + +#endif diff --git a/Sources/CPlatform/include/DuplexProcess.h b/Sources/CPlatform/include/DuplexProcess.h new file mode 100644 index 0000000..8115dbe --- /dev/null +++ b/Sources/CPlatform/include/DuplexProcess.h @@ -0,0 +1,18 @@ +#ifndef CORE_DUPLEX_PROCESS_H +#define CORE_DUPLEX_PROCESS_H +#include +#include +#include + +// Owns a new process group. Only descriptors 0...2 survive exec. +// Success transfers nonblocking parent stdin/stdout/stderr fds to the caller. +int platform_duplex_spawn(pid_t *pid, const char *executable, char *const argv[], + char *const environment[], const char *directory, + int directory_descriptor, int descriptors[3]); +// Observe without reaping, reserving the leader's identity for group cleanup. +int platform_duplex_observe(pid_t pid, bool *exited); +// Requires the leader to remain owned and unreaped; failure leaves false. +int platform_duplex_group_quiescent(pid_t pid, bool *quiescent); +int platform_duplex_signal(pid_t pid, int signal); +ssize_t platform_duplex_write(int descriptor, const void *bytes, size_t count); +#endif diff --git a/Sources/CSQLite/CSQLite.c b/Sources/CSQLite/CSQLite.c new file mode 100644 index 0000000..2530daf --- /dev/null +++ b/Sources/CSQLite/CSQLite.c @@ -0,0 +1,5 @@ +#include "CSQLite.h" + +int agents_sqlite_disable_triggers(sqlite3 *database) { + return sqlite3_db_config(database, SQLITE_DBCONFIG_ENABLE_TRIGGER, 0, (int *)0); +} diff --git a/Sources/CSQLite/include/CSQLite.h b/Sources/CSQLite/include/CSQLite.h new file mode 100644 index 0000000..62bed83 --- /dev/null +++ b/Sources/CSQLite/include/CSQLite.h @@ -0,0 +1,5 @@ +#pragma once + +#include + +int agents_sqlite_disable_triggers(sqlite3 *database); diff --git a/Sources/Components/Adapters/AntigravityAdapter.swift b/Sources/Components/Adapters/AntigravityAdapter.swift new file mode 100644 index 0000000..6a2c52d --- /dev/null +++ b/Sources/Components/Adapters/AntigravityAdapter.swift @@ -0,0 +1,78 @@ +import AgentsCore + +/// The App and CLI share a JSON format and customization directories. +enum AntigravityAdapter { + static func mcp(_ input: MCPInput) throws -> MCPEntry { + var entry = MCPEntry(input) + switch input.transport { + case .stdio(let run): + guard input.native["authProviderType"] == nil else { + throw input.issue( + ["native", "antigravity", "authProviderType"], .unsupported, + "native authentication applies to remote MCP servers") + } + try entry.command(run) + try entry.workingDirectory(run) + try entry.bindings(run.environment, field: "env", reference: nil) + case .streamableHTTP(let url, let headers): + try entry.url(url, field: "serverUrl") + try entry.bindings(headers, field: "headers", reference: nil) + case .sse: + throw input.issue( + ["transport", "kind"], .unsupported, "Antigravity remote MCP requires Streamable HTTP") + } + try entry.nativeFields([ + "disabled": .boolean, "enabledTools": .strings, "disabledTools": .strings, + "authProviderType": .oneOf(["google_credentials"]), + ]) + return entry + } + + private static let toolEvents: Set = ["PreToolUse", "PostToolUse"] + private static let events = toolEvents.union([ + "SessionStart", "PreInvocation", "PostInvocation", "Stop", + ]) + + static func components(_ lowering: LockedLowering, _ input: ComponentRenderInput) throws + -> [ReplayedArtifact] + { + let event = try NativeDocumentedHooksV1.event(input, allowed: events) + var hook = try input.checkedNative(["enabled": .boolean]) + var handler: [String: LedgerValue] = [ + "type": .init("command"), "command": try NativeDocumentedHooksV1.program(input), + ] + if let timeout = input.fields["timeoutSeconds"] { + guard timeout.integer.map({ $0 > 0 }) == true else { + throw input.issue(["timeoutSeconds"], .invalid, "native timeout must be positive seconds") + } + handler["timeout"] = timeout + } + let matcher = input.fields["matcher"] + if toolEvents.contains(event) { + let pattern = matcher?.text ?? "" + guard NativeDocumentedHooksV1.admittedMatcher(pattern) else { + throw input.issue(["matcher"], .unverified, "matcher is outside the verified regex profile") + } + let group: [String: LedgerValue] = [ + "matcher": .init(pattern), "hooks": .init(array: [.init(object: handler)]), + ] + hook[event] = .init(array: [.init(object: group)]) + } else { + guard matcher == nil else { + throw input.issue(["matcher"], .unsupported, "this native event ignores matchers") + } + hook[event] = .init(array: [.init(object: handler)]) + } + return try input.emitted( + lowering, + input.envelope( + route: .antigravityHooks, keys: [input.record.name], selection: "antigravityHook", + value: .init(object: hook))) + } + + static func commandPath(in value: LedgerValue) -> [String]? { + guard let event = value.object?.keys.first(where: events.contains) else { return nil } + return toolEvents.contains(event) + ? [event, "0", "hooks", "0", "command"] : [event, "0", "command"] + } +} diff --git a/Sources/Components/Adapters/ClaudeAdapter.swift b/Sources/Components/Adapters/ClaudeAdapter.swift new file mode 100644 index 0000000..3c5be31 --- /dev/null +++ b/Sources/Components/Adapters/ClaudeAdapter.swift @@ -0,0 +1,25 @@ +import AgentsCore + +/// Claude's local audience is a project even though Core routes it to the shared global file. +enum ClaudeAdapter { + static func mcp(_ input: MCPInput) throws -> MCPEntry { + var entry = MCPEntry(input) + switch input.transport { + case .stdio(let run): + try input.rejectWorkingDirectory(run) + entry.fields["type"] = .init("stdio") + try entry.command(run) + try entry.bindings(run.environment, field: "env", reference: .claude) + case .streamableHTTP(let url, let headers): + entry.fields["type"] = .init("http") + try entry.url(url) + try entry.bindings(headers, field: "headers", reference: .claude) + case .sse(let url, let headers): + entry.fields["type"] = .init("sse") + try entry.url(url) + try entry.bindings(headers, field: "headers", reference: .claude) + } + try entry.nativeFields([:]) + return entry + } +} diff --git a/Sources/Components/Adapters/ClaudeComponents.swift b/Sources/Components/Adapters/ClaudeComponents.swift new file mode 100644 index 0000000..519d02e --- /dev/null +++ b/Sources/Components/Adapters/ClaudeComponents.swift @@ -0,0 +1,76 @@ +import AgentsCore +import Foundation + +extension ClaudeAdapter { + static func components(_ lowering: LockedLowering, _ input: ComponentRenderInput) throws + -> [ReplayedArtifact] + { + switch input.record.kind { + case "command": + try input.noParameters() + var fields = try input.checkedNative( + NativeComponentFieldsV1.markdownRules(.claudeCode, kind: "command")) + for key in ["agent", "background"] + where fields[key] != nil && fields["context"]?.text != "fork" { + throw input.issue( + ["native", "claude-code", key], .unsupported, + "this native command field applies only with context fork") + } + fields["description"] = .init(try input.text("description")) + let name = try input.relativeName() + return try input.emitted( + lowering, + input.envelope( + route: .claudeCommand, path: name + ".md", selection: "file", + value: .init(try input.frontmatter(fields, body: input.prompt())))) + case "subagent": + if input.inPlugin, input.native["permissionMode"] != nil { + throw input.issue( + ["native", "claude-code", "permissionMode"], .unsupported, + "native plugin agents ignore this permission field") + } + var fields = try input.checkedNative( + NativeComponentFieldsV1.markdownRules(.claudeCode, kind: "subagent")) + let name = try input.filename() + guard name.count <= 256, !name.contains(":") else { + throw input.issue( + ["name"], .invalid, "native agent name is limited to 256 characters and excludes colon") + } + let description = try input.text("description") + guard !description.isEmpty else { + throw input.issue(["description"], .invalid, "native agent description is required") + } + fields["name"] = .init(name) + fields["description"] = .init(description) + fields["model"] = input.fields["model"] + fields["tools"] = input.fields["tools"] + return try input.emitted( + lowering, + input.envelope( + route: .claudeAgent, path: name + ".md", selection: "file", + value: .init(try input.frontmatter(fields, body: input.prompt())))) + case "hook": return try NativeDocumentedHooksV1.claude(lowering, input) + case "permissions": + guard input.fields["rules"]?.array?.isEmpty ?? true else { + throw input.issue( + ["rules"], .unverified, + "ordered last-match portable policy is not equivalent to native deny/ask/allow precedence; use explicit native categories" + ) + } + let fields = try input.checkedNative([ + "allow": .strings, "ask": .strings, "deny": .strings, + "defaultMode": .oneOf([ + "default", "acceptEdits", "auto", "dontAsk", "bypassPermissions", "plan", + ]), + ]) + return try input.emitted( + lowering, + input.envelope( + route: .claudeSettings, keys: ["permissions"], selection: "nativePolicy", + value: .init(object: fields))) + case "lspServer": return try NativeLSPLayoutV1.claude(lowering, input) + default: + throw input.issue(["kind"], .invalid, "component does not match this concrete native profile") + } + } +} diff --git a/Sources/Components/Adapters/CodexAdapter.swift b/Sources/Components/Adapters/CodexAdapter.swift new file mode 100644 index 0000000..bc054c9 --- /dev/null +++ b/Sources/Components/Adapters/CodexAdapter.swift @@ -0,0 +1,67 @@ +import AgentsCore + +/// Codex env_vars forwards the same variable name; it is not an environment rename operation. +enum CodexAdapter { + static func mcp(_ input: MCPInput) throws -> MCPEntry { + var entry = MCPEntry(input) + switch input.transport { + case .stdio(let run): + try entry.command(run) + try entry.workingDirectory(run) + var forwarded: [LedgerValue] = [] + var environment: [String: LedgerValue] = [:] + for (key, binding) in run.environment.sorted(by: { $0.key < $1.key }) { + if case .environment(let source) = binding, source == key { + try input.environmentName(source, field: ["transport", "environment", key]) + entry.placements.append( + .init( + path: [.key("env_vars"), .index(forwarded.count)], binding: binding, reference: true)) + forwarded.append(.init(source)) + } else { + environment[key] = try entry.binding( + binding, path: [.key("env"), .key(key)], reference: nil) + } + } + if !environment.isEmpty { entry.fields["env"] = .init(object: environment) } + if !forwarded.isEmpty { entry.fields["env_vars"] = .init(array: forwarded) } + case .streamableHTTP(let url, let headers): + try entry.url(url) + var literal: [String: LedgerValue] = [:] + var references: [String: LedgerValue] = [:] + for (key, binding) in headers.sorted(by: { $0.key < $1.key }) { + if case .environment(let name) = binding { + try input.environmentName(name, field: ["transport", "headers", key]) + references[key] = .init(name) + entry.placements.append( + .init(path: [.key("env_http_headers"), .key(key)], binding: binding, reference: true)) + } else { + literal[key] = try entry.binding( + binding, path: [.key("http_headers"), .key(key)], reference: nil) + } + } + if !literal.isEmpty { entry.fields["http_headers"] = .init(object: literal) } + if !references.isEmpty { entry.fields["env_http_headers"] = .init(object: references) } + case .sse: + throw input.issue( + ["transport", "kind"], .unsupported, + "the pinned Codex transport enum has no legacy SSE variant") + } + var rules: [String: MCPNativeField] = [ + "enabled": .boolean, "required": .boolean, + "startup_timeout_sec": .durationSeconds, "tool_timeout_sec": .durationSeconds, + ] + if case .streamableHTTP = input.transport { rules["bearer_token_env_var"] = .environmentName } + try entry.nativeFields(rules) + if input.native["bearer_token_env_var"] != nil { + let hasAuthorization = ["http_headers", "env_http_headers"].contains { field in + entry.fields[field]?.object?.keys.contains { $0.lowercased() == "authorization" } == true + } + guard !hasAuthorization else { + throw input.issue( + ["native", "bearer_token_env_var"], .invalid, + "bearer token and explicit Authorization header overlap") + } + } + return entry + } +} diff --git a/Sources/Components/Adapters/CodexComponents.swift b/Sources/Components/Adapters/CodexComponents.swift new file mode 100644 index 0000000..363bbc7 --- /dev/null +++ b/Sources/Components/Adapters/CodexComponents.swift @@ -0,0 +1,45 @@ +import AgentsCore + +extension CodexAdapter { + static func components(_ lowering: LockedLowering, _ input: ComponentRenderInput) throws + -> [ReplayedArtifact] + { + switch input.record.kind { + case "subagent": + _ = try input.checkedNative([:]) + guard input.fields["tools"] == nil else { + throw input.issue( + ["tools"], .unsupported, "role overrides do not represent a portable tool allowlist") + } + let name = try input.relativeName() + let description = try input.text("description") + guard !NativeComponentText.isBlank(description, rust: true) else { + throw input.issue(["description"], .invalid, "native role description must not be blank") + } + guard NativeComponentText.isUntrimmed(description, rust: true) else { + throw input.issue(["description"], .unsupported, "native role descriptions are trimmed") + } + let prompt = try input.prompt() + guard !NativeComponentText.isBlank(prompt, rust: true) else { + throw input.issue(["prompt"], .invalid, "native role instructions must not be blank") + } + var lines = ["developer_instructions = " + (try input.quoted(prompt))] + if let model = input.fields["model"]?.text { + lines.append("model = " + (try input.quoted(model))) + } + lines.append("") + let file = input.envelope( + route: .codexAgent, path: name + ".toml", + selection: "file", value: .init(try input.joined(lines))) + let registration = input.envelope( + route: .codexConfig, keys: ["agents", name], + value: .init(object: [ + "description": .init(description), "config_file": .init("./agents/" + name + ".toml"), + ])) + return try input.emitted(lowering, .init(array: [file, registration])) + case "hook": return try NativeHookLayoutV1.render(lowering, input) + default: + throw input.issue(["kind"], .invalid, "component does not match this concrete native profile") + } + } +} diff --git a/Sources/Components/Adapters/CursorAdapter.swift b/Sources/Components/Adapters/CursorAdapter.swift new file mode 100644 index 0000000..a48c5df --- /dev/null +++ b/Sources/Components/Adapters/CursorAdapter.swift @@ -0,0 +1,22 @@ +import AgentsCore + +/// The documented MCP shape is shared by IDE/CLI; surface acceptance remains separate. +enum CursorAdapter { + static func mcp(_ input: MCPInput) throws -> MCPEntry { + var entry = MCPEntry(input) + switch input.transport { + case .stdio(let run): + try input.rejectWorkingDirectory(run) + entry.fields["type"] = .init("stdio") + try entry.command(run) + // Captured documentation establishes interpolation fields but not its exact token grammar. + try entry.bindings(run.environment, field: "env", reference: nil) + case .streamableHTTP, .sse: + throw input.issue( + ["transport", "kind"], .unverified, + "captured Cursor documentation does not fix an explicit remote transport selector") + } + try entry.nativeFields([:]) + return entry + } +} diff --git a/Sources/Components/Adapters/CursorComponents.swift b/Sources/Components/Adapters/CursorComponents.swift new file mode 100644 index 0000000..5c87e8f --- /dev/null +++ b/Sources/Components/Adapters/CursorComponents.swift @@ -0,0 +1,54 @@ +import AgentsCore + +extension CursorAdapter { + static func components(_ lowering: LockedLowering, _ input: ComponentRenderInput) throws + -> [ReplayedArtifact] + { + switch input.record.kind { + case "command": + _ = try input.checkedNative([:]) + try input.noParameters() + // The native file is a plain prompt; its schema has no description field. + guard try input.text("description").isEmpty else { + throw input.issue( + ["description"], .unsupported, "plain Markdown command files have no description field") + } + let name = try input.filename() + return try input.emitted( + lowering, + input.envelope( + route: .cursorCommand, + path: name + ".md", selection: "file", value: .init(try input.prompt()))) + case "subagent": + guard input.fields["tools"] == nil else { + throw input.issue( + ["tools"], .unverified, + "the documented subagent schema does not establish a tool allowlist") + } + var fields = try input.checkedNative( + NativeComponentFieldsV1.markdownRules(.cursorEditor, kind: "subagent")) + let name = try input.filename() + fields["name"] = .init(name) + fields["description"] = .init(try input.text("description")) + fields["model"] = input.fields["model"] + return try input.emitted( + lowering, + input.envelope( + route: .cursorAgent, + path: name + ".md", selection: "file", + value: .init(try input.frontmatter(fields, body: input.prompt())))) + case "hook": + return try NativeDocumentedHooksV1.cursor(lowering, input) + case "ignore": + _ = try input.checkedNative([:]) + return try input.emitted( + lowering, + input.envelope( + route: .cursorIgnore, + selection: "managedIgnore", + value: LedgerPayload.strings(try NativeIgnoreLayoutV1.patterns(input)))) + default: + throw input.issue(["kind"], .invalid, "component does not match this concrete native profile") + } + } +} diff --git a/Sources/Components/Adapters/GeminiAdapter.swift b/Sources/Components/Adapters/GeminiAdapter.swift new file mode 100644 index 0000000..4f7be98 --- /dev/null +++ b/Sources/Components/Adapters/GeminiAdapter.swift @@ -0,0 +1,27 @@ +import AgentsCore + +/// Explicit type with url fixes transport; httpUrl is a deprecated Streamable HTTP field. +enum GeminiAdapter { + static func mcp(_ input: MCPInput) throws -> MCPEntry { + var entry = MCPEntry(input) + switch input.transport { + case .stdio(let run): + try entry.command(run) + try entry.workingDirectory(run) + try entry.bindings(run.environment, field: "env", reference: .gemini) + case .streamableHTTP(let url, let headers): + entry.fields["type"] = .init("http") + try entry.url(url) + try entry.bindings(headers, field: "headers", reference: .gemini) + case .sse(let url, let headers): + entry.fields["type"] = .init("sse") + try entry.url(url) + try entry.bindings(headers, field: "headers", reference: .gemini) + } + try entry.nativeFields([ + "timeout": .positiveNumber, "description": .string, + "includeTools": .strings, "excludeTools": .strings, + ]) + return entry + } +} diff --git a/Sources/Components/Adapters/GeminiComponents.swift b/Sources/Components/Adapters/GeminiComponents.swift new file mode 100644 index 0000000..b9b5bd2 --- /dev/null +++ b/Sources/Components/Adapters/GeminiComponents.swift @@ -0,0 +1,116 @@ +import AgentsCore + +extension GeminiAdapter { + static func components(_ lowering: LockedLowering, _ input: ComponentRenderInput) throws + -> [ReplayedArtifact] + { + switch input.record.kind { + case "command": + _ = try input.checkedNative([:]) + try input.noParameters() + let name = try input.relativeName() + let description = try input.quoted(input.text("description")) + let prompt = try input.quoted(input.prompt()) + let file = try input.joined(["description = " + description, "prompt = " + prompt, ""]) + return try input.emitted( + lowering, + input.envelope( + route: .geminiCommand, + path: name + ".toml", selection: "file", value: .init(file))) + case "subagent": + let native = try input.checkedNative( + NativeComponentFieldsV1.markdownRules(.geminiCLI, kind: "subagent")) + let name = try input.filename() + guard name.range(of: #"^[a-z0-9_-]+$"#, options: .regularExpression) != nil else { + throw input.issue(["name"], .invalid, "Gemini agent names must be lowercase slugs") + } + let body = try input.prompt() + guard NativeComponentText.isUntrimmed(body, rust: false) else { + throw input.issue( + ["prompt"], .unsupported, "the native agent loader trims the system prompt") + } + var fields = native + fields["name"] = .init(name) + let description = try input.text("description") + guard !description.isEmpty else { + throw input.issue(["description"], .invalid, "native agent description must not be empty") + } + fields["description"] = .init(description) + fields["model"] = input.fields["model"] + if let tools = input.fields["tools"]?.array { + for (index, value) in tools.enumerated() { + guard let name = value.text, validAgentTool(name) else { + throw input.issue( + ["tools", String(index)], .invalid, "tool name is outside the pinned agent schema") + } + } + } + fields["tools"] = input.fields["tools"] + let file = try input.frontmatter(fields, body: body) + return try input.emitted( + lowering, + input.envelope( + route: .geminiAgent, + path: name + ".md", selection: "file", value: .init(file))) + case "hook": return try NativeHookLayoutV1.render(lowering, input) + case "ignore": + _ = try input.checkedNative([:]) + let patterns = try NativeIgnoreLayoutV1.patterns(input) + return try input.emitted( + lowering, + input.envelope( + route: .geminiIgnore, + selection: "managedIgnore", value: LedgerPayload.strings(patterns))) + default: + throw input.issue(["kind"], .invalid, "component does not match this concrete native profile") + } + } +} + +extension GeminiAdapter { + static func validAgentTool(_ name: String) -> Bool { + let builtins: Set = [ + "activate_skill", + "ask_user", + "complete_task", + "enter_plan_mode", + "exit_plan_mode", + "get_internal_docs", + "glob", + "google_web_search", + "grep_search", + "invoke_agent", + "list_directory", + "list_mcp_resources", + "read_file", + "read_many_files", + "read_mcp_resource", + "replace", + "run_shell_command", + "tracker_add_dependency", + "tracker_create_task", + "tracker_get_task", + "tracker_list_tasks", + "tracker_update_task", + "tracker_visualize", + "update_topic", + "web_fetch", + "write_file", + "write_todos", + ] + if builtins.contains(name) || name == "search_file_content" + || name.hasPrefix("discovered_tool_") || name == "*" || name == "mcp_*" + { + return true + } + guard name.hasPrefix("mcp_"), !name.hasPrefix("mcp__") else { return false } + let parts = name.dropFirst(4).split( + separator: "_", maxSplits: 1, omittingEmptySubsequences: false) + guard parts.count == 2, !parts[0].isEmpty, !parts[1].isEmpty else { return false } + let slug = #"^[a-zA-Z0-9_.:-]+$"# + guard String(parts[0]).range(of: slug, options: .regularExpression) != nil else { return false } + if parts[1] == "*" { return true } + return !parts[1].allSatisfy({ $0 == "_" }) + && String(parts[1]).range(of: slug, options: .regularExpression) != nil + } +} diff --git a/Sources/Components/Adapters/OpenCodeAdapter.swift b/Sources/Components/Adapters/OpenCodeAdapter.swift new file mode 100644 index 0000000..37d7831 --- /dev/null +++ b/Sources/Components/Adapters/OpenCodeAdapter.swift @@ -0,0 +1,36 @@ +import AgentsCore + +/// OpenCode 2 remote is Streamable HTTP. protocol selects MCP negotiation, not transport. +enum OpenCodeAdapter { + static func mcp(_ input: MCPInput) throws -> MCPEntry { + try input.literal(input.name, field: ["name"]) + var entry = MCPEntry(input) + switch input.transport { + case .stdio(let run): + entry.fields["type"] = .init("local") + try entry.command(run, argv: true) + try entry.workingDirectory(run) + try entry.bindings(run.environment, field: "environment", reference: nil) + case .streamableHTTP(let url, let headers): + entry.fields["type"] = .init("remote") + try entry.url(url) + try entry.bindings(headers, field: "headers", reference: nil) + case .sse: + throw input.issue( + ["transport", "kind"], .unsupported, + "the pinned remote client constructs StreamableHTTPClientTransport only") + } + var rules: [String: MCPNativeField] = [ + "disabled": .boolean, "codemode": .boolean, "pool": .boolean, + "protocol": .oneOf(["legacy", "auto", "2026-07-28"]), + "timeout": .positiveIntegerObject(["startup", "catalog", "execution"]), + ] + if case .streamableHTTP = input.transport { rules["oauth"] = .falseOnly } + try entry.nativeFields(rules) + if case .streamableHTTP = input.transport, entry.fields["codemode"] == nil { + // The native default rewrites the endpoint with a codemode query parameter. + entry.fields["codemode"] = .init(boolean: false) + } + return entry + } +} diff --git a/Sources/Components/Adapters/OpenCodeComponents.swift b/Sources/Components/Adapters/OpenCodeComponents.swift new file mode 100644 index 0000000..1c0b757 --- /dev/null +++ b/Sources/Components/Adapters/OpenCodeComponents.swift @@ -0,0 +1,86 @@ +import AgentsCore +import Foundation + +extension OpenCodeAdapter { + static func components(_ lowering: LockedLowering, _ input: ComponentRenderInput) throws + -> [ReplayedArtifact] + { + switch input.record.kind { + case "command", "subagent": + let fields = try definition(input, prompt: input.prompt()) + return try input.emitted( + lowering, + input.envelope( + route: .openCodeConfig, + keys: [input.record.kind == "command" ? "commands" : "agents", input.record.name], + value: .init(object: fields))) + case "permissions": + _ = try input.checkedNative([:]) + let rules = try (input.fields["rules"]?.array ?? []).enumerated().map { + index, rule -> LedgerValue in + guard let fields = rule.object, let action = fields["action"]?.text, + let operation = fields["operation"], let pattern = fields["pattern"]?.text + else { + throw input.issue(["rules", String(index)], .invalid, "invalid frozen permission rule") + } + guard let name = operation.object?["tool"]?.text else { + throw input.issue( + ["rules", String(index), "operation"], .unverified, + "portable read/write/execute resource namespaces are not proved equivalent to native tool actions" + ) + } + try input.literal(name, field: ["rules", String(index), "operation"]) + try input.literal(pattern, field: ["rules", String(index), "pattern"]) + return .init(object: [ + "action": .init(name), "resource": .init(pattern), "effect": .init(action), + ]) + } + return try input.emitted( + lowering, + input.envelope( + route: .openCodeConfig, + keys: ["permissions"], selection: "orderedAppend", value: .init(array: rules))) + case "lspServer": return try NativeLSPLayoutV1.openCode(lowering, input) + default: + throw input.issue(["kind"], .invalid, "component does not match this concrete native profile") + } + } + + /// Renderer and contribution decoder share the definition fields. A file-backed prompt body + /// reaches the decoder through its sealed artifact; no source path is rediscovered there. + static func definition(_ input: ComponentRenderInput, prompt: String) throws -> [String: + LedgerValue] + { + try input.literal(prompt, field: ["prompt"], prompt: input.record.kind == "command") + if input.record.kind == "command" { + try input.noParameters() + var fields = try input.checkedNative(["agent": .string, "subagent": .boolean]) + fields["description"] = .init(try input.text("description")) + fields["template"] = .init(prompt) + return fields + } + guard input.record.kind == "subagent" else { + throw input.issue(["kind"], .invalid, "component is not an OpenCode definition") + } + guard input.fields["tools"] == nil else { + throw input.issue( + ["tools"], .unsupported, + "OpenCode agent schema has permissions rather than a tool allowlist") + } + var fields = try input.checkedNative(["hidden": .boolean, "disabled": .boolean]) + fields["system"] = .init(prompt) + fields["description"] = .init(try input.text("description")) + fields["mode"] = .init("subagent") + if let model = input.fields["model"]?.text { + guard model.range(of: #"^[^/#]+/[^#]+(?:#[^#]+)?$"#, options: .regularExpression) != nil + else { + throw input.issue( + ["model"], .invalid, "native model selection requires provider/model syntax") + } + try input.literal(model, field: ["model"]) + fields["model"] = .init(model) + } + return fields + } + +} diff --git a/Sources/Components/AntigravityRuleV1.swift b/Sources/Components/AntigravityRuleV1.swift new file mode 100644 index 0000000..b171a3c --- /dev/null +++ b/Sources/Components/AntigravityRuleV1.swift @@ -0,0 +1,172 @@ +import AgentsCore +import AgentsInstructions +import Foundation + +enum AntigravityRuleV1 { + static let byteLimit = 24_000 + static let format = InstructionLocations.antigravityFormat + private static let include = try! NSRegularExpression( + pattern: #"@\[[^\]\r\n]*\]\(([^()\r\n]+)\)"#) + private static let unresolved = try! NSRegularExpression( + pattern: #"@\[[^\]\r\n]*\]\("#) + + static func leaf(source: String, path: String) throws -> String { + let name = URL(fileURLWithPath: path).deletingPathExtension().lastPathComponent + let stem = String( + name.lowercased().utf8.map { + (97...122).contains($0) || (48...57).contains($0) || $0 == 45 || $0 == 95 + ? Character(UnicodeScalar($0)) : "-" + }.prefix(60)) + let digest = try ResolvedLedgerCodec.digest([source, path]) + return "agents-\(stem)-\(digest.dropFirst(7)).md" + } + + static func render( + _ unit: Data, path: String, leaf: String, scope: InstallScope, read: (String) throws -> Data + ) throws -> Data { + let section = try Instructions.validateSource(unit, id: path, allowRestrictions: true) + let paths = scope == .project ? section.paths : [] + guard + paths.allSatisfy({ + !$0.contains(",") && $0 == $0.trimmingCharacters(in: .whitespacesAndNewlines) + }) + else { throw failure(leaf, "paths must fit Antigravity's comma-separated glob list") } + let header = + try frontmatter(section.description, paths: paths) + + InstructionCompatibility.antigravityMarker(leaf) + "\n\n" + var cache: [String: Expansion] = [:] + var active: Set = [path] + func expand(_ text: String, path: String) throws -> Expansion { + var output = Expansion() + var start = text.startIndex + for match in include.matches(in: text, range: NSRange(text.startIndex..., in: text)) { + try Task.checkCancellation() + guard let range = Range(match.range, in: text), + let destination = Range(match.range(at: 1), in: text), + range.lowerBound == text.startIndex || text[text.index(before: range.lowerBound)] != "\\" + else { throw failure(leaf, "unsupported file reference in \(path)") } + let prefix = String(text[start.. String + { + guard !value.hasPrefix("/"), !value.hasPrefix("~"), !value.contains("\\"), + !value.contains("%"), !value.contains(":"), !value.contains("#"), !value.contains("?"), + !value.contains("\0"), value == value.trimmingCharacters(in: .whitespaces) + else { throw failure(leaf, "unsafe file reference '\(value)' in \(path)") } + var parts = path.split(separator: "/").dropLast().map(String.init) + for part in value.split(separator: "/", omittingEmptySubsequences: false) { + switch part { + case ".", "": continue + case "..": + guard parts.popLast() != nil else { + throw failure(leaf, "file reference escapes its source: '\(value)' in \(path)") + } + case ".git": throw failure(leaf, "file reference crosses Git metadata: '\(value)' in \(path)") + default: parts.append(String(part)) + } + } + guard !parts.isEmpty else { throw failure(leaf, "invalid file reference in \(path)") } + return parts.joined(separator: "/") + } + + private static func includeBody(_ bytes: Data, leaf: String, path: String) throws -> String { + guard var text = String(data: bytes, encoding: .utf8), !text.contains("\0") else { + throw failure(leaf, "included file is not UTF-8 text: \(path)") + } + if text.first == "\u{FEFF}" { text.removeFirst() } + let lines = text.split( + omittingEmptySubsequences: false, whereSeparator: { $0.isNewline }) + guard lines.first == "---" else { return text } + guard let end = lines.dropFirst().firstIndex(of: "---") else { + throw failure(leaf, "unterminated frontmatter in included file: \(path)") + } + let last = lines[end].endIndex + return last == text.endIndex ? "" : String(text[text.index(after: last)...]) + } + + private static func validateReferences(_ text: String, leaf: String, path: String) throws { + guard unresolved.firstMatch(in: text, range: NSRange(text.startIndex..., in: text)) == nil + else { + throw failure(leaf, "unresolved file reference in \(path); use @[label](relative/path)") + } + } + + private static func frontmatter(_ description: String, paths: [String] = []) throws -> String { + let encoder = JSONEncoder() + encoder.outputFormatting = [.withoutEscapingSlashes] + let quoted = String(decoding: try encoder.encode(description), as: UTF8.self) + if paths.isEmpty { return "---\ntrigger: always_on\ndescription: \(quoted)\n---\n\n" } + let globs = String(decoding: try encoder.encode(paths.joined(separator: ", ")), as: UTF8.self) + return "---\ntrigger: glob\nglobs: \(globs)\ndescription: \(quoted)\n---\n\n" + } + + static func legacyLeaf(path: String) -> String? { + guard path.hasPrefix(".agent/instructions/") else { return nil } + let name = "memex-" + (path as NSString).lastPathComponent + return InstructionLocations.isAntigravityLeaf(name, legacy: true) ? name : nil + } + + static func legacyBytes(unit: Data, path: String, revision: String) throws -> Data { + let section = try Instructions.validateSource(unit, id: path, allowRestrictions: true) + let marker = + "" + return Data( + (try frontmatter(section.description) + marker + "\n\n" + section.content + "\n").utf8) + } + + static func failure(_ leaf: String, _ reason: String) -> CoreError { + .invalidState("Antigravity rule \(leaf): \(reason)") + } +} diff --git a/Sources/Components/ArtifactAggregation.swift b/Sources/Components/ArtifactAggregation.swift new file mode 100644 index 0000000..d31df3e --- /dev/null +++ b/Sources/Components/ArtifactAggregation.swift @@ -0,0 +1,2539 @@ +import AgentsCore +import AgentsInstructions +import AgentsSkills +import Foundation +import NativeDocuments + +package struct AggregatedChange { + package let deployment: LedgerDeployment + package let url: URL + package let before: Data? + package let after: Data? + package let changed: Bool + package let native: Bool + package var instructionForeign: Bool? = nil + package var afterLink: URL? = nil + package var accessChange: PrivateAccessChange? = nil + package var effectiveReaders: [AgentID] = [] + package var privateMaterialization = false + package var requiredBindings: [String] = [] + package var memberAccessChanges: [PrivateTreeAccessChange] = [] + package var symbolicBefore: LedgerValue? = nil + package var symbolicAfter: LedgerValue? = nil + package var configurationBefore: String? = nil + package var configurationAfter: String? = nil +} + +/// One prepared physical replacement owns all logical contributions at that destination. +package final class ArtifactAggregation: PreparedEvidence { + package private(set) var ledger: ResolvedLedger + package private(set) var changes: [AggregatedChange] = [] + package private(set) var fingerprints: [String] = [] + package private(set) var antigravityConflicts: [String] = [] + package private(set) var instructionDecisionLocations: [URL] = [] + package private(set) var needsRetainedArtifactPublication = false + private let store: StateStore + private let roots: [String: URL] + private let resources: [String: URL] + private let replace: Bool + private let selectedKinds: Set? + private let selectedNames: Set + private let selectedIdentities: Set? + private let retargetedInstructions: Set + private var unownedInstructions: [String] = [] + private var unownedSkills: [String] = [] + private var targets: [String: TargetPrecondition] = [:] + private var writes: [String: FileTransaction.Source] = [:] + private var archiveDestinations: [String: ArchiveDeploymentAccess] = [:] + private var deletes = Set() + private var capsules: [String: URL] = [:] + private var skillTargets: [String: SkillInstallationTarget] = [:] + private var skillWritePaths = Set() + private var skillDeletePaths = Set() + private var skillContent: [String: (String, [String: Bool])] = [:] + private var privateWrites: + [(PreparedPrivateMaterialization, Set, (RuntimeBindingValues) throws -> Data)] = [] + private var nativePrivateWrites: + [( + PreparedPrivateMaterialization, Set, + (RuntimeBindingValues) throws -> PrivateMaterializationResult + )] = [] + private var privateTrees: [(PreparedPrivateMaterialization, [PrivateTreeEntry])] = [] + private var resourceEvidence: [TargetPrecondition] = [] + private var physicalPaths: [NativeTargetIdentity: String] = [:] + + package init( + ledger: ResolvedLedger, previous: ResolvedLedger, artifacts: [ReplayedArtifact], + resources: [String: URL], workspace: URL, store: StateStore, roots: [String: URL], + replace: Bool, + changingAccess: Bool, + kinds: Set? = nil, names: Set = [], + selectedIdentities: Set? = nil, + installations: [SkillInstallationTarget] = [], retargetedInstructions: Set = [], + offlineBaseline: Bool = false, sourcePolicy: EffectiveSourcePolicy = .init(), + verifyPriorSkillLinks: Bool = false + ) throws { + self.ledger = ledger + self.store = store + self.roots = roots + self.resources = resources + self.replace = replace + if ledger.sources.values.contains(where: { $0.archive != nil }) { + try SourceCache(store: store).requireArchivePublicationAccess() + } + for target in installations { skillTargets[target.url.path] = target } + selectedKinds = kinds + selectedNames = names + self.selectedIdentities = selectedIdentities + self.retargetedInstructions = retargetedInstructions + for (id, file) in resources where ledger.resources[id]?.kind != .liveEdit { + resourceEvidence.append(try TargetPrecondition(file)) + } + func selected(_ deployment: LedgerDeployment, in ledger: ResolvedLedger) throws -> Bool { + try deployment.owners.contains { try isSelected($0, in: ledger) } + } + var retainedArtifactEvidence: [String: TargetPrecondition] = [:] + for (id, source) in resources where ledger.resources[id]?.kind != .liveEdit { + let resource = ledger.resources[id]! + let destination = try resourceDestination(id) + if resource.kind == .artifact && resource.location != nil { + if retainedArtifactEvidence[destination.path] == nil { + let input = try TargetPrecondition(destination) + retainedArtifactEvidence[destination.path] = input + resourceEvidence.append(input) + } + } else if resource.kind != .archive, FileManager.default.fileExists(atPath: destination.path) + { + resourceEvidence.append(try TargetPrecondition(destination)) + } + if resource.kind == .embedded || (resource.kind == .artifact && resource.location == nil) { + let capsule = workspace.appendingPathComponent( + "capsule-" + FileHash.sha256Hex(data: Data(id.utf8))) + try FileSystem.createDirectory(at: capsule) + if resource.support.isEmpty { + try FileManager.default.copyItem( + at: source, to: capsule.appendingPathComponent("payload")) + } else { + var sourceRoot = source + if resource.path != "." { + for _ in resource.path.split(separator: "/") { sourceRoot.deleteLastPathComponent() } + } + let captured = try LedgerResources.capture( + source, embed: true, limits: .standard, sourceRoot: sourceRoot) + guard captured.hash == resource.hash else { + throw CoreError.invalidState("retention input changed") + } + var embedded = resource + embedded.kind = .embedded + embedded.entries = captured.entries + embedded.support = captured.support + try LedgerResources.materialize(embedded, objects: captured.objects, at: capsule) + } + capsules[id] = capsule + resourceEvidence.append(try TargetPrecondition(capsule)) + } + } + let artifacts = Dictionary(uniqueKeysWithValues: artifacts.map { ($0.name, $0) }) + let affectedPaths = try Set( + previous.deployments.filter { try selected($0, in: previous) }.map { + try installationURL($0).path + } + + ledger.deployments.filter { try selected($0, in: ledger) }.map { + try installationURL($0).path + }) + let previousByPath = try Dictionary( + grouping: previous.deployments.filter { try affectedPaths.contains(installationURL($0).path) } + ) { try installationURL($0).path } + var byPath = try Dictionary( + grouping: ledger.deployments.filter { try affectedPaths.contains(installationURL($0).path) } + ) { try installationURL($0).path } + var native: [String: [(LockedLowering, NativeMCPContribution, MaterializationTarget)]] = [:] + for lowering in ledger.lowerings + where lowering.format.hasSuffix("-mcp@1") { + let contribution = try MCPLayoutV1.contribution(lowering, ledger: ledger) + let route = try DeploymentConstruction.physicalRoute( + DeploymentConstruction.route(contribution), ledger: previous, store: store) + let target = try store.nativeTarget(for: route) + native[try physicalPath(route), default: []].append((lowering, contribution, target)) + } + // Removed native regions still participate in the same physical aggregation. + for lowering in previous.lowerings + where lowering.format.hasSuffix("-mcp@1") { + let c = try MCPLayoutV1.contribution(lowering, ledger: previous) + let path = try physicalPath( + DeploymentConstruction.physicalRoute( + DeploymentConstruction.route(c), ledger: previous, store: store)) + if native[path] == nil { native[path] = [] } + } + let currentComponents = try componentOutputs(ledger, artifacts: artifacts, routing: previous) + let oldNative = Set( + previous.lowerings.filter { + $0.format.hasSuffix("-components@1") || $0.format.hasSuffix("-generated-plugin@1") + }.map(\.id)) + try LedgerReplay.withPriorOutputs( + previous, store: store, roots: roots, lowerings: oldNative, + offline: offlineBaseline, sourcePolicy: sourcePolicy + ) { oldArtifacts in + let oldComponents = try componentOutputs( + previous, + artifacts: Dictionary(uniqueKeysWithValues: oldArtifacts.map { ($0.name, $0) }), + routing: previous) + let generatedPaths = try prepareGeneratedPlugins( + previous: previous, artifacts: artifacts, + oldArtifacts: Dictionary(uniqueKeysWithValues: oldArtifacts.map { ($0.name, $0) }), + workspace: workspace, changingAccess: changingAccess) + guard + generatedPaths.isDisjoint( + with: Set(currentComponents.keys).union(oldComponents.keys).union(native.keys)) + else { + throw CoreError.invalidState("generated native container overlaps another native target") + } + for path in generatedPaths { + native[path] = [] + byPath.removeValue(forKey: path) + } + for path in Set(native.keys).union(currentComponents.keys).union(oldComponents.keys) + .subtracting(generatedPaths).sorted() + { + let next = currentComponents[path] ?? [] + let old = oldComponents[path] ?? [] + let entries = next + old + if let first = entries.first { + switch first.output.content { + case .file, .nativePlugin, .generatedLSPPlugin: + guard native[path] == nil else { + throw CoreError.invalidState("whole native object overlaps a shared document") + } + if try entries.contains(where: { + try isSelected( + $0.contribution.component, + in: ledger.components[$0.contribution.component] == nil ? previous : ledger) + }) { + try prepareWholeNative( + path: path, next: next, old: old, previous: previous, + artifacts: artifacts, workspace: workspace, changingAccess: changingAccess) + } else { + for entry in next { + let privatePlan = + try store.materializationReceipt(for: entry.target) == nil + ? nil : store.preparePrivateMaterialization(entry.target) + try record( + entry, previous: previous, changed: false, + readers: Array( + Set( + entry.contribution.knownReaders + + DeploymentConstruction.route( + entry.output, request: entry.contribution.request + ) + .knownReaders) + ).sorted { $0.rawValue < $1.rawValue }, + privatePlan: privatePlan, ownership: .generated) + } + } + case .ignore: + guard native[path] == nil else { + throw CoreError.invalidState("ignore block overlaps a structured document") + } + try prepareIgnore(path: path, next: next, old: old, previous: previous) + default: + try prepareNative( + path: path, contributions: native[path] ?? [], previous: previous, + changingAccess: changingAccess, components: next, oldComponents: old) + } + } else { + try prepareNative( + path: path, contributions: native[path] ?? [], previous: previous, + changingAccess: changingAccess) + } + native[path] = native[path] ?? [] + byPath.removeValue(forKey: path) + } + } + for path in Set(byPath.keys).union(previousByPath.keys).sorted() where native[path] == nil { + let url = URL(fileURLWithPath: path) + let capture = try TargetPrecondition(url).capturingPublicationAccess() + targets[path] = capture + let old = previousByPath[path] ?? [] + let next = byPath[path] ?? [] + if verifyPriorSkillLinks, capture.exists, + let prior = old.first(where: { $0.route == "agents/skill@1" }), + let lowering = previous.lowerings.first(where: { $0.deployments.contains(prior.id) }), + lowering.layout.object?["mode"]?.text == InstallMode.link.rawValue, + let resource = lowering.resources.first, + try !PathSafety.matchesSymbolicLink( + at: url, destination: resourceDestination(resource, in: previous)) + { + unownedSkills.append("recorded marketplace skill link changed at \(path)") + continue + } + let sharedImport = (old + next).contains { $0.ownership == .importBlock } + fingerprints.append(try capture.displayEvidence(includeContent: !sharedImport)) + if sharedImport { + let observed = try InstructionTargets.ownedImportBytes( + TargetPrecondition.readingFile(url).bytes) + fingerprints.append(try ResolvedLedgerCodec.digest([path: observed])) + } + if next.isEmpty { + guard let deployment = old.first else { continue } + if deployment.route == "agents/skill@1" { + deletes.insert(path) + skillDeletePaths.insert(path) + changes.append( + .init( + deployment: deployment, url: url, before: nil, after: nil, + changed: FileManager.default.fileExists(atPath: path), native: false)) + } else { + let before = try TargetPrecondition.readingFile(url).bytes + let after = try InstructionCompatibility.obsolete(deployment, before: before) + if before != after { + if let after { writes[path] = .data(after) } else { deletes.insert(path) } + } + changes.append( + .init( + deployment: deployment, url: url, before: before, after: after, + changed: before != after, native: false, + instructionForeign: deployment.route == AntigravityRuleV1.format ? false : nil)) + } + continue + } + let entries = try next.map { + deployment -> (LedgerDeployment, ReplayedArtifact, LockedLowering) in + guard + let lowering = ledger.lowerings.first(where: { $0.deployments.contains(deployment.id) }), + let name = lowering.artifacts.first?.name, let artifact = artifacts[name] + else { throw CoreError.invalidState("deployment has no rendered artifact") } + return (deployment, artifact, lowering) + } + let first = entries[0] + guard + try entries.allSatisfy({ + try $0.1.digest(limits: .standard).hash == first.1.digest(limits: .standard).hash + && $0.1.kind == first.1.kind + && $0.2.layout.object?["mode"] == first.2.layout.object?["mode"] + }) + else { + throw CoreError.invalidState("incompatible contributions share a physical target") + } + let deployment = first.0 + let artifact = first.1 + let archive = next.contains { output in + ledger.lowerings.contains { + $0.deployments.contains(output.id) + && $0.resources.contains(where: { ledger.resources[$0]?.kind == .archive }) + } + } + if archive { + let access = try ArchiveDeploymentAccess(at: url) + archiveDestinations[path] = access + if let members = try access.memberAccessFingerprint() { fingerprints.append(members) } + } + 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 + { + resourceEvidence.append(try TargetPrecondition(URL(fileURLWithPath: resolved))) + } + if old.isEmpty, FileManager.default.fileExists(atPath: path) { + unownedSkills.append( + "skill '\(ledger.components[deployment.owners[0]]!.name)' in \(store.scope.rawValue) scope has unmanaged content at \(path); move or remove it first" + ) + } + let mode = first.2.layout.object?["mode"]?.text ?? "copy" + let source: FileTransaction.Source + var liveDirectory: URL? + if let id = first.2.resources.first, let resource = ledger.resources[id], + resource.kind == .liveEdit + { + let edit = try LedgerResources.liveEditSource(resource, ledger: ledger, roots: roots) + source = .link(edit.authored) + liveDirectory = edit.directory + } else if mode == InstallMode.link.rawValue { + source = .link(try resourceDestination(first.2.resources[0])) + } else if let tree = artifact.tree { + try DeploymentConstruction.validateCopiedSkill(tree) + source = .copy(tree) + } else { + throw CoreError.invalidState("skill artifact has no content") + } + let changed: Bool + switch source { + case .link(let destination): + changed = !PathSafety.matchesSymbolicLink(at: url, destination: destination) + if archive, let tree = artifact.tree { + let hash = try FileHash.folderHash(tree) + let flags = try FileHash.executableFlags(tree) + if (try? ArchiveDeploymentAccess(at: destination)) == nil + || (try? FileHash.folderHash(destination)) != hash + || (try? FileHash.executableFlags(destination)) != flags + { + needsRetainedArtifactPublication = true + } + } + if let destinationEvidence = retainedArtifactEvidence[destination.path] { + if !destinationEvidence.exists { needsRetainedArtifactPublication = true } + fingerprints.append(try destinationEvidence.displayEvidence(includeContent: false)) + } + case .copy(let tree): + let hash = try FileHash.folderHash(tree) + let flags = try FileHash.executableFlags(tree) + let type = + try? FileManager.default.attributesOfItem(atPath: url.path)[.type] as? FileAttributeType + changed = + type != .typeDirectory || (try? FileHash.folderHash(url)) != hash + || (try? FileHash.executableFlags(url)) != flags + default: changed = true + } + if let tree = artifact.tree, let id = first.2.resources.first, + let resource = ledger.resources[id] + { + skillContent[path] = (resource.hash, try FileHash.executableFlags(tree)) + } + if changed { + writes[path] = liveDirectory.map(FileTransaction.Source.link) ?? source + skillWritePaths.insert(path) + } + changes.append( + .init( + deployment: deployment, url: url, before: nil, after: nil, + changed: changed, native: false, + afterLink: { if case .link(let url) = source { url } else { nil } }())) + } else if deployment.route == AntigravityRuleV1.format { + guard let bytes = artifact.bytes else { + throw CoreError.invalidState("missing rendered Antigravity rule") + } + try prepareAntigravity( + deployment, lowering: first.2, at: url, bytes: bytes, previouslyManaged: !old.isEmpty) + } else { + let before = try TargetPrecondition.readingFile(url).bytes + var after = artifact.bytes + if deployment.route == "agents/instructions@1", let after { + try InstructionTargets(store: store).validateRenderedLinks(after, at: url) + } + if deployment.ownership == .importBlock { + guard let path = ClaudeInstructionPath(rawValue: deployment.target.path) else { + throw CoreError.invalidState("invalid locked import location") + } + after = + before == nil && !old.isEmpty + ? nil : try InstructionTargets.importBlock(in: before ?? Data(), at: path).bytes + } else if let before, before != after, !Instructions.isOwned(before), !replace { + unownedInstructions.append(InstructionLocations.key(for: url, store: store)) + } + if before != after { + if let after { writes[path] = .data(after) } else { deletes.insert(path) } + } + changes.append( + .init( + deployment: deployment, url: url, before: before, after: after, + changed: before != after, native: false)) + } + } + try validate() + } + + private func prepareAntigravity( + _ deployment: LedgerDeployment, lowering: LockedLowering, at url: URL, bytes: Data, + previouslyManaged: Bool + ) throws { + let current = try TargetPrecondition.readingFile(url) + let evidence = try current.evidence.capturingPublicationAccess() + guard targets[url.path]?.sameGeneration(as: evidence) == true else { + throw CoreError.invalidState("Antigravity rule changed during preparation: " + url.path) + } + let foreign = + current.bytes.map { + $0 != bytes + && (!previouslyManaged + || !InstructionCompatibility.ownsAntigravityRule( + $0, leaf: url.lastPathComponent, scope: store.scope)) + } ?? false + if foreign { + antigravityConflicts.append("Unmanaged content at Antigravity rule destination: " + url.path) + } else if current.bytes != bytes { + writes[url.path] = .data(bytes) + } + changes.append( + .init( + deployment: deployment, url: url, before: current.bytes, after: bytes, + changed: current.bytes != bytes, native: false, instructionForeign: foreign)) + + guard store.scope == .user, + let unitID = lowering.resources.first, let unit = ledger.resources[unitID], + let leaf = AntigravityRuleV1.legacyLeaf(path: unit.path), let file = resources[unitID] + else { return } + let legacy = try InstructionLocations.antigravityLeaf(leaf, store: store, legacy: true) + instructionDecisionLocations.append(legacy) + let installed = try TargetPrecondition.readingFile(legacy) + let legacyEvidence = try installed.evidence.capturingPublicationAccess() + fingerprints.append(try evidence.generationEvidence()) + fingerprints.append(try legacyEvidence.displayEvidence(includeContent: true)) + fingerprints.append(try legacyEvidence.generationEvidence()) + if targets.updateValue(legacyEvidence, forKey: legacy.path) != nil, installed.bytes != nil { + antigravityConflicts.append( + "Multiple selected rules claim the same Memex file: " + legacy.path) + return + } + guard let installedBytes = installed.bytes else { return } + guard let revision = ledger.sources[unit.source]?.revision, SourceCache.isObjectID(revision), + try AntigravityRuleV1.legacyBytes( + unit: FileSystem.read(at: file), path: unit.path, revision: revision) == installedBytes + else { + antigravityConflicts.append( + "Memex rule differs from the selected source path, revision or bytes: " + legacy.path) + return + } + deletes.insert(legacy.path) + changes.append( + .init( + deployment: deployment, url: legacy, before: installedBytes, after: nil, + changed: true, native: false, instructionForeign: false)) + } + + private func resourceDestination(_ id: String, in selected: ResolvedLedger? = nil) throws -> URL { + try Self.resourceDestination(id, ledger: selected ?? ledger, store: store, roots: roots) + } + + private func installationURL(_ deployment: LedgerDeployment) throws -> URL { + if deployment.route == AntigravityRuleV1.format { + guard deployment.target.root == InstructionLocations.ruleRoot(in: store.scope) else { + throw CoreError.invalidState("Antigravity rule belongs to another scope") + } + return try InstructionLocations.antigravityLeaf(deployment.target.path, store: store) + } + guard deployment.route == "agents/skill@1" else { + return InstructionLocations.physical(try deployment.target.resolve(roots: roots)) + } + guard let agent = deployment.recipients.first else { + throw CoreError.invalidState("missing skill recipient") + } + let target = try store.skillInstallationTarget(for: agent, named: deployment.target.path) + guard let admitted = skillTargets[target.url.path] else { + throw CoreError.invalidState("skill installation was not admitted") + } + return admitted.url + } + + package static func resourceDestination( + _ id: String, ledger: ResolvedLedger, store: StateStore, roots: [String: URL]? = nil + ) throws -> URL { + guard let resource = ledger.resources[id] else { + throw CoreError.invalidState("missing deployment resource") + } + if let location = resource.location { + if let artifact = resource.artifact { + return try SourceCache(store: store).artifactContentURL(digest: artifact.digest) + } + return try location.resolve(roots: roots ?? store.ledgerRoots) + } + if resource.kind == .archive { + let source = try ledger.rootSource(resource.source) + 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) + } + if let root = try gitDestination(resource, ledger: ledger, store: store, roots: roots) { + return root.appendingPathComponent(resource.path) + } + let base = store.cacheDirectory.appendingPathComponent( + "artifact-content/" + String(id.dropFirst(7))) + return base.appendingPathComponent(resource.support.isEmpty ? "payload" : resource.path) + } + + private static func gitDestination( + _ resource: LedgerResource, ledger: ResolvedLedger, store: StateStore, roots: [String: URL]? + ) throws -> URL? { + guard resource.kind == .git else { return nil } + var sourceID = resource.source + while let parent = ledger.sources[sourceID]?.container { sourceID = parent } + guard let source = ledger.sources[sourceID] else { + throw CoreError.invalidState("missing resource source") + } + return SourceCache(store: store).materializedURL( + sourceID: try ledger.sourceIdentity(sourceID, roots: roots ?? store.ledgerRoots), + revision: source.revision) + } + + private func physicalPath(_ requested: NativeTargetRoute) throws -> String { + let route = try DeploymentConstruction.physicalRoute(requested, ledger: ledger, store: store) + let target = try store.nativeTarget(for: route) + guard let identity = try store.nativeTargetIdentity(for: route) else { return target.url.path } + if let path = physicalPaths[identity] { + if path != target.url.path { resourceEvidence.append(try TargetPrecondition(target.url)) } + return path + } + physicalPaths[identity] = target.url.path + return target.url.path + } + + private func isSelected(_ id: String, in selected: ResolvedLedger) throws -> Bool { + guard let c = selected.components[id] else { return false } + if try retargetedInstructions.contains( + LedgerImpact.identity(c, ledger: selected, roots: roots)) + { + return true + } + if let selectedIdentities { + return try selectedIdentities.contains( + LedgerImpact.identity(c, ledger: selected, roots: roots)) + } + return (selectedKinds?.contains(DeclaredComponentKind(rawValue: c.kind)!) ?? true) + && (selectedNames.isEmpty + || selectedNames.contains(c.kind == "skills" ? PathSafety.sanitizeName(c.name) : c.name)) + } + + private struct ComponentOutputEntry { + let lowering: LockedLowering + let contribution: NativeComponentContribution + let output: NativeComponentOutput + let target: MaterializationTarget + let index: Int + var id: String { lowering.id + ":" + String(index) } + } + + private func componentOutputs( + _ selected: ResolvedLedger, artifacts: [String: ReplayedArtifact], routing: ResolvedLedger + ) throws -> [String: [ComponentOutputEntry]] { + var result: [String: [ComponentOutputEntry]] = [:] + for lowering in selected.lowerings where lowering.format.hasSuffix("-components@1") { + let contribution = try NativeComponentLayoutsV1.contribution( + lowering, ledger: selected, + artifacts: try lowering.artifacts.map { digest in + guard let artifact = artifacts[digest.name] else { + throw CoreError.invalidState("missing sealed native output") + } + return artifact + }, limits: .standard) + for (index, output) in contribution.outputs.enumerated() { + let route = try DeploymentConstruction.physicalRoute( + DeploymentConstruction.route(output, request: contribution.request), + ledger: selected.deployments.contains(where: { $0.route.hasPrefix("agents/opencode-") }) + ? selected : routing, store: store) + let target = try store.nativeTarget(for: route) + result[try physicalPath(route), default: []].append( + .init( + lowering: lowering, contribution: contribution, + output: output, target: target, index: index)) + } + } + return result + } + + private func location(_ target: MaterializationTarget) -> LedgerLocation { + let parts = target.path.split(separator: "/", maxSplits: 1) + return .init(kind: .registered, root: String(parts[0]), path: String(parts[1])) + } + + private func record( + _ entry: ComponentOutputEntry, previous: ResolvedLedger, changed: Bool, + readers: [AgentID], privatePlan: PreparedPrivateMaterialization? = nil, + bindings: [String] = [], ownership: LedgerDeployment.Ownership = .ownedValues + ) throws { + let identity = try LedgerImpact.identity( + ledger.components[entry.contribution.component]!, ledger: ledger, roots: roots) + let oldComponent = try previous.components.values.first { + try LedgerImpact.identity($0, ledger: previous, roots: roots) == identity + } + let deployment = LedgerDeployment( + id: entry.id, target: location(entry.target), route: entry.lowering.format, + owners: [entry.contribution.component], recipients: entry.contribution.recipients, + ownership: ownership, expectedHash: entry.lowering.artifacts[0].hash, + created: previous.deployments.first { + $0.route == entry.lowering.format + && (try? $0.target.resolve(roots: roots).path) == entry.target.url.path + }?.created ?? !FileManager.default.fileExists(atPath: entry.target.url.path)) + ledger.deployments.removeAll { $0.id == entry.id } + ledger.deployments.append(deployment) + if let i = ledger.lowerings.firstIndex(where: { $0.id == entry.lowering.id }) { + if !ledger.lowerings[i].deployments.contains(entry.id) { + ledger.lowerings[i].deployments.append(entry.id) + } + } + changes.append( + .init( + deployment: deployment, url: entry.target.url, before: nil, after: nil, + changed: changed, native: true, accessChange: privatePlan?.accessChange, + effectiveReaders: readers, + privateMaterialization: privatePlan != nil, requiredBindings: bindings, + memberAccessChanges: privatePlan?.memberAccessChanges ?? [], + symbolicBefore: oldComponent?.payload, + symbolicAfter: ledger.components[entry.contribution.component]?.payload)) + } + + private func componentValue( + _ value: NativeComponentValue, values: RuntimeBindingValues?, + selected: ResolvedLedger + ) throws -> NativeValue { + try Self.componentValue(value, values: values, selected: selected, store: store, roots: roots) + } + + private static func componentValue( + _ value: NativeComponentValue, values: RuntimeBindingValues?, + selected: ResolvedLedger, store: StateStore, roots: [String: URL], symbolicVariant: Int = 0 + ) throws -> NativeValue { + var environment = store.environment + var symbolic: [String: Data] = [:] + if values == nil { + // Preview converts the typed program without reading runtime values. + for placement in value.bindings { + switch placement.binding { + case .secret(let name): + symbolic[name] = Data( + ("agents-symbolic-secret-" + String(symbolicVariant) + "-" + + FileHash.sha256Hex(data: Data(name.utf8))).utf8) + case .environment(let name): + environment.environment[name] = + "agents-symbolic-environment-" + String(symbolicVariant) + "-" + + FileHash.sha256Hex(data: Data(name.utf8)) + case .literal: break + } + } + } + let paths = try selected.resources.keys.reduce(into: [String: String]()) { + $0[$1] = try Self.resourceDestination($1, ledger: selected, store: store, roots: roots).path + } + return try value.stagedValue( + bindings: values ?? RuntimeBindingValues(symbolic), environment: environment, + resourcePaths: paths, + budget: NativeDocumentBudget( + limits: .init( + storage: LedgerLimits.standard.resourceBytes, + work: LedgerLimits.standard.encodedBytes, nodes: LedgerLimits.standard.nodes, + depth: LedgerLimits.standard.depth, uninterruptedBytes: LedgerLimits.standard.keyBytes)), + codexCommandShell: .posix, cursorCommandShell: .posix) + } + + private static func generatedManifestMatches( + _ manifest: NativeComponentValue, observed: NativeValue?, selected: ResolvedLedger, + privateGeneration: Bool, store: StateStore, roots: [String: URL] + ) throws -> Bool { + guard let observed else { return false } + let first = try Self.componentValue( + manifest, values: nil, selected: selected, store: store, roots: roots) + guard privateGeneration, !manifest.bindings.isEmpty else { return observed == first } + let second = try Self.componentValue( + manifest, values: nil, selected: selected, store: store, roots: roots, symbolicVariant: 1) + // F determines the native positions. Only leaves changed by its binding conversion vary. + func matches(_ actual: NativeValue, _ a: NativeValue, _ b: NativeValue) -> Bool { + if a == b { return actual == a } + switch (actual, a, b) { + case (.string, .string, .string): return true + case (.object(let actual), .object(let a), .object(let b)): + guard Set(actual.keys) == Set(a.keys), Set(a.keys) == Set(b.keys) else { return false } + return a.allSatisfy { matches(actual[$0.key]!, $0.value, b[$0.key]!) } + case (.array(let actual), .array(let a), .array(let b)): + guard actual.count == a.count, a.count == b.count else { return false } + return a.indices.allSatisfy { matches(actual[$0], a[$0], b[$0]) } + default: return false + } + } + return matches(observed, first, second) + } + + private func generatedManifestBytes( + _ manifest: NativeComponentValue, values: RuntimeBindingValues? + ) throws -> Data { + try Self.generatedManifestBytes( + manifest, values: values, selected: ledger, store: store, roots: roots) + } + + /// Renders a selected symbolic value with the native JSON serializer, without physical input. + package static func configurationPreview(_ value: NativeValue) throws -> String { + func document(_ bytes: Data) throws -> NativeDocument { + try NativeDocument( + bytes: bytes, format: .json, + budget: NativeDocumentBudget( + limits: .init( + storage: LedgerLimits.standard.resourceBytes, work: LedgerLimits.standard.encodedBytes, + nodes: LedgerLimits.standard.nodes, depth: LedgerLimits.standard.depth, + uninterruptedBytes: LedgerLimits.standard.keyBytes))) + } + let region = NativeRegion(keys: ["selected"]) + let bytes = try document(Data("{}".utf8)).prepare([ + .put(region: region, expected: .absent, value: value) + ]).bytes + guard let range = try document(bytes).read(region)?.valueRange else { + throw CoreError.invalidState("selected configuration has no rendered range") + } + return String(decoding: bytes.subdata(in: range), as: UTF8.self) + } + + private static func generatedManifestBytes( + _ manifest: NativeComponentValue, values: RuntimeBindingValues?, + selected: ResolvedLedger, store: StateStore, roots: [String: URL] + ) throws -> Data { + guard + case .object(let fields) = try componentValue( + manifest, values: values, selected: selected, store: store, roots: roots) + else { throw CoreError.invalidState("generated native manifest must be an object") } + let document = try NativeDocument( + bytes: Data("{}".utf8), format: .json, + budget: NativeDocumentBudget( + limits: .init( + storage: LedgerLimits.standard.resourceBytes, work: LedgerLimits.standard.encodedBytes, + nodes: LedgerLimits.standard.nodes, depth: LedgerLimits.standard.depth, + uninterruptedBytes: LedgerLimits.standard.keyBytes))) + return try document.prepare( + fields.keys.sorted().map { + .put(region: .init(keys: [$0]), expected: .absent, value: fields[$0]!) + } + ).bytes + } + + private func prepareWholeNative( + path: String, next: [ComponentOutputEntry], old: [ComponentOutputEntry], + previous: ResolvedLedger, artifacts: [String: ReplayedArtifact], workspace: URL, + changingAccess: Bool + ) throws { + guard let target = (next.first ?? old.first)?.target else { return } + let capture = try TargetPrecondition(target.url).capturingPublicationAccess() + targets[path] = capture + fingerprints.append(try capture.displayEvidence(includeContent: false)) + var physicalReaders = Set((next + old).flatMap { $0.contribution.knownReaders }) + for entry in next + old { + physicalReaders.formUnion( + try DeploymentConstruction.route(entry.output, request: entry.contribution.request) + .knownReaders) + } + let readers = physicalReaders.sorted { $0.rawValue < $1.rawValue } + guard next.count <= 1, old.count <= 1 else { + throw CoreError.invalidState("conflicting native whole-object owners") + } + let hasBindings: Bool = next.contains { + if case .generatedLSPPlugin(_, _, let manifest) = $0.output.content { + return !manifest.bindings.isEmpty + } + return false + } + let hadBindings: Bool = old.contains { + if case .generatedLSPPlugin(_, _, let manifest) = $0.output.content { + return !manifest.bindings.isEmpty + } + return false + } + let receipt = try store.materializationReceipt(for: target) + let privatePlan = + try hasBindings || hadBindings || receipt != nil + ? store.preparePrivateMaterialization( + target, changingAccess: changingAccess, + requiringReceiptForExistingTarget: hadBindings) : nil + if let privatePlan { + struct MemberAccess: Encodable { + let path: String + let before: String + let afterOwner: UInt32 + let afterMode: UInt32 + } + fingerprints.append( + try ResolvedLedgerCodec.digest( + privatePlan.memberAccessChanges.map { + let file = try PathSafety.resolvedChild(base: target.url, subpath: $0.path) + return MemberAccess( + path: $0.path, + before: try TargetPrecondition(file).displayEvidence(includeContent: false), + afterOwner: $0.owner, afterMode: $0.mode) + })) + } + func bindingNames(_ entry: ComponentOutputEntry) -> Set { + guard case .generatedLSPPlugin(_, _, let manifest) = entry.output.content else { return [] } + return Set( + manifest.bindings.compactMap { + if case .secret(let name) = $0.binding { return name } + return nil + }) + } + func source(_ entry: ComponentOutputEntry) throws -> FileTransaction.Source { + switch entry.output.content { + case .file(_, let bytes): return .data(bytes) + case .nativePlugin(_, let resource, _): + guard let artifact = artifacts[entry.lowering.id + "/bundle"], let tree = artifact.tree, + ledger.resources[resource] != nil + else { throw CoreError.invalidState("missing frozen native container") } + return .copy(tree) + case .generatedLSPPlugin(_, let manifestPath, let manifest): + let tree = workspace.appendingPathComponent( + "native-tree-" + FileHash.sha256Hex(data: Data(entry.id.utf8))) + let file = try PathSafety.resolvedChild(base: tree, subpath: manifestPath) + try FileSystem.createDirectory(at: file.deletingLastPathComponent()) + let bytes = try generatedManifestBytes(manifest, values: nil) + try bytes.write(to: file) + return .copy(tree) + default: throw CoreError.invalidState("native whole-object content has a regional shape") + } + } + let exists = FileManager.default.fileExists(atPath: path) + if exists { + guard let old = old.first, + let deployment = previous.deployments.first(where: { $0.id == old.id }), + deployment.ownership == .generated + else { + throw CoreError.invalidState("native target contains unmanaged content") + } + switch old.output.content { + case .file(_, let bytes): + guard try Data(contentsOf: target.url) == bytes else { + throw CoreError.invalidState("owned native file drifted") + } + case .nativePlugin(_, let resource, _): + let observed = try LedgerResources.capture(target.url, embed: false, limits: .standard) + guard observed.hash == previous.resources[resource]?.hash, + observed.entries.map(\.executable) + == previous.resources[resource]?.entries.map(\.executable) + else { throw CoreError.invalidState("owned native tree drifted") } + case .generatedLSPPlugin(_, let manifestPath, let manifest): + let captured = try LedgerResources.capture(target.url, embed: false, limits: .standard) + let expectedPaths = Set([ + ".", manifestPath, (manifestPath as NSString).deletingLastPathComponent, + ]) + guard captured.entries.allSatisfy({ expectedPaths.contains($0.path) && !$0.executable }) + else { + throw CoreError.invalidState("generated native container has unmanaged members") + } + let current = try NativeDocument( + bytes: Data(contentsOf: target.url.appendingPathComponent(manifestPath)), format: .json, + budget: nativeBudget()) + guard + try Self.generatedManifestMatches( + manifest, observed: current.read(.init(keys: []))?.value, selected: previous, + privateGeneration: receipt != nil, store: store, roots: roots) + else { throw CoreError.invalidState("owned generated native tree drifted") } + default: throw CoreError.invalidState("invalid whole-object ownership") + } + } + if let entry = next.first { + let desired = try source(entry) + let changed: Bool + switch desired { + case .data(let bytes): changed = try !exists || Data(contentsOf: target.url) != bytes + case .copy(let tree): + changed = try !exists || FileHash.folderHash(target.url) != FileHash.folderHash(tree) + default: throw CoreError.invalidState("invalid native whole-object source") + } + if let privatePlan { + switch entry.output.content { + case .generatedLSPPlugin(_, let manifestPath, let manifest): + let parts = manifestPath.split(separator: "/") + var members: [PrivateTreeEntry] = [] + for count in 1.. String { + let lines = try entries.flatMap { entry -> [String] in + guard case .ignore(let lines) = entry.output.content else { + throw CoreError.invalidState("incompatible ignore owners") + } + return lines + } + return entries.isEmpty ? "" : opening + lines.joined(separator: "\n") + "\n" + closing + } + let before = capture.bytes ?? Data() + guard let text = String(data: before, encoding: .utf8) else { + throw CoreError.invalidState("ignore document is not UTF8") + } + let starts = text.components(separatedBy: opening).count - 1 + let ends = text.components(separatedBy: closing).count - 1 + guard starts == ends, starts <= 1 else { + throw CoreError.invalidState("ambiguous managed ignore block") + } + let after: String + let desired = try block(next) + if let start = text.range(of: opening), let end = text.range(of: closing), + start.lowerBound < end.upperBound + { + let range = start.lowerBound.. + let symbolic: LedgerValue + var render: (RuntimeBindingValues?) throws -> NativeValue + } + + private func prepareNative( + path: String, contributions: [(LockedLowering, NativeMCPContribution, MaterializationTarget)], + previous: ResolvedLedger, changingAccess: Bool, + components: [ComponentOutputEntry] = [], oldComponents: [ComponentOutputEntry] = [] + ) throws { + let url = URL(fileURLWithPath: path) + let capture = try TargetPrecondition.readingFile(url) + targets[path] = try capture.evidence.capturingPublicationAccess() + fingerprints.append(try capture.evidence.displayEvidence(includeContent: false)) + let old = try previous.lowerings.filter { $0.format.hasSuffix("-mcp@1") }.compactMap { + lowering -> NativeMCPContribution? in + let c = try MCPLayoutV1.contribution(lowering, ledger: previous) + return try physicalPath( + DeploymentConstruction.physicalRoute( + DeploymentConstruction.route(c), ledger: previous, store: store)) == path ? c : nil + } + let priorTarget = try old.first.map { + try store.nativeTarget( + for: DeploymentConstruction.physicalRoute( + DeploymentConstruction.route($0), ledger: previous, store: store)) + } + guard + let target = contributions.first?.2 ?? components.first?.target ?? oldComponents.first?.target + ?? priorTarget + else { return } + let format = + components.first?.output.route.documentFormat ?? oldComponents.first?.output.route + .documentFormat + ?? contributions.first?.1.descriptor.documentFormat ?? old.first!.descriptor.documentFormat + let budget = nativeBudget() + let document = try NativeDocument( + bytes: capture.bytes ?? Data((format == .toml ? "" : "{}\n").utf8), + format: format, budget: budget) + let selectedStore = store + let planningRoots = roots + func valueRoots(_ values: RuntimeBindingValues?) -> [String: URL] { + values == nil ? planningRoots : selectedStore.ledgerRoots(recordedIn: previous) + } + func names(_ bindings: [NativeComponentBindingPlacement]) -> Set { + Set( + bindings.compactMap { + switch $0.binding { + case .environment(let n), .secret(let n): n + case .literal: nil + } + }) + } + func mcp(_ c: NativeMCPContribution, selected: ResolvedLedger) throws -> NativeRegionOwner? { + let region = try c.descriptor.region( + server: c.name, + nativeProjectKey: c.descriptor.request.scope == .local + ? try store.nativeTarget(for: .claudeMCPProject).url.deletingLastPathComponent().path + : nil) + let key = try ResolvedLedgerCodec.digest(c.descriptor.request.scope.rawValue + ":" + c.name) + if try !isSelected(c.component, in: selected) { + guard let observed = try document.read(region)?.value else { return nil } + return .init( + key: key, region: region, + deployments: [ + contributions.first(where: { $0.1.component == c.component })?.0.id + ?? previous.lowerings.first(where: { + $0.inputs.contains(c.component) && $0.format.hasSuffix("-mcp@1") + })!.id + ], bindings: [], symbolic: c.value, render: { _ in observed }) + } + let bindings = Set( + c.bindings.filter { !$0.reference }.compactMap { + switch $0.binding { + case .environment(let n), .secret(let n): n + case .literal: nil + } + }) + return .init( + key: key, region: region, + deployments: [ + contributions.first(where: { $0.1.component == c.component })?.0.id + ?? previous.lowerings.first(where: { + $0.inputs.contains(c.component) && $0.format.hasSuffix("-mcp@1") + })!.id + ], bindings: bindings, symbolic: c.value, + render: { + try Self.nativeValue( + c, values: $0, ledger: selected, store: selectedStore, + roots: valueRoots($0)) + }) + } + func regional(_ entry: ComponentOutputEntry, selected: ResolvedLedger) throws + -> [NativeRegionOwner] + { + func region( + _ keys: [String], symbolic: LedgerValue, + bindings: Set = [], render: @escaping (RuntimeBindingValues?) throws -> NativeValue + ) throws -> NativeRegionOwner { + .init( + key: try ResolvedLedgerCodec.digest(keys), region: .init(keys: keys), + deployments: [entry.id], bindings: bindings, + symbolic: symbolic, render: render) + } + switch entry.output.content { + case .member(let member, let value): + if try !isSelected(entry.contribution.component, in: selected) { + guard let observed = try document.read(.init(keys: member.keys))?.value else { return [] } + return [ + try region( + member.keys, symbolic: selected.components[entry.contribution.component]!.payload, + render: { _ in observed }) + ] + } + return [ + try region( + member.keys, symbolic: selected.components[entry.contribution.component]!.payload, + bindings: names(value.bindings), + render: { + try Self.componentValue( + value, values: $0, selected: selected, store: selectedStore, roots: valueRoots($0)) + }) + ] + case .claudePermissions(let policy): + var values: [(String, NativeValue)] = [] + for (key, strings) in [("allow", policy.allow), ("ask", policy.ask), ("deny", policy.deny)] + { + if let strings { values.append((key, .array(strings.map(NativeValue.string)))) } + } + if let mode = policy.defaultMode { values.append(("defaultMode", .string(mode))) } + return try values.map { key, value in + try region( + ["permissions", key], + symbolic: selected.components[entry.contribution.component]!.payload, + render: { _ in value }) + } + case .hook(let hook): + let identity = try LedgerImpact.identity( + selected.components[entry.contribution.component]!, ledger: selected, + roots: roots) + return [ + .init( + key: "hook:" + identity + ":" + String(entry.index), region: .init(keys: hook.keys), + deployments: [entry.id], append: true, + selected: try isSelected(entry.contribution.component, in: selected), + bindings: names(hook.value.bindings), + symbolic: selected.components[entry.contribution.component]!.payload, + render: { + try Self.componentValue( + hook.value, values: $0, selected: selected, store: selectedStore, + roots: valueRoots($0)) + }) + ] + case .orderedPermissions(let rules): + let identity = try LedgerImpact.identity( + selected.components[entry.contribution.component]!, ledger: selected, + roots: roots) + let selectedOwner = try isSelected(entry.contribution.component, in: selected) + return rules.enumerated().map { index, rule in + .init( + key: "permission:" + identity + ":" + String(index), + region: .init(keys: ["permissions"]), deployments: [entry.id], append: true, + selected: selectedOwner, + bindings: [], symbolic: selected.components[entry.contribution.component]!.payload, + render: { _ in + .object([ + "action": .string(rule.tool), "resource": .string(rule.resource), + "effect": .string(rule.effect.rawValue), + ]) + }) + } + default: + throw CoreError.invalidState("whole native content cannot be prepared as a shared region") + } + } + let desiredItems = + try contributions.compactMap { try mcp($0.1, selected: ledger) } + + components.flatMap { try regional($0, selected: ledger) } + let oldItems = + try old.compactMap { try mcp($0, selected: previous) } + + oldComponents.flatMap { try regional($0, selected: previous) } + func keyed(_ items: [NativeRegionOwner]) throws -> [String: NativeRegionOwner] { + var result: [String: NativeRegionOwner] = [:] + for item in items { + if let existing = result[item.key] { + guard + (existing.bindings.isEmpty && item.bindings.isEmpty) + || existing.symbolic == item.symbolic, + try existing.render(nil) == item.render(nil) + else { throw CoreError.invalidState("conflicting native physical region owners") } + } + var combined = item + combined.deployments = Array(Set((result[item.key]?.deployments ?? []) + item.deployments)) + .sorted() + result[item.key] = combined + } + return result + } + var desired = try keyed(desiredItems) + var prior = try keyed(oldItems) + let keys = Set(desired.keys).union(prior.keys).sorted() + func componentBindings(_ entries: [ComponentOutputEntry]) -> Bool { + entries.contains { entry in + switch entry.output.content { + case .member(_, let value): !value.bindings.isEmpty + case .hook(let hook): !hook.value.bindings.isEmpty + case .generatedLSPPlugin(_, _, let value): !value.bindings.isEmpty + default: false + } + } + } + let recordedOldBindings = + old.contains { $0.bindings.contains { !$0.reference } } || componentBindings(oldComponents) + let sensitiveBindings = + recordedOldBindings + || contributions.contains { $0.1.bindings.contains { !$0.reference } } + || componentBindings(components) + let sensitive = try sensitiveBindings || store.materializationReceipt(for: target) != nil + let privatePlan = + try sensitive + ? store.preparePrivateMaterialization( + target, changingAccess: changingAccess, + requiringReceiptForExistingTarget: recordedOldBindings) : nil + let receiptArrays = try store.materializationReceipt(for: target)?.nativeArrays ?? [] + let authority = previous.nativeAuthorities?.first { + (try? $0.target.resolve(roots: roots).path) == path + } + var retained: [NativeObservation] = [] + var retainedOwners: [[String]] = [] + var expected: [String: NativeExpectedRegion] = [:] + var staleKeys = Set() + var staleRegions: [LedgerNativeOwnedRegion] = [] + for key in keys { + if let old = prior[key], old.append, capture.bytes != nil { + let records = + authority?.regions.filter { !Set($0.deployments).isDisjoint(with: old.deployments) } ?? [] + let index = + oldItems.filter { $0.deployments == old.deployments && $0.append }.firstIndex { + $0.key == key + } ?? 0 + guard records.indices.contains(index) else { + throw CoreError.invalidState("missing durable native occurrence authority") + } + let region: NativeRegion + do { + region = try NativeAuthorityComposition.region( + records[index].path, document: document, arrays: receiptArrays) + } catch { + guard let next = desired[key], !next.selected else { throw error } + staleKeys.insert(key) + staleRegions.append(.init(deployments: next.deployments, path: records[index].path)) + desired[key]!.bindings = [] + continue + } + prior[key]!.region = region + if desired[key] != nil { desired[key]!.region = region } + } + let region = (prior[key] ?? desired[key])!.region + if prior[key] == nil, desired[key]?.append == true { + expected[key] = try document.read(region).map(NativeExpectedRegion.owned) ?? .absent + continue + } + if let observation = try document.read(region) { + guard let old = prior[key] else { throw NativeDocumentError.ownershipMismatch(region) } + if old.bindings.isEmpty, try observation.value != old.render(nil) { + throw NativeDocumentError.ownershipMismatch(region) + } + expected[key] = .owned(observation) + if var next = desired[key] { + if !next.selected { + next.bindings = [] + next.render = { _ in observation.value! } + desired[key] = next + } + retained.append(observation) + retainedOwners.append(next.deployments) + } + } else { + expected[key] = .absent + } + } + var created: [NativeRegion] = [] + for container in authority?.createdContainers ?? [] where capture.bytes != nil { + let region = try NativeAuthorityComposition.region( + container.path, document: document, arrays: receiptArrays) + if try document.read(region) != nil { created.append(region) } + } + var editKeys: [String] = [] + func edits(_ values: RuntimeBindingValues?) throws -> [NativeRegionEdit] { + var result: [NativeRegionEdit] = [] + editKeys = [] + for key in keys where !staleKeys.contains(key) { + if let next = desired[key] { + if !next.selected { continue } + editKeys.append(key) + if next.append, prior[key] == nil || capture.bytes == nil { + let array = try document.read(next.region) + result.append( + .append( + region: next.region, expected: array.map(NativeExpectedRegion.owned) ?? .absent, + value: try next.render(values))) + } else { + result.append( + .put(region: next.region, expected: expected[key]!, value: try next.render(values))) + } + } else if case .owned = expected[key] { + editKeys.append(key) + result.append(.remove(region: prior[key]!.region, expected: expected[key]!)) + } + } + if (components + oldComponents).contains(where: { + if case .hook(let hook) = $0.output.content { return hook.layout == .cursorVersion1 } + return false + }), + try document.read(.init(keys: ["version"])) == nil + { + result.append(.put(region: .init(keys: ["version"]), expected: .absent, value: .integer(1))) + } + let selectedOldDeployments = Set(prior.values.filter(\.selected).flatMap(\.deployments)) + for region in created + where authority?.createdContainers.contains(where: { record in + !Set(record.deployments).isDisjoint(with: selectedOldDeployments) + && (try? NativeAuthorityComposition.region( + record.path, document: document, arrays: receiptArrays)) == region + }) == true { + result.append(.pruneCreatedContainer(region: region, observed: try document.read(region)!)) + } + return result + } + let tracking = + try capture.bytes == nil + ? [] + : receiptArrays.map { + try NativeAuthorityComposition.region($0.path, document: document) + } + let preview = try document.prepare(edits(nil), retaining: retained, trackingArrays: tracking) + let confirmedKeys = editKeys + let changed = preview.bytes != (capture.bytes ?? Data((format == .toml ? "" : "{}\n").utf8)) + let bindings = desired.values.reduce(into: Set()) { $0.formUnion($1.bindings) } + let selectedTarget = location(target) + let authorityRoute: NativeTargetRoute + if let entry = (components + oldComponents).first { + authorityRoute = try DeploymentConstruction.route( + entry.output, request: entry.contribution.request) + } else { + authorityRoute = try DeploymentConstruction.route((contributions.map(\.1) + old).first!) + } + let targetRoute = try DeploymentConstruction.physicalRoute( + authorityRoute, ledger: previous, store: store + ).rawValue + func finish(_ result: PreparedNativeChange) throws -> NativeAuthorityComposition.Result { + let final = try NativeDocument(bytes: result.bytes, format: format, budget: budget) + var owners: [(NativeObservation, [String])] = [] + for remap in result.survivingRegions { + if let observation = remap.observation { + owners.append((observation, retainedOwners[remap.index])) + } + } + for append in result.appendedOccurrences { + owners.append((append.observation, desired[confirmedKeys[append.editIndex]]!.deployments)) + } + // Keyed regions replaced by put retain their stable address even when their old value changes. + for key in keys where desired[key]?.append == false { + if let next = desired[key], let observation = try final.read(next.region), + !owners.contains(where: { $0.0.region == observation.region }) + { + owners.append((observation, next.deployments)) + } + } + let finalEvidence = try NativeAuthorityComposition.finish( + result, document: final, owners: owners, + containers: created + result.createdContainers, + previousArrays: capture.bytes == nil ? [] : receiptArrays, + sensitive: sensitive, format: format) + var containers = finalEvidence.containers + for original in authority?.createdContainers ?? [] { + guard + staleRegions.contains(where: { region in + region.path.count > original.path.count + && Array(region.path.prefix(original.path.count)) == original.path + }), !containers.contains(where: { $0.path == original.path }) + else { continue } + let owners = Set( + staleRegions.filter { + $0.path.count > original.path.count + && Array($0.path.prefix(original.path.count)) == original.path + }.flatMap(\.deployments)) + containers.append( + .init(deployments: owners.sorted(), path: original.path, kind: original.kind)) + } + if capture.bytes == nil { + return .init( + regions: finalEvidence.regions + staleRegions, containers: containers, + transitions: receiptArrays.map { .init(previous: $0, current: nil) } + + finalEvidence.transitions) + } + return .init( + regions: finalEvidence.regions + staleRegions, containers: containers, + transitions: finalEvidence.transitions) + } + let previewAuthority = try finish(preview) + recordNativeAuthority( + previewAuthority, target: selectedTarget, route: targetRoute, path: path, format: format) + if let privatePlan { + nativePrivateWrites.append( + ( + privatePlan, bindings, + { [unowned self] values in + let actual = try document.prepare( + edits(values), retaining: retained, trackingArrays: tracking) + guard + actual.appendedOccurrences.map(\.editIndex) + == preview.appendedOccurrences.map(\.editIndex), + actual.createdContainers == preview.createdContainers, + actual.survivingRegions.map({ $0.observation != nil }) + == preview.survivingRegions.map({ $0.observation != nil }) + else { + throw CoreError.invalidState("private rendering changed confirmed native structure") + } + let evidence = try finish(actual) + self.recordNativeAuthority( + evidence, target: selectedTarget, route: targetRoute, path: path, format: format) + return .init(bytes: actual.bytes, nativeArrayTransitions: evidence.transitions) + } + )) + } else if changed { + writes[path] = .data(preview.bytes) + } + var readers = Set((old + contributions.map(\.1)).flatMap { $0.descriptor.knownReaders }) + readers.formUnion((components + oldComponents).flatMap { $0.contribution.knownReaders }) + for entry in components + oldComponents { + readers.formUnion( + try DeploymentConstruction.route(entry.output, request: entry.contribution.request) + .knownReaders) + } + let effectiveReaders = readers.sorted { $0.rawValue < $1.rawValue } + for (lowering, contribution, _) in contributions { + let deployment = LedgerDeployment( + id: lowering.id, target: location(target), route: lowering.format, + owners: [contribution.component], recipients: contribution.recipients, + ownership: .ownedValues, + expectedHash: try ResolvedLedgerCodec.digest(contribution.value), + created: previous.deployments.first { $0.id == lowering.id }?.created + ?? (capture.bytes == nil)) + ledger.deployments.removeAll { $0.id == lowering.id } + ledger.deployments.append(deployment) + if let i = ledger.lowerings.firstIndex(where: { $0.id == lowering.id }) { + ledger.lowerings[i].deployments = [lowering.id] + } + changes.append( + .init( + deployment: deployment, url: url, before: nil, after: nil, changed: changed || sensitive, + native: true, accessChange: privatePlan?.accessChange, effectiveReaders: effectiveReaders, + privateMaterialization: sensitive, + requiredBindings: contribution.bindings.filter { !$0.reference }.compactMap { + switch $0.binding { + case .environment(let n), .secret(let n): n + case .literal: nil + } + }.sorted(), + symbolicBefore: old.first { $0.name == contribution.name }?.value, + symbolicAfter: contribution.value)) + } + for entry in components { + let ownBindings: [String] + switch entry.output.content { + case .member(_, let value): ownBindings = Array(names(value.bindings)).sorted() + case .hook(let hook): ownBindings = Array(names(hook.value.bindings)).sorted() + default: ownBindings = [] + } + try record( + entry, previous: previous, changed: changed || sensitive, readers: effectiveReaders, + privatePlan: privatePlan, bindings: ownBindings) + } + for deployment in previous.deployments + where (try? deployment.target.resolve(roots: roots).path) == path { + let oldOwners = try Set( + deployment.owners.map { + try LedgerImpact.identity( + previous.components[$0]!, ledger: previous, roots: roots) + }) + let retained = try ledger.deployments.contains { next in + guard next.route == deployment.route, + (try? next.target.resolve(roots: roots).path) == path + else { return false } + return try Set( + next.owners.map { + try LedgerImpact.identity( + ledger.components[$0]!, ledger: ledger, roots: roots) + }) == oldOwners + } + if retained { continue } + changes.append( + .init( + deployment: deployment, url: url, before: nil, after: nil, changed: changed, + native: true, accessChange: privatePlan?.accessChange, effectiveReaders: effectiveReaders, + privateMaterialization: sensitive, + symbolicBefore: previous.components[deployment.owners[0]]?.payload)) + } + } + + private func recordNativeAuthority( + _ result: NativeAuthorityComposition.Result, target: LedgerLocation, + route: String, path: String, format: NativeDocumentFormat + ) { + var records = ledger.nativeAuthorities ?? [] + records.removeAll { (try? $0.target.resolve(roots: roots).path) == path } + if !result.regions.isEmpty { + records.append( + .init( + target: target, targetRoute: route, + documentFormat: NativeAuthorityComposition.dialect(format), regions: result.regions, + createdContainers: result.containers)) + } + ledger.nativeAuthorities = records.isEmpty ? nil : records + } + + private func prepareGeneratedPlugins( + previous: ResolvedLedger, artifacts: [String: ReplayedArtifact], + oldArtifacts: [String: ReplayedArtifact], + workspace: URL, changingAccess: Bool + ) throws -> Set { + typealias Entry = (LockedLowering, NativeGeneratedPluginContribution, MaterializationTarget) + func entries(_ selected: ResolvedLedger, _ outputs: [String: ReplayedArtifact]) throws + -> [String: Entry] + { + var result: [String: Entry] = [:] + for lowering in selected.lowerings where lowering.format.hasSuffix("-generated-plugin@1") { + let contribution = try NativeGeneratedPluginContribution.decode( + lowering, ledger: selected, + artifacts: lowering.artifacts.map { + guard let output = outputs[$0.name] else { + throw CoreError.invalidState("missing generated native artifact") + } + return output + }, limits: .standard) + let route = try DeploymentConstruction.generatedRoute(lowering, ledger: selected) + let target = try store.nativeTarget(for: route) + let path = try physicalPath(route) + guard result[path] == nil else { + throw CoreError.invalidState("overlapping generated native containers") + } + result[path] = (lowering, contribution, target) + } + return result + } + let next = try entries(ledger, artifacts) + let old = try entries(previous, oldArtifacts) + func bindings(_ contribution: NativeGeneratedPluginContribution) -> Set { + var names = Set() + func collect(_ binding: RuntimeBinding) { + switch binding { + case .secret(let name), .environment(let name): names.insert(name) + case .literal: break + } + } + for member in contribution.members { + switch member.content { + case .mcp(let value): + for placement in value.bindings where !placement.reference { collect(placement.binding) } + case .component(let value): + for output in value.outputs { + switch output.content { + case .hook(let hook): + for placement in hook.value.bindings { collect(placement.binding) } + case .generatedLSPPlugin(_, _, let manifest): + for placement in manifest.bindings { collect(placement.binding) } + default: break + } + } + case .skill: break + } + } + return names + } + func bindingPlaceholder(_ name: String) -> String { + "agents-symbolic-binding-" + FileHash.sha256Hex(data: Data(name.utf8)) + } + let selectedEnvironment = store.environment + let generatedBudget = nativeBudget() + func bundle( + _ contribution: NativeGeneratedPluginContribution, target: MaterializationTarget, + values: RuntimeBindingValues, symbolic: Bool = false + ) throws -> [String: Data] { + var environment = selectedEnvironment + if symbolic { + for name in bindings(contribution) { + environment.environment[name] = bindingPlaceholder(name) + } + } + return try Self.generatedPluginFiles( + contribution, target: target, values: values, environment: environment, + budget: generatedBudget) + } + func symbolicFiles( + _ contribution: NativeGeneratedPluginContribution, target: MaterializationTarget + ) throws -> [String: Data] { + let values = RuntimeBindingValues( + Dictionary( + uniqueKeysWithValues: bindings(contribution).map { + ($0, Data(bindingPlaceholder($0).utf8)) + })) + return try bundle(contribution, target: target, values: values, symbolic: true) + } + func preview( + _ contribution: NativeGeneratedPluginContribution, target: MaterializationTarget, + selected: ResolvedLedger, files: [String: Data] + ) throws -> String { + var sections = ["Target: " + target.url.path] + for path in files.keys.sorted() { + guard let text = String(data: files[path]!, encoding: .utf8) else { + throw CoreError.invalidState("generated native preview is not UTF-8") + } + var displayed = text + for name in bindings(contribution).sorted() { + // Native conversion sees inert literals; display labels use the native JSON escaper. + let label = try Self.configurationPreview(.string("«binding:" + name + "»")) + displayed = displayed.replacingOccurrences( + of: bindingPlaceholder(name), with: String(label.dropFirst().dropLast())) + } + sections.append(path + "\n" + displayed) + } + let skillResources = Set( + contribution.members.compactMap { member -> String? in + if case .skill(_, let resource) = member.content { return resource } + return nil + }) + for placement in contribution.resourcePlacements { + let resource = contribution.resources[placement.resource]! + sections.append("Resource: " + placement.path) + for entry in resource.entries where entry.kind != .directory { + let suffix = entry.path == "." ? "" : "/" + entry.path + let detail = + entry.kind == .symlink + ? " -> " + (entry.link ?? "") : entry.executable ? " (executable)" : "" + sections.append(placement.path + suffix + detail) + if skillResources.contains(placement.resource), entry.path == "SKILL.md" { + let bytes: Data? + if let object = entry.object, let captured = selected.contentObjects[object] { + bytes = captured + } else if let source = resources[placement.resource] { + bytes = try Data( + contentsOf: PathSafety.resolvedChild(base: source, subpath: entry.path)) + } else { + bytes = nil + } + if let bytes, let text = String(data: bytes, encoding: .utf8) { + sections.append(text) + } else { + sections.append("Recorded skill content is unavailable in this preview.") + } + } + } + } + return sections.joined(separator: "\n\n") + } + for path in Set(next.keys).union(old.keys).sorted() { + let entry = next[path] ?? old[path]! + let target = entry.2 + let capture = try TargetPrecondition(target.url).capturingPublicationAccess() + targets[path] = capture + fingerprints.append(try capture.displayEvidence(includeContent: false)) + let receipt = try store.materializationReceipt(for: target) + let selected = try isSelected(entry.1.component, in: next[path] == nil ? previous : ledger) + let names = bindings(entry.1) + let priorNames = old[path].map { bindings($0.1) } ?? [] + let sensitive = !names.isEmpty || !priorNames.isEmpty || receipt != nil + let privatePlan = + try sensitive + ? store.preparePrivateMaterialization( + target, changingAccess: changingAccess, + requiringReceiptForExistingTarget: !priorNames.isEmpty) : nil + let exists = FileManager.default.fileExists(atPath: path) + let priorFiles = try old[path].map { try symbolicFiles($0.1, target: target) } + let configurationBefore = try old[path].map { + try preview($0.1, target: target, selected: previous, files: priorFiles!) + } + if exists && selected { + guard let prior = old[path], + previous.deployments.contains(where: { $0.id == prior.0.id && $0.ownership == .generated } + ) + else { + throw CoreError.invalidState("generated native container contains unmanaged content") + } + if receipt == nil { + let expected = priorFiles! + guard try Self.generatedTreeMatches(prior.1, target: target, files: expected) else { + throw CoreError.invalidState("owned generated native container drifted") + } + } + } + if let current = next[path] { + let deployment = LedgerDeployment( + id: current.0.id, target: location(target), route: current.0.format, + owners: [current.1.component], recipients: current.1.recipients, ownership: .generated, + expectedHash: current.0.artifacts[0].hash, + created: previous.deployments.first { $0.id == current.0.id }?.created ?? !exists) + ledger.deployments.removeAll { $0.id == deployment.id } + ledger.deployments.append(deployment) + if let index = ledger.lowerings.firstIndex(where: { $0.id == current.0.id }) { + ledger.lowerings[index].deployments = [deployment.id] + } + let symbolic = try symbolicFiles(current.1, target: target) + if selected { + let tree = workspace.appendingPathComponent( + "generated-" + FileHash.sha256Hex(data: Data(path.utf8))) + try FileSystem.createDirectory(at: tree) + for placement in current.1.resourcePlacements { + guard let source = resources[placement.resource], + let resource = ledger.resources[placement.resource] + else { throw CoreError.invalidState("missing generated native resource") } + var sourceRoot = source + if resource.path != "." { + for _ in resource.path.split(separator: "/") { sourceRoot.deleteLastPathComponent() } + } + let captured = try LedgerResources.capture( + source, embed: true, limits: .standard, sourceRoot: sourceRoot) + guard captured.hash == resource.hash else { + throw CoreError.invalidState("generated native resource changed") + } + var embedded = resource + embedded.kind = .embedded + embedded.entries = captured.entries + embedded.support = captured.support + let base = Self.generatedResourceBase(placement, resource: resource) + let destination = try PathSafety.resolvedChild(base: tree, subpath: base) + try LedgerResources.materialize(embedded, objects: captured.objects, at: destination) + if !resource.support.isEmpty && placement.path.hasPrefix("skills/") { + let alias = try PathSafety.resolvedChild(base: tree, subpath: placement.path) + try FileSystem.createDirectory(at: alias.deletingLastPathComponent()) + try FileManager.default.createSymbolicLink( + atPath: alias.path, withDestinationPath: "../" + base + "/" + resource.path) + } + } + for (file, bytes) in symbolic { + let destination = try PathSafety.resolvedChild(base: tree, subpath: file) + guard !FileManager.default.fileExists(atPath: destination.path) else { + throw CoreError.invalidState("generated native bundle collision") + } + try FileSystem.createDirectory(at: destination.deletingLastPathComponent()) + try bytes.write(to: destination) + } + if let privatePlan { + let captured = try LedgerResources.capture(tree, embed: false, limits: .standard) + let members = try captured.entries.filter { $0.path != "." }.map { + item -> PrivateTreeEntry in + if symbolic[item.path] != nil { + return .init( + item.path, + content: .boundFile(bindings: names) { values in + let actual = try bundle(current.1, target: target, values: values) + guard Set(actual.keys) == Set(symbolic.keys), let bytes = actual[item.path] + else { + throw CoreError.invalidState( + "private rendering changed generated native structure") + } + return bytes + }) + } + switch item.kind { + case .directory: return .init(item.path, content: .directory) + case .file: + return .init( + item.path, + content: .file( + try Data(contentsOf: tree.appendingPathComponent(item.path)), + executable: item.executable)) + case .symlink: return .init(item.path, content: .symlink(item.link!)) + } + } + privateTrees.append((privatePlan, members)) + } else if try !exists || FileHash.folderHash(tree) != FileHash.folderHash(target.url) { + writes[path] = .copy(tree) + } + } + changes.append( + .init( + deployment: deployment, url: target.url, before: nil, after: nil, + changed: selected && (writes[path] != nil || privatePlan != nil), native: true, + accessChange: privatePlan?.accessChange, effectiveReaders: current.1.knownReaders, + privateMaterialization: sensitive, requiredBindings: names.sorted(), + configurationBefore: configurationBefore, + configurationAfter: try preview( + current.1, target: target, selected: ledger, files: symbolic))) + } else if selected, + let deployment = previous.deployments.first(where: { $0.id == entry.0.id }) + { + if exists { deletes.insert(path) } + changes.append( + .init( + deployment: deployment, url: target.url, before: nil, after: nil, changed: exists, + native: true, + privateMaterialization: sensitive, + configurationBefore: configurationBefore)) + } + } + return Set(next.keys).union(old.keys) + } + + private static func generatedTreeMatches( + _ contribution: NativeGeneratedPluginContribution, + target: MaterializationTarget, files: [String: Data] + ) throws -> Bool { + var entries: [String: LedgerEntry] = [ + ".": .init(path: ".", kind: .directory, executable: false) + ] + func add(_ entry: LedgerEntry, at path: String) throws { + var copy = entry + copy.path = path + if let existing = entries[path], existing != copy { + throw CoreError.invalidState("conflicting generated native resource placement") + } + entries[path] = copy + let parents = path.split(separator: "/").dropLast() + if !parents.isEmpty { + for count in 1...parents.count { + let parent = parents.prefix(count).joined(separator: "/") + let directory = LedgerEntry(path: parent, kind: .directory, executable: false) + if let existing = entries[parent], existing.kind != .directory { + throw CoreError.invalidState("generated native resource ancestor collision") + } + entries[parent] = directory + } + } + } + for (path, bytes) in files { + try add( + .init( + path: path, kind: .file, object: "sha256:" + FileHash.sha256Hex(data: bytes), + executable: false, byteCount: bytes.count), at: path) + } + for placement in contribution.resourcePlacements { + let resource = contribution.resources[placement.resource]! + let base = generatedResourceBase(placement, resource: resource) + let primary = generatedResourcePath(placement, resource: resource) + for entry in resource.entries { + try add(entry, at: entry.path == "." ? primary : primary + "/" + entry.path) + } + for entry in resource.support { + try add(entry, at: entry.path == "." ? base : base + "/" + entry.path) + } + if !resource.support.isEmpty && placement.path.hasPrefix("skills/") { + try add( + .init( + path: placement.path, kind: .symlink, link: "../" + base + "/" + resource.path, + executable: false), at: placement.path) + } + } + let actual = try LedgerResources.capture(target.url, embed: true, limits: .standard) + guard actual.entries.count == entries.count else { return false } + guard + actual.entries.allSatisfy({ entry in + guard let expected = entries[entry.path] else { return false } + return entry.kind == expected.kind && entry.executable == expected.executable + && (expected.object == nil || entry.object == expected.object) + && entry.link == expected.link + }) + else { return false } + for placement in contribution.resourcePlacements { + let resource = contribution.resources[placement.resource]! + let observed = try LedgerResources.capture( + target.url.appendingPathComponent(generatedResourcePath(placement, resource: resource)), + embed: false, limits: .standard) + guard observed.hash == resource.hash else { return false } + } + return true + } + + package static func generatedResourceBase( + _ placement: NativeGeneratedPluginContribution.ResourcePlacement, + resource: LedgerResource + ) -> String { + resource.support.isEmpty + ? placement.path + : "resources/" + placement.resource.replacingOccurrences(of: "sha256:", with: "") + } + + package static func generatedResourcePath( + _ placement: NativeGeneratedPluginContribution.ResourcePlacement, + resource: LedgerResource + ) -> String { + resource.support.isEmpty + ? placement.path : generatedResourceBase(placement, resource: resource) + "/" + resource.path + } + + private static func generatedPluginFiles( + _ contribution: NativeGeneratedPluginContribution, + target: MaterializationTarget, values: RuntimeBindingValues, environment: RuntimeEnvironment, + budget: NativeDocumentBudget + ) throws -> [String: Data] { + let paths = try Dictionary( + contribution.resourcePlacements.map { + ( + $0.resource, + try PathSafety.resolvedChild( + base: target.url, + subpath: Self.generatedResourcePath($0, resource: contribution.resources[$0.resource]!) + ).path + ) + }, uniquingKeysWith: { a, _ in a }) + let rendered = try contribution.stagedBundle( + bindings: values, environment: environment, + resourcePaths: paths, budget: budget, cursorCommandShell: .posix) + var result = rendered.files + for (path, value) in rendered.documents { + guard result[path] == nil else { + throw CoreError.invalidState("generated native file collision") + } + guard case .object(let fields) = value else { + throw CoreError.invalidState("generated native document must be an object") + } + let document = try NativeDocument(bytes: Data("{}".utf8), format: .json, budget: budget) + result[path] = try document.prepare( + fields.keys.sorted().map { key in + .put(region: .init(keys: [key]), expected: .absent, value: fields[key]!) + } + ).bytes + } + return result + } + + private func nativeBudget() -> NativeDocumentBudget { + NativeDocumentBudget( + limits: .init( + storage: LedgerLimits.standard.resourceBytes, + work: LedgerLimits.standard.encodedBytes, nodes: LedgerLimits.standard.nodes, + depth: LedgerLimits.standard.depth, uninterruptedBytes: LedgerLimits.standard.keyBytes)) + } + + private static func nativeValue( + _ contribution: NativeMCPContribution, values: RuntimeBindingValues?, ledger: ResolvedLedger, + store: StateStore, roots: [String: URL] + ) throws -> NativeValue { + func convert(_ value: LedgerValue, path: [MCPValueStep]) throws -> NativeValue { + if let resource = contribution.resourcePlacements.first(where: { $0.path == path }), + ledger.resources[resource.resource] != nil + { + let destination = try resourceDestination( + resource.resource, ledger: ledger, store: store, roots: roots) + return .string(destination.path) + } + switch value.kind { + case .environment, .secret: + guard let name = value.text else { throw CoreError.invalidState("missing binding name") } + if let values { + guard let text = String(data: try values.value(for: name), encoding: .utf8) else { + throw CoreError.invalidState("runtime binding is not UTF8") + } + return .string(text) + } + return .string("") + case .string, .literal: return .string(value.text!) + case .integer: return .integer(value.integer!) + case .decimal: return .decimal(value.text!) + case .boolean: return .boolean(value.boolean!) + case .null: return .null + case .array: + return .array( + try value.array!.enumerated().map { + try convert($0.element, path: path + [.index($0.offset)]) + }) + case .object: + return .object( + try value.object!.mapValuesWithKey { try convert($1, path: path + [.key($0)]) }) + } + } + return try convert(contribution.value, path: []) + } + + package func validate(excludingTargets excluded: Set = []) throws { + for (path, access) in archiveDestinations where !excluded.contains(path) { + try access.validate() + } + for change in changes + where change.deployment.route == "agents/instructions@1" + && ledger.deployments.contains(where: { $0.id == change.deployment.id }) + { + if let bytes = change.after { + try InstructionTargets(store: store).validateRenderedLinks(bytes, at: change.url) + } + } + let paths = targets.keys.sorted().map { URL(fileURLWithPath: $0) } + for (index, path) in paths.enumerated() { + if paths.prefix(index).contains(where: { + PathSafety.isContained(path, in: $0) || PathSafety.isContained($0, in: path) + }) { + throw CoreError.invalidState("overlapping deployment targets") + } + } + for (path, evidence) in targets where !excluded.contains(path) { try evidence.validate() } + for evidence in resourceEvidence + where !excluded.contains(where: { + PathSafety.isContained(evidence.url, in: URL(fileURLWithPath: $0)) + }) { try evidence.validate() } + } + + package func requireSkillOwnership() throws { + if let reason = unownedSkills.sorted().first { throw CoreError.invalidSkill(reason) } + } + + package func requireOwnership() throws { + try requireSkillOwnership() + guard antigravityConflicts.isEmpty else { + throw InstructionError.antigravityConflicts(antigravityConflicts.sorted()) + } + guard replace || unownedInstructions.isEmpty else { + throw InstructionError.unownedTargets(unownedInstructions.sorted()) + } + } + + package func stage( + transaction: FileTransaction, provider: any RuntimeBindingProvider, roots: [String: URL] + ) throws { + var staged = Set() + for (id, source) in resources.sorted(by: { $0.key < $1.key }) { + guard let resource = ledger.resources[id], resource.kind != .liveEdit, + resource.kind != .archive + 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)))) + guard staged.insert(container.path).inserted else { continue } + let artifactFlags = + retainedArtifact + ? Dictionary( + uniqueKeysWithValues: resource.entries.filter { $0.kind == .file }.map { + ($0.path, $0.executable) + }) : nil + if FileManager.default.fileExists(atPath: container.path) { + let actual = try LedgerResources.capture(destination, embed: false, limits: .standard) + 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, + executableFlags: artifactFlags) + } else if let capsule = capsules[id] { + try transaction.replace(container, with: .copy(capsule)) + } else { + throw CoreError.invalidState("missing retained resource capsule") + } + } + for path in writes.keys.sorted() { + let source = writes[path]! + let hash: String? = { if case .link = source { nil } else { skillContent[path]?.0 } }() + if let access = archiveDestinations[path] { + try transaction.replaceArchive( + access, with: source, skill: skillTargets[path], expectedHash: hash) + } else if skillWritePaths.contains(path), let target = skillTargets[path] { + try transaction.replaceSkill( + target, with: source, expectedHash: hash, expecting: targets[path]) + } else { + try transaction.replace( + URL(fileURLWithPath: path), with: source, expectedHash: hash, + executableFlags: skillContent[path]?.1, expecting: targets[path]) + } + } + for path in deletes.sorted() { + if skillDeletePaths.contains(path), let target = skillTargets[path] { + try transaction.deleteSkill(target, expecting: targets[path]) + } else { + try transaction.delete(URL(fileURLWithPath: path), expecting: targets[path]) + } + } + for (prepared, entries) in privateTrees { + try transaction.replacePrivateTree(prepared, entries: entries, provider: provider) + } + for (prepared, bindings, produce) in nativePrivateWrites { + try transaction.replacePrivate( + prepared, bindings: bindings, provider: provider, produce: produce) + } + for (prepared, bindings, render) in privateWrites { + try transaction.replacePrivate( + prepared, bindings: bindings, provider: provider, render: render) + } + } +} + +extension Dictionary { + fileprivate func mapValuesWithKey(_ transform: (Key, Value) throws -> T) rethrows -> [Key: T] { + try [Key: T](uniqueKeysWithValues: map { (key, value) in (key, try transform(key, value)) }) + } +} + +extension ArtifactAggregation { + package static func nativeExposure( + _ deployment: LedgerDeployment, ledger: ResolvedLedger, store: StateStore, + roots admittedRoots: [String: URL]? = nil + ) throws -> (readers: [AgentID]?, sensitive: Bool) { + guard + deployment.ownership == .ownedValues || deployment.route.hasSuffix("-components@1") + || deployment.route.hasSuffix("-generated-plugin@1") + else { + return (nil, false) + } + let roots = admittedRoots ?? store.ledgerRoots + let path = try deployment.target.resolve(roots: roots).path + var identities = Set() + for route in try DeploymentConstruction.routes(ledger) { + let target = try store.nativeTarget(for: route) + if target.url.path == path, let identity = try store.nativeTargetIdentity(for: route) { + identities.insert(identity) + } + } + func matches(_ route: NativeTargetRoute, _ target: MaterializationTarget) throws -> Bool { + if target.url.path == path { return true } + return try store.nativeTargetIdentity(for: route).map(identities.contains) ?? false + } + var readers = Set() + var sensitive = false + for lowering in ledger.lowerings where lowering.format.hasSuffix("-mcp@1") { + let c = try MCPLayoutV1.contribution(lowering, ledger: ledger) + let target = try store.nativeTarget( + for: DeploymentConstruction.physicalRoute( + DeploymentConstruction.route(c), ledger: ledger, store: store)) + if target.url.path == path { + readers.formUnion(c.descriptor.knownReaders) + sensitive = + try sensitive || c.bindings.contains(where: { !$0.reference }) + || store.materializationReceipt(for: target) != nil + } + } + func hasBinding(_ value: LedgerValue) -> Bool { + value.kind == .secret || value.kind == .environment + || (value.array ?? []).contains(where: hasBinding) + || (value.object?.values ?? [:].values).contains(where: hasBinding) + } + for lowering in ledger.lowerings where lowering.format.hasSuffix("-components@1") { + let input = try NativeComponentLayoutsV1.input(lowering, ledger: ledger, limits: .standard) + var selected = ledger + selected.lowerings = [lowering] + for route in try DeploymentConstruction.routes(selected) { + let target = try store.nativeTarget(for: route) + if try matches(route, target) { + readers.formUnion( + CapabilityRegistry.componentReaders( + input.request, kind: DeclaredComponentKind(rawValue: input.record.kind)!)) + readers.formUnion(route.knownReaders) + sensitive = + try sensitive || hasBinding(input.record.payload) + || store.materializationReceipt(for: target) != nil + } + } + } + for lowering in ledger.lowerings where lowering.format.hasSuffix("-generated-plugin@1") { + let route = try DeploymentConstruction.generatedRoute(lowering, ledger: ledger) + let target = try store.nativeTarget(for: route) + if try matches(route, target) { + readers.formUnion(route.knownReaders) + if let surface = lowering.layout.object?["surface"]?.text.flatMap( + NativeClientSurface.init(rawValue:)), + let scope = lowering.layout.object?["scope"]?.text.flatMap(InstallScope.init(rawValue:)) + { + for id in lowering.inputs { + if let component = ledger.components[id], + let kind = DeclaredComponentKind(rawValue: component.kind) + { + readers.formUnion( + CapabilityRegistry.componentReaders( + .init(surface: surface, scope: scope), kind: kind)) + sensitive = sensitive || hasBinding(component.payload) + } + } + } + sensitive = try sensitive || store.materializationReceipt(for: target) != nil + } + } + return (readers.isEmpty ? nil : readers.sorted { $0.rawValue < $1.rawValue }, sensitive) + } + + /// Observes only the owned region. Private receipts validate the entire physical preimage. + package static func inspectDeployment( + _ deployment: LedgerDeployment, ledger: ResolvedLedger, store: StateStore, + roots admittedRoots: [String: URL]? = nil, permitReplay: Bool = true + ) throws -> (status: String, diagnostic: String?) { + let roots = admittedRoots ?? store.ledgerRoots + if deployment.route == AntigravityRuleV1.format { + do { + guard deployment.target.root == InstructionLocations.ruleRoot(in: store.scope) else { + return ("unverified", "Antigravity rule belongs to another scope") + } + let url = try InstructionLocations.antigravityLeaf(deployment.target.path, store: store) + guard let bytes = try TargetPrecondition.readingFile(url).bytes else { + return ("missing", "managed Antigravity rule is missing") + } + return Instructions.hash(bytes) == deployment.expectedHash + ? ("current", nil) : ("drifted", "managed Antigravity rule differs from its lock") + } catch { + return ("unverified", "Antigravity rule could not be inspected at its registered path") + } + } + let url = try deployment.target.resolve(roots: roots) + guard FileManager.default.fileExists(atPath: url.path) else { + return ("missing", "managed target is missing") + } + do { + if deployment.route == "agents/skill@1" { + let lowering = ledger.lowerings.first { $0.deployments.contains(deployment.id) } + let mode = lowering?.layout.object?["mode"]?.text + if mode == InstallMode.edit.rawValue { + guard let owner = deployment.owners.first.flatMap({ ledger.components[$0] }), + let name = owner.payload.object?["name"]?.text, + let resource = owner.resources.first.flatMap({ ledger.resources[$0] }), + resource.kind == .liveEdit + else { return ("drifted", "live skill is not linked to its recorded source") } + let edit: (authored: URL, directory: URL) + do { + edit = try LedgerResources.liveEditSource(resource, ledger: ledger, roots: roots) + } catch CoreError.unsafePath(let message) { + return ("drifted", message) + } + guard PathSafety.matchesSymbolicLink(at: url, destination: edit.authored), + PathSafety.realPath(url.path)?.utf8.elementsEqual(edit.directory.path.utf8) == true + else { + return ("drifted", "live skill is not linked to its recorded source") + } + do { try SkillOperations.validateLiveMetadata(at: edit.directory, name: name) } catch { + return ("drifted", "live skill source metadata changed") + } + return ("current", nil) + } + let resources = deployment.owners.flatMap { ledger.components[$0]?.resources ?? [] } + if mode == InstallMode.link.rawValue, let id = resources.first, + let resource = ledger.resources[id], resource.kind == .artifact, resource.location != nil, + try !PathSafety.matchesSymbolicLink( + at: url, + destination: resourceDestination(id, ledger: ledger, store: store, roots: roots)) + { + return ("drifted", "managed skill is not linked to its retained artifact") + } + let expected = deployment.expectedHash + let hash = "sha256:" + (try FileHash.folderHash(url)) + let flags = try FileHash.executableFlags(url) + let expectedFlags = resources.first.flatMap { ledger.resources[$0] }.map { + Dictionary( + uniqueKeysWithValues: $0.entries.filter { $0.kind == .file }.map { + ($0.path, $0.executable) + }) + } + return hash == expected && (expectedFlags == nil || expectedFlags == flags) + ? ("current", nil) : ("drifted", "managed skill content or executable mode changed") + } + if deployment.ownership == .ownedValues, + let lowering = ledger.lowerings.first(where: { $0.deployments.contains(deployment.id) }), + lowering.format.hasSuffix("-mcp@1") + { + let c = try MCPLayoutV1.contribution(lowering, ledger: ledger) + let target = try store.nativeTarget( + for: DeploymentConstruction.physicalRoute( + DeploymentConstruction.route(c), ledger: ledger, store: store)) + if try store.materializationReceipt(for: target) != nil { return ("current", nil) } + if c.bindings.contains(where: { !$0.reference }) { + return ( + "unverified", + "native materialization needs its private receipt or resource placement evidence" + ) + } + let document = try NativeDocument( + bytes: FileSystem.read(at: url), format: c.descriptor.documentFormat, + budget: NativeDocumentBudget( + limits: .init( + storage: LedgerLimits.standard.resourceBytes, + work: LedgerLimits.standard.encodedBytes, nodes: LedgerLimits.standard.nodes, + depth: LedgerLimits.standard.depth, uninterruptedBytes: LedgerLimits.standard.keyBytes + ))) + let region = try c.descriptor.region( + server: c.name, + nativeProjectKey: c.descriptor.request.scope == .local + ? store.nativeTarget(for: .claudeMCPProject).url.deletingLastPathComponent().path : nil) + guard let observed = try document.read(region) else { + return ("missing", "managed native region is missing") + } + return try observed.value + == nativeValue(c, values: nil, ledger: ledger, store: store, roots: roots) + ? ("current", nil) : ("drifted", "managed native region changed") + } + if deployment.route.hasSuffix("-generated-plugin@1"), + let lowering = ledger.lowerings.first(where: { $0.deployments.contains(deployment.id) }) + { + guard permitReplay else { + return ("unverified", "This native layout needs resource replay to verify drift.") + } + return try LedgerReplay.withLockedResources( + ledger, store: store, roots: roots, limits: .standard, + lowerings: [lowering.id] + ) { artifacts, _, _ in + let contribution = try NativeGeneratedPluginContribution.decode( + lowering, ledger: ledger, artifacts: artifacts, limits: .standard) + let target = try store.nativeTarget( + for: DeploymentConstruction.generatedRoute(lowering, ledger: ledger)) + if try store.materializationReceipt(for: target) != nil { return ("current", nil) } + let budget = NativeDocumentBudget( + limits: .init( + storage: LedgerLimits.standard.resourceBytes, + work: LedgerLimits.standard.encodedBytes, + nodes: LedgerLimits.standard.nodes, depth: LedgerLimits.standard.depth, + uninterruptedBytes: LedgerLimits.standard.keyBytes)) + let files = try generatedPluginFiles( + contribution, target: target, values: .init([:]), environment: store.environment, + budget: budget) + return try generatedTreeMatches(contribution, target: target, files: files) + ? ("current", nil) : ("drifted", "managed generated native container changed") + } + } + if deployment.route.hasSuffix("-components@1"), + let lowering = ledger.lowerings.first(where: { $0.deployments.contains(deployment.id) }) + { + guard permitReplay else { + return ("unverified", "This native layout needs resource replay to verify drift.") + } + return try LedgerReplay.withLockedResources( + ledger, store: store, roots: roots, limits: .standard + ) { + artifacts, _, _ in + let table = Dictionary(uniqueKeysWithValues: artifacts.map { ($0.name, $0) }) + let contribution = try NativeComponentLayoutsV1.contribution( + lowering, ledger: ledger, + artifacts: try lowering.artifacts.map { item in + guard let artifact = table[item.name] else { + throw CoreError.invalidState("missing sealed native output") + } + return artifact + }, limits: .standard) + guard + let index = contribution.outputs.indices.first(where: { + lowering.id + ":" + String($0) == deployment.id + }) + else { + throw CoreError.invalidState("missing native deployment output") + } + let output = contribution.outputs[index] + let target = try store.nativeTarget( + for: DeploymentConstruction.physicalRoute( + DeploymentConstruction.route(output, request: contribution.request), ledger: ledger, + store: store)) + let privateGeneration = try store.materializationReceipt(for: target) != nil + if privateGeneration { + switch output.content { + case .file, .nativePlugin, .generatedLSPPlugin, .hook, .orderedPermissions: break + default: return ("current", nil) + } + } + let budget = NativeDocumentBudget( + limits: .init( + storage: LedgerLimits.standard.resourceBytes, + work: LedgerLimits.standard.encodedBytes, nodes: LedgerLimits.standard.nodes, + depth: LedgerLimits.standard.depth, uninterruptedBytes: LedgerLimits.standard.keyBytes + )) + let matches: Bool + switch output.content { + case .file(_, let bytes): matches = try Data(contentsOf: url) == bytes + case .member(let member, let value): + let document = try NativeDocument( + bytes: Data(contentsOf: url), format: output.route.documentFormat!, budget: budget) + matches = + try document.read(.init(keys: member.keys))?.value + == componentValue( + value, values: nil, selected: ledger, store: store, roots: roots) + case .claudePermissions(let policy): + let document = try NativeDocument( + bytes: Data(contentsOf: url), format: .json, budget: budget) + var expected: [(String, NativeValue)] = [] + for (key, strings) in [ + ("allow", policy.allow), ("ask", policy.ask), ("deny", policy.deny), + ] { + if let strings { expected.append((key, .array(strings.map(NativeValue.string)))) } + } + if let mode = policy.defaultMode { expected.append(("defaultMode", .string(mode))) } + matches = try expected.allSatisfy { + try document.read(.init(keys: ["permissions", $0.0]))?.value == $0.1 + } + case .nativePlugin(_, let resource, _): + let observed = try LedgerResources.capture(url, embed: false, limits: .standard) + matches = + observed.hash == ledger.resources[resource]?.hash + && observed.entries.map(\.executable) + == ledger.resources[resource]?.entries.map(\.executable) + case .ignore: + var patterns: [String] = [] + for candidate in ledger.lowerings where candidate.format.hasSuffix("-components@1") { + let other = try NativeComponentLayoutsV1.contribution( + candidate, ledger: ledger, + artifacts: try candidate.artifacts.map { item in + guard let artifact = table[item.name] else { + throw CoreError.invalidState("missing sealed native output") + } + return artifact + }, limits: .standard) + for output in other.outputs { + let target = try store.nativeTarget( + for: DeploymentConstruction.physicalRoute( + DeploymentConstruction.route(output, request: other.request), ledger: ledger, + store: store)) + if target.url.path == url.path, case .ignore(let lines) = output.content { + patterns += lines + } + } + } + let text = try String(contentsOf: url, encoding: .utf8) + let opening = "# >>> agents context ignore v1\n" + let closing = "# <<< agents context ignore v1\n" + matches = + text.components(separatedBy: opening).count == 2 + && text.components(separatedBy: closing).count == 2 + && text.contains(opening + patterns.joined(separator: "\n") + "\n" + closing) + case .generatedLSPPlugin(_, let manifestPath, let manifest): + let captured = try LedgerResources.capture(url, embed: false, limits: .standard) + let paths = Set([ + ".", manifestPath, (manifestPath as NSString).deletingLastPathComponent, + ]) + let document = try NativeDocument( + bytes: Data(contentsOf: url.appendingPathComponent(manifestPath)), format: .json, + budget: budget) + matches = + try captured.entries.allSatisfy { + paths.contains($0.path) && !$0.executable + } + && generatedManifestMatches( + manifest, observed: document.read(.init(keys: []))?.value, selected: ledger, + privateGeneration: privateGeneration, store: store, roots: roots) + case .hook, .orderedPermissions: + let document = try NativeDocument( + bytes: Data(contentsOf: url), format: output.route.documentFormat!, budget: budget) + guard + let authority = ledger.nativeAuthorities?.first(where: { + (try? $0.target.resolve(roots: roots)) == url + }) + else { + return ("unverified", "managed native occurrence authority is missing") + } + let records = authority.regions.filter { $0.deployments.contains(deployment.id) } + let expected: [NativeValue] + switch output.content { + case .hook(let hook): + expected = [ + try componentValue( + hook.value, values: nil, selected: ledger, store: store, roots: roots) + ] + case .orderedPermissions(let rules): + expected = rules.map { + .object([ + "action": .string($0.tool), "resource": .string($0.resource), + "effect": .string($0.effect.rawValue), + ]) + } + default: expected = [] + } + matches = + try records.count == expected.count + && zip(records, expected).allSatisfy { record, value in + let region = try NativeAuthorityComposition.region( + record.path, document: document, + arrays: store.materializationReceipt(for: target)?.nativeArrays ?? []) + return try privateGeneration + ? document.read(region) != nil : document.read(region)?.value == value + } + } + return matches ? ("current", nil) : ("drifted", "managed native contribution changed") + } + } + let bytes = try FileSystem.read(at: url) + let hash = + deployment.ownership == .importBlock + ? try InstructionTargets.ownedImportBytes(bytes).map { + "sha256:" + FileHash.sha256Hex(data: $0) + } + : "sha256:" + FileHash.sha256Hex(data: bytes) + return hash == deployment.expectedHash + ? ("current", nil) : ("drifted", "managed instructions changed") + } catch { + return ( + "unverified", "managed target could not be verified; inspect ownership, format and access" + ) + } + } +} diff --git a/Sources/Components/CapabilityRegistry.swift b/Sources/Components/CapabilityRegistry.swift new file mode 100644 index 0000000..4487626 --- /dev/null +++ b/Sources/Components/CapabilityRegistry.swift @@ -0,0 +1,290 @@ +import AgentsCore +import NativeDocuments + +/// Surfaces with independently evidenced loading contracts. Marketing names do not select one. +package enum NativeClientSurface: String, CaseIterable, Sendable { + case antigravity, claudeCode, codexCLI, geminiCLI, openCodeCLI, cursorEditor, cursorCLI, + cursorCloud + + package var agent: AgentID { + switch self { + case .antigravity: .antigravity + case .claudeCode: .claudeCode + case .codexCLI: .codex + case .geminiCLI: .geminiCLI + case .openCodeCLI: .opencode + case .cursorEditor, .cursorCLI, .cursorCloud: .cursor + } + } +} + +package enum NativeMCPScope: String, CaseIterable, Sendable { case project, local, user } + +package struct NativeMCPRequest: Equatable, Sendable { + package let surface: NativeClientSurface + package let scope: NativeMCPScope + + package init(surface: NativeClientSurface, scope: NativeMCPScope) { + self.surface = surface + self.scope = scope + } +} + +/// Schema evidence is separate from runtime acceptance of a particular deployed candidate. +package struct NativeSchemaEvidence: Equatable, Sendable { + package let revision: String + package let sources: [String] +} + +package struct NativeMCPDescriptor { + package let request: NativeMCPRequest + package let format: String + package let documentFormat: NativeDocumentFormat + package let evidence: NativeSchemaEvidence + package var knownReaders: Set { [request.surface.agent] } + + /// Core supplies the native canonical project key; it is not a machine path saved in layout. + package func region(server: String, nativeProjectKey: String? = nil) throws -> NativeRegion { + var keys: [String] + switch request.surface { + case .codexCLI: keys = ["mcp_servers"] + case .openCodeCLI: keys = ["mcp", "servers"] + case .claudeCode where request.scope == .local: + guard let nativeProjectKey, nativeProjectKey.hasPrefix("/"), !nativeProjectKey.contains("\0") + else { + throw NativeAdapterIssue( + request: request, component: server, field: ["region", "nativeProjectKey"], + reason: .integrationRequired, detail: "Core must supply the native canonical project key") + } + keys = ["projects", nativeProjectKey, "mcpServers"] + default: keys = ["mcpServers"] + } + return NativeRegion(keys: keys + [server]) + } + +} + +package struct NativeAdapterIssue: Error, Equatable, CustomStringConvertible { + package enum Reason: String, Sendable { + case invalid, unsupported, unverified, integrationRequired + } + package let request: NativeMCPRequest + package let component: String + package let field: [String] + package let reason: Reason + package let detail: String + + package var description: String { + "\(request.surface.rawValue)/mcpServer/\(component)/\(request.scope.rawValue) " + + "\(field.joined(separator: ".")): \(reason.rawValue) (\(detail))." + } +} + +package enum CapabilityRegistry { + static let antigravityDiscovery = "https://antigravity.google/docs/customization-discovery" + + static func antigravityEvidence(_ path: String) -> NativeSchemaEvidence { + .init( + revision: "docs:2026-11-25", + sources: [antigravityDiscovery, "https://antigravity.google/docs/" + path]) + } + + package static func mcp( + _ request: NativeMCPRequest, component: String + ) throws -> NativeMCPDescriptor { + func issue(_ field: String, _ detail: String) -> NativeAdapterIssue { + .init( + request: request, component: component, field: [field], reason: .unverified, detail: detail) + } + if request.surface == .cursorCloud { + throw issue("surface", "Cloud MCP configuration loading needs separate evidence") + } + if request.scope == .local && request.surface != .claudeCode { + throw issue("scope", "a separate local MCP scope is not established by this schema evidence") + } + let name: String + let document: NativeDocumentFormat + let evidence: NativeSchemaEvidence + switch request.surface { + case .antigravity: + name = "antigravity" + document = .json + evidence = antigravityEvidence("mcp") + case .claudeCode: + name = "claude" + document = .json + evidence = .init( + revision: "installed:2.1.309", + sources: ["claude-mcp-routes.json", "https://code.claude.com/docs/en/mcp"]) + case .codexCLI: + name = "codex" + document = .toml + evidence = .init( + revision: "092d3acd6bec3e3a14bdc7e7a2810ab628ab759d", + sources: ["codex-rs/config/src/config_toml.rs", "codex-rs/config/src/mcp_types.rs"]) + case .geminiCLI: + name = "gemini" + document = .jsonc(trailingCommas: false) + evidence = .init( + revision: "5a5c7180ff3f0a02511f54b54db7f228d4982a30", + sources: [ + "packages/core/src/config/config.ts", "packages/cli/src/config/settings.ts", + "packages/cli/src/utils/envVarResolver.ts", + ]) + case .openCodeCLI: + name = "opencode" + document = .jsonc(trailingCommas: true) + evidence = .init( + revision: "fedc6f208aa2bd54c1019227214568083f6380ad", + sources: [ + "packages/schema/src/mcp.ts", "packages/schema/src/config/mcp.ts", + "packages/core/src/mcp/client.ts", "packages/core/src/config/variable.ts", + ]) + case .cursorEditor, .cursorCLI, .cursorCloud: + name = "cursor" + document = .json + evidence = .init( + revision: "sha256:f5e70852d7122b56fd3136b3659dfc1d430ab363f763431f617839fdea8df7d4", + sources: ["https://cursor.com/docs/mcp", "https://cursor.com/docs/cli/using"]) + } + return .init( + request: request, format: "agents/\(name)-mcp@1", documentFormat: document, + evidence: evidence) + } +} + +package struct NativeComponentDescriptor { + package let request: NativeComponentRequest + package let kind: DeclaredComponentKind + package let format: String + package let evidence: NativeSchemaEvidence + package var knownReaders: Set { + CapabilityRegistry.componentReaders(request, kind: kind) + } +} + +extension CapabilityRegistry { + static func componentReaders( + _ request: NativeComponentRequest, kind: DeclaredComponentKind + ) -> Set { + if request.surface == .claudeCode, [.hook, .subagent].contains(kind) { + return [.claudeCode, .cursor] + } + return [request.surface.agent] + } + package static func component( + _ request: NativeComponentRequest, + kind: DeclaredComponentKind, name: String, inPlugin: Bool = false + ) throws -> NativeComponentDescriptor { + func issue(_ field: String, _ reason: NativeAdapterIssue.Reason, _ detail: String) + -> NativeComponentIssue + { + .init( + request: request, kind: kind.rawValue, component: name, field: [field], reason: reason, + detail: detail) + } + guard ![.skills, .instructions, .mcpServer].contains(kind) else { + throw issue("kind", .invalid, "component belongs to its existing domain renderer") + } + if request.surface == .antigravity && (kind != .hook || inPlugin) { + throw issue("kind", .unsupported, "only standalone hooks use this native component profile") + } + guard request.surface != .cursorCloud || (kind == .hook && request.scope == .project) else { + throw issue( + "surface", .unverified, "Cloud deployment/loading requires a separate registered surface") + } + if kind == .command { + if request.surface == .codexCLI { + throw issue( + "kind", .unsupported, + "the pinned TUI dispatch does not register persistent named prompt files") + } + if request.surface == .cursorCLI + || (request.surface == .cursorEditor && request.scope == .user && !inPlugin) + { + throw issue( + "scope", .unverified, + "named-command registration is not established for this surface/scope") + } + } + if kind == .lspServer && request.surface != .openCodeCLI && request.surface != .claudeCode { + throw issue( + "kind", .unverified, "no complete LSP registration schema is captured for this surface") + } + if kind == .ignore { + guard request.scope == .project else { + throw issue("scope", .unverified, "no standalone user ignore file contract is established") + } + guard request.surface == .geminiCLI || request.surface == .cursorEditor else { + throw issue( + "purpose", .unverified, + "file search/watcher filters do not establish context or indexing exclusion") + } + } + if kind == .hook && request.surface == .openCodeCLI { + throw issue( + "event", .unverified, + "OpenCode hooks require executable plugin API adaptation; equivalent event I/O is not established" + ) + } + if kind == .permissions && request.surface != .openCodeCLI && request.surface != .claudeCode { + throw issue( + "rules", .unverified, + "native policy precedence differs from ordered last-match semantics; exact translation is not established" + ) + } + let pinned = try mcp( + .init( + surface: request.surface == .cursorCloud ? .cursorEditor : request.surface, + scope: request.scope == .user ? .user : .project), component: name + ).evidence + let sources: [String] + switch request.surface { + case .antigravity: sources = antigravityEvidence("hooks").sources + case .geminiCLI: + sources = [ + "docs/cli/custom-commands.md", "packages/core/src/agents/agentLoader.ts", + "docs/hooks/reference.md", "packages/core/src/hooks/hookRunner.ts", + "packages/cli/src/config/settings.ts", "packages/cli/src/utils/envVarResolver.ts", + "docs/cli/gemini-ignore.md", "packages/cli/src/config/extension-manager.ts", + ] + case .openCodeCLI: + sources = [ + "packages/schema/src/config/command.ts", "packages/schema/src/config/agent.ts", + "packages/core/src/config/plugin/command.ts", "packages/schema/src/permission.ts", + "packages/core/src/permission.ts", "packages/schema/src/config/lsp.ts", + ] + case .codexCLI: + sources = [ + "codex-rs/config/src/config_toml.rs", "codex-rs/agent-roles/src/agent_role_config.rs", + "codex-rs/agent-roles/src/loader.rs", "codex-rs/config/src/hook_config.rs", + "codex-rs/hooks/src/engine/command_runner.rs", + ] + case .cursorEditor, .cursorCLI, .cursorCloud: + sources = [ + "https://cursor.com/docs/subagents", "https://docs.cursor.com/en/agent/chat/commands", + "https://cursor.com/docs/reference/ignore-file", + "https://cursor.com/docs/reference/plugins", + "https://cursor.com/docs/hooks", + ] + case .claudeCode: + sources = [ + "https://code.claude.com/docs/en/skills", "https://code.claude.com/docs/en/sub-agents", + "https://code.claude.com/docs/en/hooks", "https://code.claude.com/docs/en/permissions", + "https://code.claude.com/docs/en/plugins/manifest-reference", + "https://cursor.com/docs/reference/third-party-hooks", "https://cursor.com/docs/subagents", + "claude-plugin-discovery.json", "route-evidence.md", + ] + } + let revision: String + switch request.surface { + case .claudeCode, .cursorEditor, .cursorCLI, .cursorCloud: + revision = "sha256:663204a0c4521fccc5ed534e5b81f3c084e9bd691cadf6882a2e95667519b9e0" + default: revision = pinned.revision + } + let evidence = NativeSchemaEvidence(revision: revision, sources: sources) + return .init( + request: request, kind: kind, format: NativeComponentLayoutsV1.format(request.surface), + evidence: evidence) + } +} diff --git a/Sources/Components/ClientCapabilityInspection.swift b/Sources/Components/ClientCapabilityInspection.swift new file mode 100644 index 0000000..fd360aa --- /dev/null +++ b/Sources/Components/ClientCapabilityInspection.swift @@ -0,0 +1,77 @@ +import AgentsCore + +/// Describes registry evidence only; field, resource and integration admission belongs to preview. +package struct ClientCapabilityEvidence { + package let surface: NativeClientSurface + package let displayName: String + package let kind: DeclaredComponentKind + package let scope: String + package let placement: String + package let status: String + package let evidence: NativeSchemaEvidence? + package let reason: String? +} + +extension NativeClientSurface { + package var displayName: String { + switch self { + case .antigravity: "Antigravity" + case .claudeCode: "Claude Code" + case .codexCLI: "Codex CLI" + case .geminiCLI: "Gemini CLI" + case .openCodeCLI: "OpenCode CLI" + case .cursorEditor: "Cursor Editor" + case .cursorCLI: "Cursor CLI" + case .cursorCloud: "Cursor Cloud" + } + } +} + +package enum ClientCapabilityInspection { + package static func entries(for agent: AgentID) -> [ClientCapabilityEvidence] { + NativeClientSurface.allCases.filter { $0.agent == agent }.flatMap { surface in + DeclaredComponentKind.allCases.flatMap { kind -> [ClientCapabilityEvidence] in + let scopes = kind == .mcpServer ? ["project", "local", "user"] : ["project", "user"] + return scopes.flatMap { scope in + let placements = kind == .command ? ["standalone", "pluginMember"] : ["standalone"] + return placements.map { placement in + var evidence: NativeSchemaEvidence? + var status = "unverified" + var reason: String? + do { + if surface == .antigravity && (kind == .skills || kind == .instructions) { + evidence = CapabilityRegistry.antigravityEvidence( + kind == .skills ? "skills" : "rules") + } else if kind == .skills || kind == .instructions { + reason = + "Existing domain locations are available; comparable frozen schema evidence is not recorded." + } else if kind == .mcpServer { + evidence = try CapabilityRegistry.mcp( + .init(surface: surface, scope: NativeMCPScope(rawValue: scope)!), component: "" + ).evidence + } else { + evidence = try CapabilityRegistry.component( + .init(surface: surface, scope: InstallScope(rawValue: scope)!), + kind: kind, name: "", inPlugin: placement == "pluginMember" + ).evidence + } + if evidence != nil { status = "recorded" } + } catch let issue as NativeAdapterIssue { + status = issue.reason == .unsupported ? "unsupportedUnderEvidence" : "unverified" + reason = issue.detail + } catch let issue as NativeComponentIssue { + status = issue.reason == .unsupported ? "unsupportedUnderEvidence" : "unverified" + reason = issue.detail + } catch { + reason = "Registry evidence could not be projected." + } + return ClientCapabilityEvidence( + surface: surface, displayName: surface.displayName, kind: kind, + scope: scope, placement: placement, status: status, evidence: evidence, reason: reason + ) + } + } + } + } + } +} diff --git a/Sources/Components/ComponentFields.swift b/Sources/Components/ComponentFields.swift new file mode 100644 index 0000000..f9ac103 --- /dev/null +++ b/Sources/Components/ComponentFields.swift @@ -0,0 +1,114 @@ +import AgentsCore + +extension ComponentDeclaration { + package var name: String? { + switch self { + case .skills, .instructions: nil + case .mcpServer(let name, _, _, _, _, _), .hook(let name, _, _, _, _, _, _, _), + .subagent(let name, _, _, _, _, _, _, _), .command(let name, _, _, _, _, _, _), + .lspServer(let name, _, _, _, _, _, _), .permissions(let name, _, _, _, _), + .ignore(let name, _, _, _, _, _), .plugin(let name, _, _, _, _, _, _, _, _): + name + } + } + + var agents: [AgentID]? { + switch self { + case .skills(_, let value): value.agents + case .instructions(let value): value.agents + case .mcpServer(_, _, let agents, _, _, _), .hook(_, _, _, _, _, let agents, _, _), + .subagent(_, _, _, _, _, let agents, _, _), .command(_, _, _, _, let agents, _, _), + .lspServer(_, _, _, _, let agents, _, _), .permissions(_, _, let agents, _, _), + .ignore(_, _, _, let agents, _, _), .plugin(_, _, _, _, _, _, let agents, _, _): + agents + } + } + + var condition: DeclarationCondition? { + switch self { + case .skills(_, let value): value.condition + case .instructions(let value): value.condition + case .mcpServer(_, _, _, let condition, _, _), .hook(_, _, _, _, _, _, let condition, _), + .subagent(_, _, _, _, _, _, let condition, _), .command(_, _, _, _, _, let condition, _), + .lspServer(_, _, _, _, _, let condition, _), .permissions(_, _, _, let condition, _), + .ignore(_, _, _, _, let condition, _), .plugin(_, _, _, _, _, _, _, let condition, _): + condition + } + } + + package var resources: [ResourceDeclaration] { + func run(_ value: ExecutableDeclaration) -> [ResourceDeclaration] { + let executable = + value.executable.contains("/") + ? [ResourceDeclaration(path: value.executable, source: value.executableSource)] : [] + return executable + (value.workingDirectory.map { [$0] } ?? []) + } + func prompt(_ value: PromptBody) -> [ResourceDeclaration] { + if case .file(let resource) = value { return [resource] } + return [] + } + switch self { + case .mcpServer(_, .stdio(let value), _, _, _, _): return run(value) + case .hook(_, _, let value, _, _, _, _, _), .lspServer(_, let value, _, _, _, _, _): + return run(value) + case .subagent(_, _, let value, _, _, _, _, _), .command(_, _, let value, _, _, _, _): + return prompt(value) + case .plugin(_, let path, let source, _, _, _, _, _, _): + return [ResourceDeclaration(path: path, source: source)] + default: return [] + } + } + + /// Content comparison uses resolved resource evidence and effective targets separately. + var comparisonPayload: ComponentDeclaration { + func run(_ value: ExecutableDeclaration) -> ExecutableDeclaration { + var result = value + result.executableSource = nil + if let path = value.workingDirectory { + result.workingDirectory = ResourceDeclaration(path: path.path) + } + return result + } + func body(_ value: PromptBody) -> PromptBody { + if case .file(let path) = value { return .file(ResourceDeclaration(path: path.path)) } + return value + } + switch self { + case .mcpServer(let name, let transport, _, _, let native, let registry): + let resolved: MCPTransportDeclaration + if case .stdio(let value) = transport { + resolved = .stdio(run(value)) + } else { + resolved = transport + } + return .mcpServer(name: name, transport: resolved, native: native, registry: registry) + case .hook(let name, let event, let invocation, let matcher, let timeout, _, _, let native): + return .hook( + name: name, event: event, run: run(invocation), matcher: matcher, timeoutSeconds: timeout, + native: native) + case .subagent(let name, let description, let prompt, let model, let tools, _, _, let native): + return .subagent( + name: name, description: description, prompt: body(prompt), model: model, tools: tools, + native: native) + case .command(let name, let description, let prompt, let parameters, _, _, let native): + return .command( + name: name, description: description, prompt: body(prompt), parameters: parameters, + native: native + ) + case .lspServer(let name, let invocation, let languages, let options, _, _, let native): + return .lspServer( + name: name, run: run(invocation), languages: languages, initializationOptions: options, + native: native) + case .permissions(let name, let rules, _, _, let native): + return .permissions(name: name, rules: rules, native: native) + case .ignore(let name, let patterns, let purpose, _, _, let native): + return .ignore(name: name, patterns: patterns, purpose: purpose, native: native) + case .plugin( + let name, let path, _, let mode, let select, let exclude, _, _, let native): + return .plugin( + name: name, path: path, source: ".", mode: mode, select: select, exclude: exclude, + native: native) + case .skills, .instructions: return self + } + } +} diff --git a/Sources/Components/ComponentLinker.swift b/Sources/Components/ComponentLinker.swift new file mode 100644 index 0000000..6610d33 --- /dev/null +++ b/Sources/Components/ComponentLinker.swift @@ -0,0 +1,468 @@ +import AgentsCore +import AgentsManifest +import Foundation + +/// Links symbolic declarations to exact, ordered contributions. The caller owns the read lock +/// and consumes borrowed resources inside `withLinkedComponents`; no state is published here. +package enum ComponentLinker { + package static func withLinkedComponents( + document: DeclarationDocument, store: StateStore, platform: DeclarationPlatform, + preserving pins: [String: SourceRevision] = [:], + directPins: [ComponentKey: SourceRevision] = [:], + retaining ledger: ResolvedLedger? = nil, sourcePolicy: EffectiveSourcePolicy = .init(), + organization: OrganizationPolicyEvaluator = .init(chains: []), + admitOrganization: @escaping @Sendable ([OrganizationPolicyFinding]) throws -> Void = { _ in }, + stagedLocalSources: [String: URL] = [:], acquisitions: GitAcquisitionCaptures? = nil, + instructionsOnly: Bool = false, + _ body: (LinkedComponents, SourceResolutionSession) throws -> T + ) throws -> T { + if let ledger { + try ResolvedLedgerCodec.checkModel(ledger, limits: .standard) + try ledger.validate() + } + return try SourceResolutionSession.withTemporaryRead( + store: store, sourcePolicy: sourcePolicy, + requireRecordedTransport: organization.requiresRecordedGitOrigin, + stagedLocalSources: stagedLocalSources, acquisitions: acquisitions + ) { session in + let linker = Linking( + document: document, store: store, platform: platform, + session: session, directPins: directPins, retainedLedger: ledger, + organization: organization, admitOrganization: admitOrganization, + instructionsOnly: instructionsOnly) + let graph = try linker.solve(preserving: pins) + return try body(graph, session) + } + } +} + +struct LinkingDocument { + let declaration: Declaration + let document: DeclarationDocument + let view: SourceSnapshot + let manifestPath: String + let producer: Bool + var importedSources: [String: SourceSnapshot] = [:] + +} + +struct SourceAddress { + let id: String + let source: SourceDeclaration? + let contained: SourceSnapshot? + let root: String +} + +struct GroupIdentity: Hashable { + let snapshot: SourceSnapshotID + let root: String + let name: String +} + +struct RequirementSearch: Error { + let constraints: [SourceConstraint] +} + +final class Linking { + let document: DeclarationDocument + let store: StateStore + let platform: DeclarationPlatform + let instructionsOnly: Bool + let session: SourceResolutionSession + let directPins: [ComponentKey: SourceRevision] + let retainedLedger: ResolvedLedger? + let budget: LinkBudget + let organization: OrganizationPolicyEvaluator + let admitOrganization: @Sendable ([OrganizationPolicyFinding]) throws -> Void + var documents: [GroupIdentity: LinkingDocument] = [:] + var nonGit = Set() + var git = Set() + var addresses: [String: SourceAddress] = [:] + var sourceUses: [LinkedSourceUse] = [] + private var componentMaps: [GroupIdentity: [String: [SourceMapEntry]]] = [:] + private var positions: [GroupIdentity: [String: SourceMapEntry]] = [:] + + init( + document: DeclarationDocument, store: StateStore, platform: DeclarationPlatform, + session: SourceResolutionSession, directPins: [ComponentKey: SourceRevision], + retainedLedger: ResolvedLedger?, organization: OrganizationPolicyEvaluator = .init(chains: []), + admitOrganization: @escaping @Sendable ([OrganizationPolicyFinding]) throws -> Void = { _ in }, + instructionsOnly: Bool = false, + budget: LinkBudget = LinkBudget() + ) { + self.document = document + self.store = store + self.platform = platform + self.instructionsOnly = instructionsOnly + self.session = session + self.directPins = directPins + self.retainedLedger = retainedLedger + self.organization = organization + self.admitOrganization = admitOrganization + self.budget = budget + } + + /// An implicit selection admits only members owned by its recorded index. The component key + /// identifies the declaring context; resource lookup still verifies the applicable exact pin. + func artifactBelongsToIndex(key: ComponentKey, source: String) throws -> Bool { + guard let pin = directPins[key], pin.revision.hasPrefix("sha256:") else { return false } + guard let ledger = retainedLedger else { + throw CoreError.invalidState("missing pinned artifact closure") + } + var recorded = false + for component in ledger.components.sorted(by: { $0.key < $1.key }).map(\.value) { + try budget.step() + guard component.kind == key.kind.rawValue, component.root == key.root, + component.group == key.group, PathSafety.sanitizeName(component.name) == key.name, + try retainedSourceIdentity(component.declaringSource, ledger: ledger) == key.source + else { continue } + recorded = true + if try retainedSourceIdentity(component.source, ledger: ledger) == source { return true } + } + guard recorded else { throw CoreError.invalidState("missing pinned artifact component") } + return false + } + + private func retainedSourceIdentity(_ id: String, ledger: ResolvedLedger) throws -> String { + try budget.step() + guard let source = ledger.sources[id] else { + throw CoreError.invalidState("missing retained source") + } + if let container = source.container { + return try retainedSourceIdentity(container, ledger: ledger) + (source.namespace ?? "") + } + let location: String + if let authored = source.location { + location = try authored.resolve(roots: [ + "project": store.environment.projectDirectory, "home": store.environment.homeDirectory, + "state": store.directory, + ]).path + } else if let transport = source.transport { + location = transport + } else { + throw CoreError.invalidState("missing retained source coordinates") + } + return try SourceDeclaration(kind: source.kind, location: location).identity( + environment: store.environment) + } + + /// Direct artifact pins use the artifact digest, independently of every other index member. + /// The caller supplies the admitted ledger closure; absence never means refresh the index. + func retainedArtifact(key: ComponentKey, source: String) throws -> LedgerResource? { + guard let pin = directPins[key], pin.revision.hasPrefix("sha256:") else { return nil } + guard let ledger = retainedLedger else { + throw CoreError.invalidState("missing pinned artifact closure") + } + for resource in ledger.resources.sorted(by: { $0.key < $1.key }).map(\.value) { + try budget.step() + guard resource.kind == .artifact, resource.artifact?.digest == pin.revision, + let origin = ledger.sources[resource.source], origin.kind == .wellKnown, + origin.revision == pin.revision, let transport = origin.transport, + try SourceDeclaration(kind: .wellKnown, location: transport).transportIdentity() == source + else { continue } + return resource + } + throw CoreError.invalidState("missing pinned artifact resource for source") + } + + func solve(preserving pins: [String: SourceRevision]) throws -> LinkedComponents { + try budget.step(document.metrics.evaluationSteps) + // Recorded commits preserve local Git provenance independently of current working-tree metadata. + if let ledger = retainedLedger { + for id in ledger.sources.keys.sorted() { + try budget.step() + let source = ledger.sources[id]! + if source.kind == .local, SourceCache.isObjectID(source.revision) { + git.insert(try retainedSourceIdentity(id, ledger: ledger)) + } + } + } + let declaration = try ManifestProjection.declaration( + of: document, environment: store.environment) + let packageRoot = + store.scope == .user ? store.directory : store.environment.projectDirectory + let root = try SourceSnapshot( + snapshot: SourceSnapshotID( + source: "local:" + packageRoot.path, + revision: "live"), pin: nil, + root: packageRoot, + localEnvironment: SourceEnvironment( + projectDirectory: packageRoot, homeDirectory: store.environment.homeDirectory), + liveRoot: packageRoot) + session.register(root) + let context = LinkingDocument( + declaration: declaration, document: document, view: root, + manifestPath: store.scope == .user ? "agents.yaml" : ".agent/agents.yaml", + producer: false) + try budget.manifest(root.snapshot, path: context.manifestPath, bytes: document.bytes.count) + guard let result = try search(root: context, choices: pins) else { + throw LinkError.incompatible(lastFailure) + } + return result + } + + var lastFailure: [SourceConstraint] = [] + + func componentLocations(at pointer: String, in context: LinkingDocument) throws + -> [SourceMapEntry] + { + let key = GroupIdentity( + snapshot: context.view.snapshot, root: context.view.discoveryPath, name: "") + if componentMaps[key] == nil { + var locations: [String: [SourceMapEntry]] = [:] + var firstPositions: [String: SourceMapEntry] = [:] + for entry in context.document.sourceMap.entries { + try budget.step() + if firstPositions[entry.pointer] == nil { firstPositions[entry.pointer] = entry } + let path = entry.pointer.split(separator: "/") + let prefix: Int + if path.first == "components", path.count >= 2 { + prefix = 2 + } else if path.first == "groups", path.count >= 4, path[2] == "components" { + prefix = 4 + } else { + continue + } + locations["/" + path.prefix(prefix).joined(separator: "/"), default: []].append(entry) + } + componentMaps[key] = locations + positions[key] = firstPositions + } + return componentMaps[key]?[pointer] ?? [] + } + + func position(at pointer: String, in context: LinkingDocument) throws -> SourceMapEntry? { + _ = try componentLocations(at: pointer, in: context) + return positions[ + GroupIdentity(snapshot: context.view.snapshot, root: context.view.discoveryPath, name: "") + ]?[pointer] + } + + private func search(root: LinkingDocument, choices initial: [String: SourceRevision]) throws + -> LinkedComponents? + { + struct Decision { + let source: String + let candidates: [SourceRevision] + var next: Int + } + var choices = initial + var decisions: [Decision] = [] + func backtrack() throws -> Bool { + while var decision = decisions.popLast() { + try budget.step() + choices.removeValue(forKey: decision.source) + if decision.next < decision.candidates.count { + choices[decision.source] = decision.candidates[decision.next] + decision.next += 1 + decisions.append(decision) + return true + } + } + return false + } + while true { + try budget.step() + let pass = Expansion(linking: self, choices: choices, emit: false) + do { try pass.expandRoot(root) } catch let error as RequirementSearch { + lastFailure = error.constraints + if try backtrack() { continue } + return nil + } + if let next = pass.constraints.keys.filter({ choices[$0] == nil }).sorted().first { + let requirements = pass.constraints[next]! + let candidates = try candidates(for: addresses[next]!.source!, requirements: requirements) + try budget.step(candidates.count) + guard let candidate = candidates.first else { + lastFailure = requirements + if try backtrack() { continue } + return nil + } + decisions.append(Decision(source: next, candidates: candidates, next: 1)) + choices[next] = candidate + continue + } + sourceUses.removeAll() + let final = Expansion(linking: self, choices: choices, emit: true) + do { try final.expandRoot(root) } catch let error as RequirementSearch { + lastFailure = error.constraints + if try backtrack() { continue } + return nil + } + return try final.result() + } + } + + func address(_ alias: String?, in context: LinkingDocument, chain: [SourceSpan]) throws + -> SourceAddress + { + try budget.step(chain.count + 1) + guard let alias, alias != "." else { + return SourceAddress( + id: context.view.snapshot.source, source: nil, + contained: context.view, root: context.view.discoveryPath) + } + if let view = context.importedSources[alias] { + return SourceAddress( + id: view.snapshot.source, source: nil, contained: view, + root: view.discoveryPath) + } + guard let source = context.declaration.sources[alias] else { + throw LinkError.missing("source alias '\(alias)'", chain) + } + if context.producer, context.view.localEnvironment == nil, source.kind == .local { + let raw = source.location + guard !raw.hasPrefix("/"), !raw.hasPrefix("~"), !raw.contains("\\") else { + throw LinkError.invalid("producer-local source must stay inside its package", chain) + } + let relative = try PathSafety.sanitizeSubpath(raw) + let directory = try context.view.directory().appendingPathComponent(relative) + .standardizedFileURL + let path = try context.view.relativePath(directory) + let sourceID = + path == "." + ? context.view.packageIdentity + : context.view.packageIdentity + ":contained:" + String(path.utf8.count) + ":" + path + let discoveryPath = try PathSafety.sanitizeSubpath(path + "/" + (source.path ?? ".")) + let view = try SourceSnapshot( + snapshot: SourceSnapshotID(source: sourceID, revision: context.view.snapshot.revision), + pin: context.view.pin, root: context.view.root, discoveryPath: discoveryPath, + packageIdentity: context.view.packageIdentity) + guard source.requirement == nil else { + throw LinkError.invalid("contained sources inherit their producer snapshot", chain) + } + try budget.snapshot(view.snapshot) + session.register(view) + return SourceAddress(id: sourceID, source: nil, contained: view, root: view.discoveryPath) + } + try session.requireSource(source) + let id = try source.identity(environment: store.environment) + let root = try PathSafety.sanitizeSubpath(source.path ?? ".") + var override: [SourceRequirement]? + if organization.active, + source.kind != .local + || BundleSourceLocation.container( + of: source.localURL(environment: store.environment), in: store) == nil + { + let origin = try SourceOrigin.declared(source, in: store.environment) + let identity = OrganizationPolicyIdentity(origin, root: root) + try admitOrganization( + organization.source(origin, root: root, path: [alias]) + + organization.packageIdentity(identity, path: [alias])) + let required = organization.requirements(for: identity) + if source.kind != .wellKnown, required.overrides { override = required.constraints } + } + let result = SourceAddress(id: id, source: source, contained: nil, root: root) + addresses[id] = result + let use = LinkedSourceUse( + source: id, root: root, requirement: source.requirement, organizationRequirements: override) + if !sourceUses.contains(use) { sourceUses.append(use) } + return result + } + + var requireArtifactOrigin: (@Sendable (SourceOrigin) throws -> Void)? { + organization.artifactOriginCheck(admitOrganization) + } + + func candidates( + for source: SourceDeclaration, requirements: [SourceConstraint] + ) throws -> [SourceRevision] { + guard organization.active else { + return try session.candidates( + for: source, requirements: requirements.map(\.requirement), spending: budget.step) + } + let origin = try SourceOrigin.declared(source, in: store.environment) + let admissions = requirements.map { constraint in + let identity = OrganizationPolicyIdentity(origin, root: constraint.root) + return (constraint, identity, organization.requirements(for: identity)) + } + let effective = admissions.flatMap { constraint, _, admission -> [SourceRequirement?] in + (admission.overrides ? [] : [constraint.requirement]) + + admission.constraints.map(Optional.some) + } + let candidates = try session.candidates( + for: source, requirements: effective, spending: budget.step) + if candidates.isEmpty { + let findings = admissions.flatMap { constraint, identity, admission in + admission.constraints.isEmpty + ? [] + : organization.version( + nil, identity: identity, authored: [constraint.requirement].compactMap { $0 }, + available: false) + } + try admitOrganization(findings) + } + return candidates + } + + func admits(_ pin: SourceRevision, for source: SourceDeclaration) throws -> Bool { + guard organization.active else { return true } + let origin = try SourceOrigin.declared(source, in: store.environment) + let identity = OrganizationPolicyIdentity(origin, root: source.path) + return organization.requirements(for: identity).constraints.allSatisfy { requirement in + pin.version.map(requirement.admitsMarketplaceVersion) ?? false + } + } + + func view(_ address: SourceAddress, pin: SourceRevision? = nil) throws -> SourceSnapshot? { + if let contained = address.contained { return contained } + let source = address.source! + guard source.kind != .wellKnown else { + throw LinkError.invalid("skill indexes cannot supply package resources", []) + } + if let pin, pin.archive?.admits(source.requirement, version: pin.version) != false, + try admits(pin, for: source) + { + let view = try session.snapshot(source, at: pin) + try budget.snapshot(view.snapshot) + return view + } + if source.requirement != nil || source.kind == .git { + git.insert(address.id) + return nil + } + if try nonGit.contains(address.id) + || (!git.contains(address.id) && !session.isGitSource(source)) + { + nonGit.insert(address.id) + let view = try session.localSnapshot(source) + try budget.snapshot(view.snapshot) + return view + } + git.insert(address.id) + return nil + } + + func producer(_ view: SourceSnapshot, chain: [SourceSpan]) throws -> LinkingDocument { + let key = GroupIdentity(snapshot: view.snapshot, root: view.discoveryPath, name: "") + if let existing = documents[key] { return existing } + let root = try view.directory() + let file = root.appendingPathComponent( + root.lastPathComponent == ".agent" ? "agents.yaml" : ".agent/agents.yaml") + let relative = try view.relativePath(file) + let handle = try FileHandle(forReadingFrom: view.resource(relative)) + defer { try? handle.close() } + let bytes = try handle.read(upToCount: ManifestLimits.Input.bytes + 1) ?? Data() + guard bytes.count <= ManifestLimits.Input.bytes else { + throw LinkError.budget("manifest input bytes") + } + try budget.manifest( + view.snapshot, path: relative, bytes: bytes.count) + let coordinates = try JSONEncoder().encode([view.snapshot.source, view.discoveryPath, relative]) + let identity = DocumentIdentity("source:" + String(decoding: coordinates, as: UTF8.self)) + let document = try DeclarationDocument(bytes: Array(bytes), identity: identity) + let environment = RuntimeEnvironment( + projectDirectory: view.localEnvironment.map { + $0.projectDirectory.appendingPathComponent(view.discoveryPath) + } ?? root, + homeDirectory: view.localEnvironment?.homeDirectory ?? store.environment.homeDirectory, + environment: [:]) + try budget.step(document.metrics.evaluationSteps) + let declaration = try ManifestProjection.declaration(of: document, environment: environment) + let result = LinkingDocument( + declaration: declaration, document: document, view: view, + manifestPath: relative, producer: true) + documents[key] = result + return result + } +} diff --git a/Sources/Components/DeploymentConstruction.swift b/Sources/Components/DeploymentConstruction.swift new file mode 100644 index 0000000..7940eaa --- /dev/null +++ b/Sources/Components/DeploymentConstruction.swift @@ -0,0 +1,477 @@ +import AgentsCore +import AgentsInstructions +import Foundation + +package enum DeploymentConstruction { + package static func validateCopiedSkill(_ tree: URL) throws { + guard let real = PathSafety.realPath(tree.path), + let children = FileManager.default.enumerator( + at: tree, includingPropertiesForKeys: [.isSymbolicLinkKey]) + else { return } + for case let child as URL in children + where try child.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink == true { + guard try PathSafety.linkStaysInside(child, root: real) else { + throw CoreError.unsafePath("copied skill link escapes its installed subtree") + } + } + } + + package struct Result { + package let ledger: ResolvedLedger + package let inputs: [TargetPrecondition] + } + package static func routes(_ ledger: ResolvedLedger) throws -> Set { + var result = Set() + for lowering in ledger.lowerings where lowering.format.hasSuffix("-mcp@1") { + let contribution = try MCPLayoutV1.contribution(lowering, ledger: ledger) + let route = try route(contribution) + result.insert(route) + if contribution.descriptor.request.surface == .openCodeCLI { + result.insert( + contribution.descriptor.request.scope == .project + ? .openCodeMCPProjectJSONC : .openCodeMCPUserJSONC) + } + } + for lowering in ledger.lowerings where lowering.format.hasSuffix("-components@1") { + let input = try NativeComponentLayoutsV1.input(lowering, ledger: ledger, limits: .standard) + let scope = input.request.scope + let name = input.record.name + switch (input.request.surface, input.record.kind) { + case (.antigravity, "hook"): + result.insert(scope == .project ? .antigravityHooksProject : .antigravityHooksUser) + case (.claudeCode, "command"): + result.insert(try .named(.claudeCommand, scope: scope, name: name)) + case (.claudeCode, "subagent"): + result.insert(try .named(.claudeAgent, scope: scope, name: name)) + case (.claudeCode, "lspServer"), (.claudeCode, "plugin"): + result.insert(try .named(.claudeSkillPlugin, scope: scope, name: name)) + case (.claudeCode, _): + result.insert(scope == .project ? .claudeSettingsProject : .claudeSettingsUser) + case (.codexCLI, "subagent"): + result.insert(try .named(.codexAgent, scope: scope, name: name)) + result.insert(scope == .project ? .codexMCPProject : .codexMCPUser) + case (.codexCLI, _): result.insert(scope == .project ? .codexHooksProject : .codexHooksUser) + case (.geminiCLI, "command"): + result.insert(try .named(.geminiCommand, scope: scope, name: name)) + case (.geminiCLI, "subagent"): + result.insert(try .named(.geminiAgent, scope: scope, name: name)) + case (.geminiCLI, "plugin"): + result.insert(try .named(.geminiExtension, scope: scope, name: name)) + case (.geminiCLI, "ignore"): result.insert(.geminiIgnoreProject) + case (.geminiCLI, _): result.insert(scope == .project ? .geminiMCPProject : .geminiMCPUser) + case (.cursorEditor, "command"): + result.insert(try .named(.cursorCommand, scope: scope, name: name)) + case (.cursorEditor, "subagent"): + result.insert(try .named(.cursorAgent, scope: scope, name: name)) + case (.cursorEditor, "plugin"): + result.insert(try .named(.cursorLocalPlugin, scope: scope, name: name)) + case (.cursorEditor, "ignore"): result.insert(.cursorIgnoreProject) + case (.cursorEditor, _): + result.insert(scope == .project ? .cursorHooksProject : .cursorHooksUser) + case (.openCodeCLI, _): + result.insert(scope == .project ? .openCodeMCPProjectJSON : .openCodeMCPUserJSON) + result.insert(scope == .project ? .openCodeMCPProjectJSONC : .openCodeMCPUserJSONC) + default: throw CoreError.invalidState("native surface has no integrated closed route") + } + } + for lowering in ledger.lowerings where lowering.format.hasSuffix("-generated-plugin@1") { + result.insert(try generatedRoute(lowering, ledger: ledger)) + } + return result + } + + package static func generatedRoute(_ lowering: LockedLowering, ledger: ResolvedLedger) throws + -> NativeTargetRoute + { + guard let surface = lowering.layout.object?["surface"]?.text, + let scopeText = lowering.layout.object?["scope"]?.text, + let scope = InstallScope(rawValue: scopeText), + let id = lowering.inputs.first, let component = ledger.components[id] + else { + throw CoreError.invalidState("invalid generated native route") + } + switch NativeClientSurface(rawValue: surface) { + case .claudeCode: return try .named(.claudeSkillPlugin, scope: scope, name: component.name) + case .cursorEditor: return try .named(.cursorLocalPlugin, scope: scope, name: component.name) + case .geminiCLI: return try .named(.geminiExtension, scope: scope, name: component.name) + default: throw CoreError.invalidState("unregistered generated native route") + } + } + + private static func surface(_ agent: AgentID) -> NativeClientSurface { + switch agent { + case .claudeCode: .claudeCode + case .codex: .codexCLI + case .cursor: .cursorEditor + case .geminiCLI: .geminiCLI + case .opencode: .openCodeCLI + case .antigravity: .antigravity + } + } + + /// Checks the native entry without reading resources or resolving any runtime binding. + package static func validateMCP( + _ transport: MCPTransportDeclaration, named name: String, agent: AgentID, scope: InstallScope, + native: NativeConfiguration = [:], requiresSymbolicBindings: Bool + ) throws { + let request = NativeMCPRequest( + surface: surface(agent), scope: scope == .user ? .user : .project) + let descriptor = try CapabilityRegistry.mcp(request, component: name) + var resources: [String] = [] + if case .stdio(let run) = transport { + if run.executable.contains("/") { resources.append(run.executable) } + if let directory = run.workingDirectory { resources.append(directory.path) } + } + let entry = try NativeMCPLowering.entry( + transport, named: name, descriptor: descriptor, native: native[agent.rawValue] ?? [:], + resources: resources) + if requiresSymbolicBindings, let literal = entry.placements.first(where: { !$0.reference }) { + throw NativeAdapterIssue( + request: request, component: name, field: literal.path.fields, reason: .unsupported, + detail: "the client cannot keep this MCP registry binding symbolic") + } + } + + private static func direct(_ component: LinkedComponent, ledger: ResolvedLedger, agent: AgentID) + throws -> LinkedComponent + { + let surface = surface(agent) + let parents = Set( + ledger.lowerings.filter { + $0.format.hasSuffix("-generated-plugin@1") + && $0.layout.object?["surface"]?.text == surface.rawValue + }.flatMap { $0.layout.object?["occurrences"]?.array?.compactMap(\.integer) ?? [] }) + let consumed = Set( + ledger.occurrences.filter { $0.pluginMember.map { parents.contains($0.parent) } ?? false } + .map(\.id)) + var result = component + result.origins.removeAll { consumed.contains($0.occurrence) } + return result + } + + package static func physicalRoute( + _ route: NativeTargetRoute, ledger: ResolvedLedger, store: StateStore + ) throws -> NativeTargetRoute { + let alternate: NativeTargetRoute + if route == .openCodeMCPProjectJSON { + alternate = .openCodeMCPProjectJSONC + } else if route == .openCodeMCPUserJSON { + alternate = .openCodeMCPUserJSONC + } else { + return route + } + let recorded = ledger.deployments.filter { $0.route.hasPrefix("agents/opencode-") } + let names = Set(recorded.map { ($0.target.path as NSString).lastPathComponent }) + if names.contains("opencode.jsonc"), !names.contains("opencode.json") { return alternate } + if names.contains("opencode.json"), !names.contains("opencode.jsonc") { return route } + let json = try store.nativeTarget(for: route) + let jsonc = try store.nativeTarget(for: alternate) + let hasJSON = FileManager.default.fileExists(atPath: json.url.path) + let hasJSONC = FileManager.default.fileExists(atPath: jsonc.url.path) + guard !(hasJSON && hasJSONC) else { + throw CoreError.invalidState( + "multiple OpenCode configuration files require an explicit native target decision") + } + return hasJSONC ? alternate : route + } + + package static func route(_ output: NativeComponentOutput, request: NativeComponentRequest) throws + -> NativeTargetRoute + { + let project = request.scope == .project + let path: String + switch output.content { + case .file(let name, _): path = name + case .generatedLSPPlugin(let directory, _, _), .nativePlugin(let directory, _, _): + path = directory + default: path = "" + } + switch output.route { + case .claudeCommand: return try .file(.claudeCommand, scope: request.scope, relativePath: path) + case .claudeAgent: return try .file(.claudeAgent, scope: request.scope, relativePath: path) + case .codexAgent: return try .file(.codexAgent, scope: request.scope, relativePath: path) + case .geminiCommand: return try .file(.geminiCommand, scope: request.scope, relativePath: path) + case .geminiAgent: return try .file(.geminiAgent, scope: request.scope, relativePath: path) + case .cursorCommand: return try .file(.cursorCommand, scope: request.scope, relativePath: path) + case .cursorAgent: return try .file(.cursorAgent, scope: request.scope, relativePath: path) + case .claudeSkillPlugin: return try .named(.claudeSkillPlugin, scope: request.scope, name: path) + case .cursorLocalPlugin: return try .named(.cursorLocalPlugin, scope: request.scope, name: path) + case .geminiExtension: return try .named(.geminiExtension, scope: request.scope, name: path) + case .claudeSettings: return project ? .claudeSettingsProject : .claudeSettingsUser + case .codexHooks: return project ? .codexHooksProject : .codexHooksUser + case .cursorHooks: return project ? .cursorHooksProject : .cursorHooksUser + case .antigravityHooks: return project ? .antigravityHooksProject : .antigravityHooksUser + case .geminiIgnore: return .geminiIgnoreProject + case .cursorIgnore: return .cursorIgnoreProject + case .geminiSettings: return project ? .geminiMCPProject : .geminiMCPUser + case .codexConfig: return project ? .codexMCPProject : .codexMCPUser + case .openCodeConfig: return project ? .openCodeMCPProjectJSON : .openCodeMCPUserJSON + } + } + + package static func route(_ contribution: NativeMCPContribution) throws -> NativeTargetRoute { + let project = contribution.descriptor.request.scope == .project + switch contribution.descriptor.request.surface { + case .claudeCode: + switch contribution.descriptor.request.scope { + case .project: return .claudeMCPProject + case .local: return .claudeMCPLocal + case .user: return .claudeMCPUser + } + case .codexCLI: return project ? .codexMCPProject : .codexMCPUser + case .geminiCLI: return project ? .geminiMCPProject : .geminiMCPUser + case .antigravity: return project ? .antigravityMCPProject : .antigravityMCPUser + case .cursorEditor: return project ? .cursorMCPProject : .cursorMCPUser + case .openCodeCLI: return project ? .openCodeMCPProjectJSON : .openCodeMCPUserJSON + case .cursorCLI, .cursorCloud: + throw NativeAdapterIssue( + request: contribution.descriptor.request, component: contribution.name, field: ["route"], + reason: .integrationRequired, detail: "this surface has no accepted registered route") + } + } + + package static func lowerNative( + linked: LinkedComponents, frozen: LedgerFreeze.Result, scope: InstallScope, + platform: DeclarationPlatform + ) throws -> ResolvedLedger { + var ledger = frozen.ledger + for parent in linked.components where parent.key.kind == .plugin { + guard case .declaration = parent.payload, + let id = frozen.ledger.occurrences.first(where: { $0.id == parent.origins[0].occurrence })? + .component, + let record = frozen.ledger.components[id], + record.payload.object?["mode"] == .init("components") + else { continue } + _ = record + for agent in parent.recipients.sorted(by: { $0.rawValue < $1.rawValue }) { + ledger.lowerings.append( + try NativeGeneratedPluginLayoutV1.lower( + parent, members: linked.components, frozen: frozen, + request: .init(surface: surface(agent), scope: scope), + id: "plugin:" + String(parent.origins[0].occurrence) + ":" + agent.rawValue, + platform: platform)) + } + } + for original in linked.components { + guard case .declaration = original.payload else { continue } + if original.key.kind == .plugin, + ledger.lowerings.contains(where: { + $0.format.hasSuffix("-generated-plugin@1") + && $0.layout.object?["occurrences"]?.array?.contains( + .init(integer: original.origins[0].occurrence)) == true + }) + { + continue + } + for agent in original.recipients.sorted(by: { $0.rawValue < $1.rawValue }) { + let component = try direct(original, ledger: ledger, agent: agent) + guard !component.origins.isEmpty else { continue } + let surface = surface(agent) + if component.key.kind != .mcpServer { + ledger.lowerings.append( + try NativeComponentLowering.lower( + component, frozen: frozen, + request: .init(surface: surface, scope: scope), + id: "native:" + String(component.origins[0].occurrence) + ":" + agent.rawValue, + platform: platform)) + continue + } + var contribution = try NativeMCPLowering.lower( + component, frozen: frozen, + request: .init(surface: surface, scope: scope == .user ? .user : .project)) + if scope == .project, surface == .claudeCode, + contribution.bindings.contains(where: { !$0.reference }) + { + contribution = try NativeMCPLowering.lower( + component, frozen: frozen, request: .init(surface: surface, scope: .local)) + } + let id = "mcp:" + String(component.origins[0].occurrence) + ":" + agent.rawValue + ledger.lowerings.append(contribution.lowering(id: id, artifact: id, platform: platform)) + } + } + return ledger + } + + package static func complete( + _ native: ResolvedLedger, linked: LinkedComponents, store: StateStore, + previous: ResolvedLedger, platform: DeclarationPlatform, roots: [String: URL], + session: SourceResolutionSession + ) throws -> Result { + var ledger = native + var inputs: [TargetPrecondition] = [] + let owners = Dictionary(uniqueKeysWithValues: ledger.occurrences.map { ($0.id, $0.component) }) + func owner(_ component: LinkedComponent) -> String { owners[component.origins[0].occurrence]! } + func add( + id: String, format: String, inputs: [String], resources: [String], location: LedgerLocation?, + agents: [AgentID], hash: String, layout: [String: LedgerValue], + ownership: LedgerDeployment.Ownership = .generated, created: Bool = false, + reference: String? = nil + ) { + let deployment = location.map { location in + LedgerDeployment( + id: id, target: location, route: format, owners: inputs, recipients: agents, + ownership: ownership, expectedHash: hash, created: created, + importReference: reference, headingOffset: ownership == .generated ? 0 : nil) + } + if let deployment { ledger.deployments.append(deployment) } + ledger.lowerings.append( + .init( + id: id, format: format, inputs: inputs, resources: resources, + deployments: deployment == nil ? [] : [id], layout: .init(object: layout), + platform: platform.rawValue, artifacts: [])) + } + for component in linked.components { + guard case .skill(_, _, _) = component.payload else { continue } + let key = owner(component) + let record = ledger.components[key]! + let resource = ledger.resources[record.resources[0]]! + for agent in component.recipients.sorted(by: { $0.rawValue < $1.rawValue }) { + let directComponent = try direct(component, ledger: ledger, agent: agent) + guard let origin = directComponent.origins.first else { continue } + let id = "skill:" + String(origin.occurrence) + ":" + agent.rawValue + add( + id: id, format: "agents/skill@1", inputs: [key], resources: record.resources, + location: .init( + kind: .registered, root: "skills-" + agent.rawValue, + path: PathSafety.sanitizeName(component.key.name)), + agents: [agent], hash: resource.hash, + layout: ["name": .init(id), "mode": record.payload.object!["mode"]!]) + } + } + let instructions = linked.components.filter { + if case .instruction = $0.payload { true } else { false } + } + let old = try previous.domainProjection(roots: roots).instructions + var merged: [String: (LockedTarget, [String], [String])] = [:] + var ruleOwners: [String: (String, String)] = [:] + for component in instructions where component.recipients.contains(.antigravity) { + guard case .instruction(let unit, _, _) = component.payload else { continue } + let key = owner(component) + let record = ledger.components[key]! + let leaf = try AntigravityRuleV1.leaf(source: component.snapshot.source, path: unit.path) + _ = try InstructionLocations.antigravityLeaf(leaf, store: store) + if let (priorSource, priorUnit) = ruleOwners[leaf] { + guard priorSource == record.source, priorUnit == record.resources[0] else { + throw AntigravityRuleV1.failure(leaf, "incompatible selections share this rule") + } + continue + } + ruleOwners[leaf] = (record.source, record.resources[0]) + let bytes = try AntigravityRuleV1.render( + unit.bytes, path: unit.path, leaf: leaf, scope: store.scope + ) { + try FileSystem.read(at: session.resource(snapshot: component.snapshot, path: $0)) + } + let id = "antigravity:" + leaf + add( + id: id, format: AntigravityRuleV1.format, inputs: [key], resources: record.resources, + location: .init( + kind: .registered, root: InstructionLocations.ruleRoot(in: store.scope), path: leaf), + agents: [.antigravity], hash: Instructions.hash(bytes), layout: ["name": .init(id)]) + } + for agent in AgentID.allCases + where agent != .antigravity && agent.supportsInstructions(in: store.scope) { + let selected = instructions.filter { $0.recipients.contains(agent) } + let sections = selected.compactMap { component in + if case .instruction(let unit, _, _) = component.payload { return unit.section } + return nil + } + guard !sections.isEmpty else { continue } + let planned = try InstructionTargets(store: store).plan( + sections: sections, agents: [agent], previous: old) + for (id, source) in ledger.sources where source.kind == .local && source.location != nil { + let identity = try ledger.sourceIdentity(id, roots: roots) + let roots = ledger.sourceUses.filter { $0.source == id }.map(\.root) + for root in roots.isEmpty ? ["."] : roots { + try InstructionTargets.validateSourceDirectories( + planned.changes, + sources: [identity: LockedSource(kind: .local, path: root == "." ? nil : root)]) + } + } + inputs += try planned.expectations.values.map { try $0.capturingPublicationAccess() } + let targets = planned.targets + for (path, target) in targets { + let selected = selected.filter { component in + if target.import != nil { return true } + if case .instruction(let unit, _, _) = component.payload { + let directory = store.scope == .project ? unit.section.directory : "" + return store.scope == .user || (path as NSString).deletingLastPathComponent == directory + || (directory.isEmpty && !(path.contains("/"))) + } + return false + } + let owners = selected.map(owner) + let resources = owners.map { ledger.components[$0]!.resources[0] } + if var existing = merged[path] { + guard existing.0.blockHash == target.blockHash, existing.2 == resources else { + throw CoreError.invalidState( + "instruction recipients require incompatible shared output: \(path)") + } + existing.0.agents += target.agents + var knownOwners = Set(existing.1) + existing.1 += owners.filter { knownOwners.insert($0).inserted } + merged[path] = existing + } else { + merged[path] = (target, owners, resources) + } + } + } + for path in merged.keys.sorted() { + let (target, owners, resources) = merged[path]! + let file = try InstructionLocations.file(for: path, store: store) + let location: LedgerLocation + if store.scope == .project { + location = .init(kind: .registered, root: "project", path: path) + } else if let agent = target.agents.first { + location = .init( + kind: .registered, root: "instructions-" + agent.rawValue, path: file.lastPathComponent) + } else { + throw CoreError.invalidState("missing instruction recipient") + } + let id = "instructions:" + path + let format = target.import == nil ? "agents/instructions@1" : "agents/claude-import@1" + add( + id: id, format: format, inputs: owners, resources: target.import == nil ? resources : [], + location: location, agents: Array(Set(target.agents)).sorted { $0.rawValue < $1.rawValue }, + hash: target.blockHash, + layout: [ + "name": .init(target.import == nil ? id : path), "headingOffset": .init(integer: 0), + ], + ownership: target.import == nil ? .generated : .importBlock, + created: target.created, reference: target.import) + } + var prompts: [String: [LinkedComponent]] = [:] + for component in instructions where component.chatGPT { + if case .instruction(_, let prompt?, _) = component.payload { + prompts[prompt, default: []].append(component) + } + } + for name in prompts.keys.sorted() { + let selected = prompts[name]! + let owners = selected.map(owner) + var resources = owners.map { ledger.components[$0]!.resources[0] } + if let append = ledger.components[owners[0]]!.resources.dropFirst().first { + resources.append(append) + } + add( + id: "prompt:" + name, format: "agents/chatgpt@1", inputs: owners, resources: resources, + location: nil, agents: [], hash: "sha256:" + String(repeating: "0", count: 64), + layout: ["name": .init("prompt:" + name), "sectionCount": .init(integer: selected.count)]) + } + for recipient in [InstructionRecipient.chatGPTApp, .geminiApp] { + let selected = instructions.filter { $0.copyRecipients.contains(recipient) } + guard !selected.isEmpty else { continue } + let id = "instruction-copy:" + recipient.rawValue + let owners = selected.map(owner) + add( + id: id, format: LockedLowering.instructionCopyFormat, inputs: owners, + resources: owners.map { ledger.components[$0]!.resources[0] }, + location: nil, agents: [], hash: "", + layout: [ + "name": .init(id), "recipient": .init(recipient.rawValue), + "sectionCount": .init(integer: selected.count), + ]) + } + return Result(ledger: ledger, inputs: inputs) + } +} diff --git a/Sources/Components/Expansion.swift b/Sources/Components/Expansion.swift new file mode 100644 index 0000000..e144cc9 --- /dev/null +++ b/Sources/Components/Expansion.swift @@ -0,0 +1,890 @@ +import AgentsCore +import AgentsInstructions +import AgentsManifest +import AgentsSkills +import Foundation + +final class Expansion { + let linking: Linking + let choices: [String: SourceRevision] + let emit: Bool + var constraints: [String: [SourceConstraint]] = [:] + var components: [LinkedComponent] = [] + var references: [LinkedReference] = [] + var active: [GroupIdentity] = [] + var nextOccurrence = 0 + var referenceParent: Int? + struct PluginFrame { + let parent: Int + let selector: ComponentReferenceDeclaration + let root: String + let containerRoot: String + let origin: ImportLocation + let input: LedgerInputProvenance + let recipients: Set + } + var pluginFrame: PluginFrame? + var pluginDepth = 0 + var pluginChildren: [Int: [Int]] = [:] + private struct IndexRequest: Hashable { + let source: String + let names: [String]? + let exclude: [String] + } + private var indexes: [IndexRequest: [SnapshotIndexSkill]] = [:] + var values = ManifestExpansionBudget() + + init(linking: Linking, choices: [String: SourceRevision], emit: Bool) { + self.linking = linking + self.choices = choices + self.emit = emit + } + + func expandRoot(_ root: LinkingDocument) throws { + try expand( + root.declaration.components, records: root.document.declaration.components, + in: root, group: nil, pointer: "/components", + condition: DeclarationCondition(), chain: [], dependencies: [], parent: nil) + for (index, use) in root.declaration.uses.enumerated() { + try expand( + use, in: root, pointer: "/uses/\(index)", condition: DeclarationCondition(), + chain: [], dependencies: [], parent: nil) + } + for (id, requirements) in constraints { + if let selected = choices[id] { + if let archive = selected.archive { + guard + requirements.allSatisfy({ + archive.admits($0.requirement, version: selected.version) + }) + else { throw RequirementSearch(constraints: requirements) } + continue + } + let candidates = try linking.candidates( + for: linking.addresses[id]!.source!, requirements: requirements) + try linking.budget.step(candidates.count) + guard candidates.contains(where: { $0.revision == selected.revision }) else { + throw RequirementSearch(constraints: requirements) + } + } + } + } + + private struct Use { + let declaration: GroupUseDeclaration + let document: LinkingDocument + let pointer: String + let condition: DeclarationCondition + let chain: [SourceSpan] + let dependencies: [SourceSnapshotID] + let parent: Int? + } + + private enum Walk { + case enter(Use) + case leave + } + + private func expand( + _ use: GroupUseDeclaration, in context: LinkingDocument, pointer: String, + condition: DeclarationCondition, chain: [SourceSpan], dependencies: [SourceSnapshotID], + parent: Int? + ) throws { + var pending: [Walk] = [ + .enter( + Use( + declaration: use, document: context, pointer: pointer, + condition: condition, chain: chain, dependencies: dependencies, parent: parent)) + ] + while let step = pending.popLast() { + switch step { + case .leave: + try linking.budget.step() + active.removeLast() + case .enter(let use): try enter(use, pending: &pending) + } + } + } + + private func enter(_ reference: Use, pending: inout [Walk]) throws { + let use = reference.declaration + let context = reference.document + let pointer = reference.pointer + var condition = reference.condition + var chain = reference.chain + var dependencies = reference.dependencies + let parent = reference.parent + try linking.budget.step(chain.count + 1) + guard active.count < 64 else { throw LinkError.budget("active references") } + let location = try linking.position(at: pointer, in: context) + chain += (location.map { [$0.span] + $0.origins } ?? []) + let address = try linking.address(use.source, in: context, chain: chain) + var target = context + var constraint: SourceConstraint? + if use.source != nil, use.source != "." { + guard address.source?.kind != .wellKnown else { + throw LinkError.invalid("skill indexes do not define an immutable export package", chain) + } + if linking.organization.active, let source = address.source { + let external = active.map(\.snapshot.source).filter { + $0 != "local:" + + (linking.store.scope == .project + ? linking.store.environment.projectDirectory.path + : linking.store.directory.path) + } + var path: [String] = [] + for identity in external + [address.id] where path.last != identity { + path.append(identity) + } + try linking.admitOrganization( + linking.organization.depth( + path.count, + path: Array(path.dropLast()) + [ + OrganizationPolicyIdentity( + try .declared(source, in: linking.store.environment), root: address.root + ).description + ])) + } + let initial = try linking.view(address, pin: choices[address.id]) + if let source = address.source, !linking.nonGit.contains(address.id) { + let entry = SourceConstraint( + source: address.id, root: address.root, + requirement: source.requirement, referenceChain: chain) + constraints[address.id, default: []].append(entry) + constraint = entry + } + guard let view = initial else { return } + target = try linking.producer(view, chain: chain) + guard target.declaration.exports.contains(use.name) else { + throw LinkError.missing("explicit export '\(use.name)'", chain) + } + } + guard let index = target.declaration.groups.firstIndex(where: { $0.name == use.name }) else { + throw LinkError.missing("group '\(use.name)'", chain) + } + let group = target.declaration.groups[index] + let key = GroupIdentity( + snapshot: target.view.snapshot, root: target.view.discoveryPath, name: group.name) + guard !active.contains(key) else { + throw LinkError.cycle((active + [key]).map(\.name), chain) + } + active.append(key) + pending.append(.leave) + let occurrence = nextOccurrence + nextOccurrence += 1 + dependencies += [target.view.snapshot] + condition = condition.intersecting(use.condition ?? DeclarationCondition()) + .intersecting(group.condition ?? DeclarationCondition()) + if emit { + references.append( + LinkedReference( + occurrence: occurrence, parent: parent, + group: group.name, snapshot: target.view.snapshot, root: target.view.discoveryPath, + constraint: constraint, referenceChain: chain, + manifestHash: target.document.digest)) + } + try expand( + group.components, + records: target.document.declaration.groups[index]["components"]!.elements!.map { + $0.record! + }, + in: target, group: group.name, + pointer: "/groups/\(index)/components", condition: condition, chain: chain, + dependencies: dependencies, parent: occurrence) + for (useIndex, nested) in group.uses.enumerated().reversed() { + pending.append( + .enter( + Use( + declaration: nested, document: target, + pointer: "/groups/\(index)/uses/\(useIndex)", condition: condition, chain: chain, + dependencies: dependencies, parent: occurrence))) + } + } + + private func expand( + _ declarations: [ComponentDeclaration], records: [DeclarationRecord], + in context: LinkingDocument, group: String?, + pointer: String, condition: DeclarationCondition, chain: [SourceSpan], + dependencies: [SourceSnapshotID], parent: Int? + ) throws { + let previousParent = referenceParent + referenceParent = parent + defer { referenceParent = previousParent } + for (index, component) in declarations.enumerated() { + try linking.budget.step(chain.count + 1) + let pointer = pointer + "/\(index)" + let position = try linking.position(at: pointer, in: context) + do { + try values.consume( + records[index], origins: chain, + locations: linking.componentLocations(at: pointer, in: context), + spending: linking.budget.step) + } catch is ManifestExpansionBudget.Failure { + throw LinkError.budget("expanded manifest values") + } + guard includes(component) else { continue } + for resource in component.resources { + try constrainResource( + resource, in: context, chain: chain + (position.map { [$0.span] + $0.origins } ?? [])) + } + guard emit else { continue } + let effective = condition.intersecting(component.condition ?? DeclarationCondition()) + try emitComponent( + component, in: context, group: group, condition: effective, + chain: chain, position: position, dependencies: dependencies, pointer: pointer) + } + } + + private func includes(_ component: ComponentDeclaration) -> Bool { + guard linking.instructionsOnly else { return true } + // Supported native container profiles do not convert rules or context files to instructions. + return component.kind == .instructions + } + + func emitComponent( + _ component: ComponentDeclaration, in context: LinkingDocument, + group: String?, condition effective: DeclarationCondition, chain: [SourceSpan], + position: SourceMapEntry?, dependencies: [SourceSnapshotID], pointer: String = "" + ) throws { + guard includes(component) else { return } + do { + switch component { + case .skills(let alias, let selection): + try skills( + selection, alias: alias, context: context, group: group, + condition: effective, chain: chain, position: position, dependencies: dependencies) + case .instructions(let selection): + for (index, section) in selection.sectionReferences.enumerated() { + try instruction( + section, prompt: nil, selection: selection, context: context, group: group, + condition: effective, chain: chain, + position: linking.position(at: pointer + "/sections/\(index)", in: context) + ?? position, + dependencies: dependencies) + } + for prompt in selection.prompts { + let promptCondition = effective.intersecting( + prompt.prompt.condition ?? DeclarationCondition()) + for section in prompt.prompt.sectionReferences { + try instruction( + section, prompt: prompt.name, selection: selection, context: context, + group: group, condition: promptCondition, chain: chain, position: position, + dependencies: dependencies, append: prompt.prompt.append) + } + } + case .plugin: + try plugin( + component, context: context, group: group, condition: effective, + chain: chain, position: position, dependencies: dependencies) + default: + if linking.organization.active, + case .mcpServer(let name, let transport, _, _, _, let registry) = component + { + // Bundle producers carry a separate qualified package identity in the frozen graph. + let stagedBundle = linking.session.bundleSources[context.view.snapshot] != nil + if !stagedBundle { + let origin: SourceOrigin + if !context.producer { + origin = .inline + } else if let descriptor = linking.addresses[context.view.snapshot.source]?.source { + origin = try .declared(descriptor, in: linking.store.environment) + } else { + origin = .missing + } + let identity = + registry?.organizationPolicyIdentity + ?? OrganizationPolicyIdentity(origin, suffix: name, root: context.view.discoveryPath) + var findings = linking.organization.mcp( + identity, transport: transport.organizationPolicyName, selfDefined: registry == nil, + transitive: context.producer, path: [name]) + for origin in registry?.origins ?? [] { + findings += linking.organization.source(origin, path: [name]) + } + try linking.admitOrganization(findings) + } + } + if let registry = component.mcpRegistry { + for origin in registry.origins { + try linking.session.sourcePolicy.require(origin, reference: registry.server) + } + } + let resources = try component.resources.map { + try resource($0, context: context, chain: chain) + } + try append( + key: key(component.name!, kind: component.kind, context: context, group: group), + snapshot: context.view.snapshot, pin: context.view.pin, + payload: .declaration(try resolvedNativeResources(component, context: context)), + context: context, + group: group, condition: effective, + recipients: effective.recipients( + requested: component.agents ?? context.declaration.defaultAgents, + scope: linking.store.scope, platform: linking.platform), chatGPT: false, + resources: resources, chain: chain, position: position, + dependencies: dependencies + resources.map(\.snapshot)) + } + } catch let error as LinkError { + throw error + } catch let error as OrganizationPolicyFailure { + throw error + } catch let error as SourcePolicyFailure { + throw SourcePolicyFailure( + violations: error.violations, + context: error.context + chain + (position.map { [$0.span] + $0.origins } ?? [])) + } catch var error as GitError { + for span in chain + (position.map { [$0.span] + $0.origins } ?? []) + where !error.context.contains(span) { + error.context.append(span) + } + throw error + } catch { + throw LinkError.invalid( + String(describing: error), chain + (position.map { [$0.span] + $0.origins } ?? [])) + } + } + + func key( + _ name: String, kind: DeclaredComponentKind, context: LinkingDocument, group: String? + ) -> ComponentKey { + ComponentKey( + source: context.view.snapshot.source, root: pluginFrame?.root ?? context.view.discoveryPath, + group: group, kind: kind, name: name, containerRoot: pluginFrame?.containerRoot) + } + + func selectedView(_ address: SourceAddress, key: ComponentKey?, live: Bool = false) throws + -> SourceSnapshot + { + if let contained = address.contained { + if live, let root = contained.liveRoot { + let view = try linking.session.liveSnapshot( + SourceDeclaration( + kind: .local, location: root.path, + path: contained.discoveryPath)) + try linking.budget.snapshot(view.snapshot) + return view + } + return contained + } + let source = address.source! + if live { + let view = try linking.session.liveSnapshot(source) + try linking.budget.snapshot(view.snapshot) + return view + } + if let key, let preserved = linking.directPins[key], + let view = try linking.view(address, pin: preserved) + { + return view + } + if let view = try linking.view(address) { return view } + let pin: SourceRevision + do { + guard + let candidate = try linking.candidates( + for: source, + requirements: [ + .init( + source: address.id, root: address.root, + requirement: source.requirement, referenceChain: []) + ] + ).first + else { + throw LinkError.incompatible([ + SourceConstraint( + source: address.id, root: address.root, + requirement: source.requirement, referenceChain: []) + ]) + } + pin = candidate + } + return try linking.view(address, pin: pin)! + } + + private func canonicalSkillName(_ value: String) -> String { + pluginFrame == nil ? PathSafety.sanitizeName(value) : value + } + + private func skills( + _ selection: SkillDeclaration, alias: String, + context: LinkingDocument, group: String?, condition: DeclarationCondition, + chain: [SourceSpan], position: SourceMapEntry?, dependencies: [SourceSnapshotID] + ) throws { + let location = chain + (position.map { [$0.span] + $0.origins } ?? []) + var address = try linking.address(alias, in: context, chain: location) + if alias == ".", !context.producer { + let source = SourceDeclaration(kind: .local, location: context.view.root.path) + address = SourceAddress( + id: context.view.snapshot.source, source: source, contained: nil, + root: context.view.discoveryPath) + } + if let source = address.source, source.kind == .wellKnown { + guard selection.path == nil else { + throw LinkError.invalid("skill paths require a filesystem source", location) + } + try indexSkills( + selection, address: address, source: source, context: context, group: group, + condition: condition, chain: chain, position: position, dependencies: dependencies) + return + } + if let path = selection.path { + let path = try PathSafety.sanitizeSubpath(path) + let root = try PathSafety.sanitizeSubpath(address.root + "/" + path) + let contained = try address.contained.map { + try SourceSnapshot( + snapshot: $0.snapshot, pin: $0.pin, root: $0.root, discoveryPath: root, + localEnvironment: $0.localEnvironment, liveRoot: $0.liveRoot, + packageIdentity: $0.packageIdentity) + } + var source = address.source + source?.path = root + address = SourceAddress(id: address.id, source: source, contained: contained, root: root) + } + let requestedNames: [String]? + switch selection.select { + case .all: requestedNames = nil + case .names(let names): requestedNames = names.map(canonicalSkillName) + } + let excluded = Set((selection.exclude ?? []).map(canonicalSkillName)) + let pluginMember = pluginFrame != nil + let selectsAll = requestedNames == nil + func selectsMembers(_ wanted: Set?) -> SkillMemberSelection { + { name, directory in + if pluginMember { + let candidate = name ?? directory + return wanted?.contains(where: { $0.utf8.elementsEqual(candidate.utf8) }) + ?? !excluded.contains(candidate) + } + let leaf = PathSafety.sanitizeName(directory) + let canonical = name.map(PathSafety.sanitizeName) + if selectsAll, excluded.contains(canonical ?? leaf) { return false } + if let wanted { + return wanted.contains(leaf) || canonical.map(wanted.contains) == true + } + return true + } + } + var overrides: [String: SkillOverride] = [:] + for (name, override) in selection.overrides ?? [:] { + let canonical = canonicalSkillName(name) + guard overrides[canonical] == nil else { + throw LinkError.invalid("duplicate canonical skill override: \(canonical)", location) + } + overrides[canonical] = override + } + func selectedMode(_ name: String) -> InstallMode { + overrides[name]?.mode ?? selection.mode ?? .link + } + struct MemberView: Hashable { + let snapshot: SourceSnapshotID + let live: Bool + } + var discovered: [MemberView: [SnapshotSkill]] = [:] + var alternateNames: Set = [] + let names: [String] + if let requestedNames { + names = requestedNames + } else { + let live = selection.mode == .edit + let primary = try selectedView(address, key: nil, live: live) + let members = try SkillSnapshotReader.read( + primary, live: live, selecting: selectsMembers(nil)) + discovered[MemberView(snapshot: primary.snapshot, live: live)] = members + let primaryNames = Set(members.map { canonicalSkillName($0.name) }) + alternateNames = Set(overrides.keys.filter { (selectedMode($0) == .edit) != live }) + .subtracting(primaryNames) + names = primaryNames.union(alternateNames).sorted() + } + // Each direct member can retain its own pin. Validate only the names assigned to each view. + let requests = try names.filter { !excluded.contains($0) }.map { name in + let requestedKey = key(name, kind: .skills, context: context, group: group) + let mode = selectedMode(name) + let view = try selectedView(address, key: requestedKey, live: mode == .edit) + if mode == .edit, view.liveRoot == nil, !alternateNames.contains(name) { + throw LinkError.invalid("edit requires an actual local skill with no requirement", location) + } + return ( + name: name, mode: mode, view: view, + memberView: MemberView(snapshot: view.snapshot, live: mode == .edit) + ) + } + let namesByView = Dictionary(grouping: requests, by: \.memberView).mapValues { + Set($0.map(\.name)) + } + for (name, mode, view, memberView) in requests { + let members: [SnapshotSkill] + if let cached = discovered[memberView] { + members = cached + } else { + members = try SkillSnapshotReader.read( + view, live: memberView.live, selecting: selectsMembers(namesByView[memberView]!)) + discovered[memberView] = members + } + if alternateNames.contains(name) + && !members.contains(where: { canonicalSkillName($0.name) == name }) + { + continue + } + if mode == .edit, view.liveRoot == nil { + throw LinkError.invalid("edit requires an actual local skill with no requirement", location) + } + let matches = members.filter { + if pluginMember { return $0.name.utf8.elementsEqual(name.utf8) } + return canonicalSkillName($0.name) == name + || PathSafety.sanitizeName(URL(fileURLWithPath: $0.path).lastPathComponent) == name + } + if matches.isEmpty, requestedNames == nil { continue } + guard matches.count == 1, let skill = matches.first else { + throw LinkError.missing("skill '\(name)'", location) + } + let componentKey = key( + canonicalSkillName(skill.name), kind: .skills, context: context, group: group) + let effective = condition.intersecting(skill.condition) + let resource = LinkedResource( + snapshot: view.snapshot, path: skill.path, + hash: skill.hash, executableFlags: skill.executableFlags) + try append( + key: componentKey, snapshot: view.snapshot, pin: view.pin, + payload: .skill(skill, mode: mode, native: selection.native), context: context, + group: group, + condition: effective, + recipients: effective.recipients( + requested: overrides[name]?.agents ?? selection.agents + ?? context.declaration.defaultAgents, + scope: linking.store.scope, platform: linking.platform), chatGPT: false, + resources: [resource], chain: chain, position: position, + dependencies: dependencies + [view.snapshot]) + } + } + + private func indexSkills( + _ selection: SkillDeclaration, address: SourceAddress, source: SourceDeclaration, + context: LinkingDocument, group: String?, condition: DeclarationCondition, + chain: [SourceSpan], position: SourceMapEntry?, dependencies: [SourceSnapshotID] + ) throws { + let requested: [String]? + switch selection.select { + case .all: requested = nil + case .names(let names): requested = names.map(canonicalSkillName) + } + let excluded = Set((selection.exclude ?? []).map(canonicalSkillName)) + var overrides: [String: SkillOverride] = [:] + for (name, override) in selection.overrides ?? [:] { + let canonical = canonicalSkillName(name) + guard overrides[canonical] == nil else { + throw LinkError.invalid("duplicate canonical skill override: \(canonical)", chain) + } + overrides[canonical] = override + } + var retained: [String: LedgerResource] = [:] + for candidate in linking.directPins.keys.sorted(by: { $0.name < $1.name }) { + try linking.budget.step() + guard candidate.kind == .skills, candidate.source == context.view.snapshot.source, + candidate.root == context.view.discoveryPath, candidate.group == group, + !excluded.contains(candidate.name), requested?.contains(candidate.name) ?? true + else { continue } + if requested == nil, try !linking.artifactBelongsToIndex(key: candidate, source: address.id) { + continue + } + guard let resource = try linking.retainedArtifact(key: candidate, source: address.id) else { + continue + } + retained[candidate.name] = resource + } + let freshNames = requested.map { $0.filter { retained[$0] == nil && !excluded.contains($0) } } + let request = IndexRequest( + source: address.id, names: freshNames?.sorted(), + exclude: excluded.union(retained.keys).sorted()) + if indexes[request] == nil { + indexes[request] = + try freshNames == [] + ? [] + : SkillSnapshotReader.index( + source, names: request.names, exclude: request.exclude, + sourcePolicy: linking.session.sourcePolicy, sourceAccess: linking.session.sourceAccess, + requireOrigin: linking.requireArtifactOrigin) + } + let available = indexes[request]! + let names = requested ?? (available.map(\.name) + retained.keys).sorted() + for name in names where !excluded.contains(name) { + let location = chain + (position.map { [$0.span] + $0.origins } ?? []) + let override = overrides[name] + let mode = override?.mode ?? selection.mode ?? .link + guard mode != .edit else { + throw LinkError.invalid("edit requires an actual local skill with no requirement", location) + } + let view: SourceSnapshot + let artifact: LockedArtifact + if let resource = retained[name] { + artifact = resource.artifact! + try linking.session.sourcePolicy.require(artifact) + try linking.admitOrganization( + EffectiveSourcePolicy.artifactOrigins(artifact).flatMap { + linking.organization.source($0, path: [name]) + }) + view = try linking.session.artifactSnapshot( + source: address.id, resource: resource, objects: linking.retainedLedger!.contentObjects) + } else { + guard let current = available.first(where: { $0.name == name }) else { + throw LinkError.missing("skill '\(name)'", location) + } + artifact = current.artifact + view = try linking.session.fileSnapshot( + source: address.id, revision: artifact.digest, + files: current.files, executableFlags: current.executableFlags) + } + try linking.budget.snapshot(view.snapshot) + guard let skill = try SkillSnapshotReader.read(view).first, + canonicalSkillName(skill.name) == name + else { + throw LinkError.missing("skill '\(name)'", location) + } + let effective = condition.intersecting(skill.condition) + try append( + key: key(name, kind: .skills, context: context, group: group), snapshot: view.snapshot, + pin: view.pin, + payload: .skill(skill, mode: mode, native: selection.native), context: context, + group: group, + condition: effective, + recipients: effective.recipients( + requested: override?.agents ?? selection.agents ?? context.declaration.defaultAgents, + scope: linking.store.scope, platform: linking.platform), chatGPT: false, + resources: [ + LinkedResource( + snapshot: view.snapshot, path: skill.path, hash: skill.hash, + executableFlags: skill.executableFlags, artifact: artifact, + artifactLocation: retained[name]?.location) + ], + chain: chain, position: position, dependencies: dependencies + [view.snapshot]) + } + } + + private func instruction( + _ section: SectionDeclaration, prompt: String?, selection: InstructionsDeclaration, + context: LinkingDocument, group: String?, condition: DeclarationCondition, chain: [SourceSpan], + position: SourceMapEntry?, dependencies: [SourceSnapshotID], append appendPath: String? = nil + ) throws { + let location = chain + (position.map { [$0.span] + $0.origins } ?? []) + let own = section.source == nil || section.source == "." + guard context.producer || linking.store.scope != .user || !own else { + throw LinkError.invalid("root user instructions require a named source", location) + } + if own, !context.producer, linking.session.sourcePolicy.isConfigured { + try linking.session.sourcePolicy.require(.local(at: context.view.root)) + } + let address = try linking.address(section.source, in: context, chain: location) + let componentKey = key(section.name, kind: .instructions, context: context, group: group) + .readingInstruction(from: address.id, root: address.root) + let view = try selectedView(address, key: componentKey) + let selected = + try own + ? InstructionSnapshotReader.read(view, own: section.name) + : InstructionSnapshotReader.read(view).first(where: { $0.name == section.name }) + guard let unit = selected + else { + throw LinkError.missing("instruction '\(section.name)'", location) + } + let effective = condition.intersecting(section.condition ?? DeclarationCondition()) + .intersecting(unit.section.condition) + let recipients = + prompt == nil + ? effective.recipients( + requested: section.recipients?.compactMap(\.localAgent) ?? selection.agents + ?? context.declaration.defaultAgents, + scope: linking.store.scope, platform: linking.platform) : [] + let matchesScope = effective.matches(scope: linking.store.scope, platform: linking.platform) + let copyRecipients = + prompt == nil && matchesScope + ? Set((section.recipients ?? []).filter { $0.localAgent == nil }) : [] + var resources = [ + LinkedResource( + snapshot: view.snapshot, path: unit.path, + hash: unit.section.hash, executableFlags: [:]) + ] + if recipients.contains(.antigravity) { + let leaf = try AntigravityRuleV1.leaf(source: view.snapshot.source, path: unit.path) + _ = try AntigravityRuleV1.render( + unit.bytes, path: unit.path, leaf: leaf, scope: linking.store.scope + ) { path in + try linking.budget.step() + let file = try view.resource(path) + 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)") + } + resources.append( + LinkedResource( + snapshot: view.snapshot, path: path, hash: Instructions.hash(bytes), + executableFlags: [:], antigravityInclude: true)) + return bytes + } + } + var localAppend: LedgerLocation? + if let appendPath { + if context.producer { + resources.append( + try resource(ResourceDeclaration(path: appendPath), context: context, chain: location)) + } else { + localAppend = LedgerLocation( + kind: .registered, root: linking.store.scope == .user ? "home" : "project", + path: try PathSafety.sanitizeSubpath(appendPath)) + try localAppend?.validate() + } + } + try self.append( + key: componentKey, snapshot: view.snapshot, pin: view.pin, + payload: .instruction(unit, prompt: prompt, native: selection.native), context: context, + group: group, condition: effective, recipients: recipients, + chatGPT: prompt != nil && matchesScope, + resources: resources, chain: chain, position: position, + dependencies: dependencies + resources.map(\.snapshot), localAppend: localAppend, + copyRecipients: copyRecipients) + } + + private func constrainResource( + _ resource: ResourceDeclaration, in context: LinkingDocument, + chain: [SourceSpan] + ) throws { + if !context.producer, resource.source == nil || resource.source == ".", + linking.session.sourcePolicy.isConfigured + { + try linking.session.sourcePolicy.require(.local(at: context.view.root)) + } + let address = try linking.address(resource.source, in: context, chain: chain) + guard let source = address.source else { return } + guard source.kind != .wellKnown else { + throw LinkError.invalid("skill indexes cannot supply package resources", chain) + } + _ = try linking.view(address, pin: choices[address.id]) + if !linking.nonGit.contains(address.id) { + constraints[address.id, default: []].append( + SourceConstraint( + source: address.id, + root: address.root, requirement: source.requirement, referenceChain: chain)) + } + } + + func resource( + _ resource: ResourceDeclaration, context: LinkingDocument, chain: [SourceSpan] + ) throws -> LinkedResource { + let address = try linking.address(resource.source, in: context, chain: chain) + guard let view = try linking.view(address, pin: choices[address.id]) else { + throw LinkError.invalid("resource source has no exact selection", chain) + } + return try self.resource(resource.path, in: view, chain: chain) + } + + func resource(_ resourcePath: String, in view: SourceSnapshot, chain: [SourceSpan]) throws + -> LinkedResource + { + let root = try view.directory() + let file = try PathSafety.resolvedChild(base: root, subpath: resourcePath) + let path = try view.relativePath(file) + let target = try view.resource(path) + var directory: ObjCBool = false + guard FileManager.default.fileExists(atPath: target.path, isDirectory: &directory) else { + throw LinkError.missing("resource '\(resourcePath)'", chain) + } + if directory.boolValue { + try view.validateResourceTree(target) + return try LinkedResource( + snapshot: view.snapshot, path: path, + hash: "sha256:" + FileHash.folderHash(target), + executableFlags: FileHash.executableFlags(target)) + } + let info = try FileManager.default.attributesOfItem(atPath: target.path) + return try LinkedResource( + snapshot: view.snapshot, path: path, + hash: "sha256:" + FileHash.sha256Hex(file: target), + executableFlags: [path: ((info[.posixPermissions] as? NSNumber)?.intValue ?? 0) & 0o111 != 0]) + } + + func append( + key: ComponentKey, snapshot: SourceSnapshotID, pin: SourceRevision? = nil, + payload: LinkedPayload, context: LinkingDocument, + group: String?, condition: DeclarationCondition, recipients: Set, chatGPT: Bool, + resources: [LinkedResource], chain: [SourceSpan], position: SourceMapEntry?, + dependencies: [SourceSnapshotID], localAppend: LedgerLocation? = nil, + copyRecipients: Set = [] + ) throws { + try linking.budget.contribution(chain: chain.count + (position?.origins.count ?? 0)) + let occurrence = nextOccurrence + nextOccurrence += 1 + let provenance = SourceProvenance( + sourceIdentity: context.view.snapshot.source, + revision: context.view.pin?.revision, + artifactDigest: context.view.snapshot.revision.hasPrefix("sha256:") + ? context.view.snapshot.revision : nil, + relativePath: pluginFrame?.origin.document ?? context.manifestPath, + format: pluginFrame?.input.format ?? "yaml", + adapterVersion: pluginFrame?.input.adapterVersion ?? "1", + group: group, referenceChain: chain, pointer: pluginFrame?.origin.pointer) + let recipients = pluginFrame.map { recipients.intersection($0.recipients) } ?? recipients + let origin = ContributionOrigin( + occurrence: occurrence, provenance: provenance, + declaration: position?.span, sourceOrigins: position?.origins ?? [], + reference: referenceParent, condition: condition, + recipients: recipients, dependencies: dependencies, consumerEditable: !context.producer, + pluginMember: pluginFrame.map { + LinkedPluginMember(parentOccurrence: $0.parent, selector: $0.selector) + }) + if let frame = pluginFrame { pluginChildren[frame.parent, default: []].append(occurrence) } + components.append( + LinkedComponent( + key: key, declaringSnapshot: context.view.snapshot, snapshot: snapshot, pin: pin, + payload: payload, + conditions: [condition], recipients: recipients, chatGPT: chatGPT, resources: resources, + origins: [origin], localAppend: localAppend, copyRecipients: copyRecipients)) + } + + func result() throws -> LinkedComponents { + var result: [LinkedComponent] = [] + var byKey: [ComponentKey: [Int]] = [:] + for component in components { + try linking.budget.step() + if component.key.kind != .instructions { + var identical: Int? + for index in byKey[component.key] ?? [] { + try linking.budget.step() + let prior = result[index] + let same = + prior.payload.sameContent(as: component.payload) + && prior.resources == component.resources + && prior.snapshot == component.snapshot && prior.pin == component.pin + if same, [.hook, .permissions].contains(component.key.kind) { + identical = index + } + if !same, + !prior.recipients.isDisjoint(with: component.recipients) + || (prior.chatGPT && component.chatGPT) + { + throw LinkError.conflict(component.key, prior.origins + component.origins) + } + } + if let index = identical { + result[index].origins += component.origins + result[index].recipients.formUnion(component.recipients) + for condition in component.conditions + where !result[index].conditions.contains(condition) { + result[index].conditions.append(condition) + } + continue + } + } + byKey[component.key, default: []].append(result.count) + result.append(component) + } + let snapshots = Set( + result.flatMap { component in + [component.snapshot] + component.resources.map(\.snapshot) + + component.origins.flatMap(\.dependencies) + + component.origins.compactMap { $0.pluginExpansion?.snapshot } + } + references.map(\.snapshot)) + return LinkedComponents( + components: result, references: references, + constraints: constraints.keys.sorted().flatMap { constraints[$0]! }, + selections: choices.filter { constraints[$0.key] != nil }, + sourceSnapshots: linking.session.sourceEvidence(for: snapshots), + sourceUses: linking.sourceUses, + declaringSnapshots: linking.session.sourceEvidence(for: Set(result.map(\.declaringSnapshot)))) + } +} diff --git a/Sources/Components/FrozenNativeIdentity.swift b/Sources/Components/FrozenNativeIdentity.swift new file mode 100644 index 0000000..b5d6c14 --- /dev/null +++ b/Sources/Components/FrozenNativeIdentity.swift @@ -0,0 +1,177 @@ +import AgentsCore +import Foundation + +/// Uses C's exact ephemeral pairing, never equal bytes or graph-local occurrence numbers alone. +enum FrozenNativeIdentity { + static func match( + _ linked: LinkedComponent, frozen: LedgerFreeze.Result, + agent: AgentID, scope: InstallScope + ) throws -> (id: String, occurrences: [Int]) { + let ledger = frozen.ledger + try ResolvedLedgerCodec.checkModel(ledger, limits: .standard) + try ledger.validate() + let sourceIDs = frozen.sources + func invalid(_ detail: String) -> CoreError { .invalidState(detail) } + guard linked.recipients.contains(agent) else { + throw invalid("the linked component does not target this recipient") + } + let payload: LedgerValue + var registry: MCPRegistryEvidence? + switch linked.payload { + case .declaration(let declaration): + payload = try LedgerPayload.component(declaration) + registry = declaration.mcpRegistry + case .skill(let skill, let mode, let native): + payload = .init(object: [ + "name": .init(skill.name), "description": .init(skill.description), + "mode": .init(mode.rawValue), "native": LedgerPayload.native(native), + ]) + case .instruction: throw invalid("instructions use their existing domain renderer") + } + let ids = Set(linked.origins.map(\.occurrence)) + let occurrences = ledger.occurrences.filter { ids.contains($0.id) } + let owners = Set(occurrences.map(\.component)) + guard !ids.isEmpty, occurrences.count == ids.count, owners.count == 1, + let id = owners.first, let record = ledger.components[id], + record.kind == linked.key.kind.rawValue, + record.name.utf8.elementsEqual(linked.key.name.utf8), + record.chatGPT == linked.chatGPT, + record.declaringSource == sourceIDs[linked.declaringSnapshot], + record.source == sourceIDs[linked.snapshot], + linked.key.source.utf8.elementsEqual(linked.declaringSnapshot.source.utf8), + record.revision == linked.pin?.revision, + record.version == (registry?.version ?? linked.pin?.version), + record.mcpRegistry == registry, + record.root.utf8.elementsEqual(linked.key.root.utf8), + record.group.map({ Data($0.utf8) }) == linked.key.group.map({ Data($0.utf8) }), + record.containerRoot.map({ Data($0.utf8) }) + == linked.key.containerRoot.map({ Data($0.utf8) }), + try ResolvedLedgerCodec.bytes(record.payload) == ResolvedLedgerCodec.bytes(payload), + record.conditions == linked.conditions.map(LedgerCondition.init), + Set(record.recipients) == linked.recipients, + record.resources.count == linked.resources.count + else { throw invalid("linked component and frozen occurrence graph do not match") } + for (origin, frozen) in zip(linked.origins, occurrences) { + guard origin.occurrence == frozen.id, origin.reference == frozen.reference, + frozen.declaringSource == record.declaringSource, + origin.provenance.sourceIdentity == linked.declaringSnapshot.source, + origin.dependencies.compactMap({ sourceIDs[$0] }) == frozen.dependencies, + origin.dependencies.allSatisfy({ sourceIDs[$0] != nil }), + LedgerCondition(origin.condition) == frozen.condition, + origin.provenance.relativePath.utf8.elementsEqual(frozen.manifestPath.utf8), + Set(origin.recipients) == Set(frozen.recipients), + origin.consumerEditable == frozen.consumerEditable, + origin.provenance.pointer.map({ Data($0.utf8) }) + == frozen.input?.pointer.map({ Data($0.utf8) }), + (origin.provenance.format == "yaml" + ? nil + : LedgerInputProvenance( + format: origin.provenance.format, adapterVersion: origin.provenance.adapterVersion, + pointer: origin.provenance.pointer)) == frozen.input, + origin.pluginMember.map { member in + let selector = LedgerPayload.reference(member.selector).object! + return LedgerPluginMember( + parent: member.parentOccurrence, + kind: selector["kind"]!.text!, name: selector["name"]!.text!) + } == frozen.pluginMember, + origin.pluginExpansion.map { expansion in + LedgerPluginExpansion( + source: sourceIDs[expansion.snapshot] ?? "", root: expansion.root, + containerRoot: expansion.containerRoot, document: expansion.document, + input: expansion.input, children: expansion.children) + } == frozen.pluginExpansion + else { throw invalid("linked origin and frozen occurrence do not match") } + } + for (resource, frozen) in zip(linked.resources, record.resources) { + guard let item = ledger.resources[frozen], item.path.utf8.elementsEqual(resource.path.utf8), + item.source == sourceIDs[resource.snapshot], item.artifact == resource.artifact, + item.hash == resource.hash, try ResolvedLedgerCodec.digest(item) == frozen + else { throw invalid("linked resource and frozen evidence do not match") } + let flags = try executableFlags(item) + guard resource.executableFlags.isEmpty || resource.executableFlags == flags else { + throw invalid("linked executable flags and frozen resource do not match") + } + } + let selected = occurrences.filter { + $0.recipients.contains(agent) && ($0.condition.scopes?.contains(scope) ?? true) + && ($0.condition.agents?.contains(agent) ?? true) + } + guard !selected.isEmpty else { + throw invalid("component has no active frozen occurrence for this recipient/scope") + } + return (id, selected.map(\.id)) + } + + /// FileHash follows the selected root directory link, but does not follow links inside + /// that directory. Supporting entries use source-root coordinates, unlike selected entries. + private static func executableFlags(_ resource: LedgerResource) throws -> [String: Bool] { + guard let root = resource.entries.first(where: { $0.path == "." }) else { + throw CoreError.invalidState("missing selected resource root") + } + if root.kind == .file { return [resource.path: root.executable] } + if root.kind == .directory { + return Dictionary( + uniqueKeysWithValues: resource.entries.filter { $0.kind == .file }.map { + ($0.path, $0.executable) + }) + } + // Core's ledger admission validates containment, ancestors, link cycles and support. + // This traversal only projects the selected referent's executable flags. + var entries = Dictionary(uniqueKeysWithValues: resource.support.map { ($0.path, $0) }) + for original in resource.entries { + var entry = original + entry.path = original.path == "." ? resource.path : resource.path + "/" + original.path + entries[entry.path] = entry + } + let parents = resource.path.split(separator: "/").dropLast() + for count in 1..<(parents.count + 1) { + let ancestor = parents.prefix(count).joined(separator: "/") + if entries[ancestor] == nil { + entries[ancestor] = .init(path: ancestor, kind: .directory, executable: false) + } + } + var path: [String] = [] + var pending = resource.path.split(separator: "/").map(String.init).reversed().map { $0 } + var remainingWork = LedgerLimits.standard.encodedBytes + while let part = pending.popLast() { + guard remainingWork > 0 else { + throw CoreError.invalidState("resource projection work budget") + } + remainingWork -= 1 + if part == "." { continue } + if part == ".." { + guard !path.isEmpty else { throw CoreError.invalidState("invalid resource referent") } + path.removeLast() + continue + } + path.append(part) + let coordinate = path.joined(separator: "/") + guard let entry = entries[coordinate] else { + throw CoreError.invalidState("missing resource referent evidence") + } + if entry.kind == .symlink { + guard let link = entry.link, link.utf8.count <= remainingWork else { + throw CoreError.invalidState("invalid resource referent evidence") + } + remainingWork -= link.utf8.count + path.removeLast() + pending += link.split(separator: "/").reversed().map(String.init) + } + } + let target = path.isEmpty ? "." : path.joined(separator: "/") + if let entry = entries[target], entry.kind == .file { + return [resource.path: entry.executable] + } + guard entries[target]?.kind == .directory else { + throw CoreError.invalidState("selected native resource link is not a directory") + } + let prefix = target == "." ? "" : target + "/" + var flags: [String: Bool] = [:] + for entry in entries.values where entry.kind == .file && entry.path.hasPrefix(prefix) { + let relative = String(entry.path.dropFirst(prefix.count)) + flags[relative] = entry.executable + } + return flags + } + +} diff --git a/Sources/Components/Import/APMInputImport.swift b/Sources/Components/Import/APMInputImport.swift new file mode 100644 index 0000000..ec49773 --- /dev/null +++ b/Sources/Components/Import/APMInputImport.swift @@ -0,0 +1,73 @@ +import AgentsCore +import Foundation + +extension SourceImport { + /// Manifest intent and a caller-selected lock retain distinct provenance. Matching requires + /// unambiguous repository, resource root and requested-ref evidence; no ref is resolved here. + package static func previewAPM( + manifest: SourceImportInput, lock: SourceImportInput?, limits: SourceImportLimits = .init() + ) throws -> SourceImportProposal { + guard manifest.profile == .apmManifest, lock == nil || lock?.profile == .apmLock else { + var result = SourceImportProposal(profile: .apmManifest) + result.diagnostics.append( + .init( + code: .invalidInput, location: .init(document: manifest.document, pointer: ""), + message: "APM composition requires an explicit manifest and optional APM lock profile.")) + return result + } + var result = try preview(manifest, limits: limits) + guard let lock else { return result } + let locked = try preview(lock, limits: limits) + result.diagnostics += locked.diagnostics + result.bindings += locked.bindings + result.deployments += locked.deployments + result.selections += locked.selections + // Keep every independent locked source and preservation plan, including transitives. + result.sources += locked.sources + result.resources += locked.resources + result.components += locked.components + for index in result.sources.indices where index < result.sources.count - locked.sources.count { + let source = result.sources[index] + guard let declaration = source.declaration, declaration.kind == .git, + let identity = try? declaration.transportIdentity() + else { continue } + let matches = locked.sources.filter { + guard let candidate = $0.declaration, candidate.kind == .git, + (try? candidate.transportIdentity()) == identity, + (candidate.path ?? ".") == (declaration.path ?? ".") + else { return false } + return true + } + guard matches.count == 1, let matched = matches.first else { + if !matches.isEmpty { + result.diagnostics.append( + .init( + code: .ambiguousSource, location: source.origin, + message: "Multiple locked entries match this manifest source; no pin is selected.")) + } + continue + } + if let requested = source.requestedRef, + ![matched.resolvedRef, matched.requestedRef, matched.pin.commit].contains(requested) + { + result.diagnostics.append( + .init( + code: .ambiguousSource, location: source.origin, + message: "Locked ref evidence does not match manifest intent; no pin is selected.")) + continue + } + guard let commit = matched.pin.commit else { continue } + var exact = declaration + exact.requirement = .revision(commit) + result.sources[index] = .init( + alias: source.alias, origin: source.origin, declaration: exact, pin: matched.pin, + requestedRef: source.requestedRef, producerPath: source.producerPath, + producerIdentity: source.producerIdentity, resolvedRef: matched.resolvedRef, + developmentOnly: source.developmentOnly) + result.diagnostics.removeAll { + $0.code == .incompletePin && $0.location == source.origin + } + } + return result + } +} diff --git a/Sources/Components/Import/APMPackageContentImport.swift b/Sources/Components/Import/APMPackageContentImport.swift new file mode 100644 index 0000000..2e417d8 --- /dev/null +++ b/Sources/Components/Import/APMPackageContentImport.swift @@ -0,0 +1,90 @@ +import AgentsCore +import Foundation + +/// APM-native authoring content is authoritative when .apm exists. Plugin-native layouts need +/// their verified container adapter; absence of .apm never selects an arbitrary fallback tree. +enum APMPackageContentImport { + static func read( + input: SourceImportInput, origin: ImportLocation, limits: SourceImportLimits, + into diagnostics: inout ImportDiagnostics + ) throws { + let parent = (input.document as NSString).deletingLastPathComponent + let path = parent.isEmpty ? ".apm" : parent + "/.apm" + let view = try ImportInput.snapshot(input.root) + let directory = try view.resource(path) + guard FileManager.default.fileExists(atPath: directory.path) else { return } + let attributes = try FileManager.default.attributesOfItem(atPath: directory.path) + guard attributes[.type] as? FileAttributeType == .typeDirectory else { + diagnostics.add(.unsafePath, origin, "APM source layout is not an admitted directory.") + return + } + var remaining = limits.resourceEntries + func children(_ path: String) throws -> [String] { + let directory = try view.resource(path) + guard FileManager.default.fileExists(atPath: directory.path) else { return [] } + guard + let iterator = FileManager.default.enumerator( + at: directory, includingPropertiesForKeys: nil, options: [.skipsSubdirectoryDescendants]) + else { throw ImportReadFailure.invalid } + var result: [String] = [] + for case let child as URL in iterator { + try Task.checkCancellation() + guard remaining > 0 else { throw ImportReadFailure.invalid } + remaining -= 1 + result.append(child.lastPathComponent) + } + return result.sorted() + } + for (index, name) in try children(path).enumerated() where name != "skills" { + diagnostics.add( + .unconverted, origin.appending("layout/member[\(index)]"), + "APM primitive requires its component semantics adapter; no native container fallback is selected." + ) + } + for (index, name) in try children(path + "/skills").enumerated() { + let location = origin.appending("skills/member[\(index)]") + guard ImportInput.name(name) else { + diagnostics.add(.unsafePath, location, "Invalid APM skill resource name.") + continue + } + let skillPath = path + "/skills/" + name + do { + let gitBoundary = try view.resource(skillPath + "/.git") + if FileManager.default.fileExists(atPath: gitBoundary.path) { + diagnostics.add( + .unconverted, location, "Nested Git checkout is outside APM authoring discovery.") + continue + } + let content = try ImportSkillContent.read(skillPath, input: input, limits: limits) + diagnostics.proposal.diagnostics += content.diagnostics + diagnostics.proposal.bindings += content.bindings + let alias = "apm-local-skill-\(index)" + diagnostics.proposal.sources.append( + .init( + alias: alias, origin: location, + declaration: .init( + kind: .local, location: content.path, + environment: .init(projectDirectory: input.root, homeDirectory: input.root)), + pin: .init(), requestedRef: nil, producerPath: nil)) + diagnostics.proposal.resources.append( + .init( + origin: location, sourceAlias: alias, producerName: name, path: ".", + producerIntegrity: nil, observedHash: content.hash, executableFlags: content.flags, + requiresStandaloneSource: true, kind: .skills)) + diagnostics.proposal.components.append( + .init( + origin: location, + declaration: .skills( + source: alias, + .init(select: .names([content.skill.name]), condition: content.skill.condition)))) + } catch is CancellationError { throw CancellationError() } catch CoreError.unsafePath { + diagnostics.add( + .unsafePath, location, "APM skill resource escapes its explicit source boundary.") + } catch { + diagnostics.add( + .unconverted, location, + "APM skill resource is missing, malformed or exceeds content bounds.") + } + } + } +} diff --git a/Sources/Components/Import/ImportFrontmatter.swift b/Sources/Components/Import/ImportFrontmatter.swift new file mode 100644 index 0000000..bb8a670 --- /dev/null +++ b/Sources/Components/Import/ImportFrontmatter.swift @@ -0,0 +1,59 @@ +import AgentsCore +import AgentsManifest +import Foundation + +/// Markdown delimiters select YAML bytes; YAML syntax and scalar admission remain in AgentsManifest. +/// Padding the opening delimiter preserves original UTF-8 offsets and line numbers. +enum ImportFrontmatter { + static func inspect( + _ bytes: Data, document: String, converted: Set, profile: SourceImportProfile, + limits: SourceImportLimits + ) throws -> (diagnostics: [SourceImportDiagnostic], bindings: [ImportBindingRequirement]) { + let parsed = try read(bytes, document: document, limits: limits) + var diagnostics = ImportDiagnostics(proposal: .init(profile: profile)) + parsed.header?.unknown(converted, into: &diagnostics) + diagnostics.finalizeBindings() + return (diagnostics.proposal.diagnostics, diagnostics.proposal.bindings) + } + + static func read(_ bytes: Data, document: String, limits: SourceImportLimits) throws + -> (header: ImportYAML?, body: Data) + { + let source = Array(bytes) + let bom = source.starts(with: [0xEF, 0xBB, 0xBF]) ? 3 : 0 + guard source.count >= bom + 4, Array(source[bom..<(bom + 3)]) == [45, 45, 45], + [10, 13].contains(source[bom + 3]) + else { return (nil, bytes) } + var index = bom + 3 + if source[index] == 13 { index += 1 } + if index < source.count, source[index] == 10 { index += 1 } + while index < source.count { + try Task.checkCancellation() + guard index <= min(limits.documentBytes, ManifestLimits.Input.bytes) else { + throw ImportReadFailure.invalid + } + let start = index + while index < source.count, ![10, 13].contains(source[index]) { + guard index <= min(limits.documentBytes, ManifestLimits.Input.bytes) else { + throw ImportReadFailure.invalid + } + index += 1 + } + if Array(source[start.. [String: + Any] + { + let bytes = try bytes(input, limits: limits) + try LedgerAdmission.check( + Data([91]) + bytes + Data([93]), + limits: .init( + encodedBytes: limits.documentBytes + 2, depth: limits.depth + 1, nodes: limits.nodes + 1, + objectBytes: limits.documentBytes, entries: limits.nodes, keyBytes: limits.documentBytes)) + guard let object = try JSONSerialization.jsonObject(with: bytes) as? [String: Any] else { + throw ImportReadFailure.invalid + } + return object + } + + static func bytes(_ input: SourceImportInput, limits: SourceImportLimits) throws -> Data { + guard limits.documentBytes >= 0, limits.documentBytes <= Int.max - 2, + limits.depth > 0, limits.depth < Int.max, limits.nodes > 0, limits.nodes < Int.max + else { throw ImportReadFailure.invalid } + let view = try snapshot(input.root) + let file = try view.resource(input.document) + let info = try FileManager.default.attributesOfItem(atPath: file.path) + guard info[.type] as? FileAttributeType == .typeRegular, + let size = (info[.size] as? NSNumber)?.intValue, + size <= limits.documentBytes + else { throw ImportReadFailure.invalid } + let handle = try FileHandle(forReadingFrom: file) + defer { try? handle.close() } + let bytes = try handle.read(upToCount: limits.documentBytes + 1) ?? Data() + guard bytes.count <= limits.documentBytes, + (try handle.read(upToCount: 1) ?? Data()).isEmpty + else { throw ImportReadFailure.invalid } + return bytes + } + + static func snapshot(_ root: URL) throws -> SourceSnapshot { + guard root.isFileURL else { throw ImportReadFailure.invalid } + return try SourceSnapshot( + snapshot: .init(source: "explicit-import", revision: "local"), pin: nil, root: root) + } + + static func string(_ value: Any?) -> String? { value as? String } + + static func version(_ value: Any?, equals expected: Int) -> Bool { + guard let value = value as? NSNumber, CFGetTypeID(value) != CFBooleanGetTypeID() else { + return false + } + return value.stringValue == String(expected) + } + + static func strings(_ value: Any?) -> [String]? { + guard let list = value as? [Any], list.allSatisfy({ $0 is String }) else { return nil } + return list.map { $0 as! String } + } + + static func name(_ value: String) -> Bool { + !value.isEmpty && value != "." && value != ".." && value.utf8.count <= 255 + && !value.contains("/") && !value.contains("\\") + && !value.unicodeScalars.contains { CharacterSet.controlCharacters.contains($0) } + } + + static func packageVersion(_ value: String?) -> Bool { + guard let value else { return false } + guard + value.range( + of: + #"^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$"#, + options: .regularExpression) != nil + else { return false } + let build = value.split(separator: "+", maxSplits: 1, omittingEmptySubsequences: false) + if build.count == 2, + build[1].split(separator: ".", omittingEmptySubsequences: false).contains("") + { + return false + } + let prerelease = build[0].split(separator: "-", maxSplits: 1) + if prerelease.count == 2 { + for item in prerelease[1].split(separator: ".", omittingEmptySubsequences: false) { + if item.isEmpty + || (item.utf8.allSatisfy { (48...57).contains($0) } && item.count > 1 + && item.first == "0") + { + return false + } + } + } + return true + } + + static func path(_ value: String) throws -> String { + guard !value.hasPrefix("~"), !value.contains("\\"), + !value.unicodeScalars.contains(where: { CharacterSet.controlCharacters.contains($0) }) + else { throw ImportReadFailure.invalid } + return try PathSafety.sanitizeSubpath(value) + } + + static func hex(_ value: String?, count: Int) -> String? { + guard let value, value.utf8.count == count, + value.utf8.allSatisfy({ (48...57).contains($0) || (97...102).contains($0) }) + else { return nil } + return value + } + + static func credentialField(_ name: String) -> Bool { + let normalized = name.lowercased().filter { $0.isLetter || $0.isNumber } + return [ + "env", "headers", "token", "password", "credentials", "auth", "apikey", "accesstoken", + "secret", "authorization", "clientsecret", + ].contains(normalized) + } + + /// Source URL credentials and query tokens become local binding requirements, never provenance. + static func safeLocator(_ value: String) -> Bool { + guard !value.isEmpty, + !value.unicodeScalars.contains(where: { CharacterSet.controlCharacters.contains($0) }), + !value.contains("?"), !value.contains("#") + else { return false } + if value.contains("://") { + guard let url = URLComponents(string: value), + url.user == nil || (url.scheme == "ssh" && url.user == "git"), url.password == nil + else { + return false + } + } else if value.contains("@") { + // SCP-style git@host:path is a transport username; arbitrary userinfo is not. + return value.hasPrefix("git@") && value.contains(":") + } + return true + } +} + +enum ImportReadFailure: Error { case invalid } + +struct ImportDiagnostics { + var proposal: SourceImportProposal + var bindingReferences: [String: RuntimeBinding] = [:] + var resolvedBindings: Set = [] + + struct CanonicalAttempt { + let components: Int + let slots: Set + let resolved: Set + } + + func beginCanonicalAttempt() -> CanonicalAttempt { + .init( + components: proposal.components.count, + slots: Set(proposal.bindings.filter(\.canonicalSlot).map(\.location)), + resolved: resolvedBindings) + } + + mutating func endCanonicalAttempt(_ attempt: CanonicalAttempt) { + guard proposal.components.count <= attempt.components else { return } + for index in proposal.bindings.indices + where !attempt.slots.contains(proposal.bindings[index].location) { + proposal.bindings[index].canonicalSlot = false + } + resolvedBindings = attempt.resolved + } + + struct ChoiceCapture { + let index: Int + let components: Int + let sources: Int + let resources: Int + let diagnostics: Int + } + + mutating func beginChoice(_ key: String, at location: ImportLocation) -> ChoiceCapture { + let index: Int + if let found = proposal.choices.firstIndex(where: { $0.key.utf8.elementsEqual(key.utf8) }) { + index = found + if !proposal.choices[index].locations.contains(location) { + proposal.choices[index].locations.append(location) + } + } else { + index = proposal.choices.count + proposal.choices.append(.init(key: key, locations: [location])) + } + return .init( + index: index, components: proposal.components.count, sources: proposal.sources.count, + resources: proposal.resources.count, diagnostics: proposal.diagnostics.count) + } + + mutating func endChoice(_ capture: ChoiceCapture) { + proposal.choices[capture.index].components += Array( + capture.components.., at location: ImportLocation) + { + for (index, field) in fields.keys.sorted().enumerated() where !allowed.contains(field) { + let child = location.appending("member[\(index)]") + if ImportInput.credentialField(field) { binding(child) } + unconverted(fields[field]!, at: child) + } + } + + private mutating func unconverted(_ value: Any, at location: ImportLocation) { + add(.unconverted, location, "Unrecognized field or item is not converted.") + if let fields = value as? [String: Any] { + for (index, field) in fields.keys.sorted().enumerated() { + let child = location.appending("member[\(index)]") + if ImportInput.credentialField(field) { binding(child) } + unconverted(fields[field]!, at: child) + } + } else if let items = value as? [Any] { + for (index, item) in items.enumerated() { + unconverted(item, at: location.appending(String(index))) + } + } else if let value = value as? String, value.contains("://"), !ImportInput.safeLocator(value) { + binding(location) + } + } + + mutating func typedFields( + _ fields: [String: Any], strings: Set, required: Set = [], + arrays: Set = [], at location: ImportLocation + ) -> Bool { + var valid = true + for field in strings.sorted() where fields[field] != nil || required.contains(field) { + if ImportInput.string(fields[field]) == nil { + add(.invalidInput, location.appending(field), "Expected a string field.") + valid = false + } + } + for field in arrays.sorted() where fields[field] != nil { + if ImportInput.strings(fields[field]) == nil { + add(.invalidInput, location.appending(field), "Expected an array of strings.") + valid = false + } + } + return valid + } + + mutating func binding(_ location: ImportLocation, environmentVariable: String? = nil) { + if environmentVariable == nil, !proposal.preservationBindings.contains(location) { + proposal.preservationBindings.append(location) + } + guard !proposal.bindings.contains(where: { $0.location == location }) else { return } + proposal.bindings.append( + .init( + location: location, reason: "Credential-bearing input requires an explicit local binding.", + environmentVariable: environmentVariable) + ) + } +} diff --git a/Sources/Components/Import/ImportSkillContent.swift b/Sources/Components/Import/ImportSkillContent.swift new file mode 100644 index 0000000..bd13147 --- /dev/null +++ b/Sources/Components/Import/ImportSkillContent.swift @@ -0,0 +1,141 @@ +import AgentsCore +import AgentsSkills +import Foundation + +struct ImportSkillContent { + let path: String + let hash: String + let flags: [String: Bool] + let skill: SnapshotSkill + let files: [(String, Data)] + let diagnostics: [SourceImportDiagnostic] + let bindings: [ImportBindingRequirement] + + static func read( + _ path: String, input: SourceImportInput, limits: SourceImportLimits, + nativeContainer: String? = nil + ) throws -> Self { + let path = try ImportInput.path(path) + let source = try ImportInput.snapshot(input.root) + let directory = try source.resource(path) + let boundary: URL + if let nativeContainer { + guard [.claudePluginV1, .cursorPluginV1, .geminiExtensionV1].contains(input.profile) else { + throw ImportReadFailure.invalid + } + boundary = try source.resource(ImportInput.path(nativeContainer)) + guard PathSafety.isContained(directory, in: boundary), + PathSafety.isContained( + directory.resolvingSymlinksInPath(), in: boundary.resolvingSymlinksInPath()) + else { throw ImportReadFailure.invalid } + } else { + boundary = directory + } + // Bound the selected physical tree before discovery. Native supporting links are admitted + // by capture against the explicit enclosing container, never as discovered members. + guard limits.resourceEntries > 0, limits.resourceBytes >= 0, limits.depth > 0, + let iterator = FileManager.default.enumerator(at: directory, includingPropertiesForKeys: nil) + else { throw ImportReadFailure.invalid } + var entries = 1 + var total = 0 + for case let entry as URL in iterator { + try Task.checkCancellation() + entries += 1 + guard entries <= limits.resourceEntries else { throw ImportReadFailure.invalid } + let relative = try source.relativePath(entry) + let depth = + relative.split(separator: "/").count - (path == "." ? 0 : path.split(separator: "/").count) + guard depth <= limits.depth else { throw ImportReadFailure.invalid } + let attributes = try FileManager.default.attributesOfItem(atPath: entry.path) + let type = attributes[.type] as? FileAttributeType + if type == .typeSymbolicLink, nativeContainer != nil { + iterator.skipDescendants() + } else if type != .typeDirectory && type != .typeRegular { + throw ImportReadFailure.invalid + } + if type == .typeRegular { + guard let size = (attributes[.size] as? NSNumber)?.intValue, + size >= 0, size <= limits.resourceBytes - total + else { throw ImportReadFailure.invalid } + total += size + } + } + let frozen = try LedgerResources.capture( + directory, embed: true, + limits: .init( + encodedBytes: limits.resourceBytes, depth: limits.depth, nodes: limits.nodes, + objectBytes: limits.resourceBytes, entries: limits.resourceEntries, + keyBytes: limits.resourceBytes, + resourceBytes: limits.resourceBytes), sourceRoot: boundary) + // Producer-specific installed-content hashes retain their regular-file-only admission. + if nativeContainer == nil { + guard frozen.entries.allSatisfy({ $0.kind != .symlink }), frozen.support.isEmpty else { + throw ImportReadFailure.invalid + } + } + guard frozen.support.allSatisfy({ $0.path.split(separator: "/").count <= limits.depth }) else { + throw ImportReadFailure.invalid + } + let files = try frozen.entries.filter { $0.kind == .file }.map { entry -> (String, Data) in + guard let object = entry.object, let bytes = frozen.objects[object] else { + throw ImportReadFailure.invalid + } + return (entry.path, bytes) + } + guard files.contains(where: { $0.0 == "SKILL.md" }) else { throw ImportReadFailure.invalid } + var semanticDiagnostics: [SourceImportDiagnostic] = [] + var bindings: [ImportBindingRequirement] = [] + // Validate captured skill YAML before existing discovery, then compare its observed tree + // with the capture. The consuming preparation owns the stable source view and freshness. + for (name, bytes) in files where name == "SKILL.md" || name.hasSuffix("/SKILL.md") { + let semantics = try ImportFrontmatter.inspect( + bytes, document: path + "/" + name, + converted: ["name", "description", "agents", "platforms", "scopes"], profile: input.profile, + limits: limits) + semanticDiagnostics += semantics.diagnostics + bindings += semantics.bindings + } + let selected = try SourceSnapshot( + snapshot: source.snapshot, pin: nil, root: input.root, discoveryPath: path) + let skills = try SkillSnapshotReader.read(selected) + guard let skill = skills.first(where: { $0.path == path }) else { + throw ImportReadFailure.invalid + } + guard skill.hash == frozen.hash else { throw ImportReadFailure.invalid } + return .init( + path: path, hash: frozen.hash, flags: frozen.flags, skill: skill, files: files, + diagnostics: semanticDiagnostics, bindings: bindings) + } + + /// Vercel skills 1.8.1 src/skill-hash.ts: byte-sorted paths, NUL-framed lengths, + /// CRLF normalization for nonbinary files, and the installer's excluded names. + static func vercelHash(_ content: Self) -> String { + var framed = Data() + let files = content.files.map { ($0.0.replacingOccurrences(of: "\\", with: "/"), $0.1) } + for (path, bytes) in files.sorted(by: { $0.0.utf8.lexicographicallyPrecedes($1.0.utf8) } + ) { + let parts = path.split(separator: "/") + if parts.contains("metadata.json") + || parts.dropLast().contains(where: { + [".git", "__pycache__", "__pypackages__"].contains($0) + }) + { + continue + } + var normalized = Data() + if bytes.contains(0) { + normalized = bytes + } else { + var index = 0 + while index < bytes.count { + if bytes[index] == 13, index + 1 < bytes.count, bytes[index + 1] == 10 { index += 1 } + normalized.append(bytes[index]) + index += 1 + } + } + framed.append(Data((path + "\0" + String(normalized.count) + "\0").utf8)) + framed.append(normalized) + } + return FileHash.sha256Hex(data: framed) + } +} diff --git a/Sources/Components/Import/NativeCatalogImport.swift b/Sources/Components/Import/NativeCatalogImport.swift new file mode 100644 index 0000000..4a06969 --- /dev/null +++ b/Sources/Components/Import/NativeCatalogImport.swift @@ -0,0 +1,167 @@ +import AgentsCore +import Foundation + +/// Catalog entries are coordinates only. Resolution, selection and fetching stay with B. +enum NativeCatalogImport { + static func read( + _ input: SourceImportInput, limits: SourceImportLimits, + into diagnostics: inout ImportDiagnostics + ) throws { + let parsed = try NativeImportDocument(input, format: .json, limits: limits) + NativeImportInput.unknown( + parsed.fields, allowed: ["name", "plugins"], at: parsed.location(), + into: &diagnostics) + guard let catalogName = parsed.fields["name"]?.importString, + NativeImportInput.name(catalogName), + parsed.fields["owner"]?.importObject?["name"]?.importString?.isEmpty == false, + case .array(let entries) = parsed.fields["plugins"] + else { + throw ImportReadFailure.invalid + } + let enumerated = Set(entries.compactMap { $0.importObject?["name"]?.importString }) + guard let selection = input.enumerateChoices ? enumerated : input.selection else { + diagnostics.add( + .unconverted, parsed.location(["plugins"]), + "Catalog coordinates require an explicit entry selection; no catalog is installed or resolved." + ) + return + } + let suffix = ".claude-plugin/marketplace.json" + guard input.document == suffix || input.document.hasSuffix("/" + suffix) else { + throw ImportReadFailure.invalid + } + let root = input.document == suffix ? "." : String(input.document.dropLast(suffix.count + 1)) + var counts: [String: Int] = [:] + for value in entries { + if let name = value.importObject?["name"]?.importString { counts[name, default: 0] += 1 } + } + var selected: Set = [] + for (index, value) in entries.enumerated() { + let origin = parsed.location(["plugins"]).appending(String(index)) + guard let fields = value.importObject, let name = fields["name"]?.importString, + NativeImportInput.name(name) + else { + NativeImportInput.unconverted(value, at: origin, into: &diagnostics) + continue + } + let choice = diagnostics.beginChoice(name, at: origin) + defer { diagnostics.endChoice(choice) } + guard selection.contains(name) else { continue } + if counts[name, default: 0] > 1 { + diagnostics.add( + .ambiguousSource, origin, + "Catalog selection has multiple declarations; no source is chosen.") + continue + } + guard selected.insert(name).inserted else { + diagnostics.add( + .ambiguousSource, origin, "Selected catalog name has multiple declarations.") + continue + } + NativeImportInput.unknown( + fields, + allowed: [ + "name", "source", "version", "description", "author", "homepage", "keywords", "category", + "tags", "strict", + ], at: origin, into: &diagnostics) + if let strict = fields["strict"], strict != .boolean(true) { + NativeImportInput.unconverted(strict, at: origin.appending("strict"), into: &diagnostics) + continue + } + for key in ["version", "description", "author", "homepage", "keywords", "category", "tags"] + where fields[key] != nil { + NativeImportInput.unconverted(fields[key]!, at: origin.appending(key), into: &diagnostics) + } + let declaration: SourceDeclaration + var exact: String? + var requested: String? + var path: String? + if let local = fields["source"]?.importString { + let relative = try NativeSourceImport.nativePath(local, container: root) + let location = root == "." ? relative : root + "/" + relative + declaration = .init( + kind: .local, location: location, + environment: .init(projectDirectory: input.root, homeDirectory: input.root)) + diagnostics.add( + .incompletePin, origin, + "Local catalog entry needs explicit content capture; a version label is not an exact content pin." + ) + } else if let source = fields["source"]?.importObject { + NativeImportInput.unknown( + source, allowed: ["source", "repo", "url", "ref", "sha", "path"], + at: origin.appending("source"), into: &diagnostics) + let location: String + if source["source"] == .string("github"), let repo = source["repo"]?.importString, + repo.split(separator: "/", omittingEmptySubsequences: false).count == 2, + repo.split(separator: "/", omittingEmptySubsequences: false).allSatisfy({ + $0.range(of: #"^[A-Za-z0-9._-]+$"#, options: .regularExpression) != nil + }) + { + location = "https://github.com/" + repo + } else if [NativeValue.string("url"), .string("git-subdir")].contains( + source["source"] ?? .null), + let url = source["url"]?.importString + { + guard ImportInput.safeLocator(url) else { + diagnostics.binding(origin.appending("source")) + continue + } + location = url + } else { + NativeImportInput.unconverted( + fields["source"]!, at: origin.appending("source"), into: &diagnostics) + continue + } + exact = ImportInput.hex(source["sha"]?.importString, count: 40) + requested = source["ref"]?.importString + if source["source"] == .string("git-subdir") { + guard let raw = source["path"]?.importString else { + diagnostics.add( + .invalidInput, origin.appending("source/path"), + "Git subdirectory source requires an explicit path.") + continue + } + path = try NativeSourceImport.nativePath(raw, container: root) + } else if source["path"] != nil { + NativeImportInput.unconverted( + source["path"]!, at: origin.appending("source/path"), into: &diagnostics) + continue + } + declaration = .init( + kind: .git, location: location, requirement: exact.map(SourceRequirement.revision), + path: path) + guard (try? declaration.transportIdentity()) != nil else { + diagnostics.add( + .invalidInput, origin, "Catalog Git coordinate is not a valid canonical source.") + continue + } + if exact == nil { + diagnostics.add( + .incompletePin, origin, + "Catalog ref/version is requested provenance; no resolved commit is invented or fetched." + ) + } + } else { + NativeImportInput.unconverted( + fields["source"] ?? .null, at: origin.appending("source"), into: &diagnostics) + continue + } + let alias = "catalog-\(index)" + diagnostics.proposal.sources.append( + .init( + alias: alias, origin: origin, declaration: declaration, + pin: .init(commit: exact), requestedRef: requested, producerPath: path, + producerIdentity: name)) + NativeImportInput.emit( + .plugin( + name: name, path: ".", source: alias, mode: .components, agents: [.claudeCode]), + selector: .plugin(name: name), origin: origin, container: root, profile: input.profile, + into: &diagnostics) + } + if !selection.isSubset(of: selected) { + diagnostics.add( + .invalidInput, parsed.location(["plugins"]), + "A selected catalog entry is absent or invalid.") + } + } +} diff --git a/Sources/Components/Import/NativeContainerImport.swift b/Sources/Components/Import/NativeContainerImport.swift new file mode 100644 index 0000000..6618d60 --- /dev/null +++ b/Sources/Components/Import/NativeContainerImport.swift @@ -0,0 +1,505 @@ +import AgentsCore +import Foundation + +/// Container discovery uses producer roots, never the parser's working directory. +enum NativeContainerImport { + static func read( + _ input: SourceImportInput, limits: SourceImportLimits, + into diagnostics: inout ImportDiagnostics + ) throws { + let suffix: String + switch input.profile { + case .claudePluginV1: suffix = ".claude-plugin/plugin.json" + case .cursorPluginV1: suffix = ".cursor-plugin/plugin.json" + default: suffix = "gemini-extension.json" + } + guard input.document == suffix || input.document.hasSuffix("/" + suffix) else { + diagnostics.add( + .invalidInput, .init(document: input.document, pointer: ""), + "Manifest location does not match the selected native container profile.") + return + } + let root = input.document == suffix ? "." : String(input.document.dropLast(suffix.count + 1)) + let parsed = try NativeImportDocument(input, format: .json, limits: limits) + guard let name = parsed.fields["name"]?.importString, NativeImportInput.name(name) else { + throw ImportReadFailure.invalid + } + let snapshot = try ImportInput.snapshot(input.root) + try parsed.admission.resource(try snapshot.resource(root), snapshot: snapshot) + let agent = NativeImportInput.agent(input.profile) + let alias = NativeImportInput.source( + input, root: root, origin: parsed.location(), into: &diagnostics) + let surface = NativeImportSemantics.surface(input.profile) + let defaults: [String: String] + do { + defaults = + agent == .geminiCLI + ? [ + "commands": "commands", "agents": "agents", "skills": "skills", + "hooks": "hooks/hooks.json", + ] + : try NativeComponentFieldsV1.pluginDefaults( + surface: surface, document: suffix, fieldPrefix: [], + explicitFields: Set(parsed.fields.keys)) + } catch let issue as NativeComponentFieldIssue { + guard issue.document == suffix else { throw ImportReadFailure.invalid } + NativeImportSemantics.report(issue, at: parsed.fieldLocation(issue.field), into: &diagnostics) + return + } + var documents: [String: NativeImportDocument] = [:] + let metadata: Set = ["name", "version"] + let members: Set = + agent == .geminiCLI + ? ["mcpServers", "contextFileName"] + : ["commands", "agents", "skills", "hooks", "mcpServers", "lspServers", "rules"] + NativeImportInput.unknown( + parsed.fields, allowed: metadata.union(members), at: parsed.location(), into: &diagnostics) + if agent == .geminiCLI { + guard let version = parsed.fields["version"]?.importString, !version.isEmpty else { + diagnostics.add( + .invalidInput, parsed.location(["version"]), "Native extension requires a version string." + ) + return + } + if !version.contains("://") || ImportInput.safeLocator(version) { + diagnostics.proposal.packageMetadata = .init( + name: name, version: version, + nameLocation: parsed.fieldLocation(["name"]), + versionLocation: parsed.fieldLocation(["version"])) + } + } + if agent != .geminiCLI { + diagnostics.proposal.packageMetadata = .init( + name: name, nameLocation: parsed.fieldLocation(["name"])) + } + // A container contributes typed children; .native selection/registration belongs to B/F. + // Unknown/dependency fields are already diagnosed rather than becoming opaque payloads. + for (field, kind) in [ + ("commands", DeclaredComponentKind.command), + ("agents", .subagent), ("skills", .skills), + ] { + let supplied = parsed.fields[field] + if agent == .geminiCLI, supplied != nil { + NativeImportInput.unconverted(supplied!, at: parsed.location([field]), into: &diagnostics) + continue + } + var paths: [String] = [] + var explicitPaths: Set = [] + if let path = defaults[field] { paths.append(path) } + if let supplied { + if let path = supplied.importString { + let relative = try componentPath(path, agent: agent) + explicitPaths.insert(relative) + paths.append(relative) + } else if let list = supplied.importStrings { + let relative = try list.map { try componentPath($0, agent: agent) } + explicitPaths.formUnion(relative) + paths += relative + } else { + NativeImportInput.unconverted(supplied, at: parsed.location([field]), into: &diagnostics) + } + } + var seen: Set = [] + for path in paths where seen.insert(path).inserted { + try discover( + path, kind: kind, root: root, input: input, limits: limits, into: &diagnostics, + admission: parsed.admission, + requiredOrigin: explicitPaths.contains(path) ? parsed.location([field]) : nil) + } + } + var mcpSources: [(NativeValue, NativeImportDocument, [String])] = [] + if let mcpDefault = defaults["mcpServers"], + let document = try optionalDocument( + mcpDefault, root: root, input: input, limits: limits, admission: parsed.admission) + { + documents[mcpDefault] = document + NativeImportInput.unknown( + document.fields, allowed: ["mcpServers"], at: document.location(), into: &diagnostics) + if let map = document.fields["mcpServers"] { + mcpSources.append((map, document, ["mcpServers"])) + } else { + NativeImportInput.unconverted( + .object(document.fields), at: document.location(), into: &diagnostics) + } + } + if let declared = parsed.fields["mcpServers"] { + try configurations( + declared, field: "mcpServers", parsed: parsed, root: root, limits: limits, + into: &mcpSources, documents: &documents, diagnostics: &diagnostics) + } + // The producer loads defaults then declarations; later duplicate names replace earlier ones. + var winners: [String: (NativeValue, NativeImportDocument, [String])] = [:] + for (value, document, keys) in mcpSources { + try NativeSourceImport.classifyMembers( + value, parsed: document, keys: keys, into: &diagnostics) + guard let fields = value.importObject else { throw ImportReadFailure.invalid } + for (name, entry) in fields { + if let previous = winners[name] { + diagnostics.add( + .unconverted, previous.1.location(previous.2 + [name]), + "Later native MCP declaration replaces this earlier source member.") + } + winners[name] = (entry, document, keys) + } + } + for name in winners.keys.sorted() { + let winner = winners[name]! + try NativeSourceImport.mcp( + .object([name: winner.0]), parsed: winner.1, keys: winner.2, + container: root, limits: limits, into: &diagnostics) + } + var observed: Set = [] + for (_, document, _) in mcpSources + where document.input.document != input.document + && observed.insert(document.input.document).inserted + { + let relative = + root == "." + ? document.input.document : String(document.input.document.dropFirst(root.count + 1)) + let rewrite = diagnostics.proposal.preservationBindings.contains { + $0.document == document.input.document + } + try NativeImportInput.resource( + relative, root: root, input: input, origin: document.location(), limits: limits, + rewrite: rewrite, into: &diagnostics, admission: parsed.admission) + } + var lspSources: [(NativeValue, NativeImportDocument, [String])] = [] + if let lspDefault = defaults["lspServers"], + let document = try optionalDocument( + lspDefault, root: root, input: input, limits: limits, admission: parsed.admission) + { + documents[lspDefault] = document + lspSources.append((.object(document.fields), document, [])) + } + if let value = parsed.fields["lspServers"] { + try configurations( + value, field: "lspServers", parsed: parsed, root: root, limits: limits, into: &lspSources, + documents: &documents, diagnostics: &diagnostics) + } + var lspWinners: [String: (NativeValue, NativeImportDocument, [String])] = [:] + for (value, document, keys) in lspSources { + try NativeSourceImport.classifyMembers( + value, parsed: document, keys: keys, into: &diagnostics) + for (name, entry) in value.importObject ?? [:] { lspWinners[name] = (entry, document, keys) } + } + for name in lspWinners.keys.sorted() { + let entry = lspWinners[name]! + try NativeSourceImport.lsp( + .object([name: entry.0]), parsed: entry.1, keys: entry.2, container: root, limits: limits, + into: &diagnostics) + } + var hookSources: [(NativeValue, NativeImportDocument, [String])] = [] + if let hookDefault = defaults["hooks"], + let document = try optionalDocument( + hookDefault, root: root, input: input, limits: limits, admission: parsed.admission) + { + documents[hookDefault] = document + NativeImportInput.unknown( + document.fields, allowed: ["hooks"], at: document.location(), into: &diagnostics) + if let value = document.fields["hooks"] { hookSources.append((value, document, ["hooks"])) } + } + if let value = parsed.fields["hooks"] { + try configurations( + value, field: "hooks", parsed: parsed, root: root, limits: limits, into: &hookSources, + documents: &documents, diagnostics: &diagnostics) + } + for (value, document, keys) in hookSources { + try NativeSourceImport.hooks( + value, parsed: document, keys: keys, container: root, limits: limits, into: &diagnostics) + } + for (_, document, _) in lspSources + hookSources + where document.input.document != input.document + && observed.insert(document.input.document).inserted + { + let path = + root == "." + ? document.input.document : String(document.input.document.dropFirst(root.count + 1)) + let rewrite = diagnostics.proposal.preservationBindings.contains { + $0.document == document.input.document + } + try NativeImportInput.resource( + path, root: root, input: input, origin: document.location(), limits: limits, + rewrite: rewrite, into: &diagnostics, admission: parsed.admission) + } + for field in ["rules", "contextFileName"] where parsed.fields[field] != nil { + NativeImportInput.unconverted( + parsed.fields[field]!, at: parsed.location([field]), into: &diagnostics) + } + if agent != .geminiCLI { + for (_, document, _) in mcpSources + lspSources + hookSources { + guard document.input.document != input.document else { continue } + let path = + root == "." + ? document.input.document : String(document.input.document.dropFirst(root.count + 1)) + documents[path] = document + } + do { + _ = try NativeComponentFieldsV1.plugin( + surface: surface, document: suffix, fieldPrefix: [], fields: parsed.fields, + entries: try inventory(snapshot, root: root, limits: limits), + documents: documents.mapValues { .object($0.fields) }, budget: parsed.admission.parser) + } catch let issue as NativeComponentFieldIssue { + if issue.document == suffix, issue.field == ["name"] { + diagnostics.proposal.packageMetadata = nil + } + let document: NativeImportDocument + if issue.document == suffix { + document = parsed + } else { + guard let captured = documents[issue.document] else { throw ImportReadFailure.invalid } + document = captured + } + NativeImportSemantics.report( + issue, at: document.fieldLocation(issue.field), into: &diagnostics) + } + } + for field in metadata { + if let value = parsed.fields[field] { + _ = NativeImportInput.sensitive(value, at: parsed.location([field]), into: &diagnostics) + } + } + if let options = parsed.fields["userConfig"]?.importObject { + for (name, value) in options { + guard let option = value.importObject, option["sensitive"] == .boolean(true), + let literal = option["default"], literal != .string("") + else { continue } + diagnostics.binding(parsed.fieldLocation(["userConfig", name, "default"])) + } + } + // Record the actual manifest, not a raw original bundle containing credential literals. + let rewrite = diagnostics.proposal.preservationBindings.contains { + $0.document == input.document + } + try NativeImportInput.resource( + suffix, root: root, input: input, origin: parsed.location(), limits: limits, rewrite: rewrite, + into: &diagnostics, admission: parsed.admission) + if diagnostics.proposal.components.isEmpty { + diagnostics.add( + .unconverted, parsed.location(), + "No typed child was converted; native container registration is required to preserve this container." + ) + } + _ = alias + } + + private static func inventory( + _ snapshot: SourceSnapshot, root: String, limits: SourceImportLimits + ) throws -> [LedgerEntry] { + let url = try snapshot.resource(root) + var entries: [LedgerEntry] = [] + func append(_ file: URL) throws { + guard entries.count < limits.resourceEntries else { throw ImportReadFailure.invalid } + let path = try snapshot.relativePath(file) + let relative = + path == root ? "." : root == "." ? path : String(path.dropFirst(root.count + 1)) + let info = try FileManager.default.attributesOfItem(atPath: file.path) + let kind: LedgerEntry.Kind + switch info[.type] as? FileAttributeType { + case .typeRegular: kind = .file + case .typeDirectory: kind = .directory + case .typeSymbolicLink: kind = .symlink + default: throw ImportReadFailure.invalid + } + entries.append( + .init( + path: relative, kind: kind, + link: kind == .symlink + ? try FileManager.default.destinationOfSymbolicLink(atPath: file.path) : nil, + executable: kind == .file + && ((info[.posixPermissions] as? NSNumber)?.intValue ?? 0) & 0o111 != 0, + byteCount: kind == .file ? (info[.size] as? NSNumber)?.intValue : nil)) + } + try append(url) + guard let walk = FileManager.default.enumerator(at: url, includingPropertiesForKeys: nil) else { + throw ImportReadFailure.invalid + } + for case let file as URL in walk { + try Task.checkCancellation() + try append(file) + if entries.last?.kind == .symlink { walk.skipDescendants() } + } + return entries + } + + private static func componentPath(_ path: String, agent: AgentID) throws -> String { + if agent == .claudeCode, !path.hasPrefix("./"), path != "." { + throw CoreError.unsafePath("native component path") + } + return try NativeSourceImport.nativePath(path, container: ".") + } + + private static func configurations( + _ value: NativeValue, field: String, parsed: NativeImportDocument, + root: String, limits: SourceImportLimits, + into sources: inout [(NativeValue, NativeImportDocument, [String])], + documents: inout [String: NativeImportDocument], + diagnostics: inout ImportDiagnostics + ) throws { + if let path = value.importString { + let relative = try componentPath(path, agent: NativeImportInput.agent(parsed.input.profile)) + guard + let document = try optionalDocument( + relative, root: root, input: parsed.input, limits: limits, admission: parsed.admission) + else { + diagnostics.add( + .missingResource, parsed.location([field]), "Explicit native component file is absent.") + return + } + documents[relative] = document + guard + let fields = field == "lspServers" + ? NativeValue.object(document.fields) : document.fields[field] + else { + NativeImportInput.unconverted( + .object(document.fields), at: document.location(), into: &diagnostics) + return + } + if field != "lspServers" { + NativeImportInput.unknown( + document.fields, allowed: [field], + at: document.location(), into: &diagnostics) + } + sources.append((fields, document, field == "lspServers" ? [] : [field])) + } else if case .array(let entries) = value { + for entry in entries { + try configurations( + entry, field: field, parsed: parsed, root: root, limits: limits, into: &sources, + documents: &documents, diagnostics: &diagnostics) + } + } else if value.importObject != nil, NativeImportInput.agent(parsed.input.profile) != .cursor { + sources.append((value, parsed, [field])) + } else { + NativeImportInput.unconverted(value, at: parsed.location([field]), into: &diagnostics) + } + } + + private static func optionalDocument( + _ path: String, root: String, input: SourceImportInput, + limits: SourceImportLimits, admission: NativeImportBudget + ) throws -> NativeImportDocument? { + let relative = root == "." ? path : root + "/" + path + let snapshot = try ImportInput.snapshot(input.root) + let url = try snapshot.resource(relative) + guard FileManager.default.fileExists(atPath: url.path) else { return nil } + return try NativeImportDocument( + .init(profile: input.profile, root: input.root, document: relative), format: .json, + limits: limits, admission: admission) + } + + private static func discover( + _ path: String, kind: DeclaredComponentKind, root: String, + input: SourceImportInput, limits: SourceImportLimits, into diagnostics: inout ImportDiagnostics, + admission: NativeImportBudget, requiredOrigin: ImportLocation? + ) throws { + let snapshot = try ImportInput.snapshot(input.root) + let relative = root == "." ? path : root + (path == "." ? "" : "/" + path) + let url = try snapshot.resource(relative) + var directory: ObjCBool = false + guard FileManager.default.fileExists(atPath: url.path, isDirectory: &directory) else { + if let requiredOrigin { + diagnostics.add(.missingResource, requiredOrigin, "Explicit native member path is absent.") + } + return + } + guard + try FileManager.default.attributesOfItem(atPath: url.path)[.type] as? FileAttributeType + != .typeSymbolicLink + else { + diagnostics.add( + .unconverted, .init(document: relative, pointer: ""), + "Native member discovery through a link requires explicit contained support closure.") + return + } + // A regular member directory reached through a linked ancestor is still link discovery. + let memberPath = + relative == root ? "." : root == "." ? relative : String(relative.dropFirst(root.count + 1)) + let memberParts = memberPath.split(separator: "/") + if memberParts.count > 1 { + for count in 1.. = + agent == .cursor + ? ["type", "command", "timeout", "matcher"] : ["type", "command", "timeout"] + NativeImportInput.unknown(fields, allowed: allowed, at: origin, into: &diagnostics) + guard Set(fields.keys).isSubset(of: allowed), + fields["type"] == nil || fields["type"] == .string("command"), + let command = fields["command"]?.importString, !command.isEmpty + else { + diagnostics.add( + .unconverted, origin, + "Native non-command handler or extra execution policy has no equivalent executable conversion." + ) + continue + } + // A single executable token needs no shell splitting or inferred interpreter. + guard command.range(of: #"^[A-Za-z0-9_./-]+$"#, options: .regularExpression) != nil else { + diagnostics.add( + .unconverted, origin.appending("command"), + "Native shell syntax is not parsed or rewritten into argv.") + continue + } + var timeout: Int? + if let value = fields["timeout"] { + guard case .integer(let seconds) = value, seconds > 0, + !(agent == .claudeCode && event == "SessionEnd" && seconds > 60) + else { + NativeImportInput.unconverted( + value, at: origin.appending("timeout"), into: &diagnostics) + continue + } + timeout = seconds + } + var executable = command + if command.hasPrefix("./") { + let path = try nativePath(command, container: container) + executable = path.contains("/") ? path : "./" + path + try NativeImportInput.resource( + path, root: container, input: parsed.input, origin: origin, + limits: limits, into: &diagnostics, admission: parsed.admission) + } else if command.contains("/") { + diagnostics.add( + .unconverted, origin, + "Native hook outside its explicit root needs a selected authoring resource.") + continue + } + let identity = event + "\0" + (matcher ?? "") + "\0" + executable + let base = event + "-" + FileHash.sha256Hex(data: Data(identity.utf8)) + let occurrence = parsed.admission.memberOccurrences[base, default: 0] + 1 + parsed.admission.memberOccurrences[base] = occurrence + let name = base + (occurrence == 1 ? "" : "-\(occurrence)") + NativeImportInput.emit( + .hook( + name: name, event: .native(event), + run: .init( + executable: executable, + executableSource: executable.contains("/") ? "native-input" : nil), + matcher: matcher, timeoutSeconds: timeout, agents: [agent]), + selector: .hook(name: name), + origin: origin, container: container, profile: parsed.input.profile, into: &diagnostics, + admission: parsed.admission) + } + } + } + } + + static func lsp( + _ value: NativeValue, parsed: NativeImportDocument, keys: [String], + container: String, limits: SourceImportLimits, into diagnostics: inout ImportDiagnostics + ) throws { + let agent = NativeImportInput.agent(parsed.input.profile) + guard [.claudeCode, .opencode].contains(agent), let servers = value.importObject else { + NativeImportInput.unconverted(value, at: parsed.location(keys), into: &diagnostics) + return + } + try classifyMembers(value, parsed: parsed, keys: keys, into: &diagnostics) + for name in servers.keys.sorted() { + let origin = try parsed.memberLocation(keys, name: name) + let canonicalAttempt = diagnostics.beginCanonicalAttempt() + defer { diagnostics.endCanonicalAttempt(canonicalAttempt) } + guard NativeImportInput.name(name), let fields = servers[name]?.importObject else { + NativeImportInput.unconverted(servers[name]!, at: origin, into: &diagnostics) + continue + } + do { + _ = try NativeComponentFieldsV1.lsp( + surface: NativeImportSemantics.surface(parsed.input.profile), + document: parsed.input.document, fieldPrefix: keys + [name], fields: fields, + budget: parsed.admission.parser) + } catch let issue as NativeComponentFieldIssue { + guard issue.document == parsed.input.document else { throw ImportReadFailure.invalid } + NativeImportSemantics.report( + issue, at: parsed.fieldLocation(issue.field), into: &diagnostics) + continue + } + var executable: String + let arguments: [String] + var languages: [String: String] = [:] + let converted: Set = [ + "command", "args", "env", "extensionToLanguage", "initializationOptions", "initialization", + ] + let extras = fields.filter { !converted.contains($0.key) } + var native: NativeConfiguration = extras.isEmpty ? [:] : [agent.rawValue: extras] + var classification = ImportDiagnostics(proposal: .init(profile: parsed.input.profile)) + if NativeImportInput.sensitive(.object(extras), at: origin, into: &classification) { + diagnostics.add(.unconverted, origin, "Native LSP extras require symbolic reconstruction.") + continue + } + if agent == .claudeCode { + guard let command = fields["command"]?.importString, + let mapping = fields["extensionToLanguage"]?.importObject, !mapping.isEmpty, + mapping.allSatisfy({ $0.key.hasPrefix(".") && $0.value.importString?.isEmpty == false }), + fields["args"] == nil || fields["args"]?.importStrings != nil + else { + diagnostics.add( + .invalidInput, origin, "Native LSP command/language mapping is malformed.") + continue + } + executable = command + arguments = fields["args"]?.importStrings ?? [] + languages = mapping.mapValues { $0.importString! } + } else { + guard let argv = fields["command"]?.importStrings, let command = argv.first, + !command.isEmpty, + fields["extensions"] == nil || MCPNativeField.strings.accepts(fields["extensions"]!), + fields["disabled"] == nil || MCPNativeField.boolean.accepts(fields["disabled"]!) + else { + diagnostics.add( + .unconverted, origin, "Native LSP entry has no executable declaration to convert.") + continue + } + executable = command + arguments = Array(argv.dropFirst()) + for key in ["extensions", "disabled"] where fields[key] != nil { + native[agent.rawValue, default: [:]][key] = fields[key] + } + } + if parsed.input.profile == .claudePluginV1, executable.hasPrefix("${CLAUDE_PLUGIN_ROOT}/") { + executable = "./" + executable.dropFirst("${CLAUDE_PLUGIN_ROOT}/".count) + } + guard !executable.isEmpty, !executable.contains("\0"), !executable.contains("${"), + !arguments.contains(where: { + $0.contains("${") || ($0.contains("://") && !ImportInput.safeLocator($0)) + }) + else { + diagnostics.add( + .unconverted, origin, + "Native LSP interpolation/arguments require explicit resource or binding conversion.") + continue + } + var credentialArgument = false + for (index, argument) in arguments.enumerated() { + let flag = argument.split(separator: "=", maxSplits: 1).first.map(String.init) ?? argument + if ImportInput.credentialField(flag) { + diagnostics.binding(origin.appending("args/\(index)")) + credentialArgument = true + } + } + if credentialArgument { + diagnostics.add( + .unconverted, origin, "Native LSP credential arguments require symbolic reconstruction.") + continue + } + let optionsKey = agent == .claudeCode ? "initializationOptions" : "initialization" + let options = fields[optionsKey]?.importObject ?? [:] + if fields[optionsKey] != nil && fields[optionsKey]?.importObject == nil { + diagnostics.add( + .invalidInput, origin.appending(optionsKey), + "Native initialization options require an object.") + continue + } + if NativeImportInput.sensitive( + .object(options), at: origin.appending(optionsKey), into: &diagnostics) + { + diagnostics.add( + .unconverted, origin, + "Native initialization data contains literal credential slots without a typed binding representation." + ) + continue + } + let environment = try NativeImportInput.bindings( + fields["env"], at: origin.appending("env"), into: &diagnostics, + profile: parsed.input.profile) + var program = executable + if executable.hasPrefix("./") { + let path = try nativePath(executable, container: container) + program = path.contains("/") ? path : "./" + path + try NativeImportInput.resource( + path, root: container, input: parsed.input, origin: origin, + limits: limits, into: &diagnostics, admission: parsed.admission) + } else if executable.contains("/") { + diagnostics.add( + .unconverted, origin, + "Native LSP executable outside its source requires a selected resource.") + continue + } + NativeImportInput.emit( + .lspServer( + name: name, + run: .init( + executable: program, executableSource: program.contains("/") ? "native-input" : nil, + arguments: arguments, environment: environment), + languages: languages, initializationOptions: options, agents: [agent], native: native), + selector: .lspServer(name: name), + origin: origin, container: container, profile: parsed.input.profile, into: &diagnostics, + admission: parsed.admission) + } + } +} diff --git a/Sources/Components/Import/NativeImportInput.swift b/Sources/Components/Import/NativeImportInput.swift new file mode 100644 index 0000000..e8cc79e --- /dev/null +++ b/Sources/Components/Import/NativeImportInput.swift @@ -0,0 +1,454 @@ +import AgentsCore +import Foundation +import NativeDocuments + +/// An operation-local reader. Native bytes and parser observations never enter the proposal. +struct NativeImportDocument { + let input: SourceImportInput + let bytes: Data + let document: NativeDocument + let fields: [String: NativeValue] + let admission: NativeImportBudget + + init( + _ input: SourceImportInput, format: NativeDocumentFormat, limits: SourceImportLimits, + admission: NativeImportBudget? = nil + ) throws { + let bytes = try ImportInput.bytes(input, limits: limits) + let admission = try admission ?? NativeImportBudget(limits) + try admission.document(bytes, path: input.document) + let budget = admission.parser + do { + let document = try NativeDocument(bytes: bytes, format: format, budget: budget) + guard let observation = try document.read(.init(keys: [])), + observation.projectionFailure == nil, case .object(let fields) = observation.value + else { throw ImportReadFailure.invalid } + self.input = input + self.bytes = bytes + self.document = document + self.fields = fields + self.admission = admission + } catch NativeDocumentError.cancelled { + throw CancellationError() + } catch NativeDocumentError.invalidDocument(_, let range) { + throw ImportLocatedFailure( + location: .init( + document: input.document, pointer: "", + span: range.map { importSpan(bytes, document: input.document, range: $0) })) + } + } + + /// Winner subsets retain coordinates from the complete original producer map. + func memberLocation(_ keys: [String], name: String) throws -> ImportLocation { + guard let fields = (try document.read(.init(keys: keys)))?.value?.importObject, + let index = fields.keys.sorted().firstIndex(of: name) + else { throw ImportReadFailure.invalid } + return location( + keys + [name], display: keys.map { "/" + $0 }.joined() + "/member[\(index)]") + } + + /// Structural helper paths are resolved against original syntax, with value-free ordinals. + func fieldLocation(_ keys: [String]) -> ImportLocation { + var prefix: [String] = [] + var display = "" + for key in keys { + let value = try? document.read(.init(keys: prefix))?.value + if let map = value?.importObject, let index = map.keys.sorted().firstIndex(of: key) { + display += "/member[\(index)]" + } else if case .array = value, Int(key) != nil { + display += "/" + key + } else { + return location(prefix, display: display) + } + prefix.append(key) + } + return location(keys, display: display) + } + + func location(_ keys: [String] = [], display: String? = nil) -> ImportLocation { + let observation = try? document.read(.init(keys: keys)) + var range = observation?.valueRange ?? observation?.entryRanges.first + if range == nil, let fields = observation?.value?.importObject { + for key in fields.keys.sorted() { + if let found = (try? document.read(.init(keys: keys + [key])))?.valueRange { + range = found + break + } + } + } + return .init( + document: input.document, pointer: display ?? keys.map { "/" + $0 }.joined(), + span: range.map { importSpan(bytes, document: input.document, range: $0) }) + } +} + +enum NativeImportInput { + static func agent(_ profile: SourceImportProfile) -> AgentID { surface(profile).agent } + + static func surface(_ profile: SourceImportProfile) -> NativeClientSurface { + switch profile { + case .codexConfigV1: .codexCLI + case .cursorMCPV1, .cursorPluginV1, .cursorCommandV1, .cursorAgentV1, .cursorIgnoreV1: + .cursorEditor + case .geminiSettingsV1, .geminiExtensionV1, .geminiCommandV1, .geminiAgentV1, .geminiIgnoreV1: + .geminiCLI + case .openCodeConfigV2, .openCodeCommandV2, .openCodeAgentV2: .openCodeCLI + default: .claudeCode + } + } + + static func name(_ text: String) -> Bool { + ImportInput.name(text) && !text.contains("://") + } + + static func unknown( + _ fields: [String: NativeValue], allowed: Set, at origin: ImportLocation, + into diagnostics: inout ImportDiagnostics + ) { + for (index, key) in fields.keys.sorted().enumerated() where !allowed.contains(key) { + let location = origin.appending("member[\(index)]") + if ImportInput.credentialField(key) { diagnostics.binding(location) } + unconverted(fields[key]!, at: location, into: &diagnostics) + } + } + + static func unconverted( + _ value: NativeValue, at location: ImportLocation, + into diagnostics: inout ImportDiagnostics + ) { + diagnostics.add( + .unconverted, location, + "Native field requires an explicit semantic conversion; it is not imported.") + switch value { + case .object(let fields): + for (index, key) in fields.keys.sorted().enumerated() { + let child = location.appending("member[\(index)]") + if ImportInput.credentialField(key) { diagnostics.binding(child) } + unconverted(fields[key]!, at: child, into: &diagnostics) + } + case .array(let values): + for (index, value) in values.enumerated() { + unconverted(value, at: location.appending(String(index)), into: &diagnostics) + } + case .string(let text) where text.contains("://") && !ImportInput.safeLocator(text): + diagnostics.binding(location) + default: break + } + } + + static func sensitive( + _ value: NativeValue, at location: ImportLocation, into diagnostics: inout ImportDiagnostics + ) -> Bool { + var found = false + if let fields = value.importObject { + for (index, key) in fields.keys.sorted().enumerated() { + let item = location.appending("member[\(index)]") + if ImportInput.credentialField(key) { + diagnostics.binding(item) + found = true + } + if sensitive(fields[key]!, at: item, into: &diagnostics) { found = true } + } + } else if case .array(let values) = value { + for (index, value) in values.enumerated() { + if sensitive(value, at: location.appending(String(index)), into: &diagnostics) { + found = true + } + } + } else if let string = value.importString, string.contains("://"), + !ImportInput.safeLocator(string) + { + diagnostics.binding(location) + found = true + } + return found + } + + static func binding( + _ location: ImportLocation, environment: String? = nil, canonical: Bool = true, + into diagnostics: inout ImportDiagnostics + ) -> RuntimeBinding { + let key = + "import-" + FileHash.sha256Hex(data: Data((location.document + "\0" + location.pointer).utf8)) + diagnostics.binding(location, environmentVariable: environment) + if let index = diagnostics.proposal.bindings.firstIndex(where: { $0.location == location }) { + diagnostics.proposal.bindings[index].key = key + if canonical { diagnostics.proposal.bindings[index].canonicalSlot = true } + } + if canonical, let reference = diagnostics.bindingReferences[key] { + switch reference { + case .environment, .secret: + diagnostics.resolvedBindings.insert(location) + return reference + case .literal: break + } + } + return environment.map(RuntimeBinding.environment) ?? .secret(key) + } + + static func bindings( + _ value: NativeValue?, at location: ImportLocation, symbolic: Bool = false, + literalsOnly: Bool = false, + into diagnostics: inout ImportDiagnostics, profile: SourceImportProfile? = nil + ) throws -> [String: RuntimeBinding] { + guard let value else { return [:] } + guard case .object(let fields) = value else { throw ImportReadFailure.invalid } + var result: [String: RuntimeBinding] = [:] + for (index, key) in fields.keys.sorted().enumerated() { + let item = location.appending("member[\(index)]") + guard name(key), let text = fields[key]?.importString else { throw ImportReadFailure.invalid } + if symbolic { + guard MCPReferenceSyntax.isName(text) + else { throw ImportReadFailure.invalid } + result[key] = + literalsOnly ? .environment(text) : binding(item, environment: text, into: &diagnostics) + } else { + var reference: String? + if let profile { + let client = agent(profile) + if [.claudeCode, .geminiCLI].contains(client), text.hasPrefix("${"), text.hasSuffix("}") { + reference = String(text.dropFirst(2).dropLast()) + } else if client == .opencode, text.hasPrefix("{env:"), text.hasSuffix("}") { + reference = String(text.dropFirst(5).dropLast()) + } + } + if let reference, + MCPReferenceSyntax.isName(reference) + { + result[key] = + literalsOnly + ? .environment(reference) : binding(item, environment: reference, into: &diagnostics) + } else if text.contains("${") || text.contains("{env:") || text.contains("{file:") { + diagnostics.binding(item) + diagnostics.add( + .unconverted, item, + "Native interpolation is not a single admitted symbolic environment reference.") + throw ImportReadFailure.invalid + } else { + result[key] = binding(item, canonical: !literalsOnly, into: &diagnostics) + } + } + } + return result + } + + /// Classifies native credential slots before selection/precedence. No member is emitted and + /// no referenced resource is read. Explicit symbolic references do not contain literal secrets. + static func preservationBindings( + _ fields: [String: NativeValue], at location: ImportLocation, + profile: SourceImportProfile, into diagnostics: inout ImportDiagnostics + ) { + let maps: Set = ["env", "environment", "headers", "http_headers", "env_http_headers"] + for field in maps.sorted() where fields[field] != nil { + do { + _ = try bindings( + fields[field], at: location.appending(field), + symbolic: field == "env_http_headers" && agent(profile) == .codex, + literalsOnly: true, into: &diagnostics, + profile: field == "env_http_headers" && agent(profile) != .codex ? nil : profile) + } catch { + diagnostics.binding(location.appending(field)) + diagnostics.add( + .invalidInput, location.appending(field), + "Native binding values cannot be admitted for preservation.") + } + } + _ = sensitive( + .object(fields.filter { !maps.contains($0.key) }), at: location, into: &diagnostics) + let argv = + fields["args"]?.importStrings ?? fields["command"]?.importStrings.map { + Array($0.dropFirst()) + } ?? [] + for (index, argument) in argv.enumerated() { + let flag = String(argument.split(separator: "=", maxSplits: 1).first ?? "") + if ImportInput.credentialField(flag) + || (argument.contains("://") && !ImportInput.safeLocator(argument)) + { + let coordinate = fields["args"] != nil ? "args/\(index)" : "command/\(index + 1)" + diagnostics.binding(location.appending(coordinate)) + } + } + } + + static func source( + _ input: SourceImportInput, root: String, origin: ImportLocation, + into diagnostics: inout ImportDiagnostics + ) -> String { + let alias = "native-input" + if !diagnostics.proposal.sources.contains(where: { $0.alias == alias }) { + diagnostics.proposal.sources.append( + .init( + alias: alias, origin: origin, + declaration: .init( + kind: .local, location: root, + environment: .init(projectDirectory: input.root, homeDirectory: input.root)), + pin: .init(), requestedRef: nil, producerPath: root)) + } + return alias + } + + static func emit( + _ declaration: ComponentDeclaration, selector: ComponentReferenceDeclaration, + origin: ImportLocation, container: String, profile: SourceImportProfile, + into diagnostics: inout ImportDiagnostics, admission: NativeImportBudget? = nil + ) { + let member = ImportMemberCoordinate( + containerRoot: container, selector: selector, + profile: profile, formatVersion: 1) + guard admission?.ambiguousMembers.contains(member) != true, + !diagnostics.proposal.components.contains(where: { $0.member == member }) + else { + diagnostics.proposal.components.removeAll { $0.member == member } + admission?.ambiguousMembers.append(member) + diagnostics.add( + .ambiguousSource, origin, "Two native declarations have the same typed member identity.") + return + } + diagnostics.proposal.components.append( + .init(origin: origin, declaration: declaration, member: member)) + } + + /// A directory may be captured before a later native document reveals a literal binding. + /// Reconcile every source-relative overlap before the operation publishes its proposal, + /// including partial proposals returned after a parsing failure. + static func reconcilePreservation(into diagnostics: inout ImportDiagnostics) { + var blockedCaptures: [String: Set] = [:] + for resource in diagnostics.proposal.resources { + guard let path = resource.path, + let root = diagnostics.proposal.sources.first(where: { + $0.alias == resource.sourceAlias + })?.producerPath + else { continue } + let relative = root == "." ? path : root + (path == "." ? "" : "/" + path) + if resource.requiresBindingRewrite + || diagnostics.proposal.preservationBindings.contains(where: { + relative == "." || $0.document == relative + || $0.document.hasPrefix(relative + "/") + }) + { + blockedCaptures[resource.sourceAlias, default: []].insert(resource.origin) + } + } + // A capture and its supporting resources share an origin and source coordinate. Literal + // classification in any part of that closure blocks preservation of the complete capture. + for index in diagnostics.proposal.resources.indices { + let resource = diagnostics.proposal.resources[index] + if blockedCaptures[resource.sourceAlias]?.contains(resource.origin) == true { + diagnostics.proposal.resources[index].requiresBindingRewrite = true + diagnostics.proposal.resources[index].observedHash = nil + } + } + } + + static func resource( + _ path: String, root: String, input: SourceImportInput, + origin: ImportLocation, limits: SourceImportLimits, rewrite: Bool = false, + into diagnostics: inout ImportDiagnostics, admission: NativeImportBudget? = nil + ) throws { + let root = try ImportInput.path(root) + let path = try ImportInput.path(path) + let relative = root == "." ? path : root + (path == "." ? "" : "/" + path) + let snapshot = try ImportInput.snapshot(input.root) + let url = try snapshot.resource(relative) + try admission?.resource(url, snapshot: snapshot) + let needsRewrite = + rewrite + || diagnostics.proposal.preservationBindings.contains { + $0.document == relative || $0.document.hasPrefix(relative + "/") + || relative == "." + } + let frozen = try LedgerResources.capture( + url, embed: false, + limits: .init( + encodedBytes: limits.resourceBytes, depth: limits.depth, nodes: limits.nodes, + objectBytes: limits.resourceBytes, entries: limits.resourceEntries, + keyBytes: limits.resourceBytes, resourceBytes: limits.resourceBytes), + sourceRoot: try snapshot.resource(root)) + for entry in frozen.support { + let supportPath = root == "." ? entry.path : root + "/" + entry.path + try admission?.resource(try snapshot.resource(supportPath), snapshot: snapshot) + } + let alias = source(input, root: root, origin: origin, into: &diagnostics) + diagnostics.proposal.resources.append( + .init( + origin: origin, sourceAlias: alias, + producerName: url.lastPathComponent, path: path, producerIntegrity: nil, + observedHash: needsRewrite ? nil : frozen.hash, executableFlags: frozen.flags, + requiresStandaloneSource: true, requiresBindingRewrite: needsRewrite)) + // Support targets remain separate resources relative to the same native-format root. + for entry in frozen.support where entry.kind == .file { + diagnostics.proposal.resources.append( + .init( + origin: origin, sourceAlias: alias, + producerName: URL(fileURLWithPath: entry.path).lastPathComponent, path: entry.path, + producerIntegrity: nil, observedHash: nil, + executableFlags: [entry.path: entry.executable], + requiresStandaloneSource: true, requiresBindingRewrite: needsRewrite)) + } + } +} + +/// Shared only within one bounded import operation; no bytes or state escape in a proposal. +final class NativeImportBudget { + let parser: NativeDocumentBudget + private let limits: SourceImportLimits + private var documentBytes: Int + private var resourceBytes: Int + private var entries: Int + var ambiguousMembers: [ImportMemberCoordinate] = [] + var memberOccurrences: [String: Int] = [:] + private var documents: Set = [] + private var resources: Set = [] + + init(_ limits: SourceImportLimits) throws { + guard limits.documentBytes >= 0, limits.documentBytes <= (Int.max - 1024) / 64, + limits.resourceBytes >= 0, limits.resourceEntries > 0, limits.depth > 0, limits.nodes > 0 + else { throw ImportReadFailure.invalid } + self.limits = limits + documentBytes = limits.documentBytes + resourceBytes = limits.resourceBytes + entries = limits.resourceEntries + parser = .init( + limits: .init( + storage: limits.documentBytes * 32 + 1024, + work: limits.documentBytes * 64 + 1024, nodes: limits.nodes, depth: limits.depth, + uninterruptedBytes: limits.documentBytes)) + } + + func document(_ bytes: Data, path: String) throws { + if documents.insert(path).inserted { + guard bytes.count <= documentBytes else { throw ImportReadFailure.invalid } + documentBytes -= bytes.count + } + } + + func resource(_ url: URL, snapshot: SourceSnapshot) throws { + func admit(_ file: URL) throws { + try Task.checkCancellation() + let path = try snapshot.relativePath(file) + guard !resources.contains(path) else { return } + guard entries > 0, path.split(separator: "/").count <= limits.depth else { + throw ImportReadFailure.invalid + } + let info = try FileManager.default.attributesOfItem(atPath: file.path) + if info[.type] as? FileAttributeType == .typeRegular { + guard let size = (info[.size] as? NSNumber)?.intValue, size >= 0, size <= resourceBytes + else { throw ImportReadFailure.invalid } + resourceBytes -= size + } else if ![FileAttributeType.typeDirectory, .typeSymbolicLink].contains( + info[.type] as? FileAttributeType ?? .typeUnknown) + { + throw ImportReadFailure.invalid + } + resources.insert(path) + entries -= 1 + } + try admit(url) + let info = try FileManager.default.attributesOfItem(atPath: url.path) + if info[.type] as? FileAttributeType == .typeDirectory { + guard let walk = FileManager.default.enumerator(at: url, includingPropertiesForKeys: nil) + else { throw ImportReadFailure.invalid } + for case let file as URL in walk { try admit(file) } + } + } +} diff --git a/Sources/Components/Import/NativeImportSemantics.swift b/Sources/Components/Import/NativeImportSemantics.swift new file mode 100644 index 0000000..715ed45 --- /dev/null +++ b/Sources/Components/Import/NativeImportSemantics.swift @@ -0,0 +1,29 @@ +import AgentsCore +import NativeDocuments + +/// Reuses F's finite conversion/validation rather than maintaining another native field table. +enum NativeImportSemantics { + static func surface(_ profile: SourceImportProfile) -> NativeClientSurface { + NativeImportInput.surface(profile) + } + + static func report( + _ issue: NativeComponentFieldIssue, at location: ImportLocation, + into diagnostics: inout ImportDiagnostics + ) { + diagnostics.add(issue.reason == .invalid ? .invalidInput : .unconverted, location, issue.detail) + } + + static func mcp( + name: String, transport: MCPTransportDeclaration, + native: [String: NativeValue], profile: SourceImportProfile, resources: [String] + ) throws { + let surface = surface(profile) + // These field converters do not consume scope or produce a deployment. Project is an + // error-context value only; no scope, route or ownership is returned by the importer. + let descriptor = try CapabilityRegistry.mcp( + .init(surface: surface, scope: .project), component: name) + _ = try NativeMCPLowering.entry( + transport, named: name, descriptor: descriptor, native: native, resources: resources) + } +} diff --git a/Sources/Components/Import/NativeMemberImport.swift b/Sources/Components/Import/NativeMemberImport.swift new file mode 100644 index 0000000..b3bf5ba --- /dev/null +++ b/Sources/Components/Import/NativeMemberImport.swift @@ -0,0 +1,194 @@ +import AgentsCore +import AgentsManifest +import Foundation +import NativeDocuments + +/// Native file bodies share the package-owned bounded YAML/TOML readers. +enum NativeMemberImport { + static func read( + _ input: SourceImportInput, container: String, + kind explicitKind: DeclaredComponentKind? = nil, limits: SourceImportLimits, + into diagnostics: inout ImportDiagnostics, admission supplied: NativeImportBudget? = nil, + discoveryRoot: String? = nil, inPlugin: Bool = false + ) throws { + let admission = try supplied ?? NativeImportBudget(limits) + let agent = NativeImportInput.agent(input.profile) + let isAgent = + explicitKind == .subagent + || [.claudeAgentV1, .geminiAgentV1, .openCodeAgentV2, .cursorAgentV1].contains(input.profile) + let bytes = try ImportInput.bytes(input, limits: limits) + try admission.document(bytes, path: input.document) + let file = URL(fileURLWithPath: input.document) + let stem = (input.document as NSString).deletingPathExtension + let fallback = + discoveryRoot.map { + stem.hasPrefix($0 + "/") + ? String(stem.dropFirst($0.count + 1)) : file.deletingPathExtension().lastPathComponent + } ?? file.deletingPathExtension().lastPathComponent + var origin = ImportLocation(document: input.document, pointer: "") + var name = fallback + let body: String + let description: String + var model: String? + var tools: [String]? + var native: NativeConfiguration = [:] + if input.profile == .geminiCommandV1 || (!isAgent && agent == .geminiCLI) { + let parsed = try NativeImportDocument( + input, format: .toml, limits: limits, admission: admission) + origin = parsed.location() + NativeImportInput.unknown( + parsed.fields, allowed: ["description", "prompt"], at: origin, into: &diagnostics) + guard Set(parsed.fields.keys).isSubset(of: ["description", "prompt"]), + let prompt = parsed.fields["prompt"]?.importString, + parsed.fields["description"] == nil || parsed.fields["description"]?.importString != nil + else { + diagnostics.add( + .invalidInput, origin, "Native command requires its fixed prompt/description fields.") + return + } + body = prompt + description = parsed.fields["description"]?.importString ?? "" + } else { + let parsed = + try agent == .cursor && !isAgent && !inPlugin + ? (header: Optional.none, body: bytes) + : ImportFrontmatter.read(bytes, document: input.document, limits: limits) + guard let text = String(data: parsed.body, encoding: .utf8) else { + throw ImportReadFailure.invalid + } + // Gemini's native agent loader trims its body; the proposal represents that loaded value. + body = + agent == .geminiCLI && isAgent ? text.trimmingCharacters(in: .whitespacesAndNewlines) : text + var fields: [String: NativeValue] = [:] + if let header = parsed.header { + origin = header.location + fields = try nativeValue(header).importObject! + } + // All original frontmatter participates in preservation admission, even on refusal. + if NativeImportInput.sensitive(.object(fields), at: origin, into: &diagnostics) { + diagnostics.add( + .unconverted, origin, + "Native frontmatter credential slots require symbolic reconstruction.") + return + } + if agent != .opencode { + do { + fields = try NativeComponentFieldsV1.markdown( + surface: NativeImportSemantics.surface(input.profile), + document: input.document, fieldPrefix: [], kind: isAgent ? .subagent : .command, + name: fallback, fields: fields, + inPlugin: inPlugin, budget: admission.parser) + } catch let issue as NativeComponentFieldIssue { + guard issue.document == input.document else { throw ImportReadFailure.invalid } + var value = parsed.header + for field in issue.field { + guard let node = value else { break } + if let child = node[field] { + value = child + } else if let index = Int(field), let items = node.items, items.indices.contains(index) + { + value = items[index] + } else { + break + } + } + NativeImportSemantics.report(issue, at: value?.location ?? origin, into: &diagnostics) + return + } + } else { + let converted: Set = + isAgent ? ["name", "description", "model", "tools"] : ["description"] + NativeImportInput.unknown(fields, allowed: converted, at: origin, into: &diagnostics) + guard Set(fields.keys).isSubset(of: converted) else { return } + for field in ["name", "description"] where fields[field] != nil { + guard fields[field]?.importString != nil else { + diagnostics.add( + .invalidInput, parsed.header?[field]?.location ?? origin, + "Native Markdown field requires a string value.") + return + } + } + if let value = fields["model"], value.importString == nil { + NativeImportInput.unconverted( + value, at: parsed.header?["model"]?.location ?? origin, into: &diagnostics) + return + } + } + name = fields["name"]?.importString ?? name + model = fields["model"]?.importString + if let value = fields["tools"] { + if let values = value.importStrings { + tools = values + } else if let text = value.importString, agent == .claudeCode { + tools = text.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) } + } else { + throw ImportReadFailure.invalid + } + } + description = fields["description"]?.importString ?? "" + let converted: Set = + isAgent ? ["name", "description", "model", "tools"] : ["description"] + let extras = fields.filter { !converted.contains($0.key) } + if !extras.isEmpty { native[agent.rawValue] = extras } + if !isAgent, agent == .claudeCode, + body.contains("$ARGUMENTS") + || body.range(of: #"\$[0-9]+"#, options: .regularExpression) != nil + { + diagnostics.add( + .unconverted, origin, + "Native command substitutions need explicit parameter conversion; no prompt parameters are guessed." + ) + return + } + } + guard + name.split(separator: "/", omittingEmptySubsequences: false).allSatisfy({ + NativeImportInput.name(String($0)) + }) + else { + diagnostics.add( + .invalidInput, origin, "Native member name is not an admitted component identifier.") + return + } + if isAgent { + NativeImportInput.emit( + .subagent( + name: name, description: description, prompt: .literal(body), + model: model, tools: tools, agents: [agent], native: native), + selector: .subagent(name: name), + origin: origin, container: container, profile: input.profile, into: &diagnostics, + admission: admission) + } else { + NativeImportInput.emit( + .command( + name: name, description: description, prompt: .literal(body), agents: [agent], + native: native), + selector: .command(name: name), origin: origin, container: container, + profile: input.profile, into: &diagnostics, admission: admission) + } + let relative = + container == "." ? input.document : String(input.document.dropFirst(container.count + 1)) + try NativeImportInput.resource( + relative, root: container, input: input, origin: origin, limits: limits, into: &diagnostics, + admission: admission) + } + + private static func nativeValue(_ yaml: ImportYAML) throws -> NativeValue { + if let pairs = yaml.pairs { + return .object( + try pairs.map { ($0.0, try nativeValue($0.1)) }.reduce(into: [:]) { $0[$1.0] = $1.1 }) + } + if let items = yaml.items { return .array(try items.map { try nativeValue($0) }) } + if let text = yaml.string { return .string(text) } + if let value = yaml.boolean { return .boolean(value) } + if let value = yaml.integer { return .integer(value) } + if let scalar = yaml.node.scalar { + if scalar.decimalTag || YAMLScalar.classify(scalar.text) == .decimal { + // Decimal spelling stays private until the finite field validator admits its domain. + return .decimal(scalar.text) + } + if YAMLScalar.classify(scalar.text) == .null { return .null } + } + throw ImportLocatedFailure(location: yaml.location) + } +} diff --git a/Sources/Components/Import/NativeSourceImport.swift b/Sources/Components/Import/NativeSourceImport.swift new file mode 100644 index 0000000..3aac7fc --- /dev/null +++ b/Sources/Components/Import/NativeSourceImport.swift @@ -0,0 +1,527 @@ +import AgentsCore +import Foundation +import NativeDocuments + +enum NativeSourceImport { + static func read( + _ input: SourceImportInput, limits: SourceImportLimits, + into diagnostics: inout ImportDiagnostics + ) throws { + defer { NativeImportInput.reconcilePreservation(into: &diagnostics) } + switch input.profile { + case .geminiIgnoreV1, .cursorIgnoreV1: + let bytes = try ImportInput.bytes(input, limits: limits) + guard let text = String(data: bytes, encoding: .utf8), !text.contains("\0") else { + throw ImportReadFailure.invalid + } + let patterns = text.components(separatedBy: .newlines).filter { !$0.isEmpty } + let origin = ImportLocation(document: input.document, pointer: "") + NativeImportInput.emit( + .ignore( + name: "native-context", patterns: patterns, + agents: [NativeImportInput.agent(input.profile)]), + selector: .ignore(name: "native-context"), origin: origin, container: ".", + profile: input.profile, into: &diagnostics) + try NativeImportInput.resource( + input.document, root: ".", input: input, origin: origin, limits: limits, into: &diagnostics) + case .claudePluginV1, .cursorPluginV1, .geminiExtensionV1: + try NativeContainerImport.read(input, limits: limits, into: &diagnostics) + case .claudeMarketplaceV1: + try NativeCatalogImport.read(input, limits: limits, into: &diagnostics) + case .claudeCommandV1, .claudeAgentV1, .geminiCommandV1, .geminiAgentV1, + .openCodeCommandV2, .openCodeAgentV2, .cursorCommandV1, .cursorAgentV1: + try NativeMemberImport.read(input, container: ".", limits: limits, into: &diagnostics) + default: + let format: NativeDocumentFormat = + input.profile == .codexConfigV1 ? .toml : .jsonc(trailingCommas: true) + let parsed = try NativeImportDocument(input, format: format, limits: limits) + let root = "." + _ = NativeImportInput.source(input, root: root, origin: parsed.location(), into: &diagnostics) + let wrapper = + input.profile == .codexConfigV1 + ? "mcp_servers" : input.profile == .openCodeConfigV2 ? "mcp" : "mcpServers" + if let value = parsed.fields[wrapper] { + if input.profile == .openCodeConfigV2 { + guard let fields = value.importObject else { throw ImportReadFailure.invalid } + NativeImportInput.unknown( + fields, allowed: ["servers"], at: parsed.location([wrapper]), into: &diagnostics) + if let servers = fields["servers"] { + try mcp( + servers, parsed: parsed, keys: [wrapper, "servers"], container: root, + limits: limits, into: &diagnostics) + } + } else { + try mcp( + value, parsed: parsed, keys: [wrapper], container: root, limits: limits, + into: &diagnostics) + } + } + var converted: Set = [wrapper, "$schema"] + if input.profile == .openCodeConfigV2 { + for (key, kind) in [("commands", "command"), ("agents", "subagent")] + where parsed.fields[key] != nil { + try openCodeMembers( + parsed.fields[key]!, kind: kind, parsed: parsed, key: key, into: &diagnostics) + converted.insert(key) + } + if let value = parsed.fields["permissions"] { + permissions(value, parsed: parsed, into: &diagnostics) + converted.insert("permissions") + } + } + if input.profile == .codexConfigV1, let agents = parsed.fields["agents"] { + try codexAgents(agents, parsed: parsed, limits: limits, into: &diagnostics) + converted.insert("agents") + } + if let value = parsed.fields["hooks"] { + try hooks( + value, parsed: parsed, keys: ["hooks"], container: root, limits: limits, + into: &diagnostics) + converted.insert("hooks") + } + if input.profile == .openCodeConfigV2, let value = parsed.fields["lsp"] { + try lsp( + value, parsed: parsed, keys: ["lsp"], container: root, limits: limits, into: &diagnostics) + converted.insert("lsp") + } + if input.profile == .claudeSettingsV1, let value = parsed.fields["permissions"] { + if let fields = value.importObject, + Set(fields.keys).isSubset(of: ["allow", "ask", "deny"]), + fields.values.allSatisfy(MCPNativeField.strings.accepts) + { + NativeImportInput.emit( + .permissions( + name: "native-policy", rules: [], agents: [.claudeCode], + native: [AgentID.claudeCode.rawValue: fields]), + selector: .permissions(name: "native-policy"), origin: parsed.location(["permissions"]), + container: root, + profile: input.profile, into: &diagnostics, admission: parsed.admission) + } else { + NativeImportInput.unconverted( + value, at: parsed.location(["permissions"]), into: &diagnostics) + } + converted.insert("permissions") + } + NativeImportInput.unknown( + parsed.fields, allowed: converted, at: parsed.location(), into: &diagnostics) + let privateInput = diagnostics.proposal.preservationBindings.contains { + $0.document == input.document + } + try NativeImportInput.resource( + input.document, root: root, input: input, origin: parsed.location(), + limits: limits, rewrite: privateInput, into: &diagnostics, admission: parsed.admission) + } + } + + /// A full parsed map is classified even when only a subset contributes canonical members. + static func classifyMembers( + _ value: NativeValue, parsed: NativeImportDocument, keys: [String], + into diagnostics: inout ImportDiagnostics + ) throws { + guard let members = value.importObject else { throw ImportReadFailure.invalid } + for name in members.keys.sorted() { + try Task.checkCancellation() + let origin = try parsed.memberLocation(keys, name: name) + if let fields = members[name]?.importObject { + NativeImportInput.preservationBindings( + fields, at: origin, profile: parsed.input.profile, into: &diagnostics) + } else { + _ = NativeImportInput.sensitive(members[name]!, at: origin, into: &diagnostics) + } + } + } + + static func mcp( + _ value: NativeValue, parsed: NativeImportDocument, keys: [String], + container: String, limits: SourceImportLimits, into diagnostics: inout ImportDiagnostics + ) throws { + guard case .object(let servers) = value else { throw ImportReadFailure.invalid } + try classifyMembers(value, parsed: parsed, keys: keys, into: &diagnostics) + let agent = NativeImportInput.agent(parsed.input.profile) + for name in servers.keys.sorted() { + try Task.checkCancellation() + let selectable = ![SourceImportProfile.claudePluginV1, .cursorPluginV1, .geminiExtensionV1] + .contains(parsed.input.profile) + let choice = + selectable && NativeImportInput.name(name) + ? diagnostics.beginChoice(name, at: try parsed.memberLocation(keys, name: name)) : nil + defer { if let choice { diagnostics.endChoice(choice) } } + if selectable, !parsed.input.enumerateChoices, + !(parsed.input.selection?.contains(name) ?? true) + { + continue + } + let location = try parsed.memberLocation(keys, name: name) + let canonicalAttempt = diagnostics.beginCanonicalAttempt() + defer { diagnostics.endCanonicalAttempt(canonicalAttempt) } + guard NativeImportInput.name(name), case .object(let fields) = servers[name] else { + NativeImportInput.unconverted(servers[name]!, at: location, into: &diagnostics) + continue + } + do { + guard + ["type", "url", "httpUrl", "cwd"].allSatisfy({ + fields[$0] == nil || fields[$0]?.importString != nil + }) + else { throw ImportReadFailure.invalid } + var allowed: Set = ["command", "args", "env", "type", "url", "headers"] + if agent == .codex { + allowed = [ + "command", "args", "env", "cwd", "env_vars", "url", "http_headers", "env_http_headers", + ] + } + if agent == .geminiCLI { + allowed.insert("cwd") + allowed.insert("httpUrl") + } + if agent == .opencode { + allowed = [ + "type", "command", "environment", "cwd", "url", "headers", "codemode", "oauth", + ] + } + let extra = fields.filter { !allowed.contains($0.key) } + for (index, key) in extra.keys.sorted().enumerated() where ImportInput.credentialField(key) + { + diagnostics.binding(location.appending("native/member[\(index)]")) + } + let transport: MCPTransportDeclaration + let explicit = fields["type"]?.importString + var native: NativeConfiguration = extra.isEmpty ? [:] : [agent.rawValue: extra] + if agent == .opencode, fields["codemode"] != nil { + guard case .boolean = fields["codemode"]! else { throw ImportReadFailure.invalid } + native[agent.rawValue, default: [:]]["codemode"] = fields["codemode"] + } + if agent == .opencode, let oauth = fields["oauth"] { + guard oauth == .boolean(false) else { + NativeImportInput.unconverted( + oauth, at: location.appending("oauth"), into: &diagnostics) + continue + } + native[agent.rawValue, default: [:]]["oauth"] = oauth + } + if let url = fields["url"]?.importString ?? fields["httpUrl"]?.importString { + guard fields["command"] == nil, ImportInput.safeLocator(url), + let address = URLComponents(string: url), ["https", "http"].contains(address.scheme), + address.host != nil + else { + if !ImportInput.safeLocator(url) { diagnostics.binding(location.appending("url")) } + throw ImportReadFailure.invalid + } + let inappropriate: Set = ["args", "env", "env_vars", "environment", "cwd"] + if !Set(fields.keys).isDisjoint(with: inappropriate) { + for key in inappropriate where fields[key] != nil { + NativeImportInput.unconverted( + fields[key]!, at: location.appending(key), into: &diagnostics) + } + continue + } + if agent == .opencode, fields["codemode"] == nil { + native[agent.rawValue, default: [:]]["codemode"] = .boolean(true) + } + let headerKey = agent == .codex ? "http_headers" : "headers" + var headers = try NativeImportInput.bindings( + fields[headerKey], at: location.appending(headerKey), into: &diagnostics, + profile: parsed.input.profile) + if agent == .codex { + let refs = try NativeImportInput.bindings( + fields["env_http_headers"], at: location.appending("env_http_headers"), + symbolic: true, into: &diagnostics, profile: parsed.input.profile) + guard Set(headers.keys).isDisjoint(with: refs.keys) else { + throw ImportReadFailure.invalid + } + headers.merge(refs) { first, _ in first } + } + if agent == .codex || (agent == .opencode && explicit == "remote") || explicit == "http" + || fields["httpUrl"] != nil + { + transport = .streamableHTTP(url: url, headers: headers) + } else if agent == .claudeCode || agent == .geminiCLI, explicit == "sse" { + transport = .sse(url: url, headers: headers) + } else { + diagnostics.add( + .unconverted, location, + "Native remote transport is not fixed by this input; no HTTP/SSE transport is guessed." + ) + continue + } + } else { + guard explicit == nil || explicit == (agent == .opencode ? "local" : "stdio") else { + throw ImportReadFailure.invalid + } + if fields["headers"] != nil || fields["http_headers"] != nil + || fields["env_http_headers"] != nil + { + for key in ["headers", "http_headers", "env_http_headers"] where fields[key] != nil { + _ = try NativeImportInput.bindings( + fields[key], at: location.appending(key), into: &diagnostics) + NativeImportInput.unconverted( + fields[key]!, at: location.appending(key), into: &diagnostics) + } + continue + } + var executable: String + var arguments: [String] + if agent == .opencode { + guard let argv = fields["command"]?.importStrings, let first = argv.first, + !first.isEmpty + else { throw ImportReadFailure.invalid } + executable = first + arguments = Array(argv.dropFirst()) + } else { + guard let command = fields["command"]?.importString, !command.isEmpty else { + throw ImportReadFailure.invalid + } + executable = command + guard fields["args"] == nil || fields["args"]?.importStrings != nil else { + throw ImportReadFailure.invalid + } + arguments = fields["args"]?.importStrings ?? [] + } + guard !executable.contains("\0"), !arguments.contains(where: { $0.contains("\0") }) else { + throw ImportReadFailure.invalid + } + var unrepresentableArgument = false + for (offset, argument) in arguments.enumerated() { + let flag = + argument.hasPrefix("--") + ? String(argument.dropFirst(2).split(separator: "=", maxSplits: 1).first ?? "") : "" + if ImportInput.credentialField(flag) + || (argument.contains("://") && !ImportInput.safeLocator(argument)) + { + diagnostics.binding(location.appending("args/\(offset)")) + diagnostics.add( + .unconverted, location.appending("args/\(offset)"), + "Secret arguments require a typed argument binding slot; the argument literal is not retained." + ) + unrepresentableArgument = true + } + if argument.contains("${CLAUDE_PLUGIN_ROOT}") || argument.contains("${extensionPath}") { + diagnostics.add( + .unconverted, location.appending("args/\(offset)"), + "Native argument resource substitution has no typed canonical argument-resource slot; no extraction path is substituted." + ) + unrepresentableArgument = true + } + } + if unrepresentableArgument { continue } + let environmentKey = agent == .opencode ? "environment" : "env" + var environment = try NativeImportInput.bindings( + fields[environmentKey], at: location.appending(environmentKey), into: &diagnostics, + profile: parsed.input.profile) + if agent == .codex, let value = fields["env_vars"] { + guard let variables = value.importStrings else { throw ImportReadFailure.invalid } + for (offset, variable) in variables.enumerated() { + guard + variable.range(of: #"^[A-Za-z_][A-Za-z0-9_]*$"#, options: .regularExpression) + != nil, + environment[variable] == nil + else { throw ImportReadFailure.invalid } + environment[variable] = NativeImportInput.binding( + location.appending("env_vars/\(offset)"), environment: variable, into: &diagnostics) + } + } + var cwd: ResourceDeclaration? + if let value = fields["cwd"] { + guard [.codex, .geminiCLI, .opencode].contains(agent), + let authoredPath = value.importString + else { throw ImportReadFailure.invalid } + let path = try nativePath(authoredPath, container: container) + try NativeImportInput.resource( + path, root: container, input: parsed.input, origin: location.appending("cwd"), + limits: limits, into: &diagnostics, admission: parsed.admission) + cwd = .init(path: path, source: "native-input") + } + if parsed.input.profile == .claudePluginV1, executable.hasPrefix("${CLAUDE_PLUGIN_ROOT}/") + { + executable = "./" + executable.dropFirst("${CLAUDE_PLUGIN_ROOT}/".count) + } else if parsed.input.profile == .geminiExtensionV1, + executable.hasPrefix("${extensionPath}/") + { + executable = "./" + executable.dropFirst("${extensionPath}/".count) + } + if executable.hasPrefix("./") { + let path = try nativePath(executable, container: container) + try NativeImportInput.resource( + path, root: container, input: parsed.input, origin: location.appending("command"), + limits: limits, into: &diagnostics, admission: parsed.admission) + executable = path.contains("/") ? path : "./" + path + } else if executable.contains("/") { + diagnostics.add( + .unconverted, location.appending("command"), + "Native executable outside the explicit container requires a caller-selected resource; no host executable is read." + ) + continue + } + transport = .stdio( + .init( + executable: executable, + executableSource: executable.contains("/") ? "native-input" : nil, + arguments: arguments, environment: environment, + workingDirectory: cwd)) + } + var resourceCoordinates: [String] = [] + if case .stdio(let run) = transport { + if run.executable.contains("/") { resourceCoordinates.append(run.executable) } + if let cwd = run.workingDirectory { resourceCoordinates.append(cwd.path) } + } + try NativeImportSemantics.mcp( + name: name, transport: transport, native: native[agent.rawValue] ?? [:], + profile: parsed.input.profile, resources: resourceCoordinates) + if let bearer = extra["bearer_token_env_var"]?.importString { + _ = NativeImportInput.binding( + location.appending("bearer_token_env_var"), environment: bearer, canonical: false, + into: &diagnostics) + } + NativeImportInput.emit( + .mcpServer(name: name, transport: transport, agents: [agent], native: native), + selector: .mcpServer(name: name), origin: location, container: container, + profile: parsed.input.profile, into: &diagnostics) + } catch let issue as NativeAdapterIssue { + diagnostics.add( + issue.reason == .invalid ? .invalidInput : .unconverted, location, + "The native field profile cannot preserve this member's field or default semantics." + ) + } catch is CancellationError { throw CancellationError() } catch CoreError.unsafePath { + diagnostics.add(.unsafePath, location, "Native resource escapes its format-owned root.") + } catch { + diagnostics.add( + .invalidInput, location, + "Native MCP member is malformed or its resource is missing; no partial server is imported." + ) + } + } + } + + static func nativePath(_ path: String, container: String) throws -> String { + guard !path.hasPrefix("/"), !path.hasPrefix("~"), !path.contains("://"), + !path.split(separator: "/").contains("..") + else { throw CoreError.unsafePath("native resource") } + return try ImportInput.path(path) + } + + private static func openCodeMembers( + _ value: NativeValue, kind: String, + parsed: NativeImportDocument, key: String, into diagnostics: inout ImportDiagnostics + ) throws { + guard case .object(let entries) = value else { throw ImportReadFailure.invalid } + try classifyMembers(value, parsed: parsed, keys: [key], into: &diagnostics) + for (index, name) in entries.keys.sorted().enumerated() { + let origin = parsed.location([key, name], display: "/\(key)/member[\(index)]") + let choice = NativeImportInput.name(name) ? diagnostics.beginChoice(name, at: origin) : nil + defer { if let choice { diagnostics.endChoice(choice) } } + guard parsed.input.enumerateChoices || (parsed.input.selection?.contains(name) ?? true) else { + continue + } + guard NativeImportInput.name(name), let fields = entries[name]?.importObject else { + NativeImportInput.unconverted(entries[name]!, at: origin, into: &diagnostics) + continue + } + let bodyKey = kind == "command" ? "template" : "system" + let allowed: Set = + kind == "command" + ? ["template", "description"] : ["system", "description", "mode", "model"] + NativeImportInput.unknown(fields, allowed: allowed, at: origin, into: &diagnostics) + guard Set(fields.keys).isSubset(of: allowed), let body = fields[bodyKey]?.importString, + fields["description"] == nil || fields["description"]?.importString != nil, + fields["model"] == nil || fields["model"]?.importString != nil, + kind == "command" || fields["mode"] == .string("subagent") + else { + NativeImportInput.unconverted(entries[name]!, at: origin, into: &diagnostics) + continue + } + let description = fields["description"]?.importString ?? "" + if kind == "command" { + NativeImportInput.emit( + .command( + name: name, description: description, prompt: .literal(body), agents: [.opencode]), + selector: .command(name: name), origin: origin, container: ".", + profile: parsed.input.profile, into: &diagnostics) + } else { + NativeImportInput.emit( + .subagent( + name: name, description: description, prompt: .literal(body), + model: fields["model"]?.importString, agents: [.opencode]), + selector: .subagent(name: name), origin: origin, container: ".", + profile: parsed.input.profile, into: &diagnostics) + } + } + } + + private static func permissions( + _ value: NativeValue, parsed: NativeImportDocument, + into diagnostics: inout ImportDiagnostics + ) { + guard case .array(let entries) = value else { + NativeImportInput.unconverted(value, at: parsed.location(["permissions"]), into: &diagnostics) + return + } + var rules: [PermissionRuleDeclaration] = [] + for (index, entry) in entries.enumerated() { + guard let fields = entry.importObject, Set(fields.keys) == ["action", "resource", "effect"], + let action = fields["action"]?.importString, + let resource = fields["resource"]?.importString, + let effect = fields["effect"]?.importString, ["allow", "ask", "deny"].contains(effect) + else { + NativeImportInput.unconverted( + entry, at: parsed.location(["permissions"]).appending(String(index)), into: &diagnostics) + return + } + switch effect { + case "allow": rules.append(.allow(.tool(action), resource)) + case "ask": rules.append(.ask(.tool(action), resource)) + default: rules.append(.deny(.tool(action), resource)) + } + } + NativeImportInput.emit( + .permissions(name: "native-policy", rules: rules, agents: [.opencode]), + selector: .permissions(name: "native-policy"), origin: parsed.location(["permissions"]), + container: ".", profile: parsed.input.profile, into: &diagnostics) + } + + private static func codexAgents( + _ value: NativeValue, parsed: NativeImportDocument, + limits: SourceImportLimits, into diagnostics: inout ImportDiagnostics + ) throws { + guard case .object(let agents) = value else { throw ImportReadFailure.invalid } + try classifyMembers(value, parsed: parsed, keys: ["agents"], into: &diagnostics) + for (index, name) in agents.keys.sorted().enumerated() { + let origin = parsed.location(["agents", name], display: "/agents/member[\(index)]") + let choice = NativeImportInput.name(name) ? diagnostics.beginChoice(name, at: origin) : nil + defer { if let choice { diagnostics.endChoice(choice) } } + guard parsed.input.enumerateChoices || (parsed.input.selection?.contains(name) ?? true) else { + continue + } + guard NativeImportInput.name(name), let fields = agents[name]?.importObject, + Set(fields.keys).isSubset(of: ["description", "config_file"]), + let description = fields["description"]?.importString, + let file = fields["config_file"]?.importString + else { + NativeImportInput.unconverted(agents[name]!, at: origin, into: &diagnostics) + continue + } + // Codex role paths are relative to the declaring config directory, unlike plugin paths. + let parent = (parsed.input.document as NSString).deletingLastPathComponent + let relative = try nativePath(file, container: parent) + let path = parent.isEmpty ? relative : parent + "/" + relative + var request = parsed.input + request = .init(profile: request.profile, root: request.root, document: path) + let role = try NativeImportDocument( + request, format: .toml, limits: limits, admission: parsed.admission) + NativeImportInput.unknown( + role.fields, allowed: ["developer_instructions", "model"], at: role.location(), + into: &diagnostics) + guard Set(role.fields.keys).isSubset(of: ["developer_instructions", "model"]), + let body = role.fields["developer_instructions"]?.importString + else { continue } + NativeImportInput.emit( + .subagent( + name: name, description: description, prompt: .literal(body), + model: role.fields["model"]?.importString, agents: [.codex]), + selector: .subagent(name: name), origin: role.location(["developer_instructions"]), + container: ".", profile: parsed.input.profile, into: &diagnostics) + try NativeImportInput.resource( + path, root: ".", input: parsed.input, origin: role.location(), limits: limits, + into: &diagnostics, admission: parsed.admission) + } + } +} diff --git a/Sources/Components/Import/RulesyncConfigImport.swift b/Sources/Components/Import/RulesyncConfigImport.swift new file mode 100644 index 0000000..7f9ef7c --- /dev/null +++ b/Sources/Components/Import/RulesyncConfigImport.swift @@ -0,0 +1,731 @@ +import AgentsCore +import Foundation +import NativeDocuments + +struct ImportLocatedFailure: Error { let location: ImportLocation } + +struct ImportJSONC { + let input: SourceImportInput + let document: NativeDocument + let fields: [String: NativeValue] + + init(_ input: SourceImportInput, limits: SourceImportLimits) throws { + let bytes = try ImportInput.bytes(input, limits: limits) + guard limits.documentBytes >= 0, limits.documentBytes <= (Int.max - 1024) / 64, + limits.nodes > 0, limits.depth > 0 + else { throw ImportReadFailure.invalid } + let budget = NativeDocumentBudget( + limits: .init( + storage: limits.documentBytes * 32 + 1024, work: limits.documentBytes * 64 + 1024, + nodes: limits.nodes, depth: limits.depth, uninterruptedBytes: limits.documentBytes)) + do { + let document = try NativeDocument( + bytes: bytes, format: .jsonc(trailingCommas: true), budget: budget) + guard let observation = try document.read(.init(keys: [])), + observation.projectionFailure == nil, + case .object(let fields) = observation.value + else { throw ImportReadFailure.invalid } + self.input = input + self.document = document + self.fields = fields + } catch NativeDocumentError.cancelled { + throw CancellationError() + } catch NativeDocumentError.invalidDocument(_, let range) { + throw ImportLocatedFailure( + location: .init( + document: input.document, pointer: "", + span: range.map { importSpan(bytes, document: input.document, range: $0) })) + } + } + func location(_ field: String? = nil) -> ImportLocation { + let region = NativeRegion(keys: field.map { [$0] } ?? []) + let range = (try? document.read(region))?.valueRange + return .init( + document: input.document, pointer: field.map { "/" + $0 } ?? "", + span: range.map { importSpan(document.bytes, document: input.document, range: $0) }) + } +} + +func importSpan(_ bytes: Data, document: String, range: Range) -> SourceSpan { + var line = 1 + var start = 0 + var index = 0 + let end = min(range.lowerBound, bytes.count) + while index < end { + if bytes[index] == 13 { + if index + 1 < end, bytes[index + 1] == 10 { index += 1 } + line += 1 + start = index + 1 + } else if bytes[index] == 10 { + line += 1 + start = index + 1 + } + index += 1 + } + return .init( + document: .init(document), start: end, end: min(range.upperBound, bytes.count), line: line, + column: end - start + 1) +} + +extension NativeValue { + var importString: String? { if case .string(let value) = self { value } else { nil } } + var importStrings: [String]? { + guard case .array(let values) = self, values.allSatisfy({ $0.importString != nil }) else { + return nil + } + return values.compactMap(\.importString) + } + var importObject: [String: NativeValue]? { + if case .object(let value) = self { value } else { nil } + } +} + +enum RulesyncConfigImport { + static func npmSelector(_ value: String) -> Bool { + value.range( + of: #"^(@[a-z0-9~][a-z0-9._~-]*/)?[a-z0-9~][a-z0-9._~-]*$"#, options: .regularExpression) + != nil + } + + static func read( + _ input: SourceImportInput, limits: SourceImportLimits, + into diagnostics: inout ImportDiagnostics + ) throws { + try read(configs: [input], locks: [], limits: limits, into: &diagnostics) + } + + static func read( + configs: [SourceImportInput], locks: [SourceImportInput], limits: SourceImportLimits, + into diagnostics: inout ImportDiagnostics + ) throws { + guard !configs.isEmpty, configs.count <= 2, + configs.allSatisfy({ $0.profile == .rulesyncConfig }), + locks.allSatisfy({ [.rulesyncSourcesV1, .rulesyncNpmV1].contains($0.profile) }) + else { throw ImportReadFailure.invalid } + var effective: [String: (NativeValue, ImportJSONC)] = [:] + for input in configs { + let parsed = try ImportJSONC(input, limits: limits) + if parsed.fields["inputRoot"] != nil && parsed.fields["inputRoots"] != nil { + diagnostics.add( + .invalidInput, parsed.location(), + "inputRoot and inputRoots cannot coexist in one producer config.") + return + } + if parsed.fields["targets"]?.importObject != nil && parsed.fields["features"] != nil { + diagnostics.add( + .invalidInput, parsed.location("features"), + "Object-form targets cannot be combined with features.") + return + } + for (key, value) in parsed.fields { effective[key] = (value, parsed) } + for (index, key) in parsed.fields.keys.sorted().enumerated() + where !["sources", "inputRoot", "inputRoots", "targets", "features"].contains(key) { + let location = parsed.location().appending("member[\(index)]") + if ImportInput.credentialField(key) { diagnostics.binding(location) } + unconverted(parsed.fields[key]!, at: location, into: &diagnostics) + } + } + for field in ["targets", "features"] { + guard let (value, parsed) = effective[field] else { continue } + if field == "targets", let values = value.importStrings, values.allSatisfy(ImportInput.name) { + diagnostics.proposal.selections.append( + .init( + origin: parsed.location(field), sourceAlias: nil, kind: .targets, values: values, + automatic: false, developmentOnly: false)) + } + unconverted(value, at: parsed.location(field), into: &diagnostics) + } + if effective["targets"]?.0.importObject != nil, effective["features"] != nil { + diagnostics.add( + .invalidInput, effective["features"]!.1.location("features"), + "Object-form targets cannot be combined with features.") + return + } + var entries: [(ImportOrderedSource, SourceDeclaration?, String)] = [] + if let (value, parsed) = effective["sources"] { + guard case .array(let sources) = value else { throw ImportReadFailure.invalid } + // Producer occurrence keys belong to the complete declaration order, before filtering. + let keys = lockKeys(sources) + for (index, source) in sources.enumerated() { + let location = parsed.location("sources").appending(String(index)) + guard let object = source.importObject, let raw = object["source"]?.importString, + !raw.isEmpty, let key = keys[index] + else { + diagnostics.add(.invalidInput, location, "Expected a producer source entry.") + continue + } + for (ordinal, key) in object.keys.sorted().enumerated() + where ![ + "source", "skills", "rules", "transport", "ref", "path", "rulesPath", "registry", + "tokenEnv", + ].contains(key) { + let member = location.appending("member[\(ordinal)]") + if ImportInput.credentialField(key) { diagnostics.binding(member) } + unconverted(object[key]!, at: member, into: &diagnostics) + } + guard + ["transport", "ref", "path", "rulesPath", "registry", "tokenEnv"].allSatisfy({ + object[$0] == nil || object[$0]?.importString != nil + }) + else { + diagnostics.add( + .invalidInput, location, "Source fields require producer string identity.") + continue + } + let admissibleKey = + object["transport"]?.importString == "npm" + ? npmSelector(raw) : (ImportInput.safeLocator(raw) || githubLocator(raw) != nil) + let choice = admissibleKey ? diagnostics.beginChoice(raw, at: location) : nil + defer { if let choice { diagnostics.endChoice(choice) } } + if !parsed.input.enumerateChoices, let selection = parsed.input.selection, + !selection.contains(raw) + { + continue + } + let transport = object["transport"]?.importString ?? "github" + guard ["github", "git", "npm"].contains(transport), + object["skills"] == nil || object["skills"]?.importStrings != nil, + object["rules"] == nil || object["rules"]?.importStrings != nil, + object["ref"] == nil || object["ref"]?.importString != nil + else { + diagnostics.add(.invalidInput, location, "Invalid source transport or selection.") + continue + } + let emptySelections = ["skills", "rules"].filter { object[$0]?.importStrings == [] } + if !emptySelections.isEmpty { + for field in emptySelections { + diagnostics.add( + .invalidInput, location.appending(field), + "An empty producer selection invalidates the whole source; omit the feature or remove the source." + ) + } + continue + } + if object["registry"] != nil || object["tokenEnv"] != nil { + guard transport == "npm" else { + diagnostics.add( + .invalidInput, location, "Registry bindings are npm-only producer fields.") + continue + } + if let registry = object["registry"]?.importString { + guard ImportInput.safeLocator(registry) else { + diagnostics.binding(location.appending("registry")) + continue + } + guard let url = URLComponents(string: registry), + ["http", "https"].contains(url.scheme), url.host?.isEmpty == false + else { + diagnostics.add( + .invalidInput, location, "Registry requires an explicit HTTP(S) locator.") + continue + } + } + if let token = object["tokenEnv"]?.importString { + guard token.range(of: #"^[A-Za-z_][A-Za-z0-9_]*$"#, options: .regularExpression) != nil + else { + diagnostics.add( + .invalidInput, location, + "Registry token binding requires an environment variable name.") + continue + } + diagnostics.binding(location.appending("tokenEnv"), environmentVariable: token) + } + } + var ref = object["ref"]?.importString + var sourcePath = object["path"]?.importString + var declaration: SourceDeclaration? + var identity = raw + if transport == "github" { + if raw.contains("://"), !ImportInput.safeLocator(raw) { + diagnostics.binding(location.appending("source")) + } + guard let github = githubLocator(raw) else { + diagnostics.add( + .unconverted, location, "Unsupported or ambiguous GitHub source selector.") + continue + } + ref = ref ?? github.ref + sourcePath = sourcePath ?? github.path + identity = raw + declaration = .init(kind: .git, location: github.location) + } else if transport == "git" { + guard ImportInput.safeLocator(raw) else { + diagnostics.binding(location) + continue + } + guard (try? SourceDeclaration(kind: .git, location: raw).transportIdentity()) != nil + else { + diagnostics.add(.invalidInput, location, "Invalid explicit Git source locator.") + continue + } + declaration = .init(kind: .git, location: raw) + } else { + guard npmSelector(raw) + else { + diagnostics.add(.invalidInput, location, "Invalid npm source package selector.") + continue + } + diagnostics.add( + .unconverted, location, + "Experimental npm source requires locked archive and captured content.") + } + if let ref, + ref.hasPrefix("-") + || ref.unicodeScalars.contains(where: { CharacterSet.controlCharacters.contains($0) }) + { + diagnostics.add(.invalidInput, location, "Invalid requested producer ref.") + continue + } + let skillsPath = sourcePath ?? "skills" + let rulesPath = object["rulesPath"]?.importString ?? "rules" + guard !skillsPath.contains(".."), !rulesPath.contains(".."), + (try? ImportInput.path(skillsPath)) != nil, (try? ImportInput.path(rulesPath)) != nil + else { + diagnostics.add( + .unsafePath, location, "Source paths must remain within their repository.") + continue + } + let intent = ImportOrderedSource( + origin: location, alias: "rulesync-source-\(index)", identity: identity, + transport: transport, registry: object["registry"]?.importString, requestedRef: ref, + skillsPath: skillsPath, rulesPath: rulesPath, + skills: object["skills"]?.importStrings ?? (object["rules"] == nil ? ["*"] : nil), + rules: object["rules"]?.importStrings?.map { + $0.hasSuffix(".md") ? String($0.dropLast(3)) : $0 + }) + entries.append((intent, declaration, key)) + diagnostics.proposal.orderedSources.append(intent) + } + } + var locked: [String: (ImportedSource, [ImportResourceProposal], [String: Any])] = [:] + for lock in locks { + var request = lock + for entry in entries + where (entry.0.transport == "npm") == (lock.profile == .rulesyncNpmV1) { + if let declaration = entry.1 { request.sourceDeclarations[entry.2] = declaration } + } + var result = ImportDiagnostics(proposal: .init(profile: lock.profile)) + let fields = try ImportInput.document(request, limits: limits) + try RulesyncSourceImport.read(fields, input: request, into: &result) + diagnostics.proposal.diagnostics += result.proposal.diagnostics + diagnostics.proposal.bindings += result.proposal.bindings + for source in result.proposal.sources where !source.alias.contains("-skill-") { + // Lookup uses exact producer lock coordinates; a normalized repository is not enough. + let map = fields["sources"] as? [String: Any] ?? [:] + let sorted = map.keys.sorted() + guard let ordinal = Int(source.alias.replacingOccurrences(of: "import-source-", with: "")), + ordinal < sorted.count + else { continue } + let key = (lock.profile == .rulesyncNpmV1 ? "npm:" : "git:") + sorted[ordinal] + if locked[key] != nil { + diagnostics.add(.ambiguousSource, source.origin, "Duplicate explicit lock identity.") + continue + } + locked[key] = ( + source, result.proposal.resources.filter { $0.sourceAlias == source.alias }, + map[sorted[ordinal]] as? [String: Any] ?? [:] + ) + } + } + let declaredKeys = Set( + entries.map { ($0.0.transport == "npm" ? "npm:" : "git:") + $0.2 }) + for key in locked.keys.sorted() where !declaredKeys.contains(key) { + diagnostics.add( + .unconverted, locked[key]!.0.origin, + "Lock entry is absent from the effective ordered source config.") + } + var winners: Set = [] + for (intent, declaration, lockKey) in entries { + let choice = diagnostics.beginChoice(intent.identity, at: intent.origin) + defer { diagnostics.endChoice(choice) } + let key = (intent.transport == "npm" ? "npm:" : "git:") + lockKey + var match = locked[key] + if let candidate = match { + let pathMatches = + (candidate.2["skillsPath"] as? String).map { + (try? ImportInput.path($0)) == (try? ImportInput.path(intent.skillsPath)) + } ?? true + let rulesMatch = + (candidate.2["rulesPath"] as? String).map { + (try? ImportInput.path($0)) == (try? ImportInput.path(intent.rulesPath)) + } ?? true + let refMatches = + intent.requestedRef == nil || intent.requestedRef == candidate.0.requestedRef + let registryMatches = + intent.registry == nil + || intent.registry?.trimmingCharacters(in: CharacterSet(charactersIn: "/")) + == candidate.0.registry?.trimmingCharacters(in: CharacterSet(charactersIn: "/")) + if !pathMatches || !rulesMatch || !refMatches || !registryMatches { + diagnostics.add( + .ambiguousSource, candidate.0.origin, + "Lock coordinates do not match the current ordered source declaration.") + match = nil + } + } + var exactDeclaration = declaration + if let commit = match?.0.pin.commit { exactDeclaration?.requirement = .revision(commit) } + diagnostics.proposal.sources.append( + .init( + alias: intent.alias, origin: intent.origin, declaration: exactDeclaration, + pin: match?.0.pin ?? .init(), requestedRef: intent.requestedRef, + producerPath: intent.skillsPath, producerIdentity: intent.identity, + registry: intent.registry ?? match?.0.registry, resolvedRef: match?.0.resolvedRef)) + if match == nil { + diagnostics.add( + .incompletePin, intent.origin, + "Ordered source has no matching explicitly supplied lock entry.") + } + for (resourceIndex, resource) in (match?.1 ?? []).enumerated() { + let kind = resource.kind == .instructions ? "rules" : "skills" + let selection = kind == "rules" ? intent.rules : intent.skills + guard selection == ["*"] || selection?.contains(resource.producerName) == true else { + diagnostics.add( + .unconverted, resource.origin, + "Locked artifact is outside the current explicit producer selection.") + continue + } + let collision = kind + ":" + resource.producerName + let selected = winners.insert(collision).inserted + if !selected { + diagnostics.add( + .unconverted, resource.origin, + "Earlier declared remote source wins this producer artifact collision.") + } + diagnostics.proposal.resources.append( + .init( + origin: resource.origin, sourceAlias: intent.alias, producerName: resource.producerName, + path: resource.path, producerIntegrity: resource.producerIntegrity, observedHash: nil, + executableFlags: [:], requiresStandaloneSource: true, kind: resource.kind, + selected: selected)) + if selected, resource.kind == .skills, let path = resource.path, var source = declaration { + let alias = intent.alias + "-skill-\(resourceIndex)" + source.path = path + source.requirement = match?.0.pin.commit.map(SourceRequirement.revision) + diagnostics.proposal.sources.append( + .init( + alias: alias, origin: resource.origin, declaration: source, + pin: match?.0.pin ?? .init(), requestedRef: intent.requestedRef, producerPath: path, + producerIdentity: intent.identity)) + diagnostics.proposal.components.append( + .init( + origin: resource.origin, + declaration: .skills(source: alias, .init(select: .names([resource.producerName]))))) + } + } + } + let roots: [(String, SourceImportInput, ImportLocation)] + if let (value, parsed) = effective["inputRoots"] { + guard let values = value.importStrings, !values.isEmpty else { + throw ImportReadFailure.invalid + } + roots = values.enumerated().map { + ($0.element, parsed.input, parsed.location("inputRoots").appending(String($0.offset))) + } + } else if let (value, parsed) = effective["inputRoot"] { + guard let value = value.importString else { throw ImportReadFailure.invalid } + roots = [ + ( + value == "." ? ".rulesync" : value + "/.rulesync", parsed.input, + parsed.location("inputRoot") + ) + ] + } else { + roots = [ + ( + ".rulesync", configs[0], + .init(document: configs[0].document, pointer: "/inputRoots/default") + ) + ] + } + try localContent(roots, limits: limits, into: &diagnostics) + } + + private static func unconverted( + _ value: NativeValue, at location: ImportLocation, into diagnostics: inout ImportDiagnostics + ) { + diagnostics.add( + .unconverted, location, + "Producer configuration semantics are not canonical installation intent.") + if let text = value.importString, text.contains("://"), !ImportInput.safeLocator(text) { + diagnostics.binding(location) + } + if case .object(let fields) = value { + for (index, key) in fields.keys.sorted().enumerated() { + let child = location.appending("member[\(index)]") + if ImportInput.credentialField(key) { + diagnostics.binding(child) + } + unconverted(fields[key]!, at: child, into: &diagnostics) + } + } else if case .array(let values) = value { + for (index, item) in values.enumerated() { + unconverted(item, at: location.appending(String(index)), into: &diagnostics) + } + } + } + + static func githubLocator(_ raw: String) -> ( + location: String, ref: String?, path: String? + )? { + guard !raw.unicodeScalars.contains(where: { CharacterSet.controlCharacters.contains($0) }), + !raw.contains("?"), !raw.contains("#") + else { return nil } + if raw.hasPrefix("http://") || raw.hasPrefix("https://") { + guard ImportInput.safeLocator(raw), let url = URLComponents(string: raw), + let host = url.host?.lowercased(), + ["github.com", "www.github.com", "gitlab.com", "www.gitlab.com"].contains(host) + else { return nil } + let parts = url.percentEncodedPath.split(separator: "/").map(String.init) + guard parts.count >= 2, parts.prefix(2).allSatisfy(ImportInput.name) else { return nil } + let repo = parts[1].hasSuffix(".git") ? String(parts[1].dropLast(4)) : parts[1] + let location = + "https://" + (host.contains("gitlab") ? "gitlab.com" : "github.com") + "/" + parts[0] + "/" + + repo + if parts.count > 2, ["tree", "blob"].contains(parts[2]) { + guard parts.count > 3, let ref = parts[3].removingPercentEncoding else { return nil } + let path = + parts.count > 4 ? parts.dropFirst(4).joined(separator: "/").removingPercentEncoding : nil + if parts.count > 4 && path == nil { return nil } + return (location, ref, path) + } + return (location, nil, nil) + } + var value = raw + var host = "github.com" + for provider in ["github", "gitlab"] where value.hasPrefix(provider + ":") { + host = provider + ".com" + value.removeFirst(provider.count + 1) + break + } + let pathParts = value.split(separator: ":", maxSplits: 1, omittingEmptySubsequences: false) + let refParts = pathParts[0].split( + separator: "@", maxSplits: 1, omittingEmptySubsequences: false) + let parts = refParts[0].split(separator: "/").map(String.init) + guard parts.count >= 2, + parts.allSatisfy({ $0.range(of: #"^[A-Za-z0-9._-]+$"#, options: .regularExpression) != nil }), + !value.contains("?"), + pathParts.count < 2 || !pathParts[1].isEmpty, refParts.count < 2 || !refParts[1].isEmpty + else { return nil } + return ( + "https://" + host + "/" + parts.joined(separator: "/"), + refParts.count == 2 ? String(refParts[1]) : nil, + pathParts.count == 2 ? String(pathParts[1]) : nil + ) + } + + private static func normalizedKey(_ value: String) -> String { + var result = value + for prefix in [ + "https://www.github.com/", "https://github.com/", "http://www.github.com/", + "http://github.com/", "https://www.gitlab.com/", "https://gitlab.com/", + "http://www.gitlab.com/", "http://gitlab.com/", + ] where result.lowercased().hasPrefix(prefix) { + result.removeFirst(prefix.count) + break + } + for prefix in ["github:", "gitlab:"] where result.hasPrefix(prefix) { + result.removeFirst(prefix.count) + break + } + while result.hasSuffix("/") { result.removeLast() } + if result.hasSuffix(".git") { result.removeLast(4) } + return result.lowercased() + } + private static func lockKeys(_ sources: [NativeValue]) -> [String?] { + let fields = sources.map(\.importObject) + let bare = fields.map { $0?["source"]?.importString.map(normalizedKey) } + var counts: [String: Int] = [:] + for index in sources.indices where fields[index]?["transport"]?.importString != "npm" { + if let key = bare[index] { counts[key, default: 0] += 1 } + } + var occurrences: [String: Int] = [:] + let allowed = CharacterSet( + charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.!~*'()/") + return sources.indices.map { index in + guard let object = fields[index], let key = bare[index] else { return nil } + guard object["transport"]?.importString != "npm", counts[key, default: 0] > 1 else { + return key + } + var qualifiers: [String] = [] + for field in ["path", "rulesPath", "ref"] { + guard var value = object[field]?.importString else { continue } + if field != "ref" { value = (try? ImportInput.path(value)) ?? value } + qualifiers.append( + field + "=" + (value.addingPercentEncoding(withAllowedCharacters: allowed) ?? "")) + } + let base = key + (qualifiers.isEmpty ? "" : "#" + qualifiers.joined(separator: "&")) + occurrences[base, default: 0] += 1 + let occurrence = occurrences[base]! + return occurrence == 1 + ? base : base + (qualifiers.isEmpty ? "#" : "&") + "entry=\(occurrence)" + } + } + + private static func localContent( + _ roots: [(String, SourceImportInput, ImportLocation)], limits: SourceImportLimits, + into diagnostics: inout ImportDiagnostics + ) throws { + struct Candidate { + let name: String + let path: String + let input: SourceImportInput + let origin: ImportLocation + let skill: Bool + } + var candidates: [String: Candidate] = [:] + var remaining = limits.resourceEntries + var seenRoots: Set = [] + for (rootIndex, root) in roots.enumerated() { + let (path, input, origin) = root + guard let relative = try? ImportInput.path(path) else { + diagnostics.add(.unsafePath, origin, "Input root must stay within its explicit boundary.") + continue + } + let view = try ImportInput.snapshot(input.root) + let directory = try view.resource(relative) + guard seenRoots.insert(directory.standardizedFileURL.path).inserted else { continue } + guard FileManager.default.fileExists(atPath: directory.path) else { + if rootIndex == 0 { + diagnostics.add(.missingResource, origin, "Primary rulesync input root is absent.") + } + continue + } + func children(_ path: String) throws -> [String] { + let file = try view.resource(path) + guard FileManager.default.fileExists(atPath: file.path) else { return [] } + guard + let iterator = FileManager.default.enumerator( + at: file, includingPropertiesForKeys: nil, options: [.skipsSubdirectoryDescendants]) + else { throw ImportReadFailure.invalid } + var values: [String] = [] + for case let entry as URL in iterator { + try Task.checkCancellation() + guard remaining > 0 else { throw ImportReadFailure.invalid } + remaining -= 1 + values.append(entry.lastPathComponent) + } + return values.sorted() + } + for (folder, skill) in [("skills", true), ("rules", false)] { + for curated in [true, false] { + let base = relative + "/" + folder + (curated ? "/.curated" : "") + for (ordinal, child) in try children(base).enumerated() where child != ".curated" { + let location = origin.appending( + "\(folder)/\(curated ? "curated" : "local")/member[\(ordinal)]") + guard ImportInput.name(child), skill || child.hasSuffix(".md") else { + diagnostics.add(.unconverted, location, "Unrecognized rulesync source artifact.") + continue + } + let itemPath = base + "/" + child + let file = try view.resource(itemPath) + let attributes = try FileManager.default.attributesOfItem(atPath: file.path) + guard attributes[.type] as? FileAttributeType == (skill ? .typeDirectory : .typeRegular) + else { + diagnostics.add( + .unsafePath, location, "Rulesync source artifact is not admitted regular content.") + continue + } + let name = skill ? child : String(child.dropLast(3)) + let key = folder + ":" + name + if let previous = candidates[key] { + diagnostics.add( + .unconverted, previous.origin, + "Producer precedence selects local over curated and later input roots over earlier roots." + ) + } + candidates[key] = Candidate( + name: name, path: itemPath, input: input, origin: location, skill: skill) + } + } + } + for (ordinal, child) in try children(relative).enumerated() + where !["skills", "rules"].contains(child) { + diagnostics.add( + .unconverted, origin.appending("member[\(ordinal)]"), + "Source tree item requires its producer component/native adapter.") + } + } + for (index, key) in candidates.keys.sorted().enumerated() { + let candidate = candidates[key]! + let alias = "rulesync-local-\(index)" + if candidate.skill { + do { + let content = try ImportSkillContent.read( + candidate.path, input: candidate.input, limits: limits) + diagnostics.proposal.diagnostics += content.diagnostics + diagnostics.proposal.bindings += content.bindings + for resourceIndex in diagnostics.proposal.resources.indices { + let resource = diagnostics.proposal.resources[resourceIndex] + if resource.selected, resource.producerName == candidate.name, + resource.kind == (candidate.skill ? .skills : .instructions) + { + diagnostics.proposal.resources[resourceIndex].selected = false + diagnostics.proposal.components.removeAll { $0.origin == resource.origin } + diagnostics.add( + .unconverted, resource.origin, + "Explicit local source content supersedes the remote curated artifact.") + } + } + diagnostics.proposal.sources.append( + .init( + alias: alias, origin: candidate.origin, + declaration: .init( + kind: .local, location: candidate.path, + environment: .init( + projectDirectory: candidate.input.root, homeDirectory: candidate.input.root)), + pin: .init(), requestedRef: nil, producerPath: candidate.path)) + diagnostics.proposal.components.append( + .init( + origin: candidate.origin, + declaration: .skills( + source: alias, + .init(select: .names([content.skill.name]), condition: content.skill.condition)))) + diagnostics.proposal.resources.append( + .init( + origin: candidate.origin, sourceAlias: alias, producerName: candidate.name, path: ".", + producerIntegrity: nil, observedHash: content.hash, executableFlags: content.flags, + requiresStandaloneSource: true, kind: candidate.skill ? .skills : .instructions)) + } catch is CancellationError { throw CancellationError() } catch { + diagnostics.add( + .invalidInput, candidate.origin, + "Selected skill content is not admitted within the explicit source boundary.") + } + } else { + var request = candidate.input + request = .init(profile: request.profile, root: request.root, document: candidate.path) + let bytes = try ImportInput.bytes(request, limits: limits) + let semantics = try ImportFrontmatter.inspect( + bytes, document: candidate.path, converted: [], profile: .rulesyncConfig, limits: limits) + diagnostics.proposal.diagnostics += semantics.diagnostics + diagnostics.proposal.bindings += semantics.bindings + for resourceIndex in diagnostics.proposal.resources.indices { + let resource = diagnostics.proposal.resources[resourceIndex] + if resource.selected, resource.producerName == candidate.name, + resource.kind == (candidate.skill ? .skills : .instructions) + { + diagnostics.proposal.resources[resourceIndex].selected = false + diagnostics.proposal.components.removeAll { $0.origin == resource.origin } + diagnostics.add( + .unconverted, resource.origin, + "Explicit local source content supersedes the remote curated artifact.") + } + } + diagnostics.proposal.sources.append( + .init( + alias: alias, origin: candidate.origin, + declaration: .init(kind: .local, location: candidate.input.root.path), pin: .init(), + requestedRef: nil, producerPath: nil)) + diagnostics.proposal.resources.append( + .init( + origin: candidate.origin, sourceAlias: alias, producerName: candidate.name, + path: candidate.path, producerIntegrity: nil, + observedHash: "sha256:" + FileHash.sha256Hex(data: bytes), executableFlags: [:], + requiresStandaloneSource: true, kind: candidate.skill ? .skills : .instructions)) + diagnostics.add( + .unconverted, candidate.origin, + "Rulesync rule frontmatter and generation semantics require explicit conversion before canonical instructions." + ) + } + } + } +} diff --git a/Sources/Components/Import/RulesyncSourceImport.swift b/Sources/Components/Import/RulesyncSourceImport.swift new file mode 100644 index 0000000..0a75d28 --- /dev/null +++ b/Sources/Components/Import/RulesyncSourceImport.swift @@ -0,0 +1,260 @@ +import AgentsCore +import Foundation + +enum RulesyncSourceImport { + static func read( + _ fields: [String: Any], input: SourceImportInput, into diagnostics: inout ImportDiagnostics + ) throws { + let origin = ImportLocation(document: input.document, pointer: "") + guard ImportInput.version(fields["lockfileVersion"], equals: 1) else { + diagnostics.add( + .unsupportedVersion, origin.appending("lockfileVersion"), "Expected lock version 1.") + return + } + diagnostics.unknown(fields, allowed: ["lockfileVersion", "sources"], at: origin) + guard let sources = fields["sources"] as? [String: Any] else { + diagnostics.add(.invalidInput, origin.appending("sources"), "Expected a source map.") + return + } + let npm = input.profile == .rulesyncNpmV1 + if npm { + diagnostics.add( + .unconverted, origin, "This npm source lock is an experimental producer format.") + } + for (index, key) in sources.keys.sorted().enumerated() { + try Task.checkCancellation() + let location = origin.appending("sources/member[\(index)]") + let repositoryKey = key.components(separatedBy: "#")[0] + let admissibleKey = + npm + ? RulesyncConfigImport.npmSelector(key) + : (ImportInput.safeLocator(repositoryKey) + || RulesyncConfigImport.githubLocator(repositoryKey) != nil) + let choice = admissibleKey ? diagnostics.beginChoice(key, at: location) : nil + defer { if let choice { diagnostics.endChoice(choice) } } + guard input.enumerateChoices || (input.selection?.contains(key) ?? true) else { continue } + if admissibleKey, !npm, input.sourceDeclarations[key] == nil { + diagnostics.requireInput(.gitSource, key: key, at: location) + } + guard let entry = sources[key] as? [String: Any] else { + diagnostics.add(.invalidInput, location, "Expected a locked source object.") + continue + } + diagnostics.unknown( + entry, + allowed: Set([ + "requestedRef", "resolvedRef", "requestedVersion", "resolvedVersion", "registry", + "integrity", "resolvedAt", "skills", "skillSelection", "skillsPath", "rules", + "ruleSelection", "rulesPath", "resolvedRuleNames", + ]).subtracting( + npm + ? ["requestedRef", "resolvedRef"] + : [ + "requestedVersion", "resolvedVersion", "registry", "integrity", + ]), at: location) + guard + diagnostics.typedFields( + entry, + strings: npm + ? [ + "requestedVersion", "resolvedVersion", "registry", "integrity", "resolvedAt", + "skillsPath", "rulesPath", + ] + : ["requestedRef", "resolvedRef", "resolvedAt", "skillsPath", "rulesPath"], + required: npm ? ["resolvedVersion"] : ["resolvedRef"], + arrays: ["skillSelection", "ruleSelection", "resolvedRuleNames"], at: location) + else { continue } + let commit = npm ? nil : ImportInput.hex(ImportInput.string(entry["resolvedRef"]), count: 40) + let version = npm ? ImportInput.string(entry["resolvedVersion"]) : nil + let integrity = npm ? sri(ImportInput.string(entry["integrity"])) : nil + let requested = ImportInput.string(entry[npm ? "requestedVersion" : "requestedRef"]) + if npm ? (!ImportInput.packageVersion(version) || integrity == nil) : commit == nil { + diagnostics.add( + .incompletePin, location, + npm + ? "Exact package version and tarball SRI are required for complete package provenance." + : "Only a full lowercase resolvedRef commit proves this Git pin.") + } + if let registry = ImportInput.string(entry["registry"]), !ImportInput.safeLocator(registry) { + diagnostics.binding(location.appending("registry")) + continue + } + let repository = key.components(separatedBy: "#")[0] + if npm, + key.range( + of: #"^(@[a-z0-9~][a-z0-9._~-]*/)?[a-z0-9~][a-z0-9._~-]*$"#, options: .regularExpression) + == nil + { + diagnostics.add(.invalidInput, location, "Expected an npm package name as source key.") + continue + } + if !npm, !ImportInput.safeLocator(repository), + RulesyncConfigImport.githubLocator(repository) == nil + { + diagnostics.binding(location) + continue + } + if !npm, repository != key, input.sourceDeclarations[key] == nil { + diagnostics.add( + .unconverted, location, + "Qualified source-key selection requires its ordered producer config; only repository identity is retained." + ) + } + var source = input.sourceDeclarations[key] + if let declaration = source, !ImportInput.safeLocator(declaration.location) { + diagnostics.binding(location) + continue + } + if npm { + source = nil + diagnostics.add( + .unconverted, location, + "npm transport requires captured content before canonical source creation.") + } else if source == nil { + diagnostics.add( + .ambiguousSource, location, + "A normalized source lock key does not establish the original provider and transport; supply the source declaration." + ) + } else if source?.kind != .git { + diagnostics.add( + .invalidInput, location, "Git source locks require a Git source declaration.") + source = nil + } + if let commit, source != nil { source?.requirement = .revision(commit) } + let alias = "import-source-\(index)" + diagnostics.proposal.sources.append( + .init( + alias: alias, origin: location, declaration: source, + pin: .init( + commit: commit, version: ImportInput.packageVersion(version) ? version : nil, + integrity: integrity), + requestedRef: requested, producerPath: nil, producerIdentity: npm ? key : repository, + registry: ImportInput.string(entry["registry"]), + resolvedRef: npm ? nil : ImportInput.string(entry["resolvedRef"]))) + for field in ["skillSelection", "ruleSelection", "resolvedRuleNames"] + where entry[field] != nil { + // Lock artifact maps are concrete resources, while selections describe producer intent. + diagnostics.add( + .unconverted, location.appending(field), + "Producer selection is not a canonical all-member declaration.") + } + try artifacts( + entry, field: "skills", pathField: "skillsPath", alias: alias, source: source, + location: location, into: &diagnostics) + if entry["rules"] != nil { + try artifacts( + entry, field: "rules", pathField: "rulesPath", alias: alias, source: source, + location: location, into: &diagnostics) + } + for field in ["resolvedAt"] where entry[field] != nil { + diagnostics.add( + .unconverted, location.appending(field), + "Producer resolution bookkeeping is not imported.") + } + } + if let selection = input.selection, !selection.isSubset(of: Set(sources.keys)) { + diagnostics.add( + .invalidInput, origin.appending("sources"), + "A selected source is absent from this document.") + } + } + + private static func artifacts( + _ entry: [String: Any], field: String, pathField: String, alias: String, + source: SourceDeclaration?, location: ImportLocation, into diagnostics: inout ImportDiagnostics + ) throws { + let location = location.appending(field) + guard let artifacts = entry[field] as? [String: Any] else { + diagnostics.add(.invalidInput, location, "Expected an artifact integrity map.") + return + } + let rawPath = ImportInput.string(entry[pathField]) ?? source?.path + let path: String? + do { path = try rawPath.map(ImportInput.path) } catch { + diagnostics.add( + .unsafePath, location, "Producer resource path must remain relative to its source.") + return + } + if path == nil { + diagnostics.add( + .unconverted, location, "Resource root is absent from this lock; supply its declared path.") + } + for (index, name) in artifacts.keys.sorted().enumerated() { + let item = location.appending("member[\(index)]") + guard ImportInput.name(name), let object = artifacts[name] as? [String: Any] else { + diagnostics.add(.invalidInput, item, "Expected a safe artifact name and integrity object.") + continue + } + diagnostics.unknown(object, allowed: ["integrity"], at: item) + let hash = ImportInput.string(object["integrity"]) + let integrity: ImportPin.Integrity? + if let hash, hash.hasPrefix("sha256-"), + ImportInput.hex(String(hash.dropFirst(7)), count: 64) != nil + { + integrity = .init(kind: .rulesyncSHA256, value: hash) + } else { + integrity = nil + diagnostics.add( + .incompletePin, item.appending("integrity"), + "Artifact SHA-256 integrity is missing or invalid.") + } + let selection = ImportInput.strings(entry["skillSelection"]) + let memberDirectory = selection.map { $0 == ["*"] || $0.count > 1 } ?? false + let resourcePath: String? + if let path, field == "rules" || memberDirectory { + let file = field == "rules" ? name + ".md" : name + resourcePath = path == "." ? file : path + "/" + file + } else { + resourcePath = nil + if path != nil { + diagnostics.add( + .unconverted, item, + "This selection can use producer root fallback; the lock does not prove the member resource path." + ) + } + } + diagnostics.proposal.resources.append( + .init( + origin: item, sourceAlias: alias, producerName: name, path: resourcePath, + producerIntegrity: integrity, observedHash: nil, executableFlags: [:], + requiresStandaloneSource: true, kind: field == "skills" ? .skills : .instructions)) + if field == "skills", let source, let resourcePath { + // Each resource root gets its own alias: canonical discovery paths belong to sources. + let itemAlias = alias + "-skill-\(index)" + var declaration = source + declaration.path = resourcePath + diagnostics.proposal.sources.append( + .init( + alias: itemAlias, origin: item, declaration: declaration, + pin: diagnostics.proposal.sources.first(where: { $0.alias == alias })!.pin, + requestedRef: diagnostics.proposal.sources.first(where: { $0.alias == alias })! + .requestedRef, + producerPath: resourcePath, + producerIdentity: diagnostics.proposal.sources.first(where: { $0.alias == alias })! + .producerIdentity)) + diagnostics.proposal.components.append( + .init( + origin: item, declaration: .skills(source: itemAlias, .init(select: .names([name]))))) + } else if field == "rules" { + diagnostics.add( + .unconverted, item, + "Rulesync rule frontmatter and targeting require semantic conversion before canonical instructions." + ) + } + } + } + + private static func sri(_ value: String?) -> ImportPin.Integrity? { + guard let value else { return nil } + let parts = value.split(separator: " ", omittingEmptySubsequences: true) + guard !parts.isEmpty else { return nil } + for part in parts { + let fields = part.split(separator: "-", maxSplits: 1) + guard fields.count == 2, + let size = ["sha256": 32, "sha384": 48, "sha512": 64][String(fields[0])], + let bytes = Data(base64Encoded: String(fields[1])), bytes.count == size + else { return nil } + } + return .init(kind: .npmSRI, value: value) + } +} diff --git a/Sources/Components/Import/SourceImport.swift b/Sources/Components/Import/SourceImport.swift new file mode 100644 index 0000000..03c4182 --- /dev/null +++ b/Sources/Components/Import/SourceImport.swift @@ -0,0 +1,85 @@ +import AgentsCore +import AgentsManifest +import Foundation + +package enum SourceImport { + package static func admitsSourceCoordinates(_ source: SourceDeclaration) -> Bool { + source.kind == .git && ImportInput.safeLocator(source.location) + && (try? source.transportIdentity()) != nil + && (source.path.map { (try? ImportInput.path($0)) != nil } ?? true) + } + + /// First explicit config is the project config; the optional second is its local override. + /// Each document retains its caller-selected boundary. No ambient config or lock is discovered. + package static func previewRulesync( + configs: [SourceImportInput], locks: [SourceImportInput] = [], + limits: SourceImportLimits = .init() + ) throws -> SourceImportProposal { + var diagnostics = ImportDiagnostics(proposal: .init(profile: .rulesyncConfig)) + do { + try RulesyncConfigImport.read( + configs: configs, locks: locks, limits: limits, into: &diagnostics) + } catch is CancellationError { throw CancellationError() } catch let failure + as ImportLocatedFailure + { + diagnostics.add(.invalidInput, failure.location, "Explicit JSONC input is not admitted.") + } catch CoreError.unsafePath { + diagnostics.add( + .unsafePath, .init(document: configs.first?.document ?? "", pointer: ""), + "Input path escapes its explicit root.") + } catch { + diagnostics.add( + .invalidInput, .init(document: configs.first?.document ?? "", pointer: ""), + "Explicit rulesync inputs are not admitted.") + } + diagnostics.finalizeBindings() + return diagnostics.proposal + } + + /// Reads only the chosen local document and explicitly supplied content. No source resolution, + /// component execution, config discovery, ownership inference or filesystem write occurs here. + package static func preview( + _ input: SourceImportInput, limits: SourceImportLimits = .init() + ) throws -> SourceImportProposal { + try Task.checkCancellation() + let origin = ImportLocation(document: input.document, pointer: "") + var diagnostics = ImportDiagnostics( + proposal: .init(profile: input.profile), bindingReferences: input.bindingReferences) + do { + _ = try ImportInput.path(input.document) + switch input.profile { + case .apmManifest, .apmLock, .rulesyncGitHubV1, .rulesyncAPMV1: + try YAMLSourceImport.read(input, limits: limits, into: &diagnostics) + case .rulesyncConfig: + try RulesyncConfigImport.read(input, limits: limits, into: &diagnostics) + case .rulesyncSourcesV1, .rulesyncNpmV1: + try RulesyncSourceImport.read( + ImportInput.document(input, limits: limits), input: input, into: &diagnostics) + case .claudeSettingsV1, .codexConfigV1, .cursorMCPV1, .geminiSettingsV1, .openCodeConfigV2, + .claudePluginV1, .cursorPluginV1, .geminiExtensionV1, .claudeMarketplaceV1, + .claudeCommandV1, .claudeAgentV1, .geminiCommandV1, .geminiAgentV1, + .openCodeCommandV2, .openCodeAgentV2, .cursorCommandV1, .cursorAgentV1, .geminiIgnoreV1, + .cursorIgnoreV1: + try NativeSourceImport.read(input, limits: limits, into: &diagnostics) + case .vercelProjectV2, .vercelUserV3: + try VercelSourceImport.read( + ImportInput.document(input, limits: limits), input: input, limits: limits, + into: &diagnostics) + } + } catch is CancellationError { throw CancellationError() } catch let failure as YAMLReadFailure + { + diagnostics.add( + .invalidInput, .init(document: input.document, pointer: "", span: failure.span), + "Input is not admitted YAML.") + } catch let failure as ImportLocatedFailure { + diagnostics.add(.invalidInput, failure.location, "Explicit JSONC input is not admitted.") + } catch CoreError.unsafePath { + diagnostics.add(.unsafePath, origin, "Input path escapes its explicit root.") + } catch { + diagnostics.add( + .invalidInput, origin, "Input is not an admitted, readable producer document.") + } + diagnostics.finalizeBindings() + return diagnostics.proposal + } +} diff --git a/Sources/Components/Import/SourceImportProposal.swift b/Sources/Components/Import/SourceImportProposal.swift new file mode 100644 index 0000000..82d2dd2 --- /dev/null +++ b/Sources/Components/Import/SourceImportProposal.swift @@ -0,0 +1,319 @@ +import AgentsCore +import Foundation + +/// Fixed input formats grounded in upstream source revisions or producer documentation. +package enum SourceImportProfile: String, Sendable { + case rulesyncSourcesV1, rulesyncNpmV1, vercelProjectV2, vercelUserV3 + case apmManifest, apmLock, rulesyncConfig, rulesyncGitHubV1, rulesyncAPMV1 + case claudeSettingsV1, codexConfigV1, cursorMCPV1, geminiSettingsV1, openCodeConfigV2 + case claudePluginV1, cursorPluginV1, geminiExtensionV1, claudeMarketplaceV1 + case claudeCommandV1, claudeAgentV1, geminiCommandV1, geminiAgentV1 + case openCodeCommandV2, openCodeAgentV2, cursorCommandV1, cursorAgentV1 + case geminiIgnoreV1, cursorIgnoreV1 + + package var specificationStatus: String { + switch self { + case .apmManifest, .apmLock: "APM working-draft profile; schema amendments are unratified" + case .rulesyncSourcesV1, .rulesyncNpmV1, .rulesyncConfig, .rulesyncGitHubV1, .rulesyncAPMV1, + .vercelProjectV2, .vercelUserV3: + "Pinned producer implementation format" + case .codexConfigV1: "Pinned Codex source format" + case .geminiSettingsV1, .geminiExtensionV1, .geminiCommandV1, .geminiAgentV1, .geminiIgnoreV1: + "Pinned Gemini CLI source format" + case .openCodeConfigV2, .openCodeCommandV2, .openCodeAgentV2: + "Pinned OpenCode source format" + case .claudeSettingsV1, .claudePluginV1, .claudeMarketplaceV1, .claudeCommandV1, .claudeAgentV1: + "Documented Claude Code format (https://code.claude.com/docs); upstream source revision unavailable" + case .cursorMCPV1, .cursorPluginV1, .cursorCommandV1, .cursorAgentV1, .cursorIgnoreV1: + "Documented Cursor format (https://cursor.com/docs); upstream source revision unavailable" + } + } + + /// Exact upstream source revision when available. Documentation-only profiles have no commit. + package var producerRevision: String? { + switch self { + case .rulesyncSourcesV1, .rulesyncNpmV1, .rulesyncConfig, .rulesyncGitHubV1, .rulesyncAPMV1: + "fbe4fe58334cab4e84b87f20d730d6450a35e0f7" + case .apmManifest, .apmLock: + "787a97cc52fbbcc344374e1567b2a1e5b8adf441" + case .vercelProjectV2, .vercelUserV3: + "e781cb4d07433dfe1d19e924ed45cc61738c55ec" + case .codexConfigV1: + "092d3acd6bec3e3a14bdc7e7a2810ab628ab759d" + case .geminiSettingsV1, .geminiExtensionV1, .geminiCommandV1, .geminiAgentV1, .geminiIgnoreV1: + "5a5c7180ff3f0a02511f54b54db7f228d4982a30" + case .openCodeConfigV2, .openCodeCommandV2, .openCodeAgentV2: + "fedc6f208aa2bd54c1019227214568083f6380ad" + case .claudeSettingsV1, .claudePluginV1, .claudeMarketplaceV1, .claudeCommandV1, .claudeAgentV1, + .cursorMCPV1, .cursorPluginV1, .cursorCommandV1, .cursorAgentV1, .cursorIgnoreV1: + nil + } + } +} + +package struct ImportLocation: Hashable, Sendable { + package let document: String + /// Object-map entries use sorted member ordinals, so credential-bearing keys are never echoed. + package let pointer: String + package var span: SourceSpan? = nil + + func appending(_ field: String) -> Self { + .init(document: document, pointer: pointer + "/" + field, span: span) + } +} + +package struct SourceImportDiagnostic: Equatable, Sendable { + package enum Code: String, Sendable { + case invalidInput, unsupportedVersion, unconverted, incompletePin, ambiguousSource + case unsafePath, credentialBinding, integrityMismatch, missingResource + } + package let code: Code + package let location: ImportLocation + /// Messages describe fields and semantics; they never interpolate imported values. + package let message: String +} + +package struct ImportBindingRequirement: Equatable, Sendable { + package let location: ImportLocation + package let reason: String + /// Symbolic producer binding only; the process environment is never read. + package var environmentVariable: String? = nil + /// Identifier used by RuntimeBinding.secret; the literal remains outside the proposal. + package var key: String? = nil + package var canonicalSlot = false +} + +package struct ImportPin: Equatable, Sendable { + package enum IntegrityKind: String, Sendable { + case rulesyncSHA256, npmSRI, vercelInstalledSHA256, githubTree, apmDigest + } + package struct Integrity: Equatable, Sendable { + package let kind: IntegrityKind + package let value: String + + package init(kind: IntegrityKind, value: String) { + self.kind = kind + self.value = value + } + } + package var commit: String? + package var version: String? + package var integrity: Integrity? +} + +package struct ImportedSource: Equatable, Sendable { + package let alias: String + package let origin: ImportLocation + package let declaration: SourceDeclaration? + package let pin: ImportPin + package let requestedRef: String? + package let resolvedRef: String? + package let resolvedURL: String? + package let developmentOnly: Bool + package let producerPath: String? + package let producerIdentity: String? + package let registry: String? + + init( + alias: String, origin: ImportLocation, declaration: SourceDeclaration?, pin: ImportPin, + requestedRef: String?, producerPath: String?, producerIdentity: String? = nil, + registry: String? = nil, resolvedRef: String? = nil, resolvedURL: String? = nil, + developmentOnly: Bool = false + ) { + self.alias = alias + self.origin = origin + self.declaration = declaration + self.pin = pin + self.requestedRef = requestedRef + self.resolvedRef = resolvedRef + self.resolvedURL = resolvedURL + self.developmentOnly = developmentOnly + self.producerPath = producerPath + self.producerIdentity = producerIdentity + self.registry = registry + } +} + +package struct ImportMemberCoordinate: Equatable, Sendable { + package let containerRoot: String + package let selector: ComponentReferenceDeclaration + package let profile: SourceImportProfile + package let formatVersion: Int + + /// Producer identifiers are byte identities, including canonically equivalent Unicode names. + package static func == (lhs: Self, rhs: Self) -> Bool { + guard lhs.containerRoot.utf8.elementsEqual(rhs.containerRoot.utf8), + lhs.profile == rhs.profile, lhs.formatVersion == rhs.formatVersion + else { return false } + switch (lhs.selector, rhs.selector) { + case (.skill(let left), .skill(let right)), + (.instruction(let left), .instruction(let right)), + (.mcpServer(let left), .mcpServer(let right)), + (.hook(let left), .hook(let right)), + (.subagent(let left), .subagent(let right)), + (.command(let left), .command(let right)), + (.lspServer(let left), .lspServer(let right)), + (.permissions(let left), .permissions(let right)), + (.ignore(let left), .ignore(let right)), + (.plugin(let left), .plugin(let right)): + return left.utf8.elementsEqual(right.utf8) + default: return false + } + } +} + +package struct ImportedComponent: Equatable, Sendable { + /// The original producer document, including inline declarations and referenced files. + package let origin: ImportLocation + package let declaration: ComponentDeclaration + package var member: ImportMemberCoordinate? = nil +} + +/// This is a preservation intention, not a retained object or an adoption receipt. E must freeze +/// independent authoring content before any target containing these bytes can be overwritten. +package struct ImportResourceProposal: Equatable, Sendable { + package let origin: ImportLocation + package let sourceAlias: String + package let producerName: String + /// Relative to the corresponding source root. Nil means exact producer coordinates are absent. + package let path: String? + package let producerIntegrity: ImportPin.Integrity? + package var observedHash: String? + package let executableFlags: [String: Bool] + package let requiresStandaloneSource: Bool + package var kind: DeclaredComponentKind? = nil + package var selected = true + /// E must reconstruct symbolic fields and keep the original freshness preimage private. + package var requiresBindingRewrite = false +} + +/// Producer package identity is provenance, not a component, source pin or deployment choice. +package struct ImportPackageMetadata: Equatable, Sendable { + package let name: String + package let version: String? + package let nameLocation: ImportLocation + package let versionLocation: ImportLocation? + + package init(name: String, nameLocation: ImportLocation) { + self.name = name + self.nameLocation = nameLocation + version = nil + versionLocation = nil + } + + package init( + name: String, version: String, nameLocation: ImportLocation, versionLocation: ImportLocation + ) { + self.name = name + self.version = version + self.nameLocation = nameLocation + self.versionLocation = versionLocation + } +} + +/// Canonical intent and evidence only. Raw documents and literal credentials never escape parsing. +/// Application, target ownership and adoption belong to the shared import lifecycle. +package struct SourceImportProposal: Equatable, Sendable { + package let profile: SourceImportProfile + package var packageMetadata: ImportPackageMetadata? = nil + package var sources: [ImportedSource] = [] + package var components: [ImportedComponent] = [] + package var resources: [ImportResourceProposal] = [] + package var diagnostics: [SourceImportDiagnostic] = [] + package var bindings: [ImportBindingRequirement] = [] + package var selections: [ImportProducerSelection] = [] + package var deployments: [ImportDeploymentEvidence] = [] + package var orderedSources: [ImportOrderedSource] = [] + package var choices: [ImportChoiceMetadata] = [] + package var requiredInputs: [ImportInputMetadata] = [] + package var preservationBindings: [ImportLocation] = [] +} + +package struct SourceImportInput: Sendable { + package let profile: SourceImportProfile + /// Caller-selected read boundary. Consuming preparation owns source stability and freshness. + package let root: URL + package let document: String + /// Nil selects every entry; empty selects none. JSON maps use producer keys, YAML lists use + /// decimal ordinals, and rulesync config sources use their explicit source selector. + package var selection: Set? = nil + package var enumerateChoices = false + package var bindingReferences: [String: RuntimeBinding] = [:] + /// Source lock keys do not reliably identify a transport/provider. These are explicit input, + /// normally supplied by the config adapter, and never inferred from a normalized lock key. + package var sourceDeclarations: [String: SourceDeclaration] = [:] + /// Actual content is read only from these explicitly supplied, input-root-relative paths. + package var installedSkills: [String: String] = [:] + + package init( + profile: SourceImportProfile, root: URL, document: String, selection: Set? = nil, + sourceDeclarations: [String: SourceDeclaration] = [:], installedSkills: [String: String] = [:] + ) { + self.profile = profile + self.root = root + self.document = document + self.selection = selection + self.sourceDeclarations = sourceDeclarations + self.installedSkills = installedSkills + } +} + +package struct SourceImportLimits: Sendable { + package var documentBytes = 16 * 1024 * 1024 + package var nodes = 200_000 + package var depth = 64 + package var resourceBytes = 64 * 1024 * 1024 + package var resourceEntries = 20_000 + package init() {} +} + +/// Producer intent is retained independently of canonical installation conditions. +package struct ImportProducerSelection: Equatable, Sendable { + package enum Kind: String, Sendable { case includes, targets, skills, rules } + package let origin: ImportLocation + package let sourceAlias: String? + package let kind: Kind + package let values: [String] + package let automatic: Bool + package let developmentOnly: Bool +} + +/// These are third-party deployment claims, never canonical ownership or adoption receipts. +package struct ImportDeploymentEvidence: Equatable, Sendable { + package let origin: ImportLocation + package let sourceAlias: String? + package let agent: String? + package let scope: String? + package let installDirectory: String? + package let files: [String] +} + +/// Declaration order governs remote source collisions, independently of lock-map order. +package struct ImportOrderedSource: Equatable, Sendable { + package let origin: ImportLocation + package let alias: String + package let identity: String + package let transport: String + package let registry: String? + package let requestedRef: String? + package let skillsPath: String + package let rulesPath: String + package let skills: [String]? + package let rules: [String]? +} + +package struct ImportChoiceMetadata: Equatable, Sendable { + package let key: String + package var locations: [ImportLocation] + package var components: [Int] = [] + package var sources: [Int] = [] + package var resources: [Int] = [] + package var diagnostics: [Int] = [] +} + +package struct ImportInputMetadata: Equatable, Sendable { + package enum Kind: String, Sendable { case gitSource, installedContent } + package let kind: Kind + package let key: String + package let location: ImportLocation +} diff --git a/Sources/Components/Import/VercelSourceImport.swift b/Sources/Components/Import/VercelSourceImport.swift new file mode 100644 index 0000000..83d07fe --- /dev/null +++ b/Sources/Components/Import/VercelSourceImport.swift @@ -0,0 +1,243 @@ +import AgentsCore +import Foundation + +enum VercelSourceImport { + static func read( + _ fields: [String: Any], input: SourceImportInput, limits: SourceImportLimits, + into diagnostics: inout ImportDiagnostics + ) throws { + let origin = ImportLocation(document: input.document, pointer: "") + let project = input.profile == .vercelProjectV2 + guard ImportInput.version(fields["version"], equals: project ? 2 : 3) else { + diagnostics.add( + .unsupportedVersion, origin.appending("version"), + "Lock version does not match the explicit profile.") + return + } + diagnostics.unknown( + fields, + allowed: project + ? ["version", "skills"] : ["version", "skills", "dismissed", "lastSelectedAgents"], + at: origin) + for field in ["dismissed", "lastSelectedAgents"] where fields[field] != nil { + diagnostics.add( + .unconverted, origin.appending(field), + "Global installer UI bookkeeping does not specify individual skill recipients.") + } + guard let skills = fields["skills"] as? [String: Any] else { + diagnostics.add(.invalidInput, origin.appending("skills"), "Expected a skill map.") + return + } + for (index, name) in skills.keys.sorted().enumerated() { + try Task.checkCancellation() + let location = origin.appending("skills/member[\(index)]") + let choice = ImportInput.name(name) ? diagnostics.beginChoice(name, at: location) : nil + defer { if let choice { diagnostics.endChoice(choice) } } + guard input.enumerateChoices || (input.selection?.contains(name) ?? true) else { continue } + var contentAdmitted = false + defer { + if ImportInput.name(name), !contentAdmitted { + diagnostics.requireInput(.installedContent, key: name, at: location) + } + } + guard ImportInput.name(name), let entry = skills[name] as? [String: Any], + let source = ImportInput.string(entry["source"]), + let sourceType = ImportInput.string(entry["sourceType"]) + else { + diagnostics.add( + .invalidInput, location, "Expected a safe skill name, source and sourceType.") + continue + } + diagnostics.unknown( + entry, + allowed: project + ? [ + "source", "sourceType", "sourceUrl", "ref", "skillPath", "version", "via", + "computedHash", "subagents", "wellKnownDigest", "installMode", + ] + : [ + "source", "sourceType", "sourceUrl", "ref", "skillPath", "skillFolderHash", + "installedAt", "updatedAt", "pluginName", "sourceBaseUrl", "wellKnownDigest", + "installMode", + ], + at: location) + guard + diagnostics.typedFields( + entry, + strings: project + ? [ + "source", "sourceType", "sourceUrl", "ref", "skillPath", "version", "via", + "computedHash", "wellKnownDigest", "installMode", + ] + : [ + "source", "sourceType", "sourceUrl", "ref", "skillPath", "skillFolderHash", + "installedAt", "updatedAt", "pluginName", "sourceBaseUrl", "wellKnownDigest", + "installMode", + ], + required: project + ? ["source", "sourceType", "computedHash"] + : ["source", "sourceType", "sourceUrl", "skillFolderHash", "installedAt", "updatedAt"], + arrays: project ? ["subagents"] : [], at: location) + else { continue } + let sourceURL = ImportInput.string(entry["sourceUrl"]) + // node_modules locks store an npm package identifier, not a credentialed URL. + let packageIdentifier = + sourceType == "node_modules" + && source.range( + of: #"^(@[a-z0-9~][a-z0-9._~-]*/)?[a-z0-9~][a-z0-9._~-]*$"#, + options: .regularExpression) != nil + guard packageIdentifier || ImportInput.safeLocator(source), + sourceURL.map(ImportInput.safeLocator) ?? project, + ImportInput.string(entry["sourceBaseUrl"]).map(ImportInput.safeLocator) ?? true + else { + diagnostics.binding(location.appending("sourceUrl")) + continue + } + let path: String? + do { path = try ImportInput.string(entry["skillPath"]).map(ImportInput.path) } catch { + diagnostics.add( + .unsafePath, location.appending("skillPath"), + "Skill path must remain inside the producer source.") + continue + } + if path == nil, input.installedSkills[name] == nil { + diagnostics.add( + .unconverted, location.appending("skillPath"), + "Original resource coordinates are absent; supply actual installed content for capture.") + } + let hashField = project ? "computedHash" : "skillFolderHash" + let hash = ImportInput.hex(ImportInput.string(entry[hashField]), count: project ? 64 : 40) + let integrity = hash.map { + ImportPin.Integrity(kind: project ? .vercelInstalledSHA256 : .githubTree, value: $0) + } + if integrity == nil { + diagnostics.add( + .incompletePin, location.appending(hashField), + "Producer content integrity is missing or invalid.") + } + // Neither release format persists a resolved repository commit. A full-looking hash in + // either integrity field or a requested ref cannot be promoted into that missing evidence. + diagnostics.add( + .incompletePin, location, + "This lock does not prove an exact upstream repository commit; no ref is fetched.") + let alias = "import-skill-\(index)" + let version = ImportInput.string(entry["version"]) + if version != nil, !ImportInput.packageVersion(version) { + diagnostics.add( + .incompletePin, location.appending("version"), + "Package version is not an exact semantic version.") + } + let upstream = canonicalSource(source: source, url: sourceURL, type: sourceType, path: path) + if upstream == nil { + diagnostics.add( + .unconverted, location.appending("sourceType"), + "Source transport cannot be represented as a canonical source without explicit content.") + } + diagnostics.proposal.sources.append( + .init( + alias: alias, origin: location, declaration: upstream, + pin: .init( + commit: nil, version: ImportInput.packageVersion(version) ? version : nil, + integrity: integrity), + requestedRef: ImportInput.string(entry["ref"]), producerPath: path, + producerIdentity: source)) + for field in [ + "via", "subagents", "pluginName", "sourceBaseUrl", "wellKnownDigest", "installMode", + "installedAt", "updatedAt", + ] where entry[field] != nil { + diagnostics.add( + .unconverted, location.appending(field), + "Producer placement, source or bookkeeping semantics require an explicit import decision." + ) + } + if let local = input.installedSkills[name] { + do { + let captured = try ImportSkillContent.read(local, input: input, limits: limits) + diagnostics.proposal.diagnostics += captured.diagnostics + diagnostics.proposal.bindings += captured.bindings + if project, let hash, ImportSkillContent.vercelHash(captured) != hash { + diagnostics.add( + .integrityMismatch, location.appending(hashField), + "Explicit installed content does not match the recorded installed-files hash.") + continue + } + if !project { + diagnostics.add( + .unconverted, location.appending(hashField), + "Captured actual local content has a SHA-256 pin; the recorded GitHub tree hash is not verified." + ) + } + contentAdmitted = true + let contentAlias = alias + "-content" + diagnostics.proposal.sources.append( + .init( + alias: contentAlias, origin: location, + declaration: .init( + kind: .local, location: captured.path, + environment: .init(projectDirectory: input.root, homeDirectory: input.root)), + pin: .init(commit: nil, version: nil, integrity: nil), requestedRef: nil, + producerPath: nil)) + diagnostics.proposal.resources.append( + .init( + origin: location, sourceAlias: contentAlias, producerName: name, path: ".", + producerIntegrity: integrity, observedHash: captured.hash, + executableFlags: captured.flags, requiresStandaloneSource: true)) + diagnostics.proposal.components.append( + .init( + origin: location, + declaration: .skills( + source: contentAlias, + .init(select: .names([captured.skill.name]), condition: captured.skill.condition)))) + } catch is CancellationError { throw CancellationError() } catch CoreError.unsafePath { + diagnostics.add( + .unsafePath, location, "Explicit installed content escapes its input root.") + } catch { + diagnostics.add( + .missingResource, location, + "Explicit installed content is missing, unsafe, malformed or exceeds resource limits.") + } + } else if let upstream { + diagnostics.proposal.resources.append( + .init( + origin: location, sourceAlias: alias, producerName: name, path: upstream.path, + producerIntegrity: integrity, observedHash: nil, executableFlags: [:], + requiresStandaloneSource: true)) + diagnostics.proposal.components.append( + .init( + origin: location, declaration: .skills(source: alias, .init(select: .names([name]))))) + } + } + if let selection = input.selection, !selection.isSubset(of: Set(skills.keys)) { + diagnostics.add( + .invalidInput, origin.appending("skills"), "A selected skill is absent from this document.") + } + } + + private static func canonicalSource( + source: String, url: String?, type: String, path: String? + ) -> SourceDeclaration? { + let location: String + switch type { + case "github": + if let url { + location = url + } else { + let parts = source.split(separator: "/") + guard parts.count == 2, parts.allSatisfy({ ImportInput.name(String($0)) }) else { + return nil + } + location = "https://github.com/" + source + } + case "git": + guard let url else { return nil } + location = url + default: return nil + } + let directory = path.map { + $0.hasSuffix("/SKILL.md") ? String($0.dropLast(9)) : ($0 == "SKILL.md" ? "." : $0) + } + let declaration = SourceDeclaration(kind: .git, location: location, path: directory) + guard (try? declaration.transportIdentity()) != nil else { return nil } + return declaration + } +} diff --git a/Sources/Components/Import/YAMLSourceImport.swift b/Sources/Components/Import/YAMLSourceImport.swift new file mode 100644 index 0000000..ce70c95 --- /dev/null +++ b/Sources/Components/Import/YAMLSourceImport.swift @@ -0,0 +1,740 @@ +import AgentsCore +import AgentsManifest +import Foundation + +/// A view of the existing immutable YAML graph; no decoded dictionary or parallel value graph. +struct ImportYAML { + let reader: YAMLReader + let node: YAMLNode + let pointer: String + + var location: ImportLocation { + .init( + document: reader.span(of: node).document.rawValue, pointer: pointer, + span: reader.span(of: node)) + } + var string: String? { + guard let scalar = node.scalar, !scalar.decimalTag, + scalar.quoted || YAMLScalar.classify(scalar.text) == .string + else { return nil } + return scalar.text + } + var integer: Int? { + guard let scalar = node.scalar, !scalar.quoted, !scalar.decimalTag, + YAMLScalar.classify(scalar.text) == .integer + else { return nil } + return YAMLScalar.integer(scalar.text) + } + var boolean: Bool? { + guard let scalar = node.scalar, !scalar.quoted, !scalar.decimalTag, + YAMLScalar.classify(scalar.text) == .boolean + else { return nil } + return scalar.text.lowercased() == "true" + } + var pairs: [(String, ImportYAML)]? { + guard let pairs = node.pairs else { return nil } + var result: [(String, ImportYAML)] = [] + for (index, pair) in pairs.enumerated() { + let key = ImportYAML(reader: reader, node: pair.key, pointer: pointer) + guard let name = key.string else { return nil } + result.append( + (name, .init(reader: reader, node: pair.value, pointer: pointer + "/member[\(index)]"))) + } + return result + } + var items: [ImportYAML]? { + node.items?.enumerated().map { + .init(reader: reader, node: $0.element, pointer: pointer + "/\($0.offset)") + } + } + var strings: [String]? { + guard let items, items.allSatisfy({ $0.string != nil }) else { return nil } + return items.compactMap(\.string) + } + subscript(_ field: String) -> ImportYAML? { pairs?.first { $0.0 == field }?.1 } + + static func check(_ root: YAMLNode, limits: SourceImportLimits) throws { + var remaining = limits.nodes + func visit(_ node: YAMLNode, depth: Int) throws { + try Task.checkCancellation() + guard remaining > 0, depth <= limits.depth else { throw ImportReadFailure.invalid } + remaining -= 1 + for pair in node.pairs ?? [] { + try visit(pair.key, depth: depth + 1) + try visit(pair.value, depth: depth + 1) + } + for item in node.items ?? [] { try visit(item, depth: depth + 1) } + } + try visit(root, depth: 0) + } + + func validate( + strings: Set = [], required: Set = [], arrays: Set = [], + booleans: Set = [], integers: Set = [], + into diagnostics: inout ImportDiagnostics + ) -> Bool { + var valid = true + for field in strings.union(required).sorted() + where self[field] != nil || required.contains(field) { + if self[field]?.string == nil { + diagnostics.add( + .invalidInput, self[field]?.location ?? location, "Expected a producer string field.") + valid = false + } + } + for field in arrays.sorted() where self[field] != nil { + if self[field]?.strings == nil { + diagnostics.add( + .invalidInput, self[field]!.location, "Expected producer string selections.") + valid = false + } + } + for field in booleans.sorted() where self[field] != nil { + if self[field]?.boolean == nil { + diagnostics.add(.invalidInput, self[field]!.location, "Expected a producer boolean field.") + valid = false + } + } + for field in integers.sorted() where self[field] != nil { + if self[field]?.integer.map({ $0 >= 0 }) != true { + diagnostics.add( + .invalidInput, self[field]!.location, "Expected a nonnegative producer integer field.") + valid = false + } + } + return valid + } + + func unknown(_ allowed: Set, into diagnostics: inout ImportDiagnostics) { + for (name, value) in pairs ?? [] where !allowed.contains(name) { + if ImportInput.credentialField(name) { + diagnostics.binding(value.location) + } + value.unconverted(into: &diagnostics) + } + } + func unconverted(into diagnostics: inout ImportDiagnostics) { + diagnostics.add(.unconverted, location, "Producer field or item has no canonical conversion.") + // Literal connection fields are never retained, including inside an otherwise unsupported item. + if let value = string, value.contains("://"), !ImportInput.safeLocator(value) { + diagnostics.binding(location) + } + for (key, value) in pairs ?? [] { + if ImportInput.credentialField(key) { + diagnostics.binding(value.location) + } + value.unconverted(into: &diagnostics) + } + for value in items ?? [] { value.unconverted(into: &diagnostics) } + } +} + +enum YAMLSourceImport { + static func read( + _ input: SourceImportInput, limits: SourceImportLimits, + into diagnostics: inout ImportDiagnostics + ) throws { + var admission = limits + admission.documentBytes = min(limits.documentBytes, ManifestLimits.Input.bytes) + let bytes = try ImportInput.bytes(input, limits: admission) + let reader = try YAMLReader(bytes: Array(bytes), identity: .init(input.document)) + let root = ImportYAML(reader: reader, node: reader.root, pointer: "") + try ImportYAML.check(root.node, limits: limits) + guard root.pairs != nil else { + diagnostics.add(.invalidInput, root.location, "Expected a YAML mapping with string keys.") + return + } + switch input.profile { + case .apmManifest: try manifest(root, input: input, limits: limits, into: &diagnostics) + case .apmLock, .rulesyncAPMV1: try lock(root, input: input, into: &diagnostics) + case .rulesyncGitHubV1: try github(root, input: input, into: &diagnostics) + default: preconditionFailure("YAML profile dispatch") + } + guard !diagnostics.proposal.diagnostics.contains(where: { $0.code == .unsupportedVersion }) + else { return } + for (index, name) in input.installedSkills.keys.sorted().enumerated() { + let location = root.location.appending("explicitContent/member[\(index)]") + guard ImportInput.name(name), let path = input.installedSkills[name] else { + diagnostics.add(.invalidInput, location, "Invalid explicit installed skill selection.") + continue + } + do { + let content = try ImportSkillContent.read(path, input: input, limits: limits) + diagnostics.proposal.diagnostics += content.diagnostics + diagnostics.proposal.bindings += content.bindings + let alias = "yaml-content-\(index)" + diagnostics.proposal.sources.append( + .init( + alias: alias, origin: location, + declaration: .init( + kind: .local, location: content.path, + environment: .init(projectDirectory: input.root, homeDirectory: input.root)), + pin: .init(), requestedRef: nil, producerPath: nil)) + diagnostics.proposal.resources.append( + .init( + origin: location, sourceAlias: alias, producerName: name, path: ".", + producerIntegrity: nil, observedHash: content.hash, executableFlags: content.flags, + requiresStandaloneSource: true, kind: .skills)) + diagnostics.proposal.components.append( + .init( + origin: location, + declaration: .skills( + source: alias, + .init(select: .names([content.skill.name]), condition: content.skill.condition)))) + diagnostics.add( + .unconverted, location, + "Actual explicitly selected local content is captured independently; it does not verify recovery of the producer's upstream commit." + ) + } catch is CancellationError { throw CancellationError() } catch CoreError.unsafePath { + diagnostics.add(.unsafePath, location, "Explicit content escapes its input root.") + } catch { + diagnostics.add( + .missingResource, location, + "Explicit installed skill content is missing, malformed or exceeds bounds.") + } + } + } + + private static func manifest( + _ root: ImportYAML, input: SourceImportInput, limits: SourceImportLimits, + into diagnostics: inout ImportDiagnostics + ) throws { + guard root["name"]?.string?.isEmpty == false, root["version"]?.string != nil else { + diagnostics.add( + .invalidInput, root.location, "APM manifest requires string name and version.") + return + } + if let schema = root["$schema"] { + let admitted = [ + "https://microsoft.github.io/apm/specs/schemas/manifest-v0.1.schema.json", + "https://microsoft.github.io/apm/specs/schemas/manifest-v0.1.48.schema.json", + ] + guard let identity = schema.string, admitted.contains(identity) else { + diagnostics.add(.unsupportedVersion, schema.location, "Unsupported APM schema identity.") + return + } + } + let name = root["name"]! + let version = root["version"]! + for field in [name, version] + where field.string!.contains("://") && !ImportInput.safeLocator(field.string!) { + diagnostics.binding(field.location) + field.unconverted(into: &diagnostics) + return + } + diagnostics.proposal.packageMetadata = .init( + name: name.string!, version: version.string!, + nameLocation: name.location, versionLocation: version.location) + root.unknown( + [ + "$schema", "name", "version", "target", "targets", "includes", "dependencies", + "devDependencies", + ], into: &diagnostics) + if root["target"] != nil && root["targets"] != nil { + diagnostics.add( + .invalidInput, root.location, "APM target and targets are mutually exclusive.") + return + } + if let targets = root["targets"] ?? root["target"] { + selection( + targets, kind: .targets, scalar: true, alias: nil, development: false, into: &diagnostics) + } + if let includes = root["includes"] { + if includes.string == "auto" { + diagnostics.proposal.selections.append( + .init( + origin: includes.location, sourceAlias: nil, kind: .includes, values: [], + automatic: true, developmentOnly: false)) + } else { + selection( + includes, kind: .includes, scalar: false, alias: nil, development: false, + into: &diagnostics) + } + } + for group in ["dependencies", "devDependencies"] { + guard let block = root[group] else { continue } + guard block.pairs != nil else { + diagnostics.add(.invalidInput, block.location, "Expected an APM dependency mapping.") + continue + } + block.unknown(["apm"], into: &diagnostics) + guard let apm = block["apm"] else { continue } + guard let items = apm.items else { + diagnostics.add(.invalidInput, apm.location, "Expected an APM dependency list.") + continue + } + for (index, item) in items.enumerated() { + try Task.checkCancellation() + let alias = "apm-\(group)-\(index)" + let choice = diagnostics.beginChoice(String(index), at: item.location) + defer { diagnostics.endChoice(choice) } + guard input.enumerateChoices || (input.selection?.contains(String(index)) ?? true) else { + continue + } + let development = group == "devDependencies" + let raw: String + var requested: String? + var path: String? + var local = false + var registry = false + if let value = item.string { + raw = value + local = + value.hasPrefix("./") || value.hasPrefix("../") || value.hasPrefix("/") + || value.hasPrefix("~") + } else if item.pairs != nil { + guard + item.validate( + strings: ["git", "path", "ref", "version", "id", "registry", "alias"], + arrays: ["skills", "targets"], into: &diagnostics) + else { continue } + item.unknown( + ["git", "path", "ref", "version", "id", "registry", "alias", "skills", "targets"], + into: &diagnostics) + guard let value = item["git"]?.string ?? item["id"]?.string ?? item["path"]?.string else { + diagnostics.add( + .invalidInput, item.location, "APM dependency has no admitted source selector.") + continue + } + raw = value + registry = item["id"] != nil || item["registry"] != nil + if item["git"] != nil && registry { + diagnostics.add( + .invalidInput, item.location, "Conflicting APM dependency source selectors.") + continue + } + local = item["git"] == nil && !registry + requested = item["ref"]?.string ?? item["version"]?.string + if item["git"] != nil { path = item["path"]?.string } + for (field, kind) in [ + ("skills", ImportProducerSelection.Kind.skills), ("targets", .targets), + ] { + if let value = item[field] { + selection( + value, kind: kind, scalar: false, alias: alias, development: development, + into: &diagnostics) + } + } + if let value = item["alias"] { value.unconverted(into: &diagnostics) } + if item["ref"] != nil, let value = item["version"] { + value.unconverted(into: &diagnostics) + } + } else { + diagnostics.add( + .invalidInput, item.location, "Expected an APM dependency string or mapping.") + continue + } + let defaultRegistry = root["registries"]?["default"]?.string != nil + let explicitGit = item["git"] != nil || raw.contains("://") || raw.hasPrefix("git@") + if registry || (!local && !explicitGit && (defaultRegistry || root["default_host"] != nil)) + { + diagnostics.add( + .unconverted, item.location, + "Registry or host-dependent resolution needs explicit locked coordinates; no resolver or user defaults are consulted." + ) + diagnostics.add( + .incompletePin, item.location, "Manifest dependency is not a resolved source pin.") + continue + } + let declaration: SourceDeclaration? + let locator: String + if local { + do { + let relative = try ImportInput.path(raw) + let base = (input.document as NSString).deletingLastPathComponent + let joined = base.isEmpty ? relative : base + "/" + relative + _ = try ImportInput.snapshot(input.root).resource(joined) + locator = joined + declaration = .init( + kind: .local, location: input.root.appendingPathComponent(joined).path) + } catch { + diagnostics.add( + .unsafePath, item.location, + "Local APM source must be explicitly readable within its input root.") + continue + } + } else { + guard let parsed = gitLocator(raw, explicitPath: path, requested: requested) else { + if !ImportInput.safeLocator(raw.components(separatedBy: "#")[0]) { + diagnostics.binding(item.location) + } + diagnostics.add( + .unconverted, item.location, + "Source coordinates are ambiguous or require producer resolution.") + continue + } + locator = parsed.location + path = parsed.path + requested = parsed.ref + declaration = .init(kind: .git, location: locator, path: path) + } + diagnostics.proposal.sources.append( + .init( + alias: alias, origin: item.location, declaration: declaration, pin: .init(), + requestedRef: requested, producerPath: path, producerIdentity: locator, + developmentOnly: development)) + diagnostics.proposal.resources.append( + .init( + origin: item.location, sourceAlias: alias, producerName: "package", path: path ?? ".", + producerIntegrity: nil, observedHash: nil, executableFlags: [:], + requiresStandaloneSource: true)) + diagnostics.add( + .incompletePin, item.location, + "Manifest intent requires a resolved lock commit or explicitly captured installed content." + ) + diagnostics.add( + .unconverted, item.location, + "APM package primitives require content inspection before canonical component conversion." + ) + } + } + try APMPackageContentImport.read( + input: input, origin: root.location.appending("localContent"), limits: limits, + into: &diagnostics) + } + + private static func selection( + _ value: ImportYAML, kind: ImportProducerSelection.Kind, scalar: Bool, alias: String?, + development: Bool, into diagnostics: inout ImportDiagnostics + ) { + guard let values = value.strings ?? (scalar ? value.string.map { [$0] } : nil) else { + diagnostics.add(.invalidInput, value.location, "Expected producer selection strings.") + return + } + if kind == .includes, values.contains(where: { (try? ImportInput.path($0)) == nil }) { + diagnostics.add( + .unsafePath, value.location, "Includes must remain within the package source.") + return + } + if kind == .targets { + let admitted: Set = [ + "all", "copilot", "vscode", "claude", "grok-build", "cursor", "opencode", "codex", "gemini", + "antigravity", "windsurf", "kiro", "agent-skills", "hermes", "grok-bot", "grok-cloud", + "openclaw", "copilot-cowork", "copilot-app", + ] + guard !values.isEmpty, values.allSatisfy(admitted.contains) else { + diagnostics.add(.invalidInput, value.location, "Unsupported APM producer target.") + return + } + } + diagnostics.proposal.selections.append( + .init( + origin: value.location, sourceAlias: alias, kind: kind, values: values, automatic: false, + developmentOnly: development)) + diagnostics.add( + .unconverted, value.location, + "Producer selection is retained independently of canonical installation scope.") + } + + /// Only syntactically unambiguous GitHub shorthand and explicit clone coordinates are converted. + static func gitLocator(_ value: String, explicitPath: String? = nil, requested: String? = nil) + -> (location: String, path: String?, ref: String?)? + { + let pieces = value.split(separator: "#", maxSplits: 1, omittingEmptySubsequences: false) + guard let base = pieces.first.map(String.init), !base.isEmpty, ImportInput.safeLocator(base), + base != "parent" + else { return nil } + let ref = requested ?? (pieces.count == 2 ? String(pieces[1]) : nil) + if let ref, + ref.isEmpty || ref.hasPrefix("-") + || ref.unicodeScalars.contains(where: { CharacterSet.controlCharacters.contains($0) }) + { + return nil + } + var path = explicitPath + let location: String + if base.contains("://") || base.hasPrefix("git@") { + guard (try? SourceDeclaration(kind: .git, location: base).transportIdentity()) != nil else { + return nil + } + location = base + } else { + let parts = base.split(separator: "/").map(String.init) + guard parts.count >= 2, !parts[0].contains(":"), !parts[0].contains("."), + parts.allSatisfy(ImportInput.name) + else { return nil } + location = "https://github.com/" + parts[0] + "/" + parts[1] + if parts.count > 2 { + guard explicitPath == nil else { return nil } + path = parts.dropFirst(2).joined(separator: "/") + } + } + if let path, (try? ImportInput.path(path)) == nil { return nil } + return (location, path, ref) + } + + private static func lock( + _ root: ImportYAML, input: SourceImportInput, into diagnostics: inout ImportDiagnostics + ) throws { + let mirror = input.profile == .rulesyncAPMV1 + guard let version = root["lockfile_version"]?.string, + (mirror ? ["1"] : ["1", "2"]).contains(version) + else { + diagnostics.add( + .unsupportedVersion, root["lockfile_version"]?.location ?? root.location, + "Unsupported producer YAML lock version.") + return + } + guard + root.validate( + strings: ["generated_at", "apm_version"], + required: mirror ? ["generated_at", "apm_version"] : [], into: &diagnostics) + else { return } + root.unknown( + ["lockfile_version", "dependencies", "generated_at", "apm_version"], into: &diagnostics) + guard let items = root["dependencies"]?.items else { + diagnostics.add(.invalidInput, root.location, "Expected locked dependencies.") + return + } + for (index, item) in items.enumerated() { + try Task.checkCancellation() + let choice = diagnostics.beginChoice(String(index), at: item.location) + defer { diagnostics.endChoice(choice) } + guard input.enumerateChoices || (input.selection?.contains(String(index)) ?? true) else { + continue + } + guard item.pairs != nil, let repo = item["repo_url"]?.string else { + diagnostics.add(.invalidInput, item.location, "Expected a locked repository entry.") + continue + } + let common: Set = [ + "repo_url", "resolved_commit", "resolved_ref", "version", "depth", "resolved_by", + "package_type", "content_hash", "is_dev", "deployed_files", "source", "local_path", + "virtual_path", "is_virtual", + ] + item.unknown( + mirror + ? common + : common.union([ + "resolved_url", "resolved_hash", "tree_sha256", "constraint", "resolved_tag", + "skill_subset", + ]), into: &diagnostics) + guard + item.validate( + strings: common.subtracting(["depth", "is_dev", "deployed_files", "is_virtual"]).union( + mirror + ? [] : ["resolved_url", "resolved_hash", "tree_sha256", "constraint", "resolved_tag"]), + required: mirror ? ["repo_url", "package_type"] : ["repo_url"], + arrays: mirror ? ["deployed_files"] : ["deployed_files", "skill_subset"], + booleans: ["is_dev", "is_virtual"], integers: ["depth"], into: &diagnostics) + else { continue } + if mirror, item["depth"]?.integer == nil || item["deployed_files"]?.strings == nil { + diagnostics.add( + .invalidInput, item.location, "Rulesync APM mirror requires depth and deployed files.") + continue + } + guard ImportInput.safeLocator(repo) else { + diagnostics.binding(item.location) + continue + } + let commit = ImportInput.hex(item["resolved_commit"]?.string, count: 40) + let sourceKind = item["source"]?.string + if let sourceKind, !["local", "registry"].contains(sourceKind) { + diagnostics.add( + .unconverted, item["source"]!.location, + "Unknown producer source transport cannot establish a canonical Git source.") + continue + } + let registry = sourceKind == "registry" + let local = sourceKind == "local" + let alias = "apm-lock-\(index)" + var declaration: SourceDeclaration? + var path = item["virtual_path"]?.string + if let value = path, (try? ImportInput.path(value)) == nil { + diagnostics.add( + .unsafePath, item.location, "Virtual package path must remain relative to its source.") + path = nil + } else if !registry && !local, let parsed = gitLocator(repo, explicitPath: path) { + declaration = .init( + kind: .git, location: parsed.location, requirement: commit.map { .revision($0) }, + path: path) + } + let digestField = + registry && !mirror + ? "resolved_hash" : !mirror && item["tree_sha256"] != nil ? "tree_sha256" : "content_hash" + let integrity = + mirror ? rulesyncDigest(item[digestField]?.string) : digest(item[digestField]?.string) + var resolvedURL: String? + if registry, !mirror { + if let locator = item["resolved_url"]?.string { + if ImportInput.safeLocator(locator) { + resolvedURL = locator + } else { + diagnostics.binding(item["resolved_url"]!.location) + } + } + diagnostics.add( + .unconverted, item.location, + "Registry archive source requires explicit content capture; no Git revision is inferred.") + } else if local { + diagnostics.add( + .unconverted, item.location, + "Local lock paths require explicit source/content selection; deployment coordinates are not authoring sources." + ) + } + if registry + ? (integrity == nil || resolvedURL == nil + || !ImportInput.packageVersion(item["version"]?.string)) : commit == nil + { + diagnostics.add( + .incompletePin, item.location, + "Locked source lacks a complete exact pin for its transport.") + } + if item[digestField] != nil && integrity == nil { + diagnostics.add( + .unconverted, item[digestField]!.location, + "Producer content hash is not a recognized digest envelope.") + } + diagnostics.proposal.sources.append( + .init( + alias: alias, origin: item.location, declaration: declaration, + pin: .init( + commit: registry || local ? nil : commit, + version: ImportInput.packageVersion(item["version"]?.string) + ? item["version"]?.string : nil, integrity: integrity), + requestedRef: item["constraint"]?.string, producerPath: path, producerIdentity: repo, + registry: nil, resolvedRef: item["resolved_ref"]?.string, resolvedURL: resolvedURL, + developmentOnly: item["is_dev"]?.boolean == true)) + diagnostics.proposal.resources.append( + .init( + origin: item.location, sourceAlias: alias, producerName: "package", path: path, + producerIntegrity: integrity, observedHash: nil, executableFlags: [:], + requiresStandaloneSource: true)) + if let files = item["deployed_files"] { + deployment(files, alias: alias, agent: nil, scope: nil, directory: nil, into: &diagnostics) + } + for field in [ + "resolved_by", "package_type", "depth", "is_dev", "local_path", "is_virtual", + "resolved_tag", "version", + ] where item[field] != nil { item[field]!.unconverted(into: &diagnostics) } + if let skills = item["skill_subset"] { + selection( + skills, kind: .skills, scalar: false, alias: alias, + development: item["is_dev"]?.boolean == true, into: &diagnostics) + } + diagnostics.add( + .unconverted, item.location, + "Lock provenance does not establish package component content or native ownership.") + } + } + + private static func github( + _ root: ImportYAML, input: SourceImportInput, into diagnostics: inout ImportDiagnostics + ) throws { + guard root["lockfile_version"]?.string == "1" else { + diagnostics.add( + .unsupportedVersion, root.location, "Expected rulesync GitHub deployment lock version 1.") + return + } + guard root.validate(required: ["generated_at"], into: &diagnostics) else { return } + root.unknown(["lockfile_version", "generated_at", "installations"], into: &diagnostics) + guard let items = root["installations"]?.items else { + diagnostics.add(.invalidInput, root.location, "Expected GitHub deployment installations.") + return + } + for (index, item) in items.enumerated() { + try Task.checkCancellation() + let choice = diagnostics.beginChoice(String(index), at: item.location) + defer { diagnostics.endChoice(choice) } + guard input.enumerateChoices || (input.selection?.contains(String(index)) ?? true) else { + continue + } + item.unknown( + [ + "source", "owner", "repo", "agent", "scope", "skill", "requested_ref", "resolved_ref", + "resolved_commit", "install_dir", "deployed_files", "content_hash", + ], into: &diagnostics) + guard + item.validate( + strings: ["requested_ref", "content_hash"], + required: [ + "source", "owner", "repo", "agent", "scope", "skill", "resolved_ref", "resolved_commit", + "install_dir", + ], arrays: ["deployed_files"], into: &diagnostics), item["deployed_files"]?.strings != nil + else { continue } + guard let owner = item["owner"]?.string, let repo = item["repo"]?.string, + let source = item["source"]?.string, + source.lowercased() == (owner + "/" + repo).lowercased(), + ImportInput.name(owner), ImportInput.name(repo), let name = item["skill"]?.string, + ImportInput.name(name), + let agent = item["agent"]?.string, ImportInput.name(agent), + let scope = item["scope"]?.string, ["project", "user"].contains(scope) + else { + diagnostics.add( + .invalidInput, item.location, "Invalid GitHub source, skill or deployment coordinates.") + continue + } + let commit = ImportInput.hex(item["resolved_commit"]?.string, count: 40) + if commit == nil { + diagnostics.add( + .incompletePin, item.location, "GitHub deployment lacks a full resolved commit.") + } + if item["content_hash"] != nil && rulesyncDigest(item["content_hash"]?.string) == nil { + diagnostics.add( + .unconverted, item["content_hash"]!.location, + "Producer content hash is not a recognized rulesync SHA-256 envelope.") + } + let alias = "rulesync-gh-\(index)" + diagnostics.proposal.sources.append( + .init( + alias: alias, origin: item.location, + declaration: .init( + kind: .git, location: "https://github.com/" + owner + "/" + repo, + requirement: commit.map { .revision($0) }), + pin: .init(commit: commit, integrity: rulesyncDigest(item["content_hash"]?.string)), + requestedRef: item["requested_ref"]?.string, producerPath: nil, producerIdentity: source, + resolvedRef: item["resolved_ref"]?.string)) + diagnostics.proposal.resources.append( + .init( + origin: item.location, sourceAlias: alias, producerName: name, path: nil, + producerIntegrity: rulesyncDigest(item["content_hash"]?.string), observedHash: nil, + executableFlags: [:], requiresStandaloneSource: true)) + if let files = item["deployed_files"] { + deployment( + files, alias: alias, agent: agent, scope: scope, directory: item["install_dir"]?.string, + into: &diagnostics) + } + diagnostics.add( + .unconverted, item.location, + "Deployment lock has no source skill path; target and scope are evidence, not canonical installation conditions or ownership." + ) + } + } + + private static func deployment( + _ files: ImportYAML, alias: String, agent: String?, scope: String?, directory: String?, + into diagnostics: inout ImportDiagnostics + ) { + guard let paths = files.strings, paths.allSatisfy({ (try? ImportInput.path($0)) != nil }), + directory.map({ (try? ImportInput.path($0)) != nil }) ?? true + else { + diagnostics.add( + .unsafePath, files.location, + "Deployment paths are outside the bounded relative-path profile; no ownership is inferred.") + return + } + diagnostics.proposal.deployments.append( + .init( + origin: files.location, sourceAlias: alias, agent: agent, scope: scope, + installDirectory: directory, files: paths)) + } + + private static func rulesyncDigest(_ value: String?) -> ImportPin.Integrity? { + guard let value, value.hasPrefix("sha256:"), + ImportInput.hex(String(value.dropFirst(7)), count: 64) != nil + else { return nil } + return .init(kind: .rulesyncSHA256, value: value) + } + + static func digest(_ value: String?) -> ImportPin.Integrity? { + guard let value else { return nil } + let parts = value.split(separator: ":", maxSplits: 1).map(String.init) + if parts.count == 1, ImportInput.hex(value, count: 64) != nil { + return .init(kind: .apmDigest, value: value) + } + guard parts.count == 2, let count = ["sha256": 64, "sha384": 96, "sha512": 128][parts[0]], + ImportInput.hex(parts[1], count: count) != nil + else { return nil } + return .init(kind: .apmDigest, value: value) + } +} diff --git a/Sources/Components/LedgerFreeze.swift b/Sources/Components/LedgerFreeze.swift new file mode 100644 index 0000000..9cee2ec --- /dev/null +++ b/Sources/Components/LedgerFreeze.swift @@ -0,0 +1,235 @@ +import AgentsCore +import Foundation + +/// Explicit authoring coordinates are keyed by B's source identity, before durable IDs are made. +/// The caller supplies their authored meaning; physical containment never infers relocation. +package struct LedgerFreezeLocations { + package var sources: [String: LedgerLocation] + package init(sources: [String: LedgerLocation]) { self.sources = sources } +} + +package enum LedgerFreeze { + /// Ephemeral B-to-C identities accompany the frozen ledger during native lowering. + /// They retain exact snapshots without persisting machine-local source coordinates. + package struct Result { + package var ledger: ResolvedLedger + package let sources: [SourceSnapshotID: String] + } + + package static func freeze( + _ linked: LinkedComponents, session: SourceResolutionSession, + locations: LedgerFreezeLocations, limits: LedgerLimits + ) throws -> ResolvedLedger { + try freezeWithSources(linked, session: session, locations: locations, limits: limits).ledger + } + + package static func freezeWithSources( + _ linked: LinkedComponents, session: SourceResolutionSession, + locations: LedgerFreezeLocations, limits: LedgerLimits + ) throws -> Result { + var ledger = ResolvedLedger() + let allSnapshots = linked.sourceSnapshots + linked.declaringSnapshots + let evidence = Dictionary( + allSnapshots.map { ($0.snapshot, $0) }, uniquingKeysWith: { first, _ in first }) + var sources: [SourceSnapshotID: String] = [:] + func sourceID(_ snapshot: SourceSnapshotID) throws -> String { + if let id = sources[snapshot] { return id } + guard let item = evidence[snapshot] else { + throw CoreError.invalidState("missing snapshot evidence") + } + let container = try item.container.map(sourceID) + let descriptor = item.source + let location = locations.sources[snapshot.source] + if descriptor?.kind == .local, container == nil, location == nil { + throw CoreError.invalidState("local source needs explicit authoring coordinates") + } + var source = LedgerSource( + kind: descriptor?.kind ?? .local, + transport: descriptor?.url ?? (descriptor?.kind == .wellKnown ? snapshot.source : nil), + location: container == nil ? location : nil, + revision: snapshot.revision, version: item.pin?.version, container: container, + namespace: item.container.map { String(snapshot.source.dropFirst($0.source.count)) }, + bundleSources: session.bundleSources[snapshot], archive: item.archive) + source.bundlePackageName = session.bundlePackageNames[snapshot] + let id = try ResolvedLedgerCodec.digest(source) + ledger.sources[id] = source + sources[snapshot] = id + return id + } + for item in allSnapshots { _ = try sourceID(item.snapshot) } + let snapshotsBySource = Dictionary(grouping: allSnapshots, by: { $0.snapshot.source }) + for use in linked.sourceUses { + for snapshot in snapshotsBySource[use.source] ?? [] { + ledger.sourceUses.append( + .init( + source: try sourceID(snapshot.snapshot), root: use.root, + requirement: use.requirement?.canonical, + organizationRequirements: snapshot.pin?.version == nil + ? nil : use.organizationRequirements)) + } + } + var objectBytes = 0 + for component in linked.components { + try Task.checkCancellation() + var resourceIDs: [String] = [] + for resource in component.resources { + let id = try sourceID(resource.snapshot) + let mode: InstallMode? + if case .skill(_, let selection, _) = component.payload { + mode = selection + } else { + mode = nil + } + let record: LedgerResource + if mode == .edit { + guard let base = locations.sources[resource.snapshot.source] else { + throw CoreError.invalidState("live skill needs explicit location") + } + var location = base + location.path = base.path == "." ? resource.path : base.path + "/" + resource.path + record = .init( + kind: .liveEdit, source: id, path: resource.path, hash: resource.hash, + entries: [], location: location) + } else { + let url = try session.resource(snapshot: resource.snapshot, path: resource.path) + 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 kind: LedgerResource.Kind = + source.archive != nil + ? .archive : resource.artifact != nil ? .artifact : git ? .git : .embedded + let captured = try LedgerResources.capture( + url, embed: kind != .git && kind != .archive, limits: limits, + sourceRoot: try session.resource(snapshot: resource.snapshot, path: ".")) + var directory: ObjCBool = false + guard FileManager.default.fileExists(atPath: url.path, isDirectory: &directory) else { + throw CoreError.invalidState("linked resource disappeared before freeze") + } + let flags = + directory.boolValue + ? captured.flags : [resource.path: captured.flags["."] ?? false] + guard captured.hash == resource.hash, + resource.executableFlags.isEmpty || flags == resource.executableFlags + else { + throw CoreError.invalidState("linked resource changed before freeze") + } + for (digest, bytes) in captured.objects where ledger.contentObjects[digest] == nil { + guard bytes.count <= limits.objectBytes - objectBytes else { + throw CoreError.invalidState("ledger aggregate content budget") + } + ledger.contentObjects[digest] = bytes + objectBytes += bytes.count + } + record = .init( + kind: kind, source: id, path: resource.path, hash: resource.hash, + entries: captured.entries, support: captured.support, artifact: resource.artifact, + location: resource.artifactLocation) + } + let resourceID = try ResolvedLedgerCodec.digest(record) + ledger.resources[resourceID] = record + resourceIDs.append(resourceID) + } + let privateSource = try [component.snapshot, component.declaringSnapshot].contains { + try ledger.rootSource(sourceID($0)).archive != nil + } + let privateResource = resourceIDs.contains { ledger.resources[$0]?.kind == .archive } + let payload: LedgerValue + var registry: MCPRegistryEvidence? + switch component.payload { + case .declaration(let declaration): + guard !privateSource, !privateResource else { + throw CoreError.unsafePath("native configuration cannot embed private archive data") + } + payload = try LedgerPayload.component(declaration) + registry = declaration.mcpRegistry + case .skill(let skill, let mode, let native): + guard !privateSource || native.isEmpty else { + throw CoreError.unsafePath("private archive native metadata cannot enter a project lock") + } + var fields: [String: LedgerValue] = [ + "name": .init(skill.name), "mode": .init(mode.rawValue), + "native": LedgerPayload.native(native), + ] + if !privateSource { fields["description"] = .init(skill.description) } + payload = .init(object: fields) + case .instruction(let instruction, let prompt, let native): + guard !privateSource || native.isEmpty else { + throw CoreError.unsafePath("private archive native metadata cannot enter a project lock") + } + var fields: [String: LedgerValue] = [ + "name": .init(instruction.name), + "sourceHash": .init(instruction.section.hash), "native": LedgerPayload.native(native), + ] + fields["prompt"] = prompt.map { .init($0) } + fields["localAppend"] = component.localAppend?.ledgerValue + if !component.copyRecipients.isEmpty { + fields["copyRecipients"] = LedgerValue( + array: component.copyRecipients.map(\.rawValue).sorted().map { .init($0) }) + } + payload = .init(object: fields) + } + let record = LedgerComponent( + declaringSource: try sourceID(component.declaringSnapshot), + source: try sourceID(component.snapshot), root: component.key.root, + group: component.key.group, containerRoot: component.key.containerRoot, + kind: component.key.kind.rawValue, name: component.key.name, + revision: component.pin?.revision, version: registry?.version ?? component.pin?.version, + payload: payload, conditions: component.conditions.map(LedgerCondition.init), + recipients: component.recipients.sorted { $0.rawValue < $1.rawValue }, + chatGPT: component.chatGPT, resources: resourceIDs, mcpRegistry: registry) + let id = try ResolvedLedgerCodec.digest(record) + ledger.components[id] = record + for origin in component.origins { + ledger.occurrences.append( + .init( + declaringSource: try sourceID(component.declaringSnapshot), + manifestPath: origin.provenance.relativePath, id: origin.occurrence, component: id, + reference: origin.reference, dependencies: try origin.dependencies.map(sourceID), + condition: LedgerCondition(origin.condition), + recipients: origin.recipients.sorted { $0.rawValue < $1.rawValue }, + consumerEditable: origin.consumerEditable, + pluginMember: origin.pluginMember.map { + let selector = LedgerPayload.reference($0.selector).object! + return LedgerPluginMember( + parent: $0.parentOccurrence, + kind: selector["kind"]!.text!, name: selector["name"]!.text!) + }, + input: origin.provenance.format == "yaml" + ? nil + : LedgerInputProvenance( + format: origin.provenance.format, adapterVersion: origin.provenance.adapterVersion, + pointer: origin.provenance.pointer), + pluginExpansion: try origin.pluginExpansion.map { + LedgerPluginExpansion( + source: try sourceID($0.snapshot), root: $0.root, + containerRoot: $0.containerRoot, document: $0.document, input: $0.input, + children: $0.children) + })) + } + } + ledger.occurrences.sort { $0.id < $1.id } + var children: [Int: [Int]] = [:] + for reference in linked.references { + if let parent = reference.parent { + children[parent, default: []].append(reference.occurrence) + } + } + for occurrence in ledger.occurrences { + if let parent = occurrence.reference { children[parent, default: []].append(occurrence.id) } + } + ledger.groups = try linked.references.map { reference in + LedgerGroup( + id: reference.occurrence, parent: reference.parent, + source: try sourceID(reference.snapshot), root: reference.root, name: reference.group, + requirement: reference.constraint?.requirement?.canonical, + manifestHash: reference.manifestHash, + children: (children[reference.occurrence] ?? []).sorted()) + } + try ResolvedLedgerCodec.checkModel(ledger, limits: limits) + try ledger.validate() + return Result(ledger: ledger, sources: sources) + } +} diff --git a/Sources/Components/LedgerImpact.swift b/Sources/Components/LedgerImpact.swift new file mode 100644 index 0000000..c16dce7 --- /dev/null +++ b/Sources/Components/LedgerImpact.swift @@ -0,0 +1,314 @@ +import AgentsCore +import AgentsInstructions +import Foundation + +/// Selection and protection are projections of the recorded graph, never of mutable producers. +package struct LedgerImpact { + package static func identity( + _ c: LedgerComponent, ledger: ResolvedLedger, roots: [String: URL] + ) throws -> String { + var coordinates = try [ + ledger.sourceIdentity(c.declaringSource, roots: roots), + ledger.sourceIdentity(c.source, roots: roots), c.root, c.group ?? "", c.kind, + c.kind == "skills" ? PathSafety.sanitizeName(c.name) : c.name, + ] + if c.kind == "instructions", + let path = c.resources.first.flatMap({ ledger.resources[$0]?.path }) + { + coordinates.append(path) + } + return try ResolvedLedgerCodec.digest(coordinates) + } + + package static func discoveryFingerprint(_ ledger: ResolvedLedger, roots: [String: URL]) throws + -> String + { + struct Component: Encodable { + let identity: String + let revision: String? + let mcpRegistry: MCPRegistryEvidence? + let payload: LedgerValue + let conditions: [LedgerCondition] + let recipients: [AgentID] + let resources: [String] + } + let components = try ledger.components.values.map { c in + Component( + identity: try identity(c, ledger: ledger, roots: roots), revision: c.revision, + mcpRegistry: c.mcpRegistry, payload: c.payload, conditions: c.conditions, + recipients: c.recipients, + resources: c.resources.map { ledger.resources[$0]!.hash }) + }.sorted { + if $0.identity != $1.identity { return $0.identity < $1.identity } + return try ResolvedLedgerCodec.digest($0) < ResolvedLedgerCodec.digest($1) + } + let sources = try ledger.sources.keys.map { id in + [try ledger.sourceIdentity(id, roots: roots), ledger.sources[id]!.revision] + }.sorted { $0.lexicographicallyPrecedes($1) } + return try ResolvedLedgerCodec.digest([ + ResolvedLedgerCodec.digest(components), ResolvedLedgerCodec.digest(sources), + ResolvedLedgerCodec.digest(ledger.groups.map(\.manifestHash)), + ]) + } + + package let pins: [String: SourceRevision] + package let directPins: [ComponentKey: SourceRevision] + + package init( + ledger: ResolvedLedger, roots: [String: URL], kinds: Set, + names: Set, updating: Bool, selectedIdentities: Set? = nil + ) throws { + func explicitlySelected(_ c: LedgerComponent) -> Bool { + if let selectedIdentities { + return (try? Self.identity(c, ledger: ledger, roots: roots)).map( + selectedIdentities.contains) == true + } + return kinds.contains(DeclaredComponentKind(rawValue: c.kind)!) + && (names.isEmpty + || names.contains(c.kind == "skills" ? PathSafety.sanitizeName(c.name) : c.name)) + } + let parents = Set( + ledger.occurrences.filter { occurrence in + ledger.components[occurrence.component].map { + $0.kind == "plugin" && explicitlySelected($0) + } ?? false + }.map(\.id)) + let members = try Set( + Dictionary(grouping: ledger.occurrences, by: \.component).compactMap { + id, occurrences -> String? in + guard !occurrences.isEmpty, + occurrences.allSatisfy({ $0.pluginMember.map { parents.contains($0.parent) } ?? false }) + else { return nil } + return try Self.identity(ledger.components[id]!, ledger: ledger, roots: roots) + }) + func selected(_ c: LedgerComponent) -> Bool { + explicitlySelected(c) + || ((try? Self.identity(c, ledger: ledger, roots: roots)).map(members.contains) ?? false) + } + var affected = Set() + if updating { + for occurrence in ledger.occurrences { + if let c = ledger.components[occurrence.component], selected(c) { + affected.formUnion(occurrence.dependencies) + affected.insert(c.source) + } + } + } + var pins: [String: SourceRevision] = [:] + for group in ledger.groups where !affected.contains(group.source) { + let source = ledger.sources[group.source]! + let archive = try ledger.rootSource(group.source).archive + if archive != nil || SourceCache.isObjectID(source.revision) { + pins[try ledger.sourceIdentity(group.source, roots: roots)] = SourceRevision( + revision: source.revision, version: source.version, archive: archive) + } + } + var direct: [ComponentKey: SourceRevision] = [:] + var ambiguous = Set() + for c in ledger.components.values where !updating || !selected(c) { + guard c.group == nil else { continue } + let artifact = c.resources.compactMap { ledger.resources[$0]?.artifact?.digest }.first + guard let revision = artifact ?? c.revision else { continue } + let key = ComponentKey( + source: try ledger.sourceIdentity(c.declaringSource, roots: roots), root: c.root, + group: nil, kind: DeclaredComponentKind(rawValue: c.kind)!, + name: c.kind == "skills" ? PathSafety.sanitizeName(c.name) : c.name) + let archive = try ledger.rootSource(c.source).archive + let pin = SourceRevision(revision: revision, version: c.version, archive: archive) + if c.kind == "instructions", + let path = c.resources.first.flatMap({ ledger.resources[$0]?.path }) + { + let source = try ledger.sourceIdentity(c.source, roots: roots) + for root in InstructionSnapshotReader.searchRoots(of: path, name: c.name) { + let input = key.readingInstruction(from: source, root: root) + if !ambiguous.contains(input) { + if let existing = direct[input], existing != pin { + direct[input] = nil + ambiguous.insert(input) + } else { + direct[input] = pin + } + } + } + } else { + direct[key] = pin + } + } + self.pins = pins + directPins = direct + } + + package static func requireProtected( + previous: ResolvedLedger, next: ResolvedLedger, kinds: Set, + names: Set = [], roots: [String: URL], selectedIdentities: Set? = nil, + retargetedInstructions: Set = [] + ) throws { + struct Projection: Encodable { + let component: LedgerComponent + let sources: [[LedgerSource]] + let resources: [LedgerResource] + } + func streams(_ ledger: ResolvedLedger) throws -> [String: [String]] { + var result: [String: [String]] = [:] + let selectedParents = try Set( + ledger.occurrences.filter { occurrence in + guard let component = ledger.components[occurrence.component], component.kind == "plugin" + else { return false } + if let selectedIdentities { + return try selectedIdentities.contains( + identity(component, ledger: ledger, roots: roots)) + } + return kinds.contains(.plugin) && (names.isEmpty || names.contains(component.name)) + }.map(\.id)) + for occurrence in ledger.occurrences { + if let member = occurrence.pluginMember, selectedParents.contains(member.parent) { + continue + } + guard var c = ledger.components[occurrence.component] else { continue } + let retargeted = + try c.kind == "instructions" && !c.chatGPT + && retargetedInstructions.contains(identity(c, ledger: ledger, roots: roots)) + let selected = try selectedIdentities.map { + try $0.contains(identity(c, ledger: ledger, roots: roots)) + } + guard + selected == false + || (selected == nil + && (!kinds.contains(DeclaredComponentKind(rawValue: c.kind)!) + || (!names.isEmpty + && !names.contains(c.kind == "skills" ? PathSafety.sanitizeName(c.name) : c.name)))) + else { continue } + func sourceChain(_ id: String) throws -> [LedgerSource] { + var result: [LedgerSource] = [] + var next: String? = id + while let current = next, var source = ledger.sources[current] { + next = source.container + source.container = nil + source.version = nil + if source.kind == .local, !SourceCache.isObjectID(source.revision) { + source.revision = "local" + } + if let transport = source.transport { + source.transport = try SourceDeclaration(kind: source.kind, location: transport) + .identity(environment: RuntimeEnvironment(environment: [:])) + } + if let location = source.location { + source.location = .init( + kind: .absolute, path: try location.resolve(roots: roots).path) + } + result.append(source) + } + return result + } + let sources = + try [sourceChain(c.source), sourceChain(c.declaringSource)] + + c.resources.map { try sourceChain(ledger.resources[$0]!.source) } + let resources = c.resources.enumerated().map { index, id in + var resource = ledger.resources[id]! + resource.source = "resource:" + String(index) + if resource.kind == .liveEdit { resource.hash = "live" } + return resource + } + if var payload = c.payload.object { + if let agents = payload["agents"]?.array { + payload["agents"] = .init(array: agents.sorted { ($0.text ?? "") < ($1.text ?? "") }) + } + if var condition = payload["condition"]?.object { + for key in ["agents", "scopes", "platforms"] { + if let values = condition[key]?.array { + condition[key] = .init(array: values.sorted { ($0.text ?? "") < ($1.text ?? "") }) + } + } + payload["condition"] = .init(object: condition) + } + if c.kind == "skills", payload["mode"]?.text == "edit" { payload["description"] = nil } + c.payload = .init(object: payload) + } + for index in c.conditions.indices { + c.conditions[index].agents?.sort { $0.rawValue < $1.rawValue } + c.conditions[index].scopes?.sort { $0.rawValue < $1.rawValue } + c.conditions[index].platforms?.sort() + } + if ["hook", "permissions"].contains(c.kind) { + try c.conditions.sort { + try ResolvedLedgerCodec.digest($0) < ResolvedLedgerCodec.digest($1) + } + c.conditions = c.conditions.reduce(into: []) { result, condition in + if !result.contains(condition) { result.append(condition) } + } + } + let retargetIdentity = retargeted ? try identity(c, ledger: ledger, roots: roots) : nil + if retargeted { c.recipients = [] } + if c.kind == "skills" { c.name = PathSafety.sanitizeName(c.name) } + c.source = "input" + c.declaringSource = "producer" + c.resources = resources.map(\.hash) + let digest = try ResolvedLedgerCodec.digest( + Projection(component: c, sources: sources, resources: resources)) + let destinations: [String] + if retargeted { + destinations = ["retarget:" + retargetIdentity!] + } else if c.kind == DeclaredComponentKind.instructions.rawValue { + destinations = + c.recipients.map(\.rawValue) + + (c.chatGPT ? ["prompt:" + (c.payload.object?["prompt"]?.text ?? "")] : []) + + (c.payload.object?["copyRecipients"]?.array ?? []).compactMap(\.text) + } else if ["hook", "permissions", "ignore", "plugin"].contains(c.kind) { + destinations = c.recipients.map { c.kind + ":" + $0.rawValue } + } else { + destinations = [c.kind + ":" + c.root + ":" + (c.group ?? "") + ":" + c.name] + } + for destination in destinations.isEmpty + ? ["inactive:" + c.kind + ":" + c.name] : destinations + { + // Coalesced origins do not change effective content; instruction occurrences retain order. + if c.kind == DeclaredComponentKind.instructions.rawValue + || !result[destination, default: []].contains(digest) + { + result[destination, default: []].append(digest) + } + } + } + return result + } + let before = try streams(previous) + let after = try streams(next) + let changed = Set(before.keys).union(after.keys).filter { before[$0] != after[$0] }.sorted() + guard changed.isEmpty else { + throw CoreError.invalidState( + "requiresCombinedUpdate: selected changes affect protected components: " + + changed.joined(separator: ", ")) + } + } + + package static func requireEditable( + _ ledger: ResolvedLedger, kinds: Set, names: Set, + roots: [String: URL], selectedIdentities: Set? = nil + ) throws { + for occurrence in ledger.occurrences where !occurrence.consumerEditable { + let c = ledger.components[occurrence.component]! + if let selectedIdentities, + !selectedIdentities.contains(try identity(c, ledger: ledger, roots: roots)) + { + continue + } + if kinds.contains(DeclaredComponentKind(rawValue: c.kind)!), + names.contains(c.kind == "skills" ? PathSafety.sanitizeName(c.name) : c.name) + { + let producer = try ledger.sourceIdentity(occurrence.declaringSource, roots: roots) + let groups = Dictionary(uniqueKeysWithValues: ledger.groups.map { ($0.id, $0) }) + var chain: [String] = [] + var parent = occurrence.reference + while let reference = parent, let group = groups[reference] { + chain.append( + try ledger.sourceIdentity(group.source, roots: roots) + ":" + group.root + "#" + + group.name) + parent = group.parent + } + throw CoreError.invalidState( + "notEditableHere: \(c.name) is owned by producer \(producer), via \(chain.reversed().joined(separator: " -> ")) (\(occurrence.manifestPath))" + ) + } + } + } +} diff --git a/Sources/Components/LedgerPayload.swift b/Sources/Components/LedgerPayload.swift new file mode 100644 index 0000000..cb91714 --- /dev/null +++ b/Sources/Components/LedgerPayload.swift @@ -0,0 +1,187 @@ +import AgentsCore + +/// Converts typed symbolic payloads to the ledger's explicit tagged vocabulary. +package enum LedgerPayload { + package static func component(_ component: ComponentDeclaration) throws -> LedgerValue { + var fields: [String: LedgerValue] + let agents: [AgentID]? + let condition: DeclarationCondition? + let native: NativeConfiguration + switch component { + case .mcpServer(let name, let transport, let a, let c, let n, _): + fields = ["name": .init(name), "transport": self.transport(transport)] + (agents, condition, native) = (a, c, n) + case .hook(let name, let event, let run, let matcher, let timeout, let a, let c, let n): + let eventValue: LedgerValue + switch event { + case .beforeTool: eventValue = .init("beforeTool") + case .afterTool: eventValue = .init("afterTool") + case .sessionStart: eventValue = .init("sessionStart") + case .sessionEnd: eventValue = .init("sessionEnd") + case .native(let value): eventValue = .init(object: ["native": .init(value)]) + } + fields = ["name": .init(name), "event": eventValue, "run": executable(run)] + fields["matcher"] = matcher.map { .init($0) } + fields["timeoutSeconds"] = timeout.map { .init(integer: $0) } + (agents, condition, native) = (a, c, n) + case .subagent(let name, let description, let body, let model, let tools, let a, let c, let n): + fields = ["name": .init(name), "description": .init(description), "prompt": prompt(body)] + fields["model"] = model.map { .init($0) } + fields["tools"] = tools.map(strings) + (agents, condition, native) = (a, c, n) + case .command(let name, let description, let body, let parameters, let a, let c, let n): + fields = [ + "name": .init(name), "description": .init(description), "prompt": prompt(body), + "parameters": .init( + array: parameters.map { parameter in + var value = [ + "name": LedgerValue(parameter.name), "description": .init(parameter.description), + ] + value["defaultValue"] = parameter.defaultValue.map { .init($0) } + return .init(object: value) + }), + ] + (agents, condition, native) = (a, c, n) + case .lspServer(let name, let run, let languages, let options, let a, let c, let n): + fields = [ + "name": .init(name), "run": executable(run), + "languages": .init(object: languages.mapValues { .init($0) }), + "initializationOptions": .init(object: options.mapValues(value)), + ] + (agents, condition, native) = (a, c, n) + case .permissions(let name, let rules, let a, let c, let n): + fields = ["name": .init(name), "rules": .init(array: rules.map(rule))] + (agents, condition, native) = (a, c, n) + case .ignore(let name, let patterns, let purpose, let a, let c, let n): + fields = [ + "name": .init(name), "patterns": strings(patterns), "purpose": .init(purpose.rawValue), + ] + (agents, condition, native) = (a, c, n) + case .plugin( + let name, let path, let source, let mode, let select, let exclude, let a, let c, let n): + fields = [ + "name": .init(name), "path": .init(path), "source": .init(source), + "mode": .init(mode.rawValue), + "exclude": .init(array: exclude.map(reference)), + ] + fields["select"] = select.map { strings($0.map(\.rawValue)) } + (agents, condition, native) = (a, c, n) + case .skills, .instructions: + throw CoreError.invalidState("selected content requires its frozen payload") + } + fields["agents"] = agents.map { strings($0.map(\.rawValue)) } + fields["condition"] = condition.map(self.condition) + fields["native"] = self.native(native) + return .init(object: fields) + } + + static func native(_ native: NativeConfiguration) -> LedgerValue { + .init(object: native.mapValues { .init(object: $0.mapValues(value)) }) + } + + static func condition(_ condition: DeclarationCondition) -> LedgerValue { + var fields: [String: LedgerValue] = [:] + fields["agents"] = condition.agents.map { strings($0.map(\.rawValue)) } + fields["scopes"] = condition.scopes.map { strings($0.map(\.rawValue)) } + fields["platforms"] = condition.platforms.map { strings($0.map(\.rawValue)) } + return .init(object: fields) + } + + static func strings(_ values: [String]) -> LedgerValue { .init(array: values.map { .init($0) }) } + + private static func value(_ value: NativeValue) -> LedgerValue { + switch value { + case .string(let text): .init(text) + case .integer(let integer): .init(integer: integer) + case .decimal(let decimal): .init(decimal, kind: .decimal) + case .boolean(let boolean): .init(boolean: boolean) + case .null: .init() + case .array(let array): .init(array: array.map(self.value)) + case .object(let object): .init(object: object.mapValues(self.value)) + } + } + + private static func binding(_ binding: RuntimeBinding) -> LedgerValue { + switch binding { + case .literal(let value): .init(value, kind: .literal) + case .environment(let value): .init(value, kind: .environment) + case .secret(let value): .init(value, kind: .secret) + } + } + + private static func resource(_ resource: ResourceDeclaration) -> LedgerValue { + var fields = ["path": LedgerValue(resource.path)] + fields["source"] = resource.source.map { .init($0) } + return .init(object: fields) + } + + private static func executable(_ run: ExecutableDeclaration) -> LedgerValue { + var fields: [String: LedgerValue] = [ + "executable": .init(run.executable), "arguments": strings(run.arguments), + "environment": .init(object: run.environment.mapValues(binding)), + ] + fields["executableSource"] = run.executableSource.map { .init($0) } + fields["workingDirectory"] = run.workingDirectory.map(resource) + return .init(object: fields) + } + + private static func transport(_ transport: MCPTransportDeclaration) -> LedgerValue { + switch transport { + case .stdio(let run): return .init(object: ["kind": .init("stdio"), "run": executable(run)]) + case .streamableHTTP(let url, let headers): + return .init(object: [ + "kind": .init("streamableHTTP"), "url": .init(url), + "headers": .init(object: headers.mapValues(binding)), + ]) + case .sse(let url, let headers): + return .init(object: [ + "kind": .init("sse"), "url": .init(url), + "headers": .init(object: headers.mapValues(binding)), + ]) + } + } + + private static func prompt(_ prompt: PromptBody) -> LedgerValue { + switch prompt { + case .literal(let text): .init(text, kind: .literal) + case .file(let file): .init(object: ["file": resource(file)]) + } + } + + private static func rule(_ rule: PermissionRuleDeclaration) -> LedgerValue { + let action: String + let operation: PermissionOperationDeclaration + let pattern: String + switch rule { + case .allow(let op, let p): (action, operation, pattern) = ("allow", op, p) + case .ask(let op, let p): (action, operation, pattern) = ("ask", op, p) + case .deny(let op, let p): (action, operation, pattern) = ("deny", op, p) + } + let op: LedgerValue + switch operation { + case .read: op = .init("read") + case .write: op = .init("write") + case .execute: op = .init("execute") + case .tool(let name): op = .init(object: ["tool": .init(name)]) + } + return .init(object: ["action": .init(action), "operation": op, "pattern": .init(pattern)]) + } + + static func reference(_ reference: ComponentReferenceDeclaration) -> LedgerValue { + let kind: String + let name: String + switch reference { + case .skill(let value): (kind, name) = ("skills", value) + case .instruction(let value): (kind, name) = ("instructions", value) + case .mcpServer(let value): (kind, name) = ("mcpServer", value) + case .hook(let value): (kind, name) = ("hook", value) + case .subagent(let value): (kind, name) = ("subagent", value) + case .command(let value): (kind, name) = ("command", value) + case .lspServer(let value): (kind, name) = ("lspServer", value) + case .permissions(let value): (kind, name) = ("permissions", value) + case .ignore(let value): (kind, name) = ("ignore", value) + case .plugin(let value): (kind, name) = ("plugin", value) + } + return .init(object: ["kind": .init(kind), "name": .init(name)]) + } +} diff --git a/Sources/Components/LedgerReplay.swift b/Sources/Components/LedgerReplay.swift new file mode 100644 index 0000000..54d8dad --- /dev/null +++ b/Sources/Components/LedgerReplay.swift @@ -0,0 +1,615 @@ +import AgentsCore +import AgentsInstructions +import Foundation + +/// Borrowed trees are valid only inside the replay closure. Shared-file values are intentions; +/// physical ownership, secret binding and publication remain with the applying operation. +package struct ReplayedArtifact { + package var name: String + package var kind: LedgerArtifactDigest.Kind + package var bytes: Data? + package var tree: URL? + package var values: LedgerValue? + package var location: LedgerLocation? + + package init( + name: String, kind: LedgerArtifactDigest.Kind, bytes: Data? = nil, + tree: URL? = nil, values: LedgerValue? = nil, location: LedgerLocation? = nil + ) { + self.name = name + self.kind = kind + self.bytes = bytes + self.tree = tree + self.values = values + self.location = location + } + + package func digest(limits: LedgerLimits) throws -> LedgerArtifactDigest { + let hash: String + switch kind { + case .link: + guard let location, bytes == nil, tree == nil, values == nil else { + throw CoreError.invalidState("invalid live link") + } + hash = try ResolvedLedgerCodec.digest(location) + case .file, .registration: + guard let bytes, tree == nil, values == nil else { + throw CoreError.invalidState("invalid rendered file") + } + hash = "sha256:" + FileHash.sha256Hex(data: bytes) + case .tree: + guard let tree, bytes == nil, values == nil else { + throw CoreError.invalidState("invalid rendered tree") + } + let captured = try LedgerResources.capture(tree, embed: false, limits: limits) + hash = try ResolvedLedgerCodec.digest( + TreeDigest(content: captured.hash, entries: captured.entries)) + case .ownedValues: + guard let values, bytes == nil, tree == nil else { + throw CoreError.invalidState("invalid owned values") + } + hash = try ResolvedLedgerCodec.digest(values) + } + return .init(name: name, kind: kind, hash: hash) + } + + private struct TreeDigest: Encodable { + let content: String + let entries: [LedgerEntry] + } +} + +package typealias LedgerRenderer = ( + _ lowering: LockedLowering, _ ledger: ResolvedLedger, _ resources: [String: URL] +) throws -> [ReplayedArtifact] + +package enum LedgerReplay { + /// Only formats with implemented production semantics are registered here. Tests explicitly + /// supply their own renderer table; a format is never selected by agent or current version. + package static var compatibilityRenderers: [String: LedgerRenderer] { + compatibilityRenderers(outputBytes: LedgerLimits.standard.resourceBytes) + } + + private static func compatibilityRenderers(outputBytes: Int) -> [String: LedgerRenderer] { + [ + "agents/skill@1": skill, + AntigravityRuleV1.format: antigravityRule, + "agents/instructions@1": { try instructions($0, $1, $2, outputBytes: outputBytes) }, + "agents/claude-import@1": { try forwarding($0, $1, $2, outputBytes: outputBytes) }, + "agents/chatgpt@1": { try renderPrompt($0, $1, $2, outputBytes: outputBytes) }, + LockedLowering.instructionCopyFormat: { + try renderPrompt($0, $1, $2, outputBytes: outputBytes) + }, + ].merging(MCPLayoutV1.renderers) { existing, _ in existing } + .merging(NativeComponentLayoutsV1.renderers(limits: .standard)) { existing, _ in existing } + } + + package static func withReplay( + _ ledger: ResolvedLedger, store: StateStore, roots: [String: URL], limits: LedgerLimits, + renderers: [String: LedgerRenderer]? = nil, + _ body: ([ReplayedArtifact]) throws -> T + ) throws -> T { + try run( + ledger, store: store, roots: roots, limits: limits, renderers: renderers, + recording: false + ) { artifacts, _, _, _ in try body(artifacts) } + } + + package static func withPreparedLowerings( + _ 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 + ) throws -> T { + try run( + ledger, store: store, roots: roots, limits: limits, renderers: nil, recording: true, + offline: offline, sourcePolicy: sourcePolicy, + requireRecordedTransport: requireRecordedTransport, acquisitions: acquisitions + ) { + artifacts, lowerings, resources, workspace in + var candidate = ledger + candidate.lowerings = lowerings + try candidate.validate() + return try body(candidate, artifacts, resources, workspace) + } + } + + package static func withLockedResources( + _ ledger: ResolvedLedger, store: StateStore, roots: [String: URL], limits: LedgerLimits, + lowerings selected: Set? = nil, offline: Bool = false, + sourcePolicy: EffectiveSourcePolicy = .init(), requireRecordedTransport: Bool = false, + acquisitions: GitAcquisitionCaptures? = nil, + additionalResources: Set = [], anchorLockedGit: Bool = false, + _ body: ([ReplayedArtifact], [String: URL], 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 + ) { + artifacts, _, resources, workspace in try body(artifacts, resources, workspace) + } + } + + /// An update reads only the prior native inputs it needs for ownership comparison. + /// A replaced source still belongs to the old lock, but no read of its former route occurs + /// unless one of these outputs actually needs bytes from it. + static func withPriorOutputs( + _ ledger: ResolvedLedger, store: StateStore, roots: [String: URL], + lowerings: Set, offline: Bool, sourcePolicy: EffectiveSourcePolicy, + _ body: ([ReplayedArtifact]) throws -> T + ) throws -> T { + try run( + ledger, store: store, roots: roots, limits: .standard, renderers: nil, recording: false, + selectedLowerings: lowerings, offline: offline, sourcePolicy: sourcePolicy, + completeSourceAdmission: false + ) { artifacts, _, _, _ in try body(artifacts) } + } + + /// Acquires just the selected locked inputs, independently of their target renderers. + package static func captureBundleResources( + _ ids: Set, ledger: ResolvedLedger, store: StateStore, roots: [String: URL], + sourcePolicy: EffectiveSourcePolicy = .init(), offline: Bool = false + ) throws -> (resources: [String: LedgerResource], objects: [String: Data]) { + if offline, ids.contains(where: { ledger.resources[$0]?.kind == .liveEdit }) { + throw CoreError.invalidState("cannot pack a live resource as a locked dependency") + } + var records: [String: LedgerResource] = [:] + var objects: [String: Data] = [:] + var remaining = LedgerLimits.standard.objectBytes + func add(_ digest: String, _ bytes: Data) throws { + guard objects[digest] == nil else { return } + guard bytes.count <= remaining else { throw CoreError.invalidState("bundle content budget") } + remaining -= bytes.count + objects[digest] = bytes + } + func capture(_ id: String, _ file: URL, _ snapshotRoot: URL?) throws { + var resource = ledger.resources[id]! + switch resource.kind { + case .embedded, .artifact: + for digest in (resource.entries + resource.support).compactMap(\.object) { + try add(digest, ledger.contentObjects[digest]!) + } + case .archive: + throw SourceAccessError.egressDenied + case .git where offline: + guard let snapshotRoot else { throw CoreError.invalidState("missing locked Git snapshot") } + let captured = try LedgerResources.captureLockedGit(resource, snapshotRoot: snapshotRoot) + resource.entries = captured.entries + resource.support = captured.support + for (digest, bytes) in captured.objects { try add(digest, bytes) } + case .liveEdit, .git: + let live = resource.kind == .liveEdit ? try TargetPrecondition(file) : nil + let sourceRoot = + try snapshotRoot + ?? ledger.sources[resource.source]?.location?.resolve(roots: roots) + let captured = try LedgerResources.capture( + file, embed: true, limits: .standard, sourceRoot: sourceRoot) + try live?.validate() + if resource.kind == .git { + func withoutObjects(_ entries: [LedgerEntry]) -> [LedgerEntry] { + entries.map { entry in + var entry = entry + entry.object = nil + return entry + } + } + guard captured.hash == resource.hash, + withoutObjects(captured.entries) == resource.entries, + withoutObjects(captured.support) == resource.support + else { throw CoreError.invalidState("locked bundle resource changed during export") } + } + resource.hash = captured.hash + resource.entries = captured.entries + resource.support = captured.support + for (digest, bytes) in captured.objects { try add(digest, bytes) } + } + resource.kind = .embedded + resource.location = nil + resource.artifact = nil + records[id] = resource + } + try run( + ledger, store: store, roots: roots, limits: .standard, renderers: nil, recording: false, + selectedLowerings: [], offline: offline, sourcePolicy: sourcePolicy, selectedResources: ids, + observeResource: capture + ) { _, _, _, _ in } + return (records, objects) + } + + /// Seals renderer output identities into a candidate before encoding or publication. + package static func prepareLowerings( + _ ledger: ResolvedLedger, store: StateStore, roots: [String: URL], limits: LedgerLimits, + renderers: [String: LedgerRenderer]? = nil + ) throws -> ResolvedLedger { + try run( + ledger, store: store, roots: roots, limits: limits, renderers: renderers, + recording: true + ) { _, lowerings, _, _ in + var candidate = ledger + candidate.lowerings = lowerings + try candidate.validate() + return candidate + } + } + + private static func run( + _ ledger: ResolvedLedger, store: StateStore, roots: [String: URL], limits: LedgerLimits, + renderers: [String: LedgerRenderer]?, recording: Bool, + selectedLowerings: Set? = nil, offline: Bool = false, + sourcePolicy: EffectiveSourcePolicy = .init(), requireRecordedTransport: Bool = false, + acquisitions: GitAcquisitionCaptures? = nil, selectedResources: Set? = nil, + additionalResources: Set = [], anchorLockedGit: Bool = false, + completeSourceAdmission: Bool = true, + observeResource: ((String, URL, URL?) throws -> Void)? = nil, + _ body: ([ReplayedArtifact], [LockedLowering], [String: URL], URL) throws -> T + ) throws -> T { + try ResolvedLedgerCodec.checkModel(ledger, limits: limits) + try ledger.validate() + if completeSourceAdmission { try sourcePolicy.require(ledger, store: store, roots: roots) } + try Task.checkCancellation() + let lowerings = ledger.lowerings.filter { selectedLowerings?.contains($0.id) ?? true } + guard selectedLowerings.map({ $0.isSubset(of: Set(ledger.lowerings.map(\.id))) }) ?? true else { + throw CoreError.invalidState("unknown selected locked lowering") + } + let resourceIDs = + (selectedResources + ?? (selectedLowerings == nil + ? Set(ledger.resources.keys) : Set(lowerings.flatMap(\.resources)))) + .union(additionalResources) + guard resourceIDs.isSubset(of: Set(ledger.resources.keys)) else { + throw CoreError.invalidState("unknown selected locked resource") + } + let platform = ProcessInfo.processInfo.operatingSystemVersionString + #if os(macOS) + let current = "macos" + #else + let current = "linux" + #endif + for lowering in lowerings { + guard (renderers ?? compatibilityRenderers)[lowering.format] != nil else { + throw CoreError.invalidState("unknown renderer format") + } + guard lowering.platform == current else { + throw CoreError.invalidState("locked lowering is incompatible with platform: " + platform) + } + } + // Charge every occurrence, not only unique stored resources. Reserve this before reads; + // the same Core expansion limit also bounds all outputs retained by this replay. + let sizes = ledger.resources.mapValues { resource in + (resource.entries + resource.support).reduce(0) { $0 + ($1.byteCount ?? 0) } + } + var remaining = limits.resourceBytes + for lowering in lowerings { + for id in lowering.resources { + let size = sizes[id]! + guard size <= remaining else { throw CoreError.invalidState("replay input byte budget") } + remaining -= size + } + } + for id in additionalResources.subtracting(lowerings.flatMap(\.resources)) { + let size = sizes[id]! + guard size <= remaining else { throw CoreError.invalidState("replay input byte budget") } + remaining -= size + } + let workspace = try SourceCache.privateWorkspace(prefix: "agents-ledger-") + defer { try? FileManager.default.removeItem(at: workspace) } + return try SourceResolutionSession.withTemporaryRead( + store: store, sourcePolicy: sourcePolicy, requireRecordedTransport: requireRecordedTransport, + acquisitions: acquisitions + ) { session in + var acquired: [String: URL] = [:] + 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? + if resource.kind == .liveEdit { + file = try LedgerResources.liveEditSource(resource, ledger: ledger, roots: roots).authored + } else if resource.kind == .embedded || resource.kind == .artifact { + if !completeSourceAdmission, let artifact = resource.artifact { + for origin in EffectiveSourcePolicy.artifactOrigins(artifact) { + try sourcePolicy.require(origin) + guard let location = origin.identity, let url = URL(string: location) else { + throw SourceAccessError.invalidRepository + } + try store.environment.sourceAccess.requireDirectHTTP(url) + } + } + file = 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 + if anchorLockedGit { + let captured = try LedgerResources.captureLockedGit(resource, snapshotRoot: view.root) + var frozen = resource + frozen.kind = .embedded + frozen.entries = captured.entries + frozen.support = captured.support + file = try materialize( + frozen, objects: captured.objects, in: workspace, preserveSpelling: true) + } else { + file = try view.resource(resource.path) + } + } + if resource.kind != .liveEdit + && !(anchorLockedGit && resource.kind == .git) + && !(offline && observeResource != nil && resource.kind == .git) + { + let captured = try LedgerResources.capture( + file, embed: false, limits: limits, sourceRoot: snapshotRoot) + 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 + else { + throw CoreError.invalidState("locked resource content or execute bits changed") + } + } + try observeResource?(id, file, snapshotRoot) + acquired[id] = file + } + var result: [ReplayedArtifact] = [] + var sealed: [LockedLowering] = [] + var names = Set() + for lowering in lowerings { + try Task.checkCancellation() + let table = renderers ?? compatibilityRenderers(outputBytes: remaining) + let rendered = try table[lowering.format]!(lowering, ledger, acquired) + for artifact in rendered { + let count: Int + if let bytes = artifact.bytes { + count = bytes.count + } else if let tree = artifact.tree { + let captured = try LedgerResources.capture(tree, embed: false, limits: limits) + count = (captured.entries + captured.support).reduce(0) { $0 + ($1.byteCount ?? 0) } + } else if let values = artifact.values { + count = try ResolvedLedgerCodec.bytes(values).count + } else if let location = artifact.location { + count = try ResolvedLedgerCodec.bytes(location).count + } else { + throw CoreError.invalidState("missing rendered output") + } + guard count <= remaining else { + throw CoreError.invalidState("replay output byte budget") + } + remaining -= count + } + let digests = try rendered.map { try $0.digest(limits: limits) } + guard recording || digests == lowering.artifacts else { + throw CoreError.invalidState("locked renderer output hash mismatch") + } + for artifact in rendered { + guard names.insert(artifact.name).inserted else { + throw CoreError.invalidState("overlapping rendered artifacts") + } + } + var locked = lowering + locked.artifacts = digests + sealed.append(locked) + result += rendered + } + return try body(result, sealed, acquired, workspace) + } + } + + private static func materialize( + _ resource: LedgerResource, objects: [String: Data], in workspace: URL, + preserveSpelling: Bool + ) throws -> URL { + var embedded = resource + embedded.kind = .embedded + let name = UUID().uuidString + let destination = workspace.appendingPathComponent(name) + // A Foundation file URL can normalize Unicode on write. The locked renderer hashes + // exact UTF-8 entry names, so construct the borrowed tree through directory descriptors. + if preserveSpelling, + !resource.support.isEmpty + || resource.entries.contains(where: { $0.path == "." && $0.kind == .directory }) + { + let entries = try LedgerResources.validatedEntries(embedded) + let parent = try DirectoryHandle.readDirectory(at: workspace) + guard + try parent.publishPortableTree( + named: name, entries: Array(entries.values), objects: objects, beforeCommit: {}) + else { throw CoreError.invalidState("replay workspace collision") } + } else { + try LedgerResources.materialize(embedded, objects: objects, at: destination) + } + return resource.support.isEmpty + ? destination : try PathSafety.resolvedChild(base: destination, subpath: resource.path) + } + + private static func skill( + _ lowering: LockedLowering, _ ledger: ResolvedLedger, _ resources: [String: URL] + ) throws -> [ReplayedArtifact] { + guard lowering.resources.count == 1, let resource = lowering.resources.first, + let tree = resources[resource], let name = lowering.layout.object?["name"]?.text + else { + throw CoreError.invalidState("invalid skill lowering") + } + if let record = ledger.resources[resource], record.kind == .liveEdit { + return [.init(name: name, kind: .link, location: record.location)] + } + return [.init(name: name, kind: .tree, tree: tree)] + } + + private static func antigravityRule( + _ lowering: LockedLowering, _ ledger: ResolvedLedger, _ resources: [String: URL] + ) throws -> [ReplayedArtifact] { + guard let owner = lowering.inputs.first, let component = ledger.components[owner], + let unitID = lowering.resources.first, let unit = ledger.resources[unitID], + let file = resources[unitID], let name = lowering.layout.object?["name"]?.text, + let deployment = ledger.deployments.first(where: { $0.id == lowering.deployments.first }) + else { throw CoreError.invalidState("invalid locked Antigravity rule") } + var inputs: [String: URL] = [:] + for id in lowering.resources.dropFirst() { + guard let input = ledger.resources[id], input.source == component.source, + let url = resources[id], inputs.updateValue(url, forKey: input.path) == nil + else { throw CoreError.invalidState("invalid locked Antigravity include") } + } + let leaf = deployment.target.path + let scope: InstallScope = + deployment.target.root == InstructionLocations.antigravityProjectRoot + ? .project : .user + let bytes = try AntigravityRuleV1.render( + FileSystem.read(at: file), path: unit.path, leaf: leaf, scope: scope + ) { + path in + guard let input = inputs.removeValue(forKey: path) else { + throw AntigravityRuleV1.failure(leaf, "file reference is missing from the lock: \(path)") + } + return try FileSystem.read(at: input) + } + guard inputs.isEmpty, Instructions.hash(bytes) == deployment.expectedHash else { + throw CoreError.invalidState("Antigravity rule does not match its locked inputs: " + leaf) + } + return [.init(name: name, kind: .file, bytes: bytes)] + } + + private static func instructions( + _ lowering: LockedLowering, _ ledger: ResolvedLedger, _ resources: [String: URL], + outputBytes: Int + ) throws -> [ReplayedArtifact] { + let bytes = try lowering.resources.map { id in + guard let resource = resources[id] else { + throw CoreError.invalidState("missing instruction input") + } + return try FileSystem.read(at: resource) + } + guard let name = lowering.layout.object?["name"]?.text, + lowering.layout.object?["headingOffset"]?.integer ?? 0 == 0 + else { + throw CoreError.invalidState("unsupported instruction layout") + } + return [ + .init( + name: name, kind: .file, + bytes: try InstructionCompatibility.renderSections( + bytes, ids: lowering.resources, byteLimit: outputBytes)) + ] + } + + package static func exportPrompt( + _ lowering: LockedLowering, ledger: ResolvedLedger, resources: [String: URL], + roots: [String: URL] + ) throws -> Data { + let locations = try lowering.inputs.compactMap { + try ledger.components[$0]?.payload.object?["localAppend"].map { + try LedgerLocation(ledgerValue: $0) + } + } + let paths = try Set(locations.map { try $0.resolve(roots: roots) }) + guard paths.count <= 1 else { + throw CoreError.invalidState("prompt has conflicting consumer append locations") + } + let append = try locations.first.map { try $0.readContainedFile(roots: roots) } + return try renderPrompt( + lowering, ledger, resources, outputBytes: LedgerLimits.standard.resourceBytes, + consumerAppend: append + ).first!.bytes! + } + + private static func renderPrompt( + _ lowering: LockedLowering, _ ledger: ResolvedLedger, _ resources: [String: URL], + outputBytes: Int, consumerAppend: Data? = nil + ) throws -> [ReplayedArtifact] { + guard let count = lowering.layout.object?["sectionCount"]?.integer, count > 0, + count <= lowering.resources.count, lowering.resources.count <= count + 1, + let name = lowering.layout.object?["name"]?.text + else { throw CoreError.invalidState("invalid prompt layout") } + let sections = try lowering.resources.prefix(count).map { id in + guard let file = resources[id] else { throw CoreError.invalidState("missing prompt section") } + return try FileSystem.read(at: file) + } + var append = try lowering.resources.dropFirst(count).first.map { id in + guard let file = resources[id] else { throw CoreError.invalidState("missing prompt append") } + return try FileSystem.read(at: file) + } + if let consumerAppend, !consumerAppend.isEmpty { + if append?.isEmpty == false { + append!.append(Data("\n".utf8)) + append!.append(consumerAppend) + } else { + append = consumerAppend + } + } + return [ + .init( + name: name, kind: .file, + bytes: try InstructionCompatibility.renderPrompt( + sections, ids: Array(lowering.resources.prefix(count)), append: append, + byteLimit: outputBytes)) + ] + } + + private static func forwarding( + _ lowering: LockedLowering, _ ledger: ResolvedLedger, _ resources: [String: URL], + outputBytes: Int + ) throws -> [ReplayedArtifact] { + guard let name = lowering.layout.object?["name"]?.text, + let target = ledger.deployments.first(where: { $0.id == lowering.deployments.first })?.target, + let path = ClaudeInstructionPath(rawValue: target.path) + else { throw CoreError.invalidState("invalid forwarding layout") } + let block = ClaudeForwarding.renderBlock(for: path) + guard block.utf8.count <= outputBytes else { + throw CoreError.invalidState("replay output byte budget") + } + return [.init(name: name, kind: .file, bytes: Data(block.utf8))] + } +} diff --git a/Sources/Components/LinkBudget.swift b/Sources/Components/LinkBudget.swift new file mode 100644 index 0000000..0a93a45 --- /dev/null +++ b/Sources/Components/LinkBudget.swift @@ -0,0 +1,39 @@ +import AgentsCore +import Foundation + +/// Spent work belongs to the whole search, including rejected candidates and repeated paths. +final class LinkBudget { + private var steps = 0 + private var snapshots = Set() + private struct Manifest: Hashable { + let snapshot: SourceSnapshotID + let path: String + } + private var manifests = Set() + private var bytes = 0 + private var contributions = 0 + + func step(_ count: Int = 1) throws { + try Task.checkCancellation() + steps += count + guard steps <= 1_000_000 else { throw LinkError.budget("resolution/evaluation steps") } + } + + func snapshot(_ value: SourceSnapshotID) throws { + try step() + snapshots.insert(value) + guard snapshots.count <= 256 else { throw LinkError.budget("distinct snapshots") } + } + + func manifest(_ snapshot: SourceSnapshotID, path: String, bytes count: Int) throws { + try step() + if manifests.insert(Manifest(snapshot: snapshot, path: path)).inserted { bytes += count } + guard bytes <= 16_777_216 else { throw LinkError.budget("aggregate manifest bytes") } + } + + func contribution(chain: Int) throws { + try step(1 + chain) + contributions += 1 + guard contributions <= 10_000 else { throw LinkError.budget("contribution occurrences") } + } +} diff --git a/Sources/Components/LinkedComponents.swift b/Sources/Components/LinkedComponents.swift new file mode 100644 index 0000000..34620e0 --- /dev/null +++ b/Sources/Components/LinkedComponents.swift @@ -0,0 +1,401 @@ +import AgentsCore +import AgentsInstructions +import AgentsSkills +import Foundation + +/// Revision-independent, producer-qualified component identity. Roots remain separate namespaces. +package struct ComponentKey: Hashable, Sendable { + package let source: String + package let root: String + package let group: String? + package let kind: DeclaredComponentKind + package let name: String + package let containerRoot: String? + let instructionInput: InstructionInput? + + struct InstructionInput: Hashable, Sendable { + let source: String + let root: String + } + + package init( + source: String, root: String, group: String?, kind: DeclaredComponentKind, + name: String, containerRoot: String? = nil + ) { + self.init( + source: source, root: root, group: group, kind: kind, name: name, + containerRoot: containerRoot, instructionInput: nil) + } + + init( + source: String, root: String, group: String?, kind: DeclaredComponentKind, name: String, + containerRoot: String?, instructionInput: InstructionInput? + ) { + self.source = source + self.root = root + self.group = group + self.kind = kind + self.name = name + self.containerRoot = containerRoot + self.instructionInput = instructionInput + } + + func readingInstruction(from source: String, root: String) -> Self { + .init( + source: self.source, root: self.root, group: group, kind: kind, name: name, + containerRoot: containerRoot, instructionInput: .init(source: source, root: root)) + } + + package static func == (lhs: Self, rhs: Self) -> Bool { + lhs.kind == rhs.kind && lhs.instructionInput == rhs.instructionInput + && lhs.source.utf8.elementsEqual(rhs.source.utf8) + && lhs.root.utf8.elementsEqual(rhs.root.utf8) && lhs.name.utf8.elementsEqual(rhs.name.utf8) + && lhs.group.map { Data($0.utf8) } == rhs.group.map { Data($0.utf8) } + && lhs.containerRoot.map { Data($0.utf8) } == rhs.containerRoot.map { Data($0.utf8) } + } + package func hash(into hasher: inout Hasher) { + hasher.combine(kind.rawValue) + hasher.combine(instructionInput) + for value in [Optional(source), root, group, name, containerRoot] { + hasher.combine(value.map { Data($0.utf8) }) + } + } +} + +/// Exact, relative resource evidence. URLs used while reading never enter this value. +package struct LinkedResource: Equatable, Sendable { + package let snapshot: SourceSnapshotID + package let path: String + package let hash: String + package let executableFlags: [String: Bool] + package let artifact: LockedArtifact? + package let artifactLocation: LedgerLocation? + package let antigravityInclude: Bool + + package init( + snapshot: SourceSnapshotID, path: String, hash: String, + executableFlags: [String: Bool], artifact: LockedArtifact? = nil, + artifactLocation: LedgerLocation? = nil, + antigravityInclude: Bool = false + ) { + self.snapshot = snapshot + self.path = path + self.hash = hash + self.executableFlags = executableFlags + self.artifact = artifact + self.artifactLocation = artifactLocation + self.antigravityInclude = antigravityInclude + } +} + +package enum LinkedPayload: Equatable, Sendable { + case declaration(ComponentDeclaration) + case skill(SnapshotSkill, mode: InstallMode, native: NativeConfiguration) + case instruction(SnapshotInstruction, prompt: String?, native: NativeConfiguration) + + func sameContent(as other: Self) -> Bool { + if case .declaration(let lhs) = self, case .declaration(let rhs) = other { + guard let a = try? ResolvedLedgerCodec.bytes(LedgerPayload.component(lhs.comparisonPayload)), + let b = try? ResolvedLedgerCodec.bytes(LedgerPayload.component(rhs.comparisonPayload)) + else { return false } + return a == b + } + return self == other + } +} + +package struct LinkedPluginMember: Equatable, Sendable { + package let parentOccurrence: Int + package let selector: ComponentReferenceDeclaration + + package static func == (lhs: Self, rhs: Self) -> Bool { + guard lhs.parentOccurrence == rhs.parentOccurrence, + let a = try? ResolvedLedgerCodec.bytes(LedgerPayload.reference(lhs.selector)), + let b = try? ResolvedLedgerCodec.bytes(LedgerPayload.reference(rhs.selector)) + else { return false } + return a == b + } +} + +package struct LinkedPluginExpansion: Equatable, Sendable { + package let snapshot: SourceSnapshotID + package let root: String + package let containerRoot: String + package let document: String + package let input: LedgerInputProvenance + package var children: [Int] + + package static func == (lhs: Self, rhs: Self) -> Bool { + lhs.snapshot.source.utf8.elementsEqual(rhs.snapshot.source.utf8) + && lhs.snapshot.revision.utf8.elementsEqual(rhs.snapshot.revision.utf8) + && lhs.root.utf8.elementsEqual(rhs.root.utf8) + && lhs.containerRoot.utf8.elementsEqual(rhs.containerRoot.utf8) + && lhs.document.utf8.elementsEqual(rhs.document.utf8) + && lhs.input == rhs.input && lhs.children == rhs.children + } +} + +package struct ContributionOrigin: Equatable, Sendable { + package let occurrence: Int + package let provenance: SourceProvenance + package let declaration: SourceSpan? + package let sourceOrigins: [SourceSpan] + package let reference: Int? + package let condition: DeclarationCondition + package let recipients: Set + /// Source variables traversed to reach this contribution, including resource dependencies. + package let dependencies: [SourceSnapshotID] + package let consumerEditable: Bool + package var pluginMember: LinkedPluginMember? = nil + package var pluginExpansion: LinkedPluginExpansion? = nil +} + +package struct LinkedComponent: Equatable, Sendable { + package let key: ComponentKey + package let declaringSnapshot: SourceSnapshotID + package let snapshot: SourceSnapshotID + package let pin: SourceRevision? + package let payload: LinkedPayload + package var conditions: [DeclarationCondition] + package var recipients: Set + /// ChatGPT is a projection, not an AgentID. Scope/platform constraints still apply. + package let chatGPT: Bool + package var resources: [LinkedResource] + package var origins: [ContributionOrigin] + /// Consumer-owned export input. It is not read or retained for installation replay. + package var localAppend: LedgerLocation? = nil + package var copyRecipients: Set = [] +} + +package struct SourceConstraint: Equatable, Sendable { + package let source: String + package let root: String + package let requirement: SourceRequirement? + package let referenceChain: [SourceSpan] +} + +package struct LinkedReference: Equatable, Sendable { + package let occurrence: Int + package let parent: Int? + package let group: String + package let snapshot: SourceSnapshotID + package let root: String + package let constraint: SourceConstraint? + package let referenceChain: [SourceSpan] + package let manifestHash: String +} + +package struct LinkedSourceUse: Equatable, Sendable { + package let source: String + package let root: String + package let requirement: SourceRequirement? + package let organizationRequirements: [SourceRequirement]? + + init( + source: String, root: String, requirement: SourceRequirement?, + organizationRequirements: [SourceRequirement]? = nil + ) { + self.source = source + self.root = root + self.requirement = requirement + self.organizationRequirements = organizationRequirements + } +} + +package struct LinkedComponents: Equatable, Sendable { + package let components: [LinkedComponent] + package let references: [LinkedReference] + package let constraints: [SourceConstraint] + package let selections: [String: SourceRevision] + package let sourceSnapshots: [SourceSnapshotEvidence] + package var sourceUses: [LinkedSourceUse] = [] + package var declaringSnapshots: [SourceSnapshotEvidence] = [] + + /// A semantic projection protects pins, payloads, resource evidence and effective targets. + /// Instructions retain order within each recipient or named prompt. Reference counts and + /// occurrence numbering do not by themselves change protected content. + package func protectedChanges( + from previous: Self, allowing kinds: Set + ) -> [ComponentKey] { + func protected(_ graph: Self) -> [ComponentKey: [LinkedComponent]] { + Dictionary( + grouping: graph.components.filter { + $0.key.kind != .instructions && !kinds.contains($0.key.kind) + }, by: \.key) + } + var changes = Set() + func relations(_ graph: Self) -> [Int: Data] { + guard + graph.components.contains(where: { + $0.origins.contains { $0.pluginMember != nil || $0.pluginExpansion != nil } + }) + else { return [:] } + let occurrences = Dictionary( + uniqueKeysWithValues: graph.components.flatMap { component in + component.origins.map { ($0.occurrence, component) } + }) + func identity(_ key: ComponentKey) -> LedgerValue { + var fields: [String: LedgerValue] = [ + "source": .init(key.source), "root": .init(key.root), + "kind": .init(key.kind.rawValue), "name": .init(key.name), + ] + fields["group"] = key.group.map { .init($0) } + fields["containerRoot"] = key.containerRoot.map { .init($0) } + return .init(object: fields) + } + var result: [Int: Data] = [:] + for component in graph.components { + for origin in component.origins { + var fields: [String: LedgerValue] = [:] + if let member = origin.pluginMember, let parent = occurrences[member.parentOccurrence] { + fields["parent"] = identity(parent.key) + fields["selector"] = LedgerPayload.reference(member.selector) + } + if let expansion = origin.pluginExpansion { + fields["source"] = .init(expansion.snapshot.source) + fields["revision"] = .init(expansion.snapshot.revision) + fields["root"] = .init(expansion.root) + fields["containerRoot"] = .init(expansion.containerRoot) + fields["children"] = .init( + array: expansion.children.compactMap { occurrences[$0] }.map { identity($0.key) }) + } + if !fields.isEmpty { + result[origin.occurrence] = try? ResolvedLedgerCodec.bytes(LedgerValue(object: fields)) + } + } + } + return result + } + let beforeRelations = relations(previous) + let afterRelations = relations(self) + func compare(_ lhs: [LinkedComponent], _ rhs: [LinkedComponent]) { + for (a, b) in zip(lhs, rhs) { + // Coalescing retains distinct complete clauses; collection order carries no restriction. + let sameConditions = + [.hook, .permissions].contains(a.key.kind) + ? a.conditions.count == b.conditions.count + && a.conditions.allSatisfy { b.conditions.contains($0) } + : a.conditions == b.conditions + let aRelations = a.origins.compactMap { beforeRelations[$0.occurrence] }.sorted { + $0.lexicographicallyPrecedes($1) + } + let bRelations = b.origins.compactMap { afterRelations[$0.occurrence] }.sorted { + $0.lexicographicallyPrecedes($1) + } + if a.key != b.key || a.snapshot != b.snapshot || a.pin != b.pin + || !a.payload.sameContent(as: b.payload) + || !sameConditions + || a.localAppend != b.localAppend + || a.recipients != b.recipients || a.chatGPT != b.chatGPT || a.resources != b.resources + || Set(a.origins.flatMap(\.dependencies)) != Set(b.origins.flatMap(\.dependencies)) + || aRelations != bRelations + { + changes.insert(a.key) + changes.insert(b.key) + } + } + for component in lhs.dropFirst(rhs.count) { changes.insert(component.key) } + for component in rhs.dropFirst(lhs.count) { changes.insert(component.key) } + } + let before = protected(previous) + let after = protected(self) + for key in Set(before.keys).union(after.keys) { + compare(before[key] ?? [], after[key] ?? []) + } + if !kinds.contains(.instructions) { + enum Destination: Hashable { + case recipient(InstructionRecipient) + case prompt(String) + case inactive(ComponentKey) + } + func instructions(_ graph: Self) -> [Destination: [LinkedComponent]] { + var streams: [Destination: [LinkedComponent]] = [:] + for component in graph.components { + guard case .instruction(_, let prompt, _) = component.payload else { continue } + for agent in component.recipients { + streams[.recipient(.local(agent)), default: []].append(component) + } + for recipient in component.copyRecipients { + streams[.recipient(recipient), default: []].append(component) + } + if component.chatGPT, let prompt { + streams[.prompt(prompt), default: []].append(component) + } else if component.recipients.isEmpty, component.copyRecipients.isEmpty { + // Inactive declarations still protect their content, without imposing output order + // between unrelated keys. + streams[.inactive(component.key), default: []].append(component) + } + } + return streams + } + let before = instructions(previous) + let after = instructions(self) + for destination in Set(before.keys).union(after.keys) { + compare(before[destination] ?? [], after[destination] ?? []) + } + } + return changes.sorted { lhs, rhs in + [lhs.source, lhs.root, lhs.containerRoot ?? "", lhs.group ?? "", lhs.kind.rawValue, lhs.name] + .lexicographicallyPrecedes( + [ + rhs.source, rhs.root, rhs.containerRoot ?? "", rhs.group ?? "", rhs.kind.rawValue, + rhs.name, + ]) + } + } + + package func requireEditable(_ key: ComponentKey) throws { + let matches = components.filter { $0.key == key } + guard !matches.isEmpty else { throw LinkError.missing("component: \(key.name)", []) } + for component in matches { + if let origin = component.origins.first(where: { !$0.consumerEditable }) { + throw LinkError.notEditableHere(key, origin.provenance) + } + } + } + + /// Keeps other domains' exact choices when removing constraints or updating direct items. + package func protectedPins(allowing kinds: Set) -> [String: SourceRevision] + { + let protected = Set( + components.filter { !kinds.contains($0.key.kind) } + .flatMap { $0.origins.flatMap(\.dependencies).map(\.source) }) + return selections.filter { protected.contains($0.key) } + } +} + +package enum LinkError: Error, Sendable, CustomStringConvertible { + case missing(String, [SourceSpan]) + case cycle([String], [SourceSpan]) + case incompatible([SourceConstraint]) + case budget(String) + case conflict(ComponentKey, [ContributionOrigin]) + case invalid(String, [SourceSpan]) + case notEditableHere(ComponentKey, SourceProvenance) + + package var description: String { + switch self { + case .missing(let value, let chain): return "Missing \(value)\(Self.locations(chain))" + case .cycle(let groups, let chain): + return "Group cycle: \(groups.joined(separator: " → "))\(Self.locations(chain))" + case .incompatible(let constraints): + return "Incompatible source requirements: " + + constraints.map { + $0.source + " " + String(describing: $0.requirement) + Self.locations($0.referenceChain) + }.joined(separator: "; ") + case .budget(let name): return "Component linking exceeded \(name) budget" + case .conflict(let key, let origins): + return "Conflicting \(key.kind.rawValue) '\(key.name)'" + + Self.locations(origins.flatMap { $0.provenance.referenceChain }) + case .invalid(let reason, let chain): return reason + Self.locations(chain) + case .notEditableHere(let key, let provenance): + return + "notEditableHere: '\(key.name)' is owned by \(provenance.sourceIdentity)/\(provenance.relativePath)" + + Self.locations(provenance.referenceChain) + } + } + + private static func locations(_ spans: [SourceSpan]) -> String { + spans.map { " at \($0.document.rawValue):\($0.line):\($0.column)" }.joined() + } +} diff --git a/Sources/Components/MCPBoundedTransport.swift b/Sources/Components/MCPBoundedTransport.swift new file mode 100644 index 0000000..6a553ec --- /dev/null +++ b/Sources/Components/MCPBoundedTransport.swift @@ -0,0 +1,193 @@ +import AgentsCore +import Foundation +import Logging +import MCP + +/// Cancellation may arrive before connect installs its resource. Installation +/// observes the latched abort, so a late resource cannot escape cleanup. +private final class MCPAbortHandle: @unchecked Sendable { + private let lock = NSLock() + private var aborted = false + private var action: (@Sendable () -> Void)? + func install(_ action: @escaping @Sendable () -> Void) { + let run = lock.withLock { + self.action = action + return aborted + } + if run { action() } + } + func abort() { + let action = lock.withLock { + aborted = true + return self.action + } + action?() + } +} + +actor MCPBoundedTransport: Transport { + nonisolated let logger = Logger( + label: "MCPConnection", factory: { _ in SwiftLogNoOpLogHandler() }) + nonisolated let sink: MCPMessageSink + private nonisolated let abortHandle = MCPAbortHandle() + private let input: MCPConnectionInput + private var process: OwnedDuplexProcess? + private var executable: String? + private var http: MCPHTTPConnection? + private var pumpTask: Task? + private var started = false + private var clean = false + private var cleanupTask: Task? + private var line = Data() + private struct Write { + var bytes: Data + var offset: Int + var continuation: CheckedContinuation + } + private var writes: [Write] = [] + private var writeBytes = 0 + + init(_ input: MCPConnectionInput, limits: MCPConnectionLimits) { + self.input = input + sink = MCPMessageSink(limits) + } + + nonisolated func abort(_ issue: MCPConnectionIssue) { + sink.fail(issue) + abortHandle.abort() + } + + func connect() async throws { + guard !started else { throw MCPConnectionIssue.protocolError } + if let issue = sink.failure { throw issue } + started = true + switch input { + case .stdio(let configuration): + do { + let process = try OwnedDuplexProcess(configuration) + self.process = process + executable = process.resolvedExecutable + abortHandle.install { process.closeInput() } + } catch DuplexProcessError.invalidInput { + throw MCPConnectionIssue.invalidInput + } catch { throw MCPConnectionIssue.connectionFailed } + case .streamableHTTP(let url, let headers): + let http = MCPHTTPConnection(url: url, headers: headers, mode: .streamable, sink: sink) + self.http = http + abortHandle.install { http.abort() } + case .legacySSE(let url, let headers): + let http = MCPHTTPConnection(url: url, headers: headers, mode: .legacy, sink: sink) + self.http = http + abortHandle.install { http.abort() } + } + pumpTask = Task { await pump() } + try await http?.connect() + if let issue = sink.failure { throw issue } + } + + func receive() -> AsyncThrowingStream { sink.stream } + + func send(_ bytes: Data) async throws { + let header = try sink.prepare(bytes) + guard started else { throw MCPConnectionIssue.connectionClosed } + if let http { + try await http.send(bytes, header: header) + return + } + guard process != nil else { throw MCPConnectionIssue.connectionClosed } + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + guard bytes.count < sink.limits.queueBytes - writeBytes, + writes.count < sink.limits.queueMessages + else { + continuation.resume(throwing: MCPConnectionIssue.queueLimit) + abort(.queueLimit) + return + } + var frame = bytes + frame.append(10) + writeBytes += frame.count + writes.append(Write(bytes: frame, offset: 0, continuation: continuation)) + } + } + + private func pump() async { + do { + while sink.failure == nil && !Task.isCancelled { + if let process { + switch try process.readStandardOutput() { + case .bytes(let bytes): + try sink.receiveBytes(bytes.count) + for byte in bytes { + if byte == 10 { + if line.last == 13 { line.removeLast() } + if !line.isEmpty { try sink.admit(line) } + line.removeAll(keepingCapacity: true) + } else { + guard line.count < sink.limits.frameBytes else { + throw MCPConnectionIssue.messageLimit + } + line.append(byte) + } + } + case .end: throw MCPConnectionIssue.connectionClosed + case .wouldBlock: break + } + switch try process.readStandardError() { + case .bytes(let bytes): try sink.receiveBytes(bytes.count, standardError: true) + case .end, .wouldBlock: break + } + if !writes.isEmpty { + let written = try process.write(writes[0].bytes, offset: writes[0].offset) + writes[0].offset += written + if writes[0].offset == writes[0].bytes.count { + let completed = writes.removeFirst() + writeBytes -= completed.bytes.count + completed.continuation.resume() + } + } + } + http?.tick() + try await Task.sleep(for: .milliseconds(1)) + } + } catch { + abort(error as? MCPConnectionIssue ?? .connectionFailed) + } + for pending in writes { + pending.continuation.resume(throwing: sink.failure ?? MCPConnectionIssue.connectionClosed) + } + writes.removeAll() + writeBytes = 0 + line.removeAll() + } + + func disconnect() async { + if let cleanupTask { + clean = await cleanupTask.value + return + } + abort(.connectionClosed) + pumpTask?.cancel() + let pump = pumpTask + let process = process + let http = http + let limits = sink.limits + let task = Task { + await pump?.value + if let process { + return await process.finish( + grace: .seconds(limits.cleanupGrace), + terminate: .seconds(limits.cleanupTerminate), killWait: .seconds(limits.cleanupKillWait)) + } + if let http { return await http.finish() } + return true + } + cleanupTask = task + clean = await task.value + self.process = nil + self.http = nil + pumpTask = nil + } + + func cleanupComplete() -> Bool { clean } + func resolvedExecutable() -> String? { executable } +} diff --git a/Sources/Components/MCPConnectionRunner.swift b/Sources/Components/MCPConnectionRunner.swift new file mode 100644 index 0000000..469c70c --- /dev/null +++ b/Sources/Components/MCPConnectionRunner.swift @@ -0,0 +1,196 @@ +import AgentsCore +import Foundation +import MCP + +private final class MCPDeadline: @unchecked Sendable { + private let lock = NSLock() + let total: ContinuousClock.Instant + private var request: ContinuousClock.Instant + init(_ limits: MCPConnectionLimits, started: ContinuousClock.Instant) { + total = started + .seconds(limits.totalTimeout) + request = min(total, .now + .seconds(limits.requestTimeout)) + } + func arm(_ seconds: TimeInterval) { + lock.withLock { request = min(total, .now + .seconds(seconds)) } + } + var expired: Bool { lock.withLock { ContinuousClock.now >= min(total, request) } } +} + +private actor MCPDiscoveryProgress { + var version: String? + var tools: [MCPDiscoveredTool] = [] + func handshake(_ version: String) { self.version = version } + func append(_ next: [MCPDiscoveredTool]) { tools.append(contentsOf: next) } + func outcome(_ status: MCPConnectionOutcome.Status) -> MCPConnectionOutcome { + MCPConnectionOutcome( + status: status, negotiatedVersion: version, tools: tools, cleanupComplete: false) + } +} + +package enum MCPConnectionRunner { + private enum Event: Sendable { + case completed(MCPConnectionOutcome.Status) + case failed(MCPConnectionIssue) + } + + package static func run( + _ input: MCPConnectionInput, client identity: MCPConnectionClient, + limits: MCPConnectionLimits = .init() + ) async -> MCPConnectionOutcome { + let started = ContinuousClock.now + do { + try limits.validate() + try validate(input, limits: limits) + guard !identity.name.isEmpty, !identity.version.isEmpty, + [identity.name, identity.version].allSatisfy({ + !$0.utf8.contains(0) && $0.utf8.count <= limits.textBytes + }) + else { throw MCPConnectionIssue.invalidInput } + try Task.checkCancellation() + } catch { + return MCPConnectionOutcome( + status: .failed(error is CancellationError ? .cancelled : .invalidInput), + negotiatedVersion: nil, tools: [], cleanupComplete: true) + } + let deadline = MCPDeadline(limits, started: started) + if deadline.expired { + return MCPConnectionOutcome( + status: .failed(.timeout), negotiatedVersion: nil, tools: [], cleanupComplete: true) + } + let transport = MCPBoundedTransport(input, limits: limits) + let client = Client( + name: identity.name, version: identity.version, capabilities: .init(), configuration: .strict) + let progress = MCPDiscoveryProgress() + return await withTaskCancellationHandler { + await withTaskGroup(of: Event.self) { group in + group.addTask { + do { + let initialized = try await client.connect(transport: transport) + guard initialized.protocolVersion == transport.sink.version else { + throw MCPConnectionIssue.protocolError + } + await progress.handshake(initialized.protocolVersion) + guard initialized.capabilities.tools != nil else { return .completed(.noTools) } + var cursor: String? + var seen = Set() + var toolCount = 0 + var pages = 0 + repeat { + guard pages < limits.pages else { throw MCPConnectionIssue.pageLimit } + deadline.arm(limits.requestTimeout) + let request = + cursor.map { ListTools.request(.init(cursor: $0)) } ?? ListTools.request(.init()) + let context = try await client.send(request) + let result = try await context.value + pages += 1 + guard result.tools.count <= limits.tools - toolCount else { + throw MCPConnectionIssue.toolLimit + } + var tools: [MCPDiscoveredTool] = [] + for tool in result.tools { + guard + [tool.name, tool.title ?? "", tool.description ?? ""].allSatisfy({ + $0.utf8.count <= limits.textBytes + }) + else { throw MCPConnectionIssue.textLimit } + tools.append( + MCPDiscoveredTool( + name: tool.name, title: tool.title, description: tool.description)) + } + toolCount += tools.count + await progress.append(tools) + cursor = result.nextCursor + if let cursor { + guard cursor.utf8.count <= limits.frameBytes else { + throw MCPConnectionIssue.messageLimit + } + guard seen.insert(cursor).inserted else { throw MCPConnectionIssue.cursorCycle } + } + } while cursor != nil + return .completed(.discovered) + } catch { + return .failed(error as? MCPConnectionIssue ?? .protocolError) + } + } + group.addTask { + while !Task.isCancelled { + if deadline.expired { + transport.abort(.timeout) + return .failed(.timeout) + } + do { try await Task.sleep(for: .milliseconds(2)) } catch { break } + } + return .failed(.cancelled) + } + group.addTask { + for await issue in transport.sink.failures { return .failed(issue) } + return .failed(.connectionClosed) + } + var event = await group.next() ?? .failed(.connectionClosed) + if case .failed(.connectionClosed) = event, transport.sink.responsesAdmitted { + // EOF must not interrupt SDK decoding of responses already admitted to + // its queue. The existing request/total timer still bounds this join. + event = await group.next() ?? event + } + let transportIssue = transport.sink.closeAdmission() + if let transportIssue, transportIssue != .connectionClosed { + event = .failed(transportIssue) + } + // A separate cleanup task is deliberately joined and is not cancelled + // with the caller: cancelling sleep must not skip EOF/TERM/KILL budgets. + let cleanup = Task { + transport.abort(.connectionClosed) + await client.disconnect() + // The runner joins the transport it created; disconnect is idempotent. + await transport.disconnect() + return await transport.cleanupComplete() + } + let clean = await cleanup.value + group.cancelAll() + while await group.next() != nil {} + let status: MCPConnectionOutcome.Status + switch event { + case .completed(let value): status = value + case .failed(let failure): + let issue = transportIssue ?? failure + let state = await progress.outcome(.failed(issue)) + status = state.negotiatedVersion == nil ? .failed(issue) : .incomplete(issue) + } + var outcome = await progress.outcome(clean ? status : .failed(.cleanupFailed)) + outcome.cleanupComplete = clean + outcome.resolvedExecutable = await transport.resolvedExecutable() + return outcome + } + } onCancel: { + transport.abort(.cancelled) + } + } + + private static func validate(_ input: MCPConnectionInput, limits: MCPConnectionLimits) throws { + var remaining = limits.inputBytes + func admit(_ string: String) throws { + // Charge the terminator as well, bounding arrays of empty arguments. + guard string.utf8.count < remaining else { throw MCPConnectionIssue.invalidInput } + remaining -= string.utf8.count + 1 + } + switch input { + case .stdio(let configuration): + try admit(configuration.executable) + try admit(configuration.directory.path) + for argument in configuration.arguments { try admit(argument) } + for (key, value) in configuration.environment { + try admit(key) + try admit(value) + } + case .streamableHTTP(let url, let headers), .legacySSE(let url, let headers): + try admit(url.absoluteString) + for (key, value) in headers { + try admit(key) + try admit(value) + } + guard MCPHTTPConnection.validURL(url), MCPHTTPConnection.validHeaders(headers) else { + throw MCPConnectionIssue.invalidInput + } + } + } +} diff --git a/Sources/Components/MCPConnectionTypes.swift b/Sources/Components/MCPConnectionTypes.swift new file mode 100644 index 0000000..61229dd --- /dev/null +++ b/Sources/Components/MCPConnectionTypes.swift @@ -0,0 +1,99 @@ +import AgentsCore +import Foundation + +/// Already-bound values borrowed only for this run. No serialization or public API. +package enum MCPConnectionInput: Sendable { + case stdio(DuplexProcessConfiguration) + case streamableHTTP(URL, headers: [String: String]) + case legacySSE(URL, headers: [String: String]) +} + +package struct MCPConnectionClient: Sendable { + package var name: String + package var version: String + package init(name: String, version: String) { + self.name = name + self.version = version + } +} + +package struct MCPConnectionLimits: Sendable { + package var totalTimeout: TimeInterval = 15 + package var requestTimeout: TimeInterval = 5 + package var cleanupGrace: TimeInterval = 0.1 + package var cleanupTerminate: TimeInterval = 0.1 + package var cleanupKillWait: TimeInterval = 1 + // Bytes: at most four 256 KiB frames queued, with 4 MiB aggregate input. + package var inputBytes = 256 * 1024 + package var frameBytes = 256 * 1024 + package var receivedBytes = 4 * 1024 * 1024 + package var sentBytes = 256 * 1024 + package var stderrBytes = 64 * 1024 + package var queueBytes = 1024 * 1024 + package var queueMessages = 4 + package var pages = 16 + package var tools = 256 + package var textBytes = 4096 + package var redirects = 4 + package var resumes = 2 + + package init() {} + + func validate() throws { + let times = [totalTimeout, requestTimeout, cleanupGrace, cleanupTerminate, cleanupKillWait] + guard times.allSatisfy({ $0.isFinite && $0 > 0 && $0 < Double(Int64.max) / 1_000_000_000 }), + [ + inputBytes, frameBytes, receivedBytes, sentBytes, stderrBytes, queueBytes, queueMessages, + pages, tools, textBytes, redirects, resumes, + ].allSatisfy({ $0 > 0 }), + queueBytes >= frameBytes + else { throw MCPConnectionIssue.invalidInput } + } +} + +package enum MCPConnectionIssue: String, Error, Sendable { + case invalidInput + case connectionFailed + case connectionClosed + case protocolError + case unsupportedVersion + case authenticationRequired + case forbidden + case authorityChanged + case sessionExpired + case messageLimit + case receiveLimit + case sendLimit + case stderrLimit + case queueLimit + case pageLimit + case toolLimit + case textLimit + case redirectLimit + case resumeLimit + case cursorCycle + case timeout + case cancelled + case cleanupFailed +} + +package struct MCPDiscoveredTool: Sendable { + package var name: String + package var title: String? + package var description: String? +} + +/// Private result values must be redacted by the facade before presentation. +package struct MCPConnectionOutcome: Sendable { + package enum Status: Sendable, Equatable { + case discovered + case noTools + case incomplete(MCPConnectionIssue) + case failed(MCPConnectionIssue) + } + package var status: Status + package var negotiatedVersion: String? + package var tools: [MCPDiscoveredTool] + package var cleanupComplete: Bool + package var resolvedExecutable: String? = nil +} diff --git a/Sources/Components/MCPHTTPConnection.swift b/Sources/Components/MCPHTTPConnection.swift new file mode 100644 index 0000000..fa64a98 --- /dev/null +++ b/Sources/Components/MCPHTTPConnection.swift @@ -0,0 +1,406 @@ +import Foundation +import MCP + +#if canImport(FoundationNetworking) + import FoundationNetworking +#endif + +/// One ephemeral session per explicit connection test. All job and endpoint +/// state is protected by lock; delegate callbacks never create Swift Tasks. +final class MCPHTTPConnection: NSObject, URLSessionDataDelegate, @unchecked Sendable { + enum Mode { case streamable, legacy } + private final class Job { + var request: URLRequest + let expected: ID? + let events: Bool + let legacyPost: Bool + var continuation: CheckedContinuation? + var parser: MCPSSEParser + var body = Data() + var sse = false + var json = false + var responseSeen = false + var redirects = 0 + var resumes = 0 + var retryAt = ContinuousClock.now + init( + request: URLRequest, expected: ID?, events: Bool, legacyPost: Bool, + continuation: CheckedContinuation?, limit: Int + ) { + self.request = request + self.expected = expected + self.events = events + self.legacyPost = legacyPost + self.continuation = continuation + parser = MCPSSEParser(limit: limit) + } + func finish(_ error: MCPConnectionIssue? = nil) { + let pending = continuation + continuation = nil + if let error { pending?.resume(throwing: error) } else { pending?.resume() } + } + } + + private let lock = NSLock() + private let sink: MCPMessageSink + private let mode: Mode + private let url: URL + private let headers: [String: String] + private let limits: MCPConnectionLimits + private var session: URLSession! + private var sessionID: String? + private var endpoint: URL? + private var endpointWaiter: CheckedContinuation? + private var active: [Int: Job] = [:] + private var resumes: [Job] = [] + private var closed = false + private var invalidated = false + + init(url: URL, headers: [String: String], mode: Mode, sink: MCPMessageSink) { + self.url = url + self.headers = headers + self.mode = mode + self.sink = sink + limits = sink.limits + super.init() + let configuration = URLSessionConfiguration.ephemeral + configuration.httpCookieStorage = nil + configuration.urlCache = nil + configuration.urlCredentialStorage = nil + configuration.httpShouldSetCookies = false + configuration.connectionProxyDictionary = [:] + configuration.timeoutIntervalForRequest = limits.totalTimeout + configuration.timeoutIntervalForResource = limits.totalTimeout + configuration.httpMaximumConnectionsPerHost = limits.queueMessages + let queue = OperationQueue() + queue.maxConcurrentOperationCount = 1 + session = URLSession(configuration: configuration, delegate: self, delegateQueue: queue) + } + + static func validURL(_ url: URL) -> Bool { + ["http", "https"].contains(url.scheme?.lowercased() ?? "") && url.host != nil + && url.user == nil && url.password == nil && url.fragment == nil + } + + static func validHeaders(_ headers: [String: String]) -> Bool { + let reserved = [ + "host", "content-length", "transfer-encoding", "connection", "content-type", "accept", + "mcp-session-id", "mcp-protocol-version", "last-event-id", + ] + let punctuation = Set("!#$%&'*+-.^_`|~".utf8) + var names = Set() + return headers.allSatisfy { key, value in + !key.isEmpty && names.insert(key.lowercased()).inserted + && !reserved.contains(key.lowercased()) + && key.utf8.allSatisfy { + (48...57).contains($0) || (65...90).contains($0) || (97...122).contains($0) + || punctuation.contains($0) + } + && value.utf8.allSatisfy { $0 == 9 || ($0 >= 32 && $0 != 127) } + } + } + + private static func sameOrigin(_ first: URL, _ second: URL) -> Bool { + func port(_ url: URL) -> Int { url.port ?? (url.scheme?.lowercased() == "https" ? 443 : 80) } + return validURL(second) && first.scheme?.lowercased() == second.scheme?.lowercased() + && first.host?.lowercased() == second.host?.lowercased() && port(first) == port(second) + } + + private func request(_ target: URL, method: String, body: Data? = nil) -> URLRequest { + var request = URLRequest(url: target) + request.httpMethod = method + request.httpBody = body + for (name, value) in headers { request.setValue(value, forHTTPHeaderField: name) } + request.setValue("application/json, text/event-stream", forHTTPHeaderField: "Accept") + if body != nil { request.setValue("application/json", forHTTPHeaderField: "Content-Type") } + if mode == .streamable { + request.setValue(sink.version ?? Version.latest, forHTTPHeaderField: "MCP-Protocol-Version") + if let sessionID { request.setValue(sessionID, forHTTPHeaderField: "Mcp-Session-Id") } + } + return request + } + + private func startLocked(_ job: Job) throws { + guard !closed else { throw MCPConnectionIssue.connectionClosed } + guard active.count + resumes.count < limits.queueMessages else { + throw MCPConnectionIssue.queueLimit + } + let task = session.dataTask(with: job.request) + active[task.taskIdentifier] = job + task.resume() + } + + func connect() async throws { + if mode == .streamable { return } + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + lock.withLock { + guard !closed else { + continuation.resume(throwing: MCPConnectionIssue.connectionClosed) + return + } + endpointWaiter = continuation + do { + try startLocked( + Job( + request: request(url, method: "GET"), expected: nil, + events: true, legacyPost: false, continuation: nil, limit: limits.frameBytes)) + } catch { + endpointWaiter = nil + continuation.resume(throwing: MCPConnectionIssue.connectionFailed) + sink.fail(.connectionFailed) + } + } + } + } + + func send(_ data: Data, header: MCPWireHeader) async throws { + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + lock.withLock { + guard !closed else { + continuation.resume(throwing: MCPConnectionIssue.connectionClosed) + return + } + let target = mode == .legacy ? endpoint : url + guard let target else { + continuation.resume(throwing: MCPConnectionIssue.protocolError) + return + } + let job = Job( + request: request(target, method: "POST", body: data), + expected: header.method == nil ? nil : header.id, + events: false, legacyPost: mode == .legacy, + continuation: continuation, limit: limits.frameBytes) + do { try startLocked(job) } catch { + let issue = error as? MCPConnectionIssue ?? .connectionFailed + job.finish(issue) + sink.fail(issue) + } + } + } + } + + /// A single transport pump owns bounded resumption scheduling; delegate + /// callbacks queue at most queueMessages resumptions and never replay POST. + func tick() { + lock.withLock { + guard !closed else { return } + while let index = resumes.firstIndex(where: { $0.retryAt <= .now }) { + let job = resumes.remove(at: index) + do { try startLocked(job) } catch { + job.finish(.connectionFailed) + sink.fail(.connectionFailed) + } + } + } + } + + func abort() { + let session: URLSession? = lock.withLock { + guard !closed else { return nil } + closed = true + endpointWaiter?.resume(throwing: MCPConnectionIssue.connectionClosed) + endpointWaiter = nil + for job in resumes { job.finish(.connectionClosed) } + resumes.removeAll() + return self.session + } + session?.invalidateAndCancel() + } + + func finish() async -> Bool { + abort() + let deadline = ContinuousClock.now + .seconds(limits.cleanupKillWait) + repeat { + if lock.withLock({ invalidated && active.isEmpty && resumes.isEmpty }) { return true } + try? await Task.sleep(for: .milliseconds(2)) + } while ContinuousClock.now < deadline + return false + } + + func urlSession( + _ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, + completionHandler: @escaping @Sendable (URLSession.ResponseDisposition) -> Void + ) { + let allow = lock.withLock { () -> Bool in + guard !closed, let job = active[dataTask.taskIdentifier], + let response = response as? HTTPURLResponse + else { return false } + let issue: MCPConnectionIssue? + switch response.statusCode { + case 401: issue = .authenticationRequired + case 403: issue = .forbidden + case 404 where sessionID != nil: issue = .sessionExpired + case 200, 202, 204: issue = nil + default: issue = .connectionFailed + } + if let issue { + sink.fail(issue) + return false + } + if let value = response.value(forHTTPHeaderField: "Mcp-Session-Id"), mode == .streamable { + guard !value.isEmpty, value.utf8.count <= 1024, + value.utf8.allSatisfy({ $0 >= 33 && $0 <= 126 }), + sessionID == nil || sessionID == value + else { + sink.fail(.protocolError) + return false + } + sessionID = value + } + let type = response.value(forHTTPHeaderField: "Content-Type")?.split(separator: ";").first? + .trimmingCharacters(in: .whitespaces).lowercased() + job.sse = type == "text/event-stream" + job.json = type == "application/json" + if job.events || (job.expected != nil && !job.legacyPost) { + guard response.statusCode == 200, job.sse || (!job.events && job.json) else { + sink.fail(.protocolError) + return false + } + } + return true + } + completionHandler(allow ? .allow : .cancel) + } + + func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive bytes: Data) { + lock.withLock { + guard !closed, let job = active[dataTask.taskIdentifier] else { return } + do { + try sink.receiveBytes(bytes.count) + if job.legacyPost { return } + if job.expected == nil && !job.events && !bytes.isEmpty { + throw MCPConnectionIssue.protocolError + } + if job.sse { + var parser = job.parser + try parser.feed(bytes) { event in + if mode == .legacy && job.events && event.name == "endpoint" { + guard endpoint == nil, let text = String(data: event.data, encoding: .utf8), + let candidate = URL(string: text, relativeTo: url)?.absoluteURL, + Self.sameOrigin(url, candidate) + else { throw MCPConnectionIssue.authorityChanged } + endpoint = candidate + endpointWaiter?.resume() + endpointWaiter = nil + } else if event.name.isEmpty || event.name == "message" { + try sink.admit(event.data) + if let expected = job.expected, + let header = try? JSONDecoder().decode(MCPWireHeader.self, from: event.data), + header.id == expected && header.method == nil + { + job.responseSeen = true + } + } + } + job.parser = parser + } else if job.json { + guard bytes.count <= limits.frameBytes - job.body.count else { + throw MCPConnectionIssue.messageLimit + } + job.body.append(bytes) + } else if !bytes.isEmpty { + throw MCPConnectionIssue.protocolError + } + } catch { + sink.fail(error as? MCPConnectionIssue ?? .protocolError) + dataTask.cancel() + } + } + } + + func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { + lock.withLock { + guard let job = active.removeValue(forKey: task.taskIdentifier) else { return } + if closed || sink.failure != nil { + job.finish(sink.failure ?? .connectionClosed) + return + } + do { + if (error as? URLError)?.code == .timedOut { throw MCPConnectionIssue.timeout } + if job.json && job.expected != nil && !job.legacyPost { + if error != nil { throw MCPConnectionIssue.connectionFailed } + let header = try? JSONDecoder().decode(MCPWireHeader.self, from: job.body) + guard header?.id == job.expected, header?.method == nil else { + throw MCPConnectionIssue.protocolError + } + try sink.admit(job.body) + job.responseSeen = true + } + if job.events { throw MCPConnectionIssue.connectionClosed } + if job.sse && job.expected != nil && !job.responseSeen && mode == .streamable, + let id = job.parser.lastID, !id.isEmpty + { + guard job.resumes < limits.resumes else { throw MCPConnectionIssue.resumeLimit } + let delay = job.parser.retry ?? 0 + guard delay < limits.totalTimeout else { throw MCPConnectionIssue.timeout } + job.resumes += 1 + job.retryAt = .now + .seconds(delay) + job.request = request(url, method: "GET") + job.request.setValue(id, forHTTPHeaderField: "Last-Event-ID") + job.parser.restart() + resumes.append(job) + return + } + if error != nil { throw MCPConnectionIssue.connectionFailed } + if job.expected != nil && !job.legacyPost && !job.responseSeen { + throw MCPConnectionIssue.protocolError + } + job.finish() + } catch { + let issue = error as? MCPConnectionIssue ?? .connectionFailed + job.finish(issue) + sink.fail(issue) + } + } + } + + func urlSession( + _ session: URLSession, task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, + completionHandler: @escaping @Sendable (URLRequest?) -> Void + ) { + let next: URLRequest? = lock.withLock { + guard !closed, let job = active[task.taskIdentifier], let target = request.url, + Self.sameOrigin(url, target) + else { + sink.fail(.authorityChanged) + return nil + } + guard job.redirects < limits.redirects else { + sink.fail(.redirectLimit) + return nil + } + guard request.httpMethod == job.request.httpMethod else { + sink.fail(.protocolError) + return nil + } + job.redirects += 1 + job.request.url = target + return job.request + } + completionHandler(next) + } + + func urlSession( + _ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, + completionHandler: + @escaping @Sendable (URLSession.AuthChallengeDisposition, URLCredential?) -> Void + ) { + #if canImport(Security) + if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { + completionHandler(.performDefaultHandling, nil) + return + } + #endif + sink.fail(.authenticationRequired) + completionHandler(.cancelAuthenticationChallenge, nil) + } + + func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { + lock.withLock { + invalidated = true + for job in active.values { job.finish(.connectionClosed) } + active.removeAll() + } + } +} diff --git a/Sources/Components/MCPLayoutV1.swift b/Sources/Components/MCPLayoutV1.swift new file mode 100644 index 0000000..02e440f --- /dev/null +++ b/Sources/Components/MCPLayoutV1.swift @@ -0,0 +1,186 @@ +import AgentsCore +import Foundation + +/// Version 1 stores regional intentions, references and exact resource identities. Its renderer +/// does not choose a route, expand a binding or turn temporary replay trees into native paths. +/// The owned-values artifact is the complete region-intention envelope, so its digest also pins +/// targeting and binding placement. E decodes it to a contribution before native preparation. +package enum MCPLayoutV1 { + static var renderers: [String: LedgerRenderer] { + [ + "agents/antigravity-mcp@1": render, + "agents/claude-mcp@1": render, + "agents/codex-mcp@1": render, + "agents/gemini-mcp@1": render, + "agents/opencode-mcp@1": render, + "agents/cursor-mcp@1": render, + ] + } + + package static func contribution( + _ lowering: LockedLowering, ledger: ResolvedLedger + ) throws -> NativeMCPContribution { + func invalid() -> CoreError { .invalidState("invalid version 1 MCP layout") } + try lowering.layout.validate() + guard let layout = lowering.layout.object, + Set(layout.keys) == [ + "artifact", "surface", "scope", "component", "name", "value", "occurrences", + "recipients", "knownReaders", "bindings", "resourcePlacements", + ], + let surfaceText = string(layout["surface"]), + let surface = NativeClientSurface(rawValue: surfaceText), + let scopeText = string(layout["scope"]), let scope = NativeMCPScope(rawValue: scopeText), + let name = string(layout["name"]), !name.isEmpty, + let component = string(layout["component"]), lowering.inputs == [component], + let record = ledger.components[component], record.name == name, record.kind == "mcpServer", + record.recipients.contains(surface.agent), lowering.resources == record.resources, + let value = layout["value"], value.kind == .object, + let artifact = string(layout["artifact"]), !artifact.isEmpty, + layout["occurrences"]?.kind == .array, let occurrenceValues = layout["occurrences"]?.array, + layout["bindings"]?.kind == .array, let bindingValues = layout["bindings"]?.array, + layout["resourcePlacements"]?.kind == .array, + let resourceValues = layout["resourcePlacements"]?.array + else { throw invalid() } + let descriptor = try CapabilityRegistry.mcp( + .init(surface: surface, scope: scope), component: name) + guard lowering.format == descriptor.format, + layout["recipients"] == LedgerPayload.strings([surface.agent.rawValue]), + layout["knownReaders"] + == LedgerPayload.strings(descriptor.knownReaders.map(\.rawValue).sorted()) + else { throw invalid() } + let occurrences = try occurrenceValues.map { value in + guard value.kind == .integer, let id = value.integer else { throw invalid() } + return id + } + guard !occurrences.isEmpty, + Set(occurrences).count == occurrences.count, + occurrences + == ledger.occurrences.filter({ + $0.component == component && occurrences.contains($0.id) + }).map(\.id) + else { throw invalid() } + let bindings: [MCPBindingPlacement] = try bindingValues.map { item in + guard let fields = item.object, Set(fields.keys) == ["path", "binding", "reference"], + let encoded = fields["binding"], let name = encoded.text, + fields["reference"]?.kind == .boolean, let reference = fields["reference"]?.boolean + else { throw invalid() } + let binding: RuntimeBinding + switch encoded.kind { + case .environment: binding = .environment(name) + case .secret where !reference: binding = .secret(name) + default: throw invalid() + } + let steps = try steps(fields["path"]) + let slot = try at(steps, in: value) + if reference { + guard MCPReferenceSyntax.isName(name) + else { + throw invalid() + } + let expected: LedgerValue + switch surface { + case .claudeCode: expected = .init(MCPReferenceSyntax.claude.render(name)) + case .geminiCLI: expected = .init(MCPReferenceSyntax.gemini.render(name)) + case .codexCLI: expected = .init(name) + case .openCodeCLI, .cursorEditor, .cursorCLI, .cursorCloud, .antigravity: throw invalid() + } + guard slot == expected else { throw invalid() } + } else { + guard slot == encoded else { throw invalid() } + } + return .init(path: steps, binding: binding, reference: reference) + } + let resourcePlacements: [MCPResourcePlacement] = try resourceValues.map { item in + guard let fields = item.object, Set(fields.keys) == ["path", "resource"], + let resource = string(fields["resource"]), lowering.resources.contains(resource) + else { throw invalid() } + let steps = try steps(fields["path"]) + guard try at(steps, in: value) == .init(object: ["resource": .init(resource)]) else { + throw invalid() + } + return .init(path: steps, resource: resource) + } + var paths: [[MCPValueStep]] = [] + for path in bindings.map(\.path) + resourcePlacements.map(\.path) { + guard !paths.contains(where: { $0.starts(with: path) || path.starts(with: $0) }) else { + throw invalid() + } + paths.append(path) + } + return .init( + descriptor: descriptor, component: component, name: name, occurrences: occurrences, + recipients: [surface.agent], bindings: bindings, resourcePlacements: resourcePlacements, + value: value, resources: lowering.resources) + } + + static func path(_ path: [MCPValueStep]) -> LedgerValue { + .init( + array: path.map { step in + switch step { + case .key(let key): .init(object: ["key": .init(key)]) + case .index(let index): .init(object: ["index": .init(integer: index)]) + } + }) + } + + static func binding(_ binding: RuntimeBinding) -> LedgerValue { + switch binding { + case .literal(let value): .init(value, kind: .literal) + case .environment(let name): .init(name, kind: .environment) + case .secret(let name): .init(name, kind: .secret) + } + } + + private static func string(_ value: LedgerValue?) -> String? { + value?.kind == .string ? value?.text : nil + } + + private static func steps(_ value: LedgerValue?) throws -> [MCPValueStep] { + guard value?.kind == .array, let array = value?.array, !array.isEmpty else { + throw CoreError.invalidState("invalid MCP slot path") + } + return try array.map { item in + guard let object = item.object, object.count == 1 else { + throw CoreError.invalidState("invalid MCP slot step") + } + if let key = string(object["key"]) { return .key(key) } + if let index = object["index"], index.kind == .integer, let i = index.integer, i >= 0 { + return .index(i) + } + throw CoreError.invalidState("invalid MCP slot step") + } + } + + private static func at(_ path: [MCPValueStep], in root: LedgerValue) throws -> LedgerValue { + var value = root + for step in path { + switch step { + case .key(let key): + guard let next = value.object?[key] else { + throw CoreError.invalidState("missing MCP slot") + } + value = next + case .index(let index): + guard let array = value.array, array.indices.contains(index) else { + throw CoreError.invalidState("missing MCP slot") + } + value = array[index] + } + } + return value + } + + private static func render( + _ lowering: LockedLowering, _ ledger: ResolvedLedger, _ resources: [String: URL] + ) throws -> [ReplayedArtifact] { + _ = try contribution(lowering, ledger: ledger) + guard lowering.resources.allSatisfy({ resources[$0] != nil }) else { + throw CoreError.invalidState("missing frozen MCP resource") + } + return [ + .init( + name: lowering.layout.object!["artifact"]!.text!, kind: .ownedValues, + values: lowering.layout) + ] + } +} diff --git a/Sources/Components/MCPLowering.swift b/Sources/Components/MCPLowering.swift new file mode 100644 index 0000000..4cd7fe2 --- /dev/null +++ b/Sources/Components/MCPLowering.swift @@ -0,0 +1,419 @@ +import AgentsCore +import Foundation +import NativeDocuments + +/// Slots are relative to one server value, never to an arbitrary physical document. +package enum MCPValueStep: Equatable, Sendable { + case key(String) + case index(Int) +} + +package struct MCPBindingPlacement: Equatable, Sendable { + package let path: [MCPValueStep] + package let binding: RuntimeBinding + /// A reference needs the downstream client's environment, not the applying process's value. + package let reference: Bool +} + +package struct MCPResourcePlacement: Equatable, Sendable { + package let path: [MCPValueStep] + package let resource: String +} + +/// One logical contribution. E combines physical documents and establishes regional ownership. +package struct NativeMCPContribution { + package let descriptor: NativeMCPDescriptor + package let component: String + package let name: String + package let occurrences: [Int] + /// Intended readers of this region. The complete producer targeting stays on its ledger owner. + package let recipients: [AgentID] + package let bindings: [MCPBindingPlacement] + package let resourcePlacements: [MCPResourcePlacement] + package let value: LedgerValue + package let resources: [String] + + /// Produces reference-safe native values. Literal binding and final resource placement are + /// deliberately deferred to E's staged render using Core's sole provider/publication policy. + package func referenceValue() throws -> NativeValue { + if let binding = bindings.first(where: { !$0.reference }) { + throw issue(binding.path.fields, "staged binding through Core is required") + } + if let resource = resourcePlacements.first { + throw issue(resource.path.fields, "E must place this frozen resource before staged rendering") + } + return try nativeValue(value) + } + + package func lowering( + id: String, artifact: String, platform: DeclarationPlatform, deployments: [String] = [] + ) -> LockedLowering { + .init( + id: id, format: descriptor.format, inputs: [component], resources: resources, + deployments: deployments, + layout: .init(object: [ + "artifact": .init(artifact), "surface": .init(descriptor.request.surface.rawValue), + "scope": .init(descriptor.request.scope.rawValue), + "component": .init(component), "name": .init(name), "value": value, + "occurrences": .init(array: occurrences.map { .init(integer: $0) }), + "recipients": LedgerPayload.strings(recipients.map(\.rawValue)), + "knownReaders": LedgerPayload.strings( + descriptor.knownReaders.map(\.rawValue).sorted()), + "bindings": .init( + array: bindings.map { placement in + .init(object: [ + "path": MCPLayoutV1.path(placement.path), + "binding": MCPLayoutV1.binding(placement.binding), + "reference": .init(boolean: placement.reference), + ]) + }), + "resourcePlacements": .init( + array: resourcePlacements.map { placement in + .init(object: [ + "path": MCPLayoutV1.path(placement.path), "resource": .init(placement.resource), + ]) + }), + ]), platform: platform.rawValue, artifacts: []) + } + + private func issue(_ field: [String], _ detail: String) -> NativeAdapterIssue { + .init( + request: descriptor.request, component: name, field: field, + reason: .integrationRequired, detail: detail) + } + + private func nativeValue(_ value: LedgerValue) throws -> NativeValue { + switch value.kind { + case .string, .literal: return .string(value.text!) + case .integer: return .integer(value.integer!) + case .decimal: return .decimal(value.text!) + case .boolean: return .boolean(value.boolean!) + case .null: return .null + case .array: return .array(try value.array!.map(nativeValue)) + case .object: return .object(try value.object!.mapValues(nativeValue)) + case .environment, .secret: + throw issue(["value"], "staged binding through Core is required") + } + } +} + +package enum NativeMCPLowering { + /// The frozen occurrence graph connects the linked identity to its exact durable component. + /// Call once per requested recipient; this method never aggregates equal native values. + package static func lower( + _ linked: LinkedComponent, frozen: LedgerFreeze.Result, request: NativeMCPRequest + ) throws -> NativeMCPContribution { + let ledger = frozen.ledger + let descriptor = try CapabilityRegistry.mcp(request, component: linked.key.name) + func invalid(_ detail: String) -> NativeAdapterIssue { + .init( + request: request, component: linked.key.name, field: ["component"], reason: .invalid, + detail: detail) + } + guard case .declaration(let declaration) = linked.payload, + case .mcpServer(let name, let transport, _, _, let native, _) = declaration + else { + throw invalid("the linked component is not an MCP server") + } + let identity: (id: String, occurrences: [Int]) + do { + identity = try FrozenNativeIdentity.match( + linked, frozen: frozen, + agent: request.surface.agent, scope: request.scope == .user ? .user : .project) + } catch { throw invalid("linked component and frozen source identity do not match") } + let id = identity.id + let record = ledger.components[id]! + let entry = try entry( + transport, named: name, descriptor: descriptor, + native: native[request.surface.agent.rawValue] ?? [:], resources: record.resources) + return .init( + descriptor: descriptor, component: id, name: name, occurrences: identity.occurrences, + recipients: [request.surface.agent], bindings: entry.placements, + resourcePlacements: entry.resourcePlacements, value: .init(object: entry.fields), + resources: record.resources) + } + + static func entry( + _ transport: MCPTransportDeclaration, named name: String, descriptor: NativeMCPDescriptor, + native: [String: NativeValue], resources: [String] + ) throws -> MCPEntry { + let input = MCPInput( + descriptor: descriptor, name: name, transport: transport, native: native, resources: resources + ) + switch descriptor.request.surface { + case .claudeCode: return try ClaudeAdapter.mcp(input) + case .codexCLI: return try CodexAdapter.mcp(input) + case .geminiCLI: return try GeminiAdapter.mcp(input) + case .openCodeCLI: return try OpenCodeAdapter.mcp(input) + case .cursorEditor, .cursorCLI, .cursorCloud: return try CursorAdapter.mcp(input) + case .antigravity: return try AntigravityAdapter.mcp(input) + } + } +} + +struct MCPInput { + let descriptor: NativeMCPDescriptor + let name: String + let transport: MCPTransportDeclaration + let native: [String: NativeValue] + let resources: [String] + + func issue(_ field: [String], _ reason: NativeAdapterIssue.Reason, _ detail: String) + -> NativeAdapterIssue + { + .init( + request: descriptor.request, component: name, field: field, reason: reason, detail: detail) + } + + func rejectWorkingDirectory(_ run: ExecutableDeclaration) throws { + guard run.workingDirectory == nil else { + throw issue( + ["transport", "workingDirectory"], .unverified, + "this client contract does not establish an MCP working-directory field") + } + } + + func environmentName(_ name: String, field: [String]) throws { + guard MCPReferenceSyntax.isName(name) + else { throw issue(field, .invalid, "native environment reference needs a variable name") } + } + + func literal(_ value: String, field: [String]) throws { + try descriptor.validateLiteral(value, component: name, field: field) + } +} + +extension NativeMCPDescriptor { + func validateLiteral(_ value: String, component: String, field: [String]) throws { + func issue(_ reason: NativeAdapterIssue.Reason, _ detail: String) -> NativeAdapterIssue { + .init(request: request, component: component, field: field, reason: reason, detail: detail) + } + guard !value.contains("\0") else { throw issue(.invalid, "NUL is not a native string") } + if let first = field.first, ["headers", "http_headers"].contains(first), + value.utf8.contains(13) || value.utf8.contains(10) + { + throw issue(.invalid, "native header value contains a line break") + } + let interpolates: Bool + switch request.surface { + case .claudeCode: interpolates = value.contains("${") + case .geminiCLI: + interpolates = value.range(of: #"\$(?:\w|\{)"#, options: .regularExpression) != nil + case .openCodeCLI: interpolates = value.contains("{env:") || value.contains("{file:") + case .cursorEditor, .cursorCLI, .cursorCloud, .antigravity: interpolates = value.contains("${") + case .codexCLI: interpolates = false + } + guard !interpolates else { + throw issue( + .unverified, "literal preservation across native interpolation needs evidence") + } + } +} + +enum MCPReferenceSyntax { + case claude, gemini + static func isName(_ name: String) -> Bool { + let bytes = Array(name.utf8) + guard let first = bytes.first, + first == 95 || (65...90).contains(first) || (97...122).contains(first) + else { return false } + return bytes.allSatisfy { + $0 == 95 || (48...57).contains($0) || (65...90).contains($0) || (97...122).contains($0) + } + } + + func render(_ name: String) -> String { + switch self { + case .claude, .gemini: "${" + name + "}" + } + } +} + +enum MCPNativeField { + case boolean, falseOnly, string, strings, positiveNumber, positiveInteger, durationSeconds, + environmentName + case oneOf(Set) + case positiveIntegerObject(Set) + case numberOrNull + case object, nonnegativeInteger + + func accepts(_ value: NativeValue) -> Bool { + switch (self, value) { + case (.object, .object): true + case (.nonnegativeInteger, .integer(let value)): value >= 0 && Double(exactly: value) != nil + case (.nonnegativeInteger, .decimal(let value)): + Double(value).map { $0.isFinite && $0 >= 0 && $0.rounded(.towardZero) == $0 } ?? false + case (.numberOrNull, .null), (.numberOrNull, .integer): true + case (.numberOrNull, .decimal(let number)): Double(number)?.isFinite == true + case (.boolean, .boolean): true + case (.falseOnly, .boolean(false)): true + case (.string, .string), (.environmentName, .string): true + case (.strings, .array(let array)): + array.allSatisfy { if case .string = $0 { true } else { false } } + case (.durationSeconds, .integer(let number)): number >= 0 + case (.durationSeconds, .decimal(let number)): + // Rust Duration uses u64 seconds. The f64 immediately below 2^64 is 2048 seconds + // smaller, so fractional nanosecond rounding cannot overflow an accepted f64. + Double(number).map { $0 >= 0 && $0 < 0x1p64 } ?? false + case (.positiveInteger, .integer(let number)): number > 0 && Double(exactly: number) != nil + case (.positiveInteger, .decimal(let text)): + Double(text).map { $0.isFinite && $0 > 0 && $0.rounded(.towardZero) == $0 } ?? false + case (.positiveNumber, .integer(let number)): number > 0 + case (.positiveNumber, .decimal(let number)): + Double(number).map { $0.isFinite && $0 > 0 } ?? false + case (.oneOf(let allowed), .string(let text)): allowed.contains(text) + case (.positiveIntegerObject(let allowed), .object(let object)): + object.allSatisfy { key, value in + allowed.contains(key) && { if case .integer(let i) = value { i > 0 } else { false } }() + } + default: false + } + } +} + +struct MCPEntry { + let input: MCPInput + var fields: [String: LedgerValue] = [:] + var placements: [MCPBindingPlacement] = [] + var resourcePlacements: [MCPResourcePlacement] = [] + init(_ input: MCPInput) { self.input = input } + + mutating func command(_ run: ExecutableDeclaration, argv: Bool = false) throws { + guard !run.executable.isEmpty else { + throw input.issue(["transport", "executable"], .invalid, "executable must not be empty") + } + let executable: LedgerValue + if run.executable.contains("/") { + guard let id = input.resources.first else { + throw input.issue( + ["transport", "executable"], .invalid, "missing frozen executable resource") + } + let path: [MCPValueStep] = argv ? [.key("command"), .index(0)] : [.key("command")] + executable = .init(object: ["resource": .init(id)]) + resourcePlacements.append(.init(path: path, resource: id)) + } else { + try input.literal(run.executable, field: ["transport", "executable"]) + executable = .init(run.executable) + } + for (index, argument) in run.arguments.enumerated() { + try input.literal(argument, field: ["transport", "arguments", String(index)]) + } + if argv { + fields["command"] = .init(array: [executable] + run.arguments.map { .init($0) }) + } else { + fields["command"] = executable + fields["args"] = LedgerPayload.strings(run.arguments) + } + } + + mutating func workingDirectory(_ run: ExecutableDeclaration) throws { + guard run.workingDirectory != nil else { return } + let index = run.executable.contains("/") ? 1 : 0 + guard index < input.resources.count else { + throw input.issue( + ["transport", "workingDirectory"], .invalid, "missing frozen directory resource") + } + let id = input.resources[index] + fields["cwd"] = .init(object: ["resource": .init(id)]) + resourcePlacements.append(.init(path: [.key("cwd")], resource: id)) + } + + mutating func url(_ url: String, field: String = "url") throws { + guard let parsed = URL(string: url), ["http", "https"].contains(parsed.scheme), + parsed.host?.isEmpty == false, parsed.user == nil, parsed.password == nil + else { + throw input.issue(["transport", "url"], .invalid, "a credential-free HTTP URL is required") + } + try input.literal(url, field: ["transport", "url"]) + fields[field] = .init(url) + } + + mutating func bindings( + _ bindings: [String: RuntimeBinding], field: String, reference: MCPReferenceSyntax? + ) throws { + if bindings.isEmpty { return } + var values: [String: LedgerValue] = [:] + for (key, value) in bindings.sorted(by: { $0.key < $1.key }) { + values[key] = try binding(value, path: [.key(field), .key(key)], reference: reference) + } + fields[field] = .init(object: values) + } + + mutating func binding( + _ binding: RuntimeBinding, path: [MCPValueStep], reference: MCPReferenceSyntax? + ) throws -> LedgerValue { + if input.descriptor.request.surface == .openCodeCLI, case .key(let key) = path.last { + try input.literal(key, field: path.fields + ["key"]) + } + switch binding { + case .literal(let text): + try input.literal(text, field: path.fields) + return .init(text) + case .environment(let name): + try input.environmentName(name, field: path.fields) + placements.append(.init(path: path, binding: binding, reference: reference != nil)) + return reference.map { .init($0.render(name)) } ?? .init(name, kind: .environment) + case .secret(let name): + placements.append(.init(path: path, binding: binding, reference: false)) + return .init(name, kind: .secret) + } + } + + mutating func nativeFields(_ rules: [String: MCPNativeField]) throws { + for (key, value) in input.native.sorted(by: { $0.key < $1.key }) { + let path = ["native", input.descriptor.request.surface.agent.rawValue, key] + guard fields[key] == nil else { + throw input.issue(path, .invalid, "native field overlaps the portable MCP mapping") + } + guard let rule = rules[key] else { + throw input.issue(path, .unverified, "no verified field mapping in this native schema") + } + guard rule.accepts(value) else { + throw input.issue(path, .invalid, "value is outside the verified native field profile") + } + if case .environmentName = rule, case .string(let name) = value { + try input.environmentName(name, field: path) + placements.append(.init(path: [.key(key)], binding: .environment(name), reference: true)) + } else { + try checkStrings(value, path: path) + } + fields[key] = ledgerValue(value) + } + } + + private func checkStrings(_ value: NativeValue, path: [String]) throws { + switch value { + case .string(let text): try input.literal(text, field: path) + case .array(let array): + for (i, value) in array.enumerated() { try checkStrings(value, path: path + [String(i)]) } + case .object(let object): + for (key, value) in object.sorted(by: { $0.key < $1.key }) { + try checkStrings(value, path: path + [key]) + } + default: break + } + } + + private func ledgerValue(_ value: NativeValue) -> LedgerValue { + switch value { + case .string(let text): .init(text) + case .integer(let number): .init(integer: number) + case .decimal(let number): .init(number, kind: .decimal) + case .boolean(let boolean): .init(boolean: boolean) + case .null: .init() + case .array(let array): .init(array: array.map(ledgerValue)) + case .object(let object): .init(object: object.mapValues(ledgerValue)) + } + } +} + +extension Array where Element == MCPValueStep { + var fields: [String] { + map { step in + switch step { + case .key(let key): key + case .index(let index): String(index) + } + } + } +} diff --git a/Sources/Components/MCPMessageSink.swift b/Sources/Components/MCPMessageSink.swift new file mode 100644 index 0000000..2d4ad77 --- /dev/null +++ b/Sources/Components/MCPMessageSink.swift @@ -0,0 +1,235 @@ +import Foundation +import MCP + +struct MCPWireHeader: Decodable { + var id: ID? + var method: String? +} + +/// The delegate and stdio pump share one locked admission boundary. Stream +/// capacity times frameBytes never exceeds queueBytes, even for a slow consumer. +final class MCPMessageSink: @unchecked Sendable { + let stream: AsyncThrowingStream + let failures: AsyncStream + private let continuation: AsyncThrowingStream.Continuation + private let failureContinuation: AsyncStream.Continuation + private let lock = NSLock() + let limits: MCPConnectionLimits + private var received = 0 + private var sent = 0 + private var stderr = 0 + private var issue: MCPConnectionIssue? + private var pendingResponses = Set() + private var initializeID: ID? + private var negotiated: String? + + init(_ limits: MCPConnectionLimits) { + self.limits = limits + (stream, continuation) = AsyncThrowingStream.makeStream( + bufferingPolicy: .bufferingOldest( + min(limits.queueMessages, limits.queueBytes / limits.frameBytes))) + (failures, failureContinuation) = AsyncStream.makeStream(bufferingPolicy: .bufferingOldest(1)) + } + + var failure: MCPConnectionIssue? { lock.withLock { issue } } + var version: String? { lock.withLock { negotiated } } + var responsesAdmitted: Bool { lock.withLock { pendingResponses.isEmpty } } + + /// Seal admission and capture its preexisting failure in one locked step. + /// The runner's intentional close must not replace an already-latched limit. + func closeAdmission() -> MCPConnectionIssue? { + lock.withLock { + let terminal = issue + finishLocked(.connectionClosed) + return terminal + } + } + + func fail(_ error: MCPConnectionIssue) { + lock.withLock { finishLocked(error) } + } + + private func finishLocked(_ error: MCPConnectionIssue) { + guard issue == nil else { return } + issue = error + continuation.finish(throwing: error) + failureContinuation.yield(error) + failureContinuation.finish() + } + + func receiveBytes(_ count: Int, standardError: Bool = false) throws { + try lock.withLock { + if let issue { throw issue } + if standardError { + guard count <= limits.stderrBytes - stderr else { + finishLocked(.stderrLimit) + throw MCPConnectionIssue.stderrLimit + } + stderr += count + } else { + guard count <= limits.receivedBytes - received else { + finishLocked(.receiveLimit) + throw MCPConnectionIssue.receiveLimit + } + received += count + } + } + } + + /// Call before I/O. Initialize belongs to SDK Client, not the runner. + func prepare(_ data: Data) throws -> MCPWireHeader { + try lock.withLock { + if let issue { throw issue } + guard data.count <= limits.frameBytes else { throw MCPConnectionIssue.messageLimit } + guard data.count < limits.sentBytes - sent else { throw MCPConnectionIssue.sendLimit } + sent += data.count + 1 // Includes the stdio newline; conservatively shared by HTTP. + let header: MCPWireHeader + do { header = try JSONDecoder().decode(MCPWireHeader.self, from: data) } catch { + throw MCPConnectionIssue.protocolError + } + if header.method == Initialize.name { + guard initializeID == nil else { throw MCPConnectionIssue.protocolError } + guard let id = header.id else { throw MCPConnectionIssue.protocolError } + initializeID = id + } else if header.method == InitializedNotification.name { + guard negotiated != nil else { throw MCPConnectionIssue.unsupportedVersion } + } else if let method = header.method, method != ListTools.name { + throw MCPConnectionIssue.protocolError + } + if header.method != nil, let id = header.id { pendingResponses.insert(id) } + return header + } + } + + /// Raw bytes have already been counted, and the frame bound precedes SDK decode. + func admit(_ data: Data) throws { + try lock.withLock { + if let issue { throw issue } + guard data.count <= limits.frameBytes else { + finishLocked(.messageLimit) + throw MCPConnectionIssue.messageLimit + } + let header = try? JSONDecoder().decode(MCPWireHeader.self, from: data) + if negotiated == nil && header?.method == nil { + let response: Response + do { response = try JSONDecoder().decode(Response.self, from: data) } catch { + finishLocked(.protocolError) + throw MCPConnectionIssue.protocolError + } + guard response.id == initializeID else { + finishLocked(.protocolError) + throw MCPConnectionIssue.protocolError + } + if case .success(let result) = response.result { + guard Version.supported.contains(result.protocolVersion) else { + finishLocked(.unsupportedVersion) + throw MCPConnectionIssue.unsupportedVersion + } + negotiated = result.protocolVersion + } + } + switch continuation.yield(data) { + case .enqueued: + if header?.method == nil, let id = header?.id { pendingResponses.remove(id) } + case .dropped: + finishLocked(.queueLimit) + throw MCPConnectionIssue.queueLimit + case .terminated: + finishLocked(.connectionClosed) + throw MCPConnectionIssue.connectionClosed + @unknown default: + finishLocked(.connectionClosed) + throw MCPConnectionIssue.connectionClosed + } + } + } +} + +/// Incremental SSE line/event parser. All raw bytes, including comments, are +/// counted by its caller; neither an unterminated line nor event can grow freely. +struct MCPSSEParser { + struct Event { + var name: String + var data: Data + var id: String? + var retry: TimeInterval? + } + private var line = Data() + private var data = Data() + private var name = "" + private var eventID: String? + private(set) var lastID: String? + private(set) var retry: TimeInterval? + private var afterCR = false + private var firstLine = true + let limit: Int + + init(limit: Int) { + self.limit = limit + } + + mutating func restart() { + line.removeAll(keepingCapacity: true) + data.removeAll(keepingCapacity: true) + name = "" + eventID = nil + afterCR = false + firstLine = true + } + + mutating func feed(_ bytes: Data, emit: (Event) throws -> Void) throws { + for byte in bytes { + if byte == 10 && afterCR { + afterCR = false + continue + } + afterCR = byte == 13 + if byte == 10 || byte == 13 { + try endLine(emit) + } else { + guard line.count < limit else { throw MCPConnectionIssue.messageLimit } + line.append(byte) + } + } + } + + private mutating func endLine(_ emit: (Event) throws -> Void) throws { + defer { + line.removeAll(keepingCapacity: true) + firstLine = false + } + if firstLine && line.starts(with: [0xEF, 0xBB, 0xBF]) { line.removeFirst(3) } + if line.isEmpty { + if !data.isEmpty { + data.removeLast() // SSE removes the final data-field newline. + try emit(Event(name: name, data: data, id: eventID ?? lastID, retry: retry)) + } + if let eventID { lastID = eventID } + eventID = nil + data.removeAll(keepingCapacity: true) + name = "" + return + } + if line.first == 58 { return } + let separator = line.firstIndex(of: 58) ?? line.endIndex + let field = String(decoding: line[..= 48 && $0 <= 57 }), + let milliseconds = UInt64(String(decoding: value, as: UTF8.self)) + { + retry = Double(milliseconds) / 1000 + } + default: break + } + } +} diff --git a/Sources/Components/MCPStagedValues.swift b/Sources/Components/MCPStagedValues.swift new file mode 100644 index 0000000..a2a1133 --- /dev/null +++ b/Sources/Components/MCPStagedValues.swift @@ -0,0 +1,89 @@ +import AgentsCore +import Foundation +import NativeDocuments + +extension NativeMCPContribution { + /// Call only in E/D's private render closure. The caller admits final registered resource + /// paths and supplies its immutable environment snapshot; this method never invokes a provider. + /// The returned value is ephemeral and must not enter a lowering, ledger or public report. + package func stagedValue( + bindings supplied: RuntimeBindingValues, environment: RuntimeEnvironment, + resourcePaths: [String: String], budget: NativeDocumentBudget + ) throws -> NativeValue { + func failure(_ path: [MCPValueStep], _ detail: String) -> NativeAdapterIssue { + .init( + request: descriptor.request, component: name, field: path.fields, + reason: .invalid, detail: detail) + } + func literal(_ text: String, at path: [MCPValueStep]) throws -> NativeValue { + try budget.allocate(text.utf8.count, stage: "staged native string") + try budget.step(text.utf8.count) + try descriptor.validateLiteral(text, component: name, field: path.fields) + if case .key(let field) = path.first, + ["headers", "http_headers"].contains(field), + text.utf8.contains(13) || text.utf8.contains(10) + { + throw failure(path, "native header value contains a line break") + } + return .string(text) + } + func convert(_ value: LedgerValue, path: [MCPValueStep], depth: Int) throws -> NativeValue { + try budget.node(depth: depth) + try budget.step(bindings.count + resourcePlacements.count + 1) + if let placement = bindings.first(where: { $0.path == path }), !placement.reference { + let text: String + switch placement.binding { + case .environment(let variable): + guard let found = environment.environment[variable] else { + throw failure(path, "required native environment value is unavailable") + } + text = found + case .secret(let binding): + let bytes: Data + do { bytes = try supplied.value(for: binding) } catch { + throw failure(path, "required native binding is unavailable") + } + try budget.allocate(bytes.count, stage: "staged native UTF8") + try budget.step(bytes.count) + guard let decoded = String(data: bytes, encoding: .utf8) else { + throw failure(path, "native binding is not UTF8") + } + text = decoded + case .literal(let found): text = found + } + return try literal(text, at: path) + } + if let placement = resourcePlacements.first(where: { $0.path == path }) { + guard let final = resourcePaths[placement.resource], !final.isEmpty else { + throw failure(path, "final registered resource placement is required") + } + return try literal(final, at: path) + } + switch value.kind { + case .string, .literal: + try budget.allocate(value.text!.utf8.count, stage: "native string") + return .string(value.text!) + case .integer: return .integer(value.integer!) + case .decimal: return .decimal(value.text!) + case .boolean: return .boolean(value.boolean!) + case .null: return .null + case .array: + try budget.allocate(value.array!.count, stage: "native array") + return .array( + try value.array!.enumerated().map { index, value in + try convert(value, path: path + [.index(index)], depth: depth + 1) + }) + case .object: + var fields: [String: NativeValue] = [:] + for (key, value) in value.object!.sorted(by: { $0.key < $1.key }) { + try budget.allocate(key.utf8.count, stage: "native key") + fields[key] = try convert(value, path: path + [.key(key)], depth: depth + 1) + } + return .object(fields) + case .environment, .secret: + throw failure(path, "native symbolic slot has no binding placement") + } + } + return try convert(value, path: [], depth: 0) + } +} diff --git a/Sources/Components/NativeAuthorityComposition.swift b/Sources/Components/NativeAuthorityComposition.swift new file mode 100644 index 0000000..0844b20 --- /dev/null +++ b/Sources/Components/NativeAuthorityComposition.swift @@ -0,0 +1,160 @@ +import AgentsCore +import Foundation +import NativeDocuments + +/// Bridges durable local authority to one verified native preimage and its same-edit remap. +enum NativeAuthorityComposition { + static func dialect(_ format: NativeDocumentFormat) -> String { + switch format { + case .json: "json" + case .jsonc(let trailing): trailing ? "jsonc-trailing-commas" : "jsonc" + case .toml: "toml" + } + } + + static func address(_ region: NativeRegion) throws -> [PrivateNativeAddressStep] { + try region.steps.map { + switch $0 { + case .key(let key): return .key(key) + case .occurrence(let e): + if let key = e.idKey, let value = e.id { return .stableID(key: key, value: value) } + guard let ordinal = e.ordinal else { + throw CoreError.invalidState("missing native ordinal") + } + return .position(index: ordinal) + } + } + } + + static func region(_ path: [PrivateNativeAddressStep], document: NativeDocument) throws + -> NativeRegion + { + var result = NativeRegion(keys: []) + for step in path { + switch step { + case .key(let key): result = NativeRegion(result.steps + [.key(key)]) + case .stableID(let key, let value): + result = NativeRegion(result.steps + [.occurrence(.init(idKey: key, id: value))]) + case .position(let index): + result = try document.validatedOccurrences( + in: result, matching: document.arrayDigest(result), ordinals: [index])[0] + } + } + return result + } + + static func region( + _ path: [LedgerNativePathStep], document: NativeDocument, + arrays: [PrivateNativeArrayRecord] + ) throws -> NativeRegion { + var result = NativeRegion(keys: []) + for step in path { + switch step { + case .key(let key): result = NativeRegion(result.steps + [.key(key)]) + case .stableID(let key, let value): + result = NativeRegion(result.steps + [.occurrence(.init(idKey: key, id: value))]) + case .position(let index, let evidence): + let digest: NativeArrayDigest + switch evidence { + case .semantic(let format, let hash): + digest = .init(format: format, digest: String(hash.dropFirst("sha256:".count))) + case .privateArray(let token): + let coordinates = try address(result) + guard let record = arrays.first(where: { $0.token == token && $0.path == coordinates }) + else { + throw CoreError.invalidState("native array authority is stale") + } + digest = .init( + format: record.semanticFormat, + digest: String(record.semanticDigest.dropFirst("sha256:".count))) + } + result = try document.validatedOccurrences(in: result, matching: digest, ordinals: [index])[ + 0] + } + } + return result + } + + struct Result { + let regions: [LedgerNativeOwnedRegion] + let containers: [LedgerNativeCreatedContainer] + let transitions: [PrivateNativeArrayTransition] + } + + static func finish( + _ change: PreparedNativeChange, document: NativeDocument, + owners: [(NativeObservation, [String])], containers: [NativeRegion], + previousArrays: [PrivateNativeArrayRecord], sensitive: Bool, + format: NativeDocumentFormat + ) throws -> Result { + var arrays: [PrivateNativeArrayRecord] = [] + var transitions: [PrivateNativeArrayTransition] = [] + for transition in change.arrayTransitions { + let previous = previousArrays[transition.index] + let current: PrivateNativeArrayRecord? + if let region = transition.region, let digest = transition.digest { + current = .init( + path: try address(region), documentFormat: dialect(format), + token: transition.canRetainToken ? previous.token : UUID(), + semanticFormat: digest.format, semanticDigest: "sha256:" + digest.digest) + arrays.append(current!) + } else { + current = nil + } + transitions.append(.init(previous: previous, current: current)) + } + func path(_ region: NativeRegion) throws -> [LedgerNativePathStep] { + var prefix = NativeRegion(keys: []) + var result: [LedgerNativePathStep] = [] + for step in region.steps { + switch step { + case .key(let key): result.append(.key(key)) + case .occurrence(let e): + if let key = e.idKey, let value = e.id { + result.append(.stableID(key: key, value: value)) + } else { + guard let ordinal = e.ordinal else { + throw CoreError.invalidState("missing native ordinal") + } + let digest = try document.arrayDigest(prefix) + let evidence: LedgerNativeArrayEvidence + if sensitive { + let coordinates = try address(prefix) + let record: PrivateNativeArrayRecord + if let existing = arrays.first(where: { $0.path == coordinates }) { + record = existing + } else { + record = .init( + path: coordinates, documentFormat: dialect(format), token: UUID(), + semanticFormat: digest.format, semanticDigest: "sha256:" + digest.digest) + arrays.append(record) + transitions.append(.init(previous: nil, current: record)) + } + evidence = .privateArray(token: record.token) + } else { + evidence = .semantic(format: digest.format, digest: "sha256:" + digest.digest) + } + result.append(.position(index: ordinal, evidence: evidence)) + } + } + prefix = NativeRegion(prefix.steps + [step]) + } + return result + } + let regions = try owners.map { + try LedgerNativeOwnedRegion(deployments: $0.1.sorted(), path: path($0.0.region)) + } + var created: [LedgerNativeCreatedContainer] = [] + for container in containers { + guard let observed = try document.read(container) else { continue } + let p = try path(container) + let ids = Set( + regions.filter { $0.path.count > p.count && Array($0.path.prefix(p.count)) == p }.flatMap( + \.deployments)) + if !ids.isEmpty { + created.append(.init(deployments: ids.sorted(), path: p, kind: observed.nativeKind)) + } + } + return Result(regions: regions, containers: created, transitions: transitions) + } +} diff --git a/Sources/Components/NativeComponentContribution.swift b/Sources/Components/NativeComponentContribution.swift new file mode 100644 index 0000000..72db59e --- /dev/null +++ b/Sources/Components/NativeComponentContribution.swift @@ -0,0 +1,203 @@ +import AgentsCore +import Foundation +import NativeDocuments + +/// One frozen logical owner. Physical reader union and native ownership observations belong to E. +package struct NativeComponentContribution { + package let format: String + package let request: NativeComponentRequest + package let component: String + package let kind: DeclaredComponentKind + package let name: String + package let occurrences: [Int] + package let recipients: [AgentID] + package let knownReaders: [AgentID] + package let resources: [String: LedgerResource] + package let outputs: [NativeComponentOutput] +} + +/// These are the concrete current native surfaces, not caller-programmable document edits. +package struct NativeComponentOutput { + package let route: NativeComponentRoute + package let content: Content + + package enum Content { + /// Whole UTF8 file, with no executable bit. The relative name is admitted under the route by D. + case file(path: String, bytes: Data) + case member(NativeComponentMember, NativeComponentValue) + /// One owned array occurrence. Preserve ordering; equal unmanaged occurrences confer no authority. + case hook(NativeComponentHook) + /// Last-match native tool/resource rules, appended in their declared order. + case orderedPermissions([NativeComponentPermission]) + /// Native deny/ask/allow categories, not a portable ordered policy. + case claudePermissions(NativeClaudePermissions) + /// Ordered lines for E's existing managed ignore block, not independent line ownership. + case ignore([String]) + /// One generated Claude plugin manifest and its coupled registered plugin directory. + case generatedLSPPlugin(directory: String, manifestPath: String, manifest: NativeComponentValue) + /// Complete opaque frozen tree. Entries retain file kinds, symlinks and executable bits. + case nativePlugin(directory: String, resource: String, manifest: String) + } +} + +package enum NativeComponentMember { + case antigravityHook(String) + case openCodeCommand(String) + case openCodeAgent(String) + case openCodeLSP(String) + /// The config_file points at the coupled codexAgent file output of this same owner. + case codexAgent(String) + + package var keys: [String] { + switch self { + case .antigravityHook(let name): [name] + case .openCodeCommand(let name): ["commands", name] + case .openCodeAgent(let name): ["agents", name] + case .openCodeLSP(let name): ["lsp", name] + case .codexAgent(let name): ["agents", name] + } + } +} + +package struct NativeComponentHook { + package enum Layout: Equatable { + /// An event array contains groups with matcher/sequential metadata and a hooks array. + case group + /// Cursor's event array contains handlers directly; the root must have version = 1. + case cursorVersion1 + } + package let event: String + package let layout: Layout + package let value: NativeComponentValue + package var keys: [String] { ["hooks", event] } + + /// E supplies the staged value and a fresh array precondition. Ownership comes only from + /// prepare's appendedOccurrences result, never from an equal existing handler. + package func append(value: NativeValue, expected: NativeExpectedRegion) -> NativeRegionEdit { + .append(region: NativeRegion(keys: keys), expected: expected, value: value) + } +} + +package struct NativeComponentPermission { + package enum Effect: String { case allow, ask, deny } + package let tool: String + package let resource: String + package let effect: Effect +} + +package struct NativeClaudePermissions { + /// nil differs from a supplied empty category. E must preserve that distinction. + package let allow: [String]? + package let ask: [String]? + package let deny: [String]? + package let defaultMode: String? +} + +/// Slots identify only actual native program positions. They never address arbitrary settings data. +package enum NativeComponentSlot: Equatable { + case executable + case argument(Int) + case environment(String) + case workingDirectory +} + +package struct NativeComponentBindingPlacement { + package let slot: NativeComponentSlot + package let binding: RuntimeBinding +} + +package struct NativeComponentResourcePlacement { + package let slot: NativeComponentSlot + package let resource: String +} + +/// A decoder-created native value. Its symbolic payload cannot be mutated or constructed by E. +package struct NativeComponentValue { + package let bindings: [NativeComponentBindingPlacement] + package let resourcePlacements: [NativeComponentResourcePlacement] + private let envelope: LedgerValue + private let requiresProgramConversion: Bool + private let manifestProjection: Bool + + init( + envelope: LedgerValue, bindings: [NativeComponentBindingPlacement], + resourcePlacements: [NativeComponentResourcePlacement], requiresProgramConversion: Bool, + manifestProjection: Bool + ) { + self.envelope = envelope + self.bindings = bindings + self.resourcePlacements = resourcePlacements + self.requiresProgramConversion = requiresProgramConversion + self.manifestProjection = manifestProjection + } + + /// Invoke only in E/D's private render closure. Core values and final admitted paths are inputs; + /// this operation never invokes a provider, writes a file or persists materialized bindings. + package func stagedValue( + bindings: RuntimeBindingValues, environment: RuntimeEnvironment, + resourcePaths: [String: String], budget: NativeDocumentBudget, + codexCommandShell: NativeProgramV1.CommandShell? = nil, + cursorCommandShell: NativeProgramV1.CommandShell? = nil + ) throws -> NativeValue { + if requiresProgramConversion { + let converted = try NativeProgramV1.stagedValue( + envelope, bindings: bindings, environment: environment, resourcePaths: resourcePaths, + budget: budget, codexCommandShell: codexCommandShell, + cursorCommandShell: cursorCommandShell) + if manifestProjection { + guard case .object(let files) = converted, + let manifest = files[".claude-plugin/plugin.json"] + else { + throw CoreError.invalidState("missing staged native plugin manifest") + } + return manifest + } + return converted + } + return try literalValue(envelope.object!["value"]!, budget: budget, depth: 0) + } + + /// A key member with no program can be prepared without requesting any runtime values. + package func referenceValue(budget: NativeDocumentBudget) throws -> NativeValue { + guard !requiresProgramConversion else { + let fields = envelope.object! + throw NativeComponentIssue( + request: .init( + surface: NativeClientSurface(rawValue: fields["surface"]!.text!)!, + scope: InstallScope(rawValue: fields["scope"]!.text!)!), + kind: fields["kind"]!.text!, component: fields["name"]!.text!, field: ["value"], + reason: .integrationRequired, detail: "private staged native program conversion is required" + ) + } + return try literalValue(envelope.object!["value"]!, budget: budget, depth: 0) + } + + private func literalValue(_ value: LedgerValue, budget: NativeDocumentBudget, depth: Int) throws + -> NativeValue + { + try budget.node(depth: depth) + try budget.step() + switch value.kind { + case .string, .literal, .decimal: + try budget.allocate(value.text!.utf8.count, stage: "native component string") + try budget.step(value.text!.utf8.count) + if value.kind == .decimal { return .decimal(value.text!) } + return .string(value.text!) + case .integer: return .integer(value.integer!) + case .boolean: return .boolean(value.boolean!) + case .null: return .null + case .array: + return .array(try value.array!.map { try literalValue($0, budget: budget, depth: depth + 1) }) + case .object: + var result: [String: NativeValue] = [:] + for (key, child) in value.object!.sorted(by: { $0.key < $1.key }) { + try budget.allocate(key.utf8.count, stage: "native component key") + try budget.step(key.utf8.count) + result[key] = try literalValue(child, budget: budget, depth: depth + 1) + } + return .object(result) + case .environment, .secret: + throw CoreError.invalidState("symbolic value outside a native component program") + } + } +} diff --git a/Sources/Components/NativeComponentDecodingV1.swift b/Sources/Components/NativeComponentDecodingV1.swift new file mode 100644 index 0000000..d328985 --- /dev/null +++ b/Sources/Components/NativeComponentDecodingV1.swift @@ -0,0 +1,455 @@ +import AgentsCore +import Foundation +import NativeDocuments + +extension NativeComponentLayoutsV1 { + /// Decode exactly one sealed lowering's replay artifacts. Call inside LedgerReplay's closure: + /// the ledger has passed Core admission, bundle trees are borrowed there, and replay verifies + /// source bytes and executable bits. This is not a second whole-ledger admission operation. + /// Sealing authenticates file bodies without introducing another native file parser in E. + package static func contribution( + _ lowering: LockedLowering, ledger: ResolvedLedger, artifacts: [ReplayedArtifact], + limits: LedgerLimits + ) throws -> NativeComponentContribution { + guard ledger.lowerings.filter({ $0.id == lowering.id }) == [lowering], + !lowering.artifacts.isEmpty, artifacts.count == lowering.artifacts.count, + let component = lowering.inputs.first, ledger.components[component]?.payload.object != nil + else { throw CoreError.invalidState("unsealed or mismatched native component lowering") } + let input = try input(lowering, ledger: ledger, limits: limits) + let decoder = NativeComponentDecoderV1(input: input) + try decoder.admit(lowering.layout) + if ["hook", "lspServer"].contains(input.record.kind) { + try NativeProgramV1.validateFrozenRun(input) + } + guard artifacts.first?.kind == .ownedValues, + artifacts.first?.name == lowering.id, + (input.record.kind == "plugin" && artifacts.count == 2 + && artifacts[1].kind == .tree && artifacts[1].name == lowering.id + "/bundle") + || (input.record.kind != "plugin" && artifacts.count == 1) + else { throw decoder.invalid() } + for artifact in artifacts { + guard artifact.location == nil else { throw decoder.invalid() } + if let value = artifact.values { try decoder.admit(value) } + } + guard try artifacts.map({ try $0.digest(limits: limits) }) == lowering.artifacts, + artifacts[0].name == lowering.id, artifacts[0].kind == .ownedValues, + let envelope = artifacts[0].values + else { throw decoder.invalid() } + let envelopes: [LedgerValue] + if input.request.surface == .codexCLI, input.record.kind == "subagent" { + guard let pair = envelope.array, pair.count == 2 else { throw decoder.invalid() } + envelopes = pair + } else { + guard envelope.kind == .object else { throw decoder.invalid() } + envelopes = [envelope] + } + let outputs = try envelopes.enumerated().map { + try decoder.output($0.element, index: $0.offset) + } + // Reuse the production semantic validators for all programmable regional outputs. No native + // event/field tables are copied into the decoder or importer. File bodies are pinned by seal. + if ["hook", "permissions", "lspServer"].contains(input.record.kind) { + let expected: [ReplayedArtifact] + switch input.request.surface { + case .antigravity: expected = try AntigravityAdapter.components(lowering, input) + case .claudeCode: expected = try ClaudeAdapter.components(lowering, input) + case .codexCLI: expected = try CodexAdapter.components(lowering, input) + case .geminiCLI: expected = try GeminiAdapter.components(lowering, input) + case .openCodeCLI: expected = try OpenCodeAdapter.components(lowering, input) + case .cursorEditor, .cursorCLI, .cursorCloud: + expected = try CursorAdapter.components(lowering, input) + } + guard expected.count == 1, expected[0].values == envelope else { throw decoder.invalid() } + } + if input.record.kind == "plugin" { + guard artifacts.count == 2, artifacts[1].name == lowering.id + "/bundle", + artifacts[1].kind == .tree, artifacts[1].tree != nil, + artifacts[1].bytes == nil, artifacts[1].values == nil + else { throw decoder.invalid() } + let resource = ledger.resources[lowering.resources[0]]! + let entries = resource.entries.map { entry in + var entry = entry + entry.object = nil + return entry + } + guard + lowering.artifacts[1].hash + == (try ResolvedLedgerCodec.digest( + NativeComponentTreeDigestV1(content: resource.hash, entries: entries))) + else { + throw decoder.invalid(["resources"]) + } + } else { + guard artifacts.count == 1 else { throw decoder.invalid() } + } + let kind = DeclaredComponentKind(rawValue: input.record.kind)! + return .init( + format: lowering.format, request: input.request, component: input.component, kind: kind, + name: input.record.name, occurrences: input.occurrences, + recipients: [input.request.surface.agent], + knownReaders: CapabilityRegistry.componentReaders(input.request, kind: kind) + .sorted { $0.rawValue < $1.rawValue }, + resources: lowering.resources.reduce(into: [:]) { $0[$1] = ledger.resources[$1]! }, + outputs: outputs) + } +} + +private struct NativeComponentTreeDigestV1: Encodable { + let content: String + let entries: [LedgerEntry] +} + +private struct NativeComponentDecoderV1 { + let input: ComponentRenderInput + func invalid(_ field: [String] = ["output"]) -> NativeComponentIssue { + input.issue(field, .invalid, "invalid sealed native component contribution") + } + + /// Charge decoded values before validation, equality, hashing, copying or staging. + func admit(_ value: LedgerValue, depth: Int = 0) throws { + try input.budget.node(depth: depth) + try input.budget.step() + if let text = value.text { + try input.budget.allocate(text.utf8.count, stage: "native contribution string") + try input.budget.step(text.utf8.count) + guard !text.utf8.contains(0) else { throw invalid() } + if value.kind == .decimal, + text.range( + of: #"\A-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\z"#, + options: .regularExpression) == nil + { + throw invalid(["value"]) + } + } + for child in value.array ?? [] { try admit(child, depth: depth + 1) } + for (key, child) in value.object ?? [:] { + try input.budget.allocate(key.utf8.count, stage: "native contribution key") + try input.budget.step(key.utf8.count) + guard !key.utf8.contains(0) else { throw invalid() } + try admit(child, depth: depth + 1) + } + // Children have already been bounded; validate this node's tag without recursive validation. + var node = value + if node.array != nil { node.array = [] } + if node.object != nil { node.object = [:] } + try node.validate() + } + + func text(_ value: LedgerValue?) throws -> String { + guard value?.kind == .string, let text = value?.text else { throw invalid() } + return text + } + func strings(_ value: LedgerValue?) throws -> [String] { + guard let items = value?.array else { throw invalid() } + return try items.map { try text($0) } + } + + func output(_ envelope: LedgerValue, index: Int) throws -> NativeComponentOutput { + let kind = DeclaredComponentKind(rawValue: input.record.kind)! + guard let fields = envelope.object, + Set(fields.keys).subtracting(["path", "rootRequirements"]) == [ + "route", "surface", "scope", "kind", "name", "component", "occurrences", + "recipients", "knownReaders", "keys", "selection", "value", + ], + fields["surface"] == .init(input.request.surface.rawValue), + fields["scope"] == .init(input.request.scope.rawValue), + fields["kind"] == .init(input.record.kind), fields["name"] == .init(input.record.name), + fields["component"] == .init(input.component), + fields["occurrences"] == .init(array: input.occurrences.map { .init(integer: $0) }), + fields["recipients"] == LedgerPayload.strings([input.request.surface.agent.rawValue]), + fields["knownReaders"] + == LedgerPayload.strings( + CapabilityRegistry.componentReaders(input.request, kind: kind).map(\.rawValue).sorted()), + let route = NativeComponentRoute(rawValue: try text(fields["route"])), + let value = fields["value"] + else { throw invalid(["identity"]) } + let keys = try strings(fields["keys"]) + let selection = try text(fields["selection"]) + let path = try fields["path"].map { try text($0) } + if let path { + do { + guard path != ".", try PathSafety.sanitizeSubpath(path) == path else { + throw invalid(["path"]) + } + } catch { throw invalid(["path"]) } + } + if selection != "cursorHook", fields["rootRequirements"] != nil { throw invalid() } + let content: NativeComponentOutput.Content + switch selection { + case "file": + guard keys.isEmpty, let path, [.command, .subagent].contains(kind), index == 0, + value.kind == .string + else { throw invalid() } + let expectedRoute: NativeComponentRoute + let suffix: String + switch (input.request.surface, kind) { + case (.claudeCode, .command): + expectedRoute = .claudeCommand + suffix = ".md" + case (.claudeCode, .subagent): + expectedRoute = .claudeAgent + suffix = ".md" + case (.geminiCLI, .command): + expectedRoute = .geminiCommand + suffix = ".toml" + case (.geminiCLI, .subagent): + expectedRoute = .geminiAgent + suffix = ".md" + case (.codexCLI, .subagent): + expectedRoute = .codexAgent + suffix = ".toml" + case (.cursorEditor, .command): + expectedRoute = .cursorCommand + suffix = ".md" + case (.cursorEditor, .subagent), (.cursorCLI, .subagent): + expectedRoute = .cursorAgent + suffix = ".md" + default: throw invalid(["route"]) + } + let nested = + (input.request.surface == .claudeCode && kind == .command) + || (input.request.surface == .geminiCLI && kind == .command) + || (input.request.surface == .codexCLI && kind == .subagent) + let name = try nested ? input.relativeName() : input.filename() + guard route == expectedRoute, path == name + suffix else { throw invalid(["path"]) } + let text = try text(value) + try input.budget.allocate(text.utf8.count, stage: "native contribution file") + content = .file(path: path, bytes: Data(text.utf8)) + case "key", "lsp": + guard path == nil, value.kind == .object else { throw invalid() } + let member: NativeComponentMember + switch (input.request.surface, kind, selection) { + case (.openCodeCLI, .command, "key"): + member = .openCodeCommand(input.record.name) + guard value.object?["template"]?.kind == .string, + value.object?["description"]?.kind == .string + else { throw invalid() } + case (.openCodeCLI, .subagent, "key"): + member = .openCodeAgent(input.record.name) + guard value.object?["system"]?.kind == .string, + value.object?["description"]?.kind == .string, + value.object?["mode"] == .init("subagent") + else { throw invalid() } + case (.openCodeCLI, .lspServer, "lsp"): member = .openCodeLSP(input.record.name) + case (.codexCLI, .subagent, "key"): + member = .codexAgent(input.record.name) + guard index == 1, + value + == .init(object: [ + "description": input.fields["description"]!, + "config_file": .init("./agents/" + input.record.name + ".toml"), + ]) + else { throw invalid() } + default: throw invalid(["route"]) + } + guard keys == member.keys, + route == (input.request.surface == .codexCLI ? .codexConfig : .openCodeConfig) + else { throw invalid(["route"]) } + if input.request.surface == .openCodeCLI, kind == .command || kind == .subagent { + let body = try text(value.object?[kind == .command ? "template" : "system"]) + guard value == .init(object: try OpenCodeAdapter.definition(input, prompt: body)) else { + throw invalid(["value"]) + } + } + content = .member(member, try template(envelope, selection: selection)) + case "antigravityHook": + guard kind == .hook, input.request.surface == .antigravity, route == .antigravityHooks, + path == nil, keys == [input.record.name], !input.record.name.isEmpty + else { throw invalid() } + content = .member( + .antigravityHook(input.record.name), try template(envelope, selection: selection)) + case "hookGroup", "cursorHook": + guard kind == .hook, path == nil, keys.count == 2, keys[0] == "hooks", + keys[1] == input.fields["event"]?.object?["native"]?.text + else { throw invalid() } + let expected: NativeComponentRoute + switch input.request.surface { + case .claudeCode: expected = .claudeSettings + case .codexCLI: expected = .codexHooks + case .geminiCLI: expected = .geminiSettings + case .cursorEditor, .cursorCLI, .cursorCloud: expected = .cursorHooks + default: throw invalid(["route"]) + } + guard route == expected, (selection == "cursorHook") == (expected == .cursorHooks) else { + throw invalid(["route"]) + } + if selection == "cursorHook" { + guard fields["rootRequirements"] == .init(object: ["version": .init(integer: 1)]) else { + throw invalid() + } + } + content = .hook( + .init( + event: keys[1], layout: selection == "cursorHook" ? .cursorVersion1 : .group, + value: try template(envelope, selection: selection))) + case "orderedAppend": + guard kind == .permissions, input.request.surface == .openCodeCLI, + route == .openCodeConfig, path == nil, keys == ["permissions"], let rules = value.array + else { throw invalid() } + content = .orderedPermissions( + try rules.map { rule in + guard let fields = rule.object, Set(fields.keys) == ["action", "resource", "effect"], + let effect = NativeComponentPermission.Effect(rawValue: try text(fields["effect"])) + else { throw invalid() } + return .init( + tool: try text(fields["action"]), resource: try text(fields["resource"]), effect: effect + ) + }) + case "nativePolicy": + guard kind == .permissions, input.request.surface == .claudeCode, + route == .claudeSettings, path == nil, keys == ["permissions"], let policy = value.object, + Set(policy.keys).isSubset(of: ["allow", "ask", "deny", "defaultMode"]) + else { throw invalid() } + content = .claudePermissions( + .init( + allow: try policy["allow"].map { try strings($0) }, + ask: try policy["ask"].map { try strings($0) }, + deny: try policy["deny"].map { try strings($0) }, + defaultMode: try policy["defaultMode"].map { try text($0) })) + case "managedIgnore": + guard kind == .ignore, path == nil, keys.isEmpty, + (input.request.surface == .geminiCLI && route == .geminiIgnore) + || (input.request.surface == .cursorEditor && route == .cursorIgnore), + value == LedgerPayload.strings(try NativeIgnoreLayoutV1.patterns(input)) + else { throw invalid() } + content = .ignore(try strings(value)) + case "generatedPlugin": + guard kind == .lspServer, input.request.surface == .claudeCode, + route == .claudeSkillPlugin, path == input.record.name, keys.isEmpty, + Set(value.object?.keys.map { $0 } ?? []) == [".claude-plugin/plugin.json"] + else { throw invalid() } + _ = try input.filename() + content = .generatedLSPPlugin( + directory: input.record.name, manifestPath: ".claude-plugin/plugin.json", + manifest: try template(envelope, selection: selection)) + case "nativePlugin": + guard kind == .plugin, input.fields["mode"] == .init("native"), + path == input.record.name, keys.isEmpty, input.record.resources.count == 1, + let resource = input.record.resources.first, + let frozen = input.ledger.resources[resource], + input.record.recipients == [input.request.surface.agent] + else { throw invalid() } + let manifest: String + switch (input.request.surface, input.request.scope, route) { + case (.claudeCode, _, .claudeSkillPlugin): manifest = ".claude-plugin/plugin.json" + case (.cursorEditor, .user, .cursorLocalPlugin): manifest = ".cursor-plugin/plugin.json" + case (.geminiCLI, .user, .geminiExtension): manifest = "gemini-extension.json" + default: throw invalid(["route"]) + } + guard frozen.entries.contains(where: { $0.path == manifest && $0.kind == .file }), + value == .init(object: ["resource": .init(resource), "manifest": .init(manifest)]) + else { throw invalid(["resources"]) } + _ = try input.filename() + content = .nativePlugin(directory: input.record.name, resource: resource, manifest: manifest) + default: throw invalid(["selection"]) + } + return .init(route: route, content: content) + } + + func template(_ envelope: LedgerValue, selection: String) throws -> NativeComponentValue { + let value = envelope.object!["value"]! + var bindings: [NativeComponentBindingPlacement] = [] + var resources: [NativeComponentResourcePlacement] = [] + func string(_ value: LedgerValue, slot: NativeComponentSlot, resource: Bool = false) throws { + switch value.kind { + case .string, .literal: break + case .environment: + guard let name = value.text, !name.isEmpty else { + throw invalid(["bindings"]) + } + bindings.append(.init(slot: slot, binding: .environment(name))) + case .secret: + guard let name = value.text, !name.isEmpty else { throw invalid(["bindings"]) } + bindings.append(.init(slot: slot, binding: .secret(name))) + case .object where resource: + guard Set(value.object!.keys) == ["resource"], + let id = value.object?["resource"], id.kind == .string, + input.record.resources.contains(id.text!), input.ledger.resources[id.text!] != nil + else { throw invalid(["resources"]) } + resources.append(.init(slot: slot, resource: id.text!)) + default: throw invalid(["bindings"]) + } + } + func environment(_ value: LedgerValue?) throws { + guard let value else { return } + guard let fields = value.object else { throw invalid(["bindings"]) } + for (key, item) in fields.sorted(by: { $0.key < $1.key }) { + guard !key.isEmpty, !key.contains("="), + !["hookGroup", "cursorHook", "antigravityHook"].contains(selection) + || MCPReferenceSyntax.isName(key) + else { throw invalid(["bindings"]) } + try string(item, slot: .environment(key)) + } + } + let program: [String: LedgerValue]? + if selection == "hookGroup" { + program = value.object?["hooks"]?.array?.first?.object?["command"]?.object?["program"]?.object + } else if selection == "cursorHook" { + program = value.object?["command"]?.object?["program"]?.object + } else if selection == "antigravityHook", let path = AntigravityAdapter.commandPath(in: value) { + let command = path.reduce(Optional(value)) { current, step in + step == "0" ? current?.array?.first : current?.object?[step] + } + program = command?.object?["program"]?.object + } else { + program = nil + } + if ["hookGroup", "cursorHook", "antigravityHook"].contains(selection) { + guard let program, + Set(program.keys).isSubset(of: [ + "executable", "arguments", "environment", "workingDirectory", + ]), + let executable = program["executable"], let arguments = program["arguments"]?.array + else { throw invalid(["program"]) } + try string(executable, slot: .executable, resource: true) + for (index, item) in arguments.enumerated() { try string(item, slot: .argument(index)) } + try environment(program["environment"]) + if let cwd = program["workingDirectory"] { + guard cwd.kind == .object else { throw invalid(["resources"]) } + try string(cwd, slot: .workingDirectory, resource: true) + } + } else if selection == "lsp" || selection == "generatedPlugin" { + let config: [String: LedgerValue]? + if selection == "generatedPlugin" { + config = + value.object?[".claude-plugin/plugin.json"]?.object?["lspServers"]?.object?[ + input.record.name]?.object + } else { + config = value.object + } + guard let config else { throw invalid(["program"]) } + if selection == "lsp" { + guard let command = config["command"]?.array, let executable = command.first else { + throw invalid(["program"]) + } + try string(executable, slot: .executable, resource: true) + for (index, item) in command.dropFirst().enumerated() { + try string(item, slot: .argument(index)) + } + } else { + guard let executable = config["command"] else { throw invalid(["program"]) } + try string(executable, slot: .executable, resource: true) + } + try environment(config["env"]) + } else { + func literal(_ value: LedgerValue) throws { + guard value.kind != .environment, value.kind != .secret else { throw invalid(["bindings"]) } + for item in value.array ?? [] { try literal(item) } + for item in value.object?.values ?? [:].values { try literal(item) } + } + try literal(value) + } + func symbolicCount(_ value: LedgerValue) -> Int { + if value.kind == .environment || value.kind == .secret { return 1 } + return (value.array ?? []).reduce(0) { $0 + symbolicCount($1) } + + (value.object?.values ?? [:].values).reduce(0) { $0 + symbolicCount($1) } + } + guard symbolicCount(value) == bindings.count else { throw invalid(["bindings"]) } + return .init( + envelope: envelope, bindings: bindings, resourcePlacements: resources, + requiresProgramConversion: [ + "hookGroup", "cursorHook", "antigravityHook", "lsp", "generatedPlugin", + ].contains( + selection), manifestProjection: selection == "generatedPlugin") + } +} diff --git a/Sources/Components/NativeComponentFieldsV1.swift b/Sources/Components/NativeComponentFieldsV1.swift new file mode 100644 index 0000000..a0d0eb5 --- /dev/null +++ b/Sources/Components/NativeComponentFieldsV1.swift @@ -0,0 +1,318 @@ +import AgentsCore +import Foundation +import NativeDocuments + +/// Source coordinates are relative to the caller-selected producer root. Details contain +/// no imported field values or machine paths. +package struct NativeComponentFieldIssue: Error { + package let document: String + package let field: [String] + package let reason: NativeAdapterIssue.Reason + package let detail: String +} + +/// Finite native field semantics shared by rendering and parsed source input. +/// Callers own syntax, source locations, aggregate admission and source capture. +/// Supply the document coordinate and the parsed value's field prefix; failures retain +/// both, switching to producer-relative document roots for referenced plugin JSON. +package enum NativeComponentFieldsV1 { + static func markdownRules(_ surface: NativeClientSurface, kind: String) -> [String: + MCPNativeField] + { + switch (surface, kind) { + case (.claudeCode, "command"): + return [ + "argument-hint": .string, "allowed-tools": .strings, + "disallowed-tools": .strings, "when_to_use": .string, + "disable-model-invocation": .boolean, "user-invocable": .boolean, + "model": .string, "context": .oneOf(["fork"]), "agent": .string, + "background": .boolean, "effort": .oneOf(["low", "medium", "high", "xhigh", "max"]), + ] + case (.claudeCode, "subagent"): + return [ + "disallowedTools": .strings, + "permissionMode": .oneOf([ + "default", "manual", "acceptEdits", "auto", "dontAsk", "bypassPermissions", "plan", + ]), + "maxTurns": .positiveInteger, "skills": .strings, + "memory": .oneOf(["user", "project", "local"]), "background": .boolean, + "omitClaudeMd": .boolean, "isolation": .oneOf(["worktree"]), + "effort": .oneOf(["low", "medium", "high", "xhigh", "max"]), + ] + case (.cursorEditor, "subagent"): return ["readonly": .boolean, "is_background": .boolean] + case (.geminiCLI, "subagent"): + return [ + "max_turns": .positiveInteger, "timeout_mins": .positiveInteger, + ] + default: return [:] + } + } +} + +extension NativeComponentFieldsV1 { + /// Applicable default coordinates beneath the explicitly selected producer container. + /// Explicit Claude commands/agents replace discovery; skills add and configs merge. + /// Cursor explicit component fields replace default discovery for that component. + package static func pluginDefaults( + surface: NativeClientSurface, document: String, fieldPrefix: [String] = [], + explicitFields: Set + ) throws -> [String: String] { + let defaults: [String: String] + switch surface { + case .claudeCode: + defaults = [ + "commands": "commands", "agents": "agents", "skills": "skills", + "hooks": "hooks/hooks.json", "mcpServers": ".mcp.json", "lspServers": ".lsp.json", + ] + return defaults.filter { + !["commands", "agents"].contains($0.key) || !explicitFields.contains($0.key) + } + case .cursorEditor: + defaults = [ + "commands": "commands", "agents": "agents", "skills": "skills", "rules": "rules", + "hooks": "hooks/hooks.json", "mcpServers": "mcp.json", + ] + return defaults.filter { !explicitFields.contains($0.key) } + default: + throw failure( + document, fieldPrefix, .unverified, + "native plugin defaults are not established for this surface") + } + } + + /// Values are already parsed. Resource entries/documents are relative to the producer's + /// explicit container root; they convey presence and kind, never deployment ownership. + package static func plugin( + surface: NativeClientSurface, document: String, fieldPrefix: [String] = [], + fields: [String: NativeValue], + entries: [LedgerEntry], documents: [String: NativeValue], budget: NativeDocumentBudget + ) throws -> [String: NativeValue] { + guard surface == .claudeCode || surface == .cursorEditor else { + throw failure( + document, fieldPrefix, .unverified, + "this container profile has no shared parsed-field contract") + } + try admit(.object(fields), budget: budget) + try budget.step(entries.count) + var coordinates = Set() + for entry in entries { + try budget.allocate(entry.path.utf8.count, stage: "native resource coordinate") + try budget.step(entry.path.utf8.count) + guard (try? PathSafety.sanitizeSubpath(entry.path)) == entry.path, + coordinates.insert(entry.path).inserted + else { + throw failure( + document, fieldPrefix, .invalid, + "native resource coordinates must be unique and contained") + } + } + for (path, value) in documents { + try budget.allocate(path.utf8.count, stage: "native document coordinate") + try admit(value, budget: budget) + } + let validator = NativePluginFieldsV1( + surface: surface, document: document, fieldPrefix: fieldPrefix, entries: entries, + budget: budget, documents: documents) + try validator.validate(fields) + return fields + } + + /// One native Claude/OpenCode LSP entry, without launch or placeholder expansion. Native + /// placeholders remain source syntax; G must convert bindings before canonical capture. + package static func lsp( + surface: NativeClientSurface, document: String, fieldPrefix: [String] = [], + fields: [String: NativeValue], + budget: NativeDocumentBudget + ) throws -> [String: NativeValue] { + try admit(.object(fields), budget: budget) + switch surface { + case .claudeCode: + try NativePluginFieldsV1( + surface: surface, document: document, fieldPrefix: fieldPrefix, entries: [], budget: budget, + documents: [:] + ) + .lsp(.object(fields), field: []) + case .openCodeCLI: + // A disabled built-in entry has no explicit executable to project into a declaration. + if fields == ["disabled": .boolean(true)] { return fields } + var rules = NativeLSPLayoutV1.openCodeNativeFields + rules["command"] = .strings + rules["env"] = .object + rules["initialization"] = .object + guard fields["command"] != nil else { + throw failure( + document, fieldPrefix + ["command"], .invalid, + "native LSP server entry requires command argv") + } + for item in fields.sorted(by: { $0.key < $1.key }) { + guard let rule = rules[item.key] else { + throw failure( + document, fieldPrefix + [item.key], .unverified, + "native LSP field is outside the finite profile") + } + guard rule.accepts(item.value) else { + throw failure( + document, fieldPrefix + [item.key], .invalid, + "native LSP field has an invalid type or range") + } + if item.key == "env", case .object(let values) = item.value, + !values.values.allSatisfy({ if case .string = $0 { true } else { false } }) + { + throw failure( + document, fieldPrefix + ["env"], .invalid, + "native LSP environment requires string values") + } + } + default: + throw failure( + document, fieldPrefix, .unverified, "this surface has no shared native LSP input contract") + } + return fields + } + + /// A finite command/subagent frontmatter object. Name is the source member coordinate, + /// used only by schemas that permit a filename fallback. inPlugin is the actual source + /// registration context, not inferred from the desired deployment scope. No fields are dropped. + package static func markdown( + surface: NativeClientSurface, document: String, fieldPrefix: [String] = [], + kind: DeclaredComponentKind, name: String, + fields: [String: NativeValue], inPlugin: Bool, budget: NativeDocumentBudget + ) throws -> [String: NativeValue] { + guard [.claudeCode, .cursorEditor, .geminiCLI].contains(surface), + kind == .command || kind == .subagent, + !(surface == .geminiCLI && kind == .command) + else { + throw failure( + document, fieldPrefix, .unverified, "native Markdown input is outside this finite profile") + } + try admit(.object(fields), budget: budget) + try budget.allocate(name.utf8.count, stage: "native member coordinate") + try budget.step(name.utf8.count) + if kind == .command { + guard name != ".", !name.isEmpty, + (try? PathSafety.sanitizeSubpath(name)) == name + else { + throw failure( + document, fieldPrefix + ["name"], .invalid, + "native command requires an exact contained relative name") + } + if surface == .cursorEditor, name.contains("/") { + throw failure( + document, fieldPrefix + ["name"], .unverified, + "nested command discovery is not established for this profile") + } + } + + var rules = markdownRules(surface, kind: kind.rawValue) + if kind == .subagent { + rules["name"] = .string + rules["description"] = .string + rules["model"] = .string + if surface != .cursorEditor { rules["tools"] = .strings } + } else if surface == .claudeCode { + rules["description"] = .string + } + for item in fields.sorted(by: { $0.key < $1.key }) { + guard let rule = rules[item.key] else { + throw failure( + document, fieldPrefix + [item.key], .unverified, + "native frontmatter field has no verified projection") + } + // The native source format also admits comma-separated tools. Preserve its source + // spelling for G's canonical projection rather than guessing tool-pattern tokenization. + if surface == .claudeCode, kind == .subagent, item.key == "tools", + case .string = item.value + { + continue + } + guard rule.accepts(item.value) else { + throw failure( + document, fieldPrefix + [item.key], .invalid, + "native frontmatter field has an invalid type or range") + } + } + if inPlugin, surface == .claudeCode, kind == .subagent, fields["permissionMode"] != nil { + throw failure( + document, fieldPrefix + ["permissionMode"], .unsupported, + "native plugin agents ignore this field; standalone policy projection would change meaning") + } + if surface == .claudeCode, kind == .command { + for key in ["agent", "background"] + where fields[key] != nil && fields["context"] != .string("fork") { + throw failure( + document, fieldPrefix + [key], .unsupported, "native command field requires context fork") + } + } + if kind == .subagent { + if surface != .cursorEditor { + guard case .string(let description) = fields["description"], !description.isEmpty, + fields["name"] != nil + else { + throw failure( + document, fieldPrefix, .invalid, "native agent requires name and nonempty description") + } + } + let effective: String + if case .string(let supplied) = fields["name"] { + effective = supplied + } else { + effective = name + } + guard !effective.isEmpty, !effective.contains("/"), !effective.contains("\\"), + effective != ".", effective != "..", !effective.utf8.contains(0) + else { + throw failure( + document, fieldPrefix + ["name"], .invalid, "native agent requires a contained filename") + } + if surface == .claudeCode, effective.count > 256 || effective.contains(":") { + throw failure( + document, fieldPrefix + ["name"], .invalid, "native agent name exceeds its native domain") + } + if surface == .geminiCLI { + guard effective.range(of: #"^[a-z0-9_-]+$"#, options: .regularExpression) != nil else { + throw failure( + document, fieldPrefix + ["name"], .invalid, "native agent requires a lowercase slug") + } + if case .array(let tools) = fields["tools"] { + guard + tools.allSatisfy({ + if case .string(let tool) = $0 { return GeminiAdapter.validAgentTool(tool) } + return false + }) + else { + throw failure( + document, fieldPrefix + ["tools"], .invalid, + "native tool is outside the pinned schema") + } + } + } + } + return fields + } + + private static func failure( + _ document: String, _ field: [String], _ reason: NativeAdapterIssue.Reason, _ detail: String + ) -> NativeComponentFieldIssue { + .init(document: document, field: field, reason: reason, detail: detail) + } + + private static func admit(_ value: NativeValue, budget: NativeDocumentBudget, depth: Int = 0) + throws + { + try budget.node(depth: depth) + switch value { + case .string(let text), .decimal(let text): + try budget.allocate(text.utf8.count, stage: "native parsed value") + try budget.step(text.utf8.count) + case .array(let values): + for child in values { try admit(child, budget: budget, depth: depth + 1) } + case .object(let fields): + for (key, child) in fields { + try budget.allocate(key.utf8.count, stage: "native parsed key") + try budget.step(key.utf8.count) + try admit(child, budget: budget, depth: depth + 1) + } + default: break + } + } +} diff --git a/Sources/Components/NativeComponentLayoutsV1.swift b/Sources/Components/NativeComponentLayoutsV1.swift new file mode 100644 index 0000000..89c676b --- /dev/null +++ b/Sources/Components/NativeComponentLayoutsV1.swift @@ -0,0 +1,107 @@ +import AgentsCore +import Foundation + +package enum NativeComponentLayoutsV1 { + package static func format(_ surface: NativeClientSurface) -> String { + switch surface { + case .antigravity: "agents/antigravity-components@1" + case .claudeCode: "agents/claude-components@1" + case .codexCLI: "agents/codex-components@1" + case .geminiCLI: "agents/gemini-components@1" + case .openCodeCLI: "agents/opencode-components@1" + case .cursorEditor, .cursorCLI, .cursorCloud: "agents/cursor-components@1" + } + } + + package static func renderers(limits: LedgerLimits) -> [String: LedgerRenderer] { + [ + "agents/antigravity-components@1": { + try render($0, $1, $2, limits: limits, surface: .antigravity) + }, + "agents/claude-components@1": { + try render($0, $1, $2, limits: limits, surface: .claudeCode) + }, + "agents/codex-components@1": { try render($0, $1, $2, limits: limits, surface: .codexCLI) }, + "agents/gemini-components@1": { try render($0, $1, $2, limits: limits, surface: .geminiCLI) }, + "agents/opencode-components@1": { + try render($0, $1, $2, limits: limits, surface: .openCodeCLI) + }, + "agents/cursor-components@1": { + try render($0, $1, $2, limits: limits, surface: .cursorEditor) + }, + ].merging(NativeGeneratedPluginLayoutV1.renderers(limits: limits)) { existing, _ in existing } + } + + private static func render( + _ lowering: LockedLowering, _ ledger: ResolvedLedger, + _ resources: [String: URL], limits: LedgerLimits, surface: NativeClientSurface + ) throws -> [ReplayedArtifact] { + let input = try input(lowering, ledger: ledger, resources: resources, limits: limits) + let record = input.record + let declared = input.request.surface + guard format(declared) == format(surface) else { + throw CoreError.invalidState("invalid version 1 native component renderer") + } + if record.kind == "plugin" { return try NativePluginLayoutV1.render(lowering, input) } + switch declared { + case .antigravity: return try AntigravityAdapter.components(lowering, input) + case .geminiCLI: return try GeminiAdapter.components(lowering, input) + case .openCodeCLI: return try OpenCodeAdapter.components(lowering, input) + case .codexCLI: return try CodexAdapter.components(lowering, input) + case .cursorEditor, .cursorCLI, .cursorCloud: + return try CursorAdapter.components(lowering, input) + case .claudeCode: return try ClaudeAdapter.components(lowering, input) + } + } + + static func input( + _ lowering: LockedLowering, ledger: ResolvedLedger, resources: [String: URL]? = nil, + limits: LedgerLimits + ) throws -> ComponentRenderInput { + func invalid() -> CoreError { .invalidState("invalid version 1 native component layout") } + guard lowering.layout.kind == .object, let layout = lowering.layout.object, + Set(layout.keys).subtracting(["inPlugin"]) == ["surface", "scope", "occurrences"], + layout["inPlugin"] == nil || layout["inPlugin"] == .init(boolean: true), + layout["surface"]?.kind == .string, + let declared = layout["surface"]?.text.flatMap(NativeClientSurface.init(rawValue:)), + layout["scope"]?.kind == .string, + let scope = layout["scope"]?.text.flatMap(InstallScope.init(rawValue:)), + lowering.format == format(declared), lowering.inputs.count == 1, + let component = lowering.inputs.first, let record = ledger.components[component], + record.payload.kind == .object, + ledger.sources[record.source] != nil, ledger.sources[record.declaringSource] != nil, + record.resources.allSatisfy({ ledger.resources[$0] != nil }), + lowering.resources == record.resources, + layout["occurrences"]?.kind == .array, let items = layout["occurrences"]?.array, + items.allSatisfy({ $0.kind == .integer }), !items.isEmpty + else { throw invalid() } + let occurrences = items.compactMap(\.integer) + guard Set(occurrences).count == occurrences.count, + occurrences + == ledger.occurrences.filter({ $0.component == component && occurrences.contains($0.id) }) + .map(\.id), + ledger.occurrences.filter({ occurrences.contains($0.id) }).allSatisfy({ + $0.recipients.contains(declared.agent) && ($0.condition.scopes?.contains(scope) ?? true) + && ($0.condition.agents?.contains(declared.agent) ?? true) + && ($0.condition.platforms?.contains(lowering.platform) ?? true) + }) + else { throw invalid() } + if layout["inPlugin"] != nil, + !ledger.occurrences.filter({ occurrences.contains($0.id) }).allSatisfy({ + $0.pluginMember != nil + }) + { + throw invalid() + } + let input = ComponentRenderInput( + record: record, component: component, + request: .init(surface: declared, scope: scope), occurrences: occurrences, + resources: resources ?? [:], ledger: ledger, limits: limits, + inPlugin: layout["inPlugin"] != nil) + if let resources, !record.resources.allSatisfy({ resources[$0] != nil }) { + throw invalid() + } + try input.validateProfile() + return input + } +} diff --git a/Sources/Components/NativeComponentLowering.swift b/Sources/Components/NativeComponentLowering.swift new file mode 100644 index 0000000..f8af69a --- /dev/null +++ b/Sources/Components/NativeComponentLowering.swift @@ -0,0 +1,451 @@ +import AgentsCore +import Foundation +import NativeDocuments + +package struct NativeComponentRequest: Equatable { + package let surface: NativeClientSurface + package let scope: InstallScope + package init(surface: NativeClientSurface, scope: InstallScope) { + self.surface = surface + self.scope = scope + } +} + +package struct NativeComponentIssue: Error, CustomStringConvertible { + package let request: NativeComponentRequest + package let kind: String + package let component: String + package let field: [String] + package let reason: NativeAdapterIssue.Reason + package let detail: String + package var description: String { + "\(request.surface.rawValue)/\(kind)/\(component)/\(request.scope.rawValue) " + + "\(field.joined(separator: ".")): \(reason.rawValue) (\(detail))." + } +} + +/// Closed recipes are resolved/admitted by Core/E. A source cannot supply a native path. +package enum NativeComponentRoute: String { + case geminiCommand, geminiAgent, geminiSettings, geminiIgnore + case openCodeConfig, codexConfig, codexAgent, codexHooks + case cursorCommand, cursorAgent, cursorIgnore + case claudeSkillPlugin, cursorLocalPlugin, geminiExtension + case claudeCommand, claudeAgent, claudeSettings, cursorHooks, antigravityHooks + + /// Structured shared documents only. Whole files, ignore blocks and plugin trees have their + /// concrete content shape on NativeComponentOutput and do not use a shared-document editor. + package var documentFormat: NativeDocumentFormat? { + switch self { + case .claudeSettings, .codexHooks, .cursorHooks, .antigravityHooks: .json + case .codexConfig: .toml + case .geminiSettings: .jsonc(trailingCommas: false) + case .openCodeConfig: .jsonc(trailingCommas: true) + default: nil + } + } +} + +package enum NativeComponentLowering { + package static func lower( + _ linked: LinkedComponent, frozen: LedgerFreeze.Result, + request: NativeComponentRequest, id: String, platform: DeclarationPlatform + ) throws -> LockedLowering { + let owner: (id: String, occurrences: [Int]) + do { + owner = try FrozenNativeIdentity.match( + linked, frozen: frozen, + agent: request.surface.agent, scope: request.scope) + } catch { + throw NativeComponentIssue( + request: request, kind: linked.key.kind.rawValue, + component: linked.key.name, field: ["component"], reason: .invalid, + detail: "linked component and frozen source identity do not match") + } + let selected = Set(owner.occurrences) + guard + frozen.ledger.occurrences.filter({ selected.contains($0.id) }).allSatisfy({ + $0.condition.platforms?.contains(platform.rawValue) ?? true + }) + else { + throw NativeComponentIssue( + request: request, kind: linked.key.kind.rawValue, + component: linked.key.name, field: ["platform"], reason: .invalid, + detail: "frozen occurrence does not target the requested output platform") + } + let format = NativeComponentLayoutsV1.format(request.surface) + let record = frozen.ledger.components[owner.id]! + let input = ComponentRenderInput( + record: record, component: owner.id, request: request, + occurrences: owner.occurrences, resources: [:], ledger: frozen.ledger, limits: .standard) + try input.validateProfile() + return .init( + id: id, format: format, inputs: [owner.id], resources: record.resources, deployments: [], + layout: .init(object: [ + "surface": .init(request.surface.rawValue), + "scope": .init(request.scope.rawValue), + "occurrences": .init(array: owner.occurrences.map { .init(integer: $0) }), + ]), + platform: platform.rawValue, artifacts: []) + } +} + +/// A concrete profile emits its native file contents or regional values plus route/ownership +/// metadata. E alone groups these contributions into physical documents and transactions. +struct ComponentRenderInput { + let record: LedgerComponent + let component: String + let request: NativeComponentRequest + let occurrences: [Int] + let resources: [String: URL] + let ledger: ResolvedLedger + let limits: LedgerLimits + let budget: NativeDocumentBudget + let inPlugin: Bool + init( + record: LedgerComponent, component: String, request: NativeComponentRequest, + occurrences: [Int], resources: [String: URL], ledger: ResolvedLedger, limits: LedgerLimits, + inPlugin: Bool = false + ) { + self.inPlugin = inPlugin + self.record = record + self.component = component + self.request = request + self.occurrences = occurrences + self.resources = resources + self.ledger = ledger + self.limits = limits + budget = .init( + limits: .init( + storage: limits.encodedBytes, work: limits.encodedBytes, + nodes: limits.nodes, depth: limits.depth, uninterruptedBytes: limits.resourceBytes)) + } + var fields: [String: LedgerValue] { record.payload.object! } + var native: [String: LedgerValue] { + fields["native"]?.object?[request.surface.agent.rawValue]?.object ?? [:] + } + + func issue(_ field: [String], _ reason: NativeAdapterIssue.Reason, _ detail: String) + -> NativeComponentIssue + { + .init( + request: request, kind: record.kind, component: record.name, field: field, + reason: reason, detail: detail) + } + + func validateProfile() throws { + func admit(_ value: LedgerValue, depth: Int) throws { + try budget.node(depth: depth) + if let text = value.text { + try budget.allocate(text.utf8.count, stage: "native input string") + try budget.step(text.utf8.count) + } + for item in value.array ?? [] { try admit(item, depth: depth + 1) } + for (key, item) in value.object ?? [:] { + try budget.allocate(key.utf8.count, stage: "native input key") + try budget.step(key.utf8.count) + try admit(item, depth: depth + 1) + } + var node = value + if node.array != nil { node.array = [] } + if node.object != nil { node.object = [:] } + try node.validate() + } + try admit(record.payload, depth: 0) + guard fields["name"] == .init(record.name) else { + throw issue(["name"], .invalid, "frozen payload and component identity do not match") + } + for key in ["model", "matcher", "description", "purpose", "mode"] where fields[key] != nil { + guard fields[key]?.kind == .string else { + throw issue([key], .invalid, "frozen native field requires a string") + } + } + for key in ["tools", "patterns"] where fields[key] != nil { + guard let values = fields[key]?.array, values.allSatisfy({ $0.kind == .string }) else { + throw issue([key], .invalid, "frozen native field requires strings") + } + } + if let timeout = fields["timeoutSeconds"] { + guard timeout.kind == .integer, timeout.integer.map({ $0 > 0 }) == true else { + throw issue(["timeoutSeconds"], .invalid, "frozen native timeout requires positive seconds") + } + } + if let native = fields["native"] { + guard let clients = native.object, + clients[request.surface.agent.rawValue] == nil + || clients[request.surface.agent.rawValue]?.kind == .object + else { throw issue(["native"], .invalid, "frozen native configuration requires objects") } + } + guard record.recipients.contains(request.surface.agent) else { + throw issue(["recipients"], .invalid, "component does not target this recipient") + } + try literal(record.name, field: ["name"]) + for key in ["model", "tools", "matcher"] { + if let value = fields[key] { + try NativeProgramV1.validateLiterals(value, input: self, path: [key]) + } + } + guard let kind = DeclaredComponentKind(rawValue: record.kind) else { + throw issue(["kind"], .invalid, "invalid frozen component kind") + } + _ = try CapabilityRegistry.component(request, kind: kind, name: record.name, inPlugin: inPlugin) + if kind == .ignore, fields["purpose"]?.text != "context" { + throw issue( + ["purpose"], .unverified, "a distinct current indexing-only contract is not established") + } + } + + func checkedNative(_ rules: [String: MCPNativeField]) throws -> [String: LedgerValue] { + for (key, value) in native.sorted(by: { $0.key < $1.key }) { + guard let rule = rules[key] else { + throw issue( + ["native", request.surface.agent.rawValue, key], .unverified, + "no verified field mapping in this native schema") + } + try NativeProgramV1.validateLiterals( + value, input: self, path: ["native", request.surface.agent.rawValue, key]) + guard rule.accepts(try nativeValue(value)) else { + throw issue( + ["native", request.surface.agent.rawValue, key], .invalid, + "value is outside the verified native field profile") + } + } + return native + } + + func text(_ key: String) throws -> String { + guard let value = fields[key]?.text else { + throw issue([key], .invalid, "required frozen string is missing") + } + try literal(value, field: [key]) + return value + } + + func literal(_ value: String, field: [String], prompt: Bool = false) throws { + guard !value.utf8.contains(0) else { + throw issue(field, .invalid, "NUL is not a native string") + } + if prompt && value.contains("$${input:") { + throw issue( + field, .unverified, "literal input-token escaping needs a verified native representation") + } + let interpolation: Bool + switch request.surface { + case .claudeCode: + interpolation = + (record.kind == "hook" && value.contains("${")) + || (prompt && (value.contains("$") || value.contains("!`") || value.contains("${"))) + case .openCodeCLI: + interpolation = + value.contains("{env:") || value.contains("{file:") + || (prompt + && (value.range(of: #"\$(?:ARGUMENTS|[1-9])|!`"#, options: .regularExpression) != nil)) + case .geminiCLI: + interpolation = + (record.kind == "hook" + && value.range( + of: #"\$(?:[A-Za-z0-9_]+|\{[^}]+?(?::-[^}]*)?\})"#, options: .regularExpression) != nil) + || (prompt && (value.contains("{{args}}") || value.contains("!{") || value.contains("@{"))) + default: interpolation = false + } + guard !interpolation else { + throw issue( + field, .unverified, "exact literal preservation across native interpolation needs evidence") + } + if prompt && request.surface == .openCodeCLI, + !NativeComponentText.isUntrimmed(value, rust: false) + { + throw issue( + field, .unsupported, "the native template evaluator trims leading and trailing whitespace") + } + } + + func prompt() throws -> String { + guard let prompt = fields["prompt"] else { + throw issue(["prompt"], .invalid, "missing frozen prompt") + } + let value: String + if prompt.kind == .literal { + value = prompt.text! + } else { + guard let id = record.resources.first, let resource = ledger.resources[id], + resource.path == prompt.object?["file"]?.object?["path"]?.text, + let url = resources[id], resource.entries.count == 1, + resource.entries[0].kind == .file, resource.entries[0].path == "." + else { throw issue(["prompt"], .invalid, "frozen prompt resource is not a single file") } + guard let size = resource.entries[0].byteCount, size <= limits.resourceBytes else { + throw issue(["prompt"], .invalid, "prompt resource exceeds output budget") + } + try budget.allocate(size, stage: "frozen prompt bytes") + try budget.allocate(size, stage: "frozen prompt UTF8") + try budget.step(size) + let bytes = try Data(contentsOf: url) + guard bytes.count == size, let decoded = String(data: bytes, encoding: .utf8) else { + throw issue(["prompt"], .invalid, "prompt resource is not exact UTF8") + } + value = decoded + } + guard value.utf8.count <= limits.resourceBytes else { + throw issue(["prompt"], .invalid, "prompt exceeds output budget") + } + try literal(value, field: ["prompt"], prompt: record.kind == "command") + return value + } + + func relativeName() throws -> String { + do { + let name = try PathSafety.sanitizeSubpath(record.name) + guard name == record.name, name != "." else { throw CoreError.invalidState("invalid name") } + return name + } catch { + throw issue(["name"], .invalid, "native filename requires an exact contained relative name") + } + } + + func filename() throws -> String { + let name = try relativeName() + guard !name.contains("/") else { + throw issue( + ["name"], .unverified, "nested file discovery is not established by this native profile") + } + return name + } + + func noParameters() throws { + guard fields["parameters"]?.array?.isEmpty ?? true else { + throw issue( + ["parameters"], .unsupported, + "native command schema does not represent named parameter descriptions/defaults") + } + } + + func nativeValue(_ value: LedgerValue) throws -> NativeValue { + switch value.kind { + case .string, .literal: return .string(value.text!) + case .integer: return .integer(value.integer!) + case .decimal: return .decimal(value.text!) + case .boolean: return .boolean(value.boolean!) + case .null: return .null + case .array: return .array(try value.array!.map(nativeValue)) + case .object: return .object(try value.object!.mapValues(nativeValue)) + case .environment, .secret: + throw issue( + ["value"], .integrationRequired, "native binding requires private staged conversion") + } + } + + func envelope( + route: NativeComponentRoute, path: String? = nil, + keys: [String] = [], selection: String = "key", value: LedgerValue + ) -> LedgerValue { + var result: [String: LedgerValue] = [ + "route": .init(route.rawValue), + "surface": .init(request.surface.rawValue), "scope": .init(request.scope.rawValue), + "kind": .init(record.kind), "name": .init(record.name), "component": .init(component), + "occurrences": .init(array: occurrences.map { .init(integer: $0) }), + "recipients": LedgerPayload.strings([request.surface.agent.rawValue]), + "knownReaders": LedgerPayload.strings( + CapabilityRegistry.componentReaders( + request, kind: DeclaredComponentKind(rawValue: record.kind)! + ).map(\.rawValue).sorted()), + "keys": LedgerPayload.strings(keys), "selection": .init(selection), "value": value, + ] + result["path"] = path.map { .init($0) } + return .init(object: result) + } + + func quoted(_ value: String) throws -> String { + guard limits.resourceBytes >= 2, value.utf8.count <= (limits.resourceBytes - 2) / 6 else { + throw issue(["output"], .invalid, "native string exceeds encoding budget") + } + try budget.allocate(value.utf8.count * 6 + 2, stage: "native scalar encoding") + try budget.step(value.utf8.count) + let encoder = JSONEncoder() + encoder.outputFormatting = [.withoutEscapingSlashes] + return String(decoding: try encoder.encode(value), as: UTF8.self) + .replacingOccurrences(of: "\u{0085}", with: "\\u0085") + .replacingOccurrences(of: "\u{2028}", with: "\\u2028") + .replacingOccurrences(of: "\u{2029}", with: "\\u2029") + } + + func joined(_ parts: [String], separator: String = "\n") throws -> String { + var size = 0 + for part in parts { + guard part.utf8.count <= limits.resourceBytes - size else { + throw issue(["output"], .invalid, "native file exceeds output budget") + } + size += part.utf8.count + } + for _ in parts.dropFirst() { + guard separator.utf8.count <= limits.resourceBytes - size else { + throw issue(["output"], .invalid, "native file exceeds output budget") + } + size += separator.utf8.count + } + try budget.allocate(size, stage: "native file") + try budget.step(size) + return parts.joined(separator: separator) + } + + func frontmatter(_ values: [String: LedgerValue], body: String) throws -> String { + var lines = ["---"] + for (key, value) in values.sorted(by: { $0.key < $1.key }) { + let text: String + if value.kind == .decimal, let decimal = value.text { + text = decimal + } else if let value = value.text { + text = try quoted(value) + } else if let values = value.array { + text = try joined(values.map { try quoted($0.text!) }, separator: ", ") + lines.append("\(key): [\(text)]") + continue + } else if let value = value.boolean { + text = value ? "true" : "false" + } else if let value = value.integer { + text = String(value) + } else { + throw issue(["native", key], .invalid, "unsupported frontmatter scalar") + } + lines.append("\(key): \(text)") + } + lines.append("---") + lines.append(body) + return try joined(lines) + } + + func emitted(_ lowering: LockedLowering, _ envelope: LedgerValue) throws -> [ReplayedArtifact] { + try envelope.validate() + func admit(_ value: LedgerValue, depth: Int) throws { + try budget.node(depth: depth) + if let text = value.text { + try budget.allocate(text.utf8.count, stage: "native output") + try budget.step(text.utf8.count) + } + for child in value.array ?? [] { try admit(child, depth: depth + 1) } + for (key, child) in value.object ?? [:] { + try budget.allocate(key.utf8.count, stage: "native output key") + try admit(child, depth: depth + 1) + } + } + try admit(envelope, depth: 0) + return [.init(name: lowering.id, kind: .ownedValues, values: envelope)] + } +} + +/// Source-pinned loaders use JavaScript trim or Rust str::trim, whose Unicode edge sets differ. +enum NativeComponentText { + static func whitespace(_ scalar: Unicode.Scalar, rust: Bool) -> Bool { + let value = scalar.value + return (9...13).contains(value) + || [0x20, 0xA0, 0x1680, 0x2028, 0x2029, 0x202F, 0x205F, 0x3000].contains(value) + || (0x2000...0x200A).contains(value) || (rust ? value == 0x85 : value == 0xFEFF) + } + static func isUntrimmed(_ value: String, rust: Bool) -> Bool { + guard let first = value.unicodeScalars.first, let last = value.unicodeScalars.last else { + return true + } + return !whitespace(first, rust: rust) && !whitespace(last, rust: rust) + } + static func isBlank(_ value: String, rust: Bool) -> Bool { + value.unicodeScalars.allSatisfy { whitespace($0, rust: rust) } + } +} diff --git a/Sources/Components/NativeDocumentedHooksV1.swift b/Sources/Components/NativeDocumentedHooksV1.swift new file mode 100644 index 0000000..693a4cd --- /dev/null +++ b/Sources/Components/NativeDocumentedHooksV1.swift @@ -0,0 +1,208 @@ +import AgentsCore + +/// Native event names retain the client's own stdin/stdout contract, not portable event aliases. +enum NativeDocumentedHooksV1 { + static let claudeEvents: Set = [ + "SessionStart", "Setup", "InstructionsLoaded", "UserPromptSubmit", "UserPromptExpansion", + "MessageDisplay", "PreToolUse", "PermissionRequest", "PermissionDenied", "PostToolUse", + "PostToolUseFailure", "PostToolBatch", "Notification", "SubagentStart", "SubagentStop", + "Stop", "StopFailure", "TeammateIdle", "TaskCreated", "TaskCompleted", "ConfigChange", + "CwdChanged", "DirectoryAdded", "FileChanged", "WorktreeCreate", "WorktreeRemove", + "PreCompact", "PostCompact", "PreModelSwitch", "PostModelSwitch", "Elicitation", + "ElicitationResult", "SessionEnd", + ] + static let claudeWithoutMatcher: Set = [ + "CwdChanged", "UserPromptSubmit", "PostToolBatch", "Stop", "TeammateIdle", "TaskCreated", + "TaskCompleted", "WorktreeCreate", "WorktreeRemove", "MessageDisplay", + ] + static let cursorEvents: Set = [ + "sessionStart", "sessionEnd", "preToolUse", "postToolUse", "postToolUseFailure", + "subagentStart", "subagentStop", "beforeShellExecution", "afterShellExecution", + "beforeMCPExecution", "afterMCPExecution", "beforeReadFile", "afterFileEdit", + "beforeSubmitPrompt", "preCompact", "stop", "afterAgentResponse", "afterAgentThought", + "beforeTabFileRead", "afterTabFileEdit", "workspaceOpen", + ] + static let cursorCloudEvents: Set = [ + "beforeShellExecution", "afterShellExecution", "beforeReadFile", "afterFileEdit", + "preToolUse", "postToolUse", "postToolUseFailure", "subagentStart", "subagentStop", + "beforeSubmitPrompt", "preCompact", "afterAgentResponse", "afterAgentThought", "stop", + ] + static let cursorMatcherEvents: Set = [ + "preToolUse", "postToolUse", "postToolUseFailure", "subagentStart", "subagentStop", + "beforeShellExecution", "afterShellExecution", "beforeReadFile", "afterFileEdit", + "beforeTabFileRead", "afterTabFileEdit", "beforeSubmitPrompt", "stop", + "afterAgentResponse", "afterAgentThought", + ] + /// These fragments are valid in the native JavaScript regex engine without substituting + /// a different engine's syntax or matching behavior. More complex syntax stays explicit. + static func admittedMatcher(_ matcher: String) -> Bool { + if matcher.isEmpty || matcher == "*" { return true } + return matcher.split(separator: "|", omittingEmptySubsequences: false).allSatisfy { part in + var part = part[...] + if part.hasPrefix("^") { part = part.dropFirst() } + if part.hasSuffix("$") { part = part.dropLast() } + if part.hasSuffix(".*") { part = part.dropLast(2) } + return !part.contains(where: { "\\[]{}()+?*^$".contains($0) }) + } + } + + static func event(_ input: ComponentRenderInput, allowed: Set) throws -> String { + guard let event = input.fields["event"]?.object?["native"]?.text else { + throw input.issue( + ["event"], .unverified, + "portable event payload/output equivalence is not established; select an explicit native event" + ) + } + guard allowed.contains(event) else { + throw input.issue( + ["event"], .unsupported, "event is absent from this documented native surface") + } + return event + } + + static func program(_ input: ComponentRenderInput) throws -> LedgerValue { + guard let run = input.fields["run"]?.object else { + throw input.issue(["run"], .invalid, "missing frozen hook program") + } + var result = run + result["executable"] = try NativeProgramV1.executable(run, input: input) + if run["workingDirectory"] != nil { + let index = run["executable"]?.text?.contains("/") == true ? 1 : 0 + guard input.record.resources.indices.contains(index) else { + throw input.issue(["run", "workingDirectory"], .invalid, "missing frozen hook directory") + } + result["workingDirectory"] = .init(object: ["resource": .init(input.record.resources[index])]) + } + try NativeProgramV1.validateLiterals(.init(object: result), input: input, path: ["run"]) + return .init(object: ["program": .init(object: result)]) + } + + static func claude(_ lowering: LockedLowering, _ input: ComponentRenderInput) throws + -> [ReplayedArtifact] + { + let event = try event(input, allowed: claudeEvents) + try commandType(input) + if input.fields["matcher"] != nil, claudeWithoutMatcher.contains(event) { + throw input.issue(["matcher"], .unsupported, "this native event ignores matchers") + } + if let matcher = input.fields["matcher"]?.text, !admittedMatcher(matcher) { + throw input.issue( + ["matcher"], .unverified, + "exact native JavaScript regex admission is required beyond this fragment profile") + } + var hook = try input.checkedNative([ + "type": .oneOf(["command"]), "statusMessage": .string, + "async": .boolean, "asyncRewake": .boolean, "if": .string, + "onFailure": .oneOf(["continue", "block"]), + ]) + let toolEvents: Set = [ + "PreToolUse", "PostToolUse", "PostToolUseFailure", "PermissionRequest", "PermissionDenied", + ] + if hook["if"] != nil, !toolEvents.contains(event) { + throw input.issue( + ["native", "claude-code", "if"], .unsupported, "native if filters never run on this event") + } + if hook["onFailure"] != nil { + guard hook["async"]?.boolean != true, hook["asyncRewake"]?.boolean != true else { + throw input.issue( + ["native", "claude-code", "onFailure"], .unsupported, + "native background hooks ignore this failure policy") + } + guard ["PreToolUse", "PermissionRequest", "UserPromptSubmit"].contains(event) else { + throw input.issue( + ["native", "claude-code", "onFailure"], .unverified, + "failure blocking is not verified for this event") + } + } + if let timeout = input.fields["timeoutSeconds"] { + guard timeout.integer.map({ $0 > 0 }) == true else { + throw input.issue(["timeoutSeconds"], .invalid, "native timeout must be positive seconds") + } + guard hook["async"]?.boolean != true, hook["asyncRewake"]?.boolean != true else { + throw input.issue( + ["timeoutSeconds"], .unsupported, "native background hooks do not enforce this timeout") + } + if event == "SessionEnd", timeout.integer! > 60 { + throw input.issue( + ["timeoutSeconds"], .unsupported, "native SessionEnd budget is capped at sixty seconds") + } + hook["timeout"] = timeout + } + hook["type"] = .init("command") + hook["command"] = try program(input) + var group: [String: LedgerValue] = ["hooks": .init(array: [.init(object: hook)])] + group["matcher"] = input.fields["matcher"] + return try input.emitted( + lowering, + input.envelope( + route: .claudeSettings, keys: ["hooks", event], selection: "hookGroup", + value: .init(object: group))) + } + + static func cursor(_ lowering: LockedLowering, _ input: ComponentRenderInput) throws + -> [ReplayedArtifact] + { + let allowed: Set + switch input.request.surface { + case .cursorCloud: allowed = cursorCloudEvents + case .cursorCLI: allowed = cursorEvents.subtracting(["beforeTabFileRead", "afterTabFileEdit"]) + default: allowed = cursorEvents + } + let event = try event(input, allowed: allowed) + try commandType(input) + if input.fields["matcher"] != nil, !cursorMatcherEvents.contains(event) { + throw input.issue( + ["matcher"], .unverified, "the documented matcher target is not established for this event") + } + if let matcher = input.fields["matcher"]?.text, !admittedMatcher(matcher) { + throw input.issue( + ["matcher"], .unverified, + "exact native JavaScript regex admission is required beyond this fragment profile") + } + var hook = try input.checkedNative([ + "type": .oneOf(["command"]), "failClosed": .boolean, "loop_limit": .numberOrNull, + ]) + if let loop = input.native["loop_limit"] { + // Only these two event callers consume the field. Unknown/ignored fields are never dropped. + guard ["stop", "subagentStop"].contains(event) else { + throw input.issue( + ["native", "cursor", "loop_limit"], .unsupported, + "only stop/subagentStop consume loop_limit") + } + hook["loop_limit"] = loop + } + if hook["failClosed"]?.boolean == true, event == "sessionStart" { + throw input.issue( + ["native", "cursor", "failClosed"], .unsupported, + "sessionStart is fire-and-forget and cannot block creation") + } + hook["type"] = .init("command") + hook["command"] = try program(input) + hook["matcher"] = input.fields["matcher"] + hook["timeout"] = input.fields["timeoutSeconds"] + if let seconds = input.fields["timeoutSeconds"]?.integer, seconds <= 0 { + throw input.issue(["timeoutSeconds"], .invalid, "native timeout must be positive seconds") + } + var envelope = input.envelope( + route: .cursorHooks, keys: ["hooks", event], selection: "cursorHook", + value: .init(object: hook) + ).object! + envelope["rootRequirements"] = .init(object: ["version": .init(integer: 1)]) + return try input.emitted(lowering, .init(object: envelope)) + } + + private static func commandType(_ input: ComponentRenderInput) throws { + guard let type = input.native["type"] else { return } + guard let name = type.text else { + throw input.issue( + ["native", input.request.surface.agent.rawValue, "type"], .invalid, + "native handler type requires a string") + } + guard name == "command" else { + throw input.issue( + ["native", input.request.surface.agent.rawValue, "type"], .unsupported, + "an executable hook declaration cannot replace its run with a native prompt, agent, HTTP or MCP handler" + ) + } + } +} diff --git a/Sources/Components/NativeGeneratedPluginContribution.swift b/Sources/Components/NativeGeneratedPluginContribution.swift new file mode 100644 index 0000000..054a0d2 --- /dev/null +++ b/Sources/Components/NativeGeneratedPluginContribution.swift @@ -0,0 +1,282 @@ +import AgentsCore +import Foundation +import NativeDocuments + +/// Registration is the existing closed named-directory recipe. E owns reader union, all physical +/// writes, owner retirement, private receipts and publication. Members never become direct owners. +package struct NativeGeneratedPluginContribution { + package let request: NativeComponentRequest + package let component: String + package let directory: String + package let route: NativeComponentRoute + package let manifestPath: String + package let occurrences: [Int] + package let recipients: [AgentID] + package let knownReaders: [AgentID] + package let members: [Member] + package let resources: [String: LedgerResource] + private let metadata: [String: NativeValue] + + package struct Member { + package let component: String + package let occurrences: [Int] + package let content: Content + package enum Content { + case component(NativeComponentContribution) + case mcp(NativeMCPContribution) + case skill(name: String, resource: String) + } + } + + /// E materializes these exact frozen resource roots through Core, including supporting links + /// and file modes; it admits final paths before calling stagedBundle. No copy is performed here. + package struct ResourcePlacement { + package let resource: String + package let path: String + } + package var resourcePlacements: [ResourcePlacement] { + let skills = members.compactMap { member -> ResourcePlacement? in + if case .skill(let name, let resource) = member.content { + return .init(resource: resource, path: "skills/" + name) + } + return nil + } + let skillResources = Set(skills.map(\.resource)) + return skills + + resources.keys.sorted().filter { !skillResources.contains($0) }.map { + .init(resource: $0, path: "resources/" + $0.replacingOccurrences(of: "sha256:", with: "")) + } + } + + package struct Bundle { + /// UTF8 native files are nonexecutable. Resource modes are on the frozen resource entries. + package let files: [String: Data] + /// JSON document values for the existing NativeDocuments writer, including the manifest. + package let documents: [String: NativeValue] + } + + /// Invoke only inside D/E's private render closure. Values and intermediate bundle documents + /// are ephemeral; never persist them in the public lowering, content store, report or hashes. + package func stagedBundle( + bindings: RuntimeBindingValues, environment: RuntimeEnvironment, + resourcePaths: [String: String], budget: NativeDocumentBudget, + cursorCommandShell: NativeProgramV1.CommandShell? = nil + ) throws -> Bundle { + var files: [String: Data] = [:] + var manifest = metadata + manifest["name"] = .string(directory) + var hooks: [String: [NativeValue]] = [:] + var servers: [String: NativeValue] = [:] + var lsps: [String: NativeValue] = [:] + var paths: [String: [NativeValue]] = [:] + func invalid() -> CoreError { .invalidState("invalid generated native bundle composition") } + func put(_ path: String, _ bytes: Data) throws { + try budget.allocate(bytes.count, stage: "generated native file") + try budget.step(bytes.count) + guard files[path] == nil else { throw invalid() } + files[path] = bytes + } + for member in members { + try budget.step() + switch member.content { + case .skill(let name, _): + paths["skills", default: []].append(.string("./skills/" + name)) + case .mcp(let contribution): + guard servers[contribution.name] == nil else { throw invalid() } + servers[contribution.name] = try contribution.stagedValue( + bindings: bindings, environment: environment, resourcePaths: resourcePaths, budget: budget + ) + case .component(let contribution): + for output in contribution.outputs { + switch output.content { + case .file(let path, let bytes): + let field = contribution.kind == .command ? "commands" : "agents" + let relative = field + "/" + path + try put(relative, bytes) + paths[field, default: []].append(.string("./" + relative)) + case .hook(let hook): + if request.surface == .cursorEditor { + // Plugin hooks only support command handlers, regardless of standalone capability. + let value = try hook.value.stagedValue( + bindings: bindings, environment: environment, resourcePaths: resourcePaths, + budget: budget, cursorCommandShell: cursorCommandShell) + guard case .object(let handler) = value, handler["type"] == .string("command") else { + throw invalid() + } + hooks[hook.event, default: []].append(value) + } else { + hooks[hook.event, default: []].append( + try hook.value.stagedValue( + bindings: bindings, environment: environment, resourcePaths: resourcePaths, + budget: budget)) + } + case .generatedLSPPlugin(_, _, let value): + guard request.surface == .claudeCode, + case .object(let fields) = try value.stagedValue( + bindings: bindings, environment: environment, resourcePaths: resourcePaths, + budget: budget), + case .object(let entries) = fields["lspServers"] + else { throw invalid() } + for (name, server) in entries { + guard lsps[name] == nil else { throw invalid() } + lsps[name] = server + } + default: throw invalid() + } + } + } + } + var documents: [String: NativeValue] = [:] + if !hooks.isEmpty { + var value: [String: NativeValue] = ["hooks": .object(hooks.mapValues(NativeValue.array))] + if request.surface == .cursorEditor { value["version"] = .integer(1) } + if request.surface == .claudeCode { + manifest["hooks"] = .object(hooks.mapValues(NativeValue.array)) + } else { + documents["hooks/hooks.json"] = .object(value) + if request.surface == .cursorEditor { manifest["hooks"] = .string("./hooks/hooks.json") } + } + } + if !servers.isEmpty { + if request.surface == .cursorEditor { + documents["mcp.json"] = .object(["mcpServers": .object(servers)]) + manifest["mcpServers"] = .string("./mcp.json") + } else { + manifest["mcpServers"] = .object(servers) + } + } + if !lsps.isEmpty { manifest["lspServers"] = .object(lsps) } + if request.surface != .geminiCLI { + for (field, values) in paths { manifest[field] = .array(values) } + } + documents[manifestPath] = .object(manifest) + return .init(files: files, documents: documents) + } + + package static func decode( + _ lowering: LockedLowering, ledger: ResolvedLedger, artifacts: [ReplayedArtifact], + limits: LedgerLimits + ) throws -> NativeGeneratedPluginContribution { + let (input, nested, owners) = try NativeGeneratedPluginLayoutV1.decode( + lowering, ledger: ledger, limits: limits) + func invalid() -> CoreError { + .invalidState("invalid sealed generated native plugin contribution") + } + guard ledger.lowerings.filter({ $0.id == lowering.id }) == [lowering], + lowering.artifacts.count == 1, artifacts.count == 1, artifacts[0].name == lowering.id, + artifacts[0].kind == .ownedValues, artifacts[0].location == nil, + let values = artifacts[0].values?.object?["members"]?.array, values.count == nested.count + else { throw invalid() } + try admit(artifacts[0].values!, budget: input.budget) + guard try artifacts[0].digest(limits: limits) == lowering.artifacts[0], + try ResolvedLedgerCodec.bytes(artifacts[0].values!) + == ResolvedLedgerCodec.bytes( + NativeGeneratedPluginLayoutV1.envelope(input, members: values)) + else { throw invalid() } + let (route, manifest) = try NativeGeneratedPluginLayoutV1.recipe(input) + let directory = try input.filename() + if input.request.surface == .claudeCode, !NativePluginFieldsV1.validClaudeName(directory) { + throw invalid() + } + if input.request.surface == .cursorEditor, + directory.range(of: #"^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$"#, options: .regularExpression) + == nil + { + throw invalid() + } + if input.request.surface == .geminiCLI, + directory.range(of: #"^[a-zA-Z0-9-]+$"#, options: .regularExpression) == nil + { + throw invalid() + } + let metadataFields = try input.checkedNative(["version": .string, "description": .string]) + if input.request.surface == .geminiCLI, metadataFields["version"]?.text?.isEmpty != false { + throw input.issue( + ["native", "gemini-cli", "version"], .integrationRequired, + "generated Gemini extensions require explicit frozen native version metadata") + } + var metadata: [String: NativeValue] = [:] + for (key, value) in metadataFields { metadata[key] = .string(value.text!) } + if input.request.surface != .geminiCLI { + _ = try NativeComponentFieldsV1.plugin( + surface: input.request.surface, document: manifest, + fields: metadata.merging(["name": .string(directory)]) { value, _ in value }, + entries: [], documents: [:], budget: input.budget) + } + var members: [Member] = [] + var names = Set() + var nativeNames = Set() + for (index, var child) in nested.enumerated() { + let component = child.inputs[0] + let record = ledger.components[component]! + let identity = record.kind + "/" + record.name + guard names.insert(Data(identity.utf8)).inserted, nativeNames.insert(identity).inserted else { + throw input.issue( + ["children"], .invalid, "native member identities conflict in the generated container") + } + let content: Member.Content + if record.kind == "skills" { + guard + record.payload.object?["native"]?.object?[input.request.surface.agent.rawValue]?.object? + .isEmpty ?? true + else { + throw input.issue( + ["children", "skills", "native"], .unverified, + "native skill options require their exact container interpretation") + } + guard values[index] == .init(), !record.name.isEmpty, + !record.name.contains("/"), !record.name.contains("\\"), record.name != ".", + record.name != ".." + else { throw invalid() } + content = .skill(name: record.name, resource: record.resources[0]) + } else if record.kind == "mcpServer" { + guard values[index] == child.layout else { throw invalid() } + content = .mcp(try MCPLayoutV1.contribution(child, ledger: ledger)) + } else { + let output = ReplayedArtifact(name: child.id, kind: .ownedValues, values: values[index]) + child.artifacts = [try output.digest(limits: limits)] + var childLedger = ledger + childLedger.lowerings = [child] + let contribution = try NativeComponentLayoutsV1.contribution( + child, ledger: childLedger, artifacts: [output], limits: limits) + content = .component(contribution) + } + members.append(.init(component: component, occurrences: owners[index], content: content)) + } + var readers: Set = [input.request.surface.agent] + for member in members { + if case .component(let contribution) = member.content { + readers.formUnion(contribution.knownReaders) + } else if case .mcp(let contribution) = member.content { + readers.formUnion(contribution.descriptor.knownReaders) + } + } + return .init( + request: input.request, component: input.component, directory: directory, route: route, + manifestPath: manifest, occurrences: input.occurrences, + recipients: [input.request.surface.agent], + knownReaders: readers.sorted { $0.rawValue < $1.rawValue }, members: members, + resources: Dictionary( + uniqueKeysWithValues: lowering.resources.map { ($0, ledger.resources[$0]!) }), + metadata: metadata) + } + + static func admit(_ value: LedgerValue, budget: NativeDocumentBudget, depth: Int = 0) throws { + try budget.node(depth: depth) + try budget.step() + if let text = value.text { + try budget.allocate(text.utf8.count, stage: "generated native input") + try budget.step(text.utf8.count) + } + for child in value.array ?? [] { try admit(child, budget: budget, depth: depth + 1) } + for (key, child) in value.object ?? [:] { + try budget.allocate(key.utf8.count, stage: "generated native key") + try budget.step(key.utf8.count) + try admit(child, budget: budget, depth: depth + 1) + } + var node = value + if node.array != nil { node.array = [] } + if node.object != nil { node.object = [:] } + try node.validate() + } +} diff --git a/Sources/Components/NativeGeneratedPluginLayoutV1.swift b/Sources/Components/NativeGeneratedPluginLayoutV1.swift new file mode 100644 index 0000000..63eccd2 --- /dev/null +++ b/Sources/Components/NativeGeneratedPluginLayoutV1.swift @@ -0,0 +1,320 @@ +import AgentsCore +import Foundation + +/// A fixed closure of native members. Cold rendering consumes sealed layouts, never import input. +package enum NativeGeneratedPluginLayoutV1 { + package static func format(_ surface: NativeClientSurface) -> String { + "agents/\(surface.agent.rawValue)-generated-plugin@1" + } + + static func renderers(limits: LedgerLimits) -> [String: LedgerRenderer] { + Dictionary( + uniqueKeysWithValues: [NativeClientSurface.claudeCode, .cursorEditor, .geminiCLI].map { + ( + format($0), + { lowering, ledger, resources in + try render(lowering, ledger: ledger, resources: resources, limits: limits) + } as LedgerRenderer + ) + }) + } + + /// Members must be the actual linked graph frozen by C, including independent occurrences. + /// Only origins reachable through this parent's complete frozen closure enter this lowering. + package static func lower( + _ parent: LinkedComponent, members: [LinkedComponent], frozen: LedgerFreeze.Result, + request: NativeComponentRequest, id: String, platform: DeclarationPlatform + ) throws -> LockedLowering { + let identity = try FrozenNativeIdentity.match( + parent, frozen: frozen, agent: request.surface.agent, scope: request.scope) + let ledger = frozen.ledger + let record = ledger.components[identity.id]! + let input = ComponentRenderInput( + record: record, component: identity.id, request: request, occurrences: identity.occurrences, + resources: [:], ledger: ledger, limits: .standard) + _ = try recipe(input) + guard record.payload.object?["mode"] == .init("components") else { + throw input.issue(["mode"], .invalid, "generated native plugins require typed component mode") + } + let closure = try selectedChildren(input, platform: platform.rawValue) + let grouped = Dictionary(grouping: closure, by: \.component) + var byOrigin: [Int: LinkedComponent] = [:] + for member in members { + for origin in member.origins { + try input.budget.step() + guard byOrigin.updateValue(member, forKey: origin.occurrence) == nil else { + throw input.issue(["children"], .invalid, "duplicate linked native occurrence") + } + } + } + var childLayouts: [LedgerValue] = [] + var inputs = [identity.id] + var resources: [String] = [] + var resourceSet = Set() + var seen = Set() + for occurrence in closure { + guard seen.insert(occurrence.component).inserted else { continue } + let owners = grouped[occurrence.component]!.map(\.id) + let child = ledger.components[occurrence.component]! + guard + ["skills", "mcpServer", "command", "subagent", "hook", "lspServer"].contains(child.kind) + else { + throw input.issue( + ["children", child.kind], .unverified, + "this component has no established generated native container field") + } + inputs.append(occurrence.component) + for resource in child.resources where resourceSet.insert(resource).inserted { + resources.append(resource) + } + let childID = id + "/member/" + String(childLayouts.count) + try input.budget.step(ledger.occurrences.count + ledger.components.count) + let linked = byOrigin[occurrence.id] + guard let linked else { + throw input.issue(["children"], .invalid, "frozen member has no paired linked input") + } + let lowering: LockedLowering + if child.kind == "skills" { + let paired = try FrozenNativeIdentity.match( + linked, frozen: frozen, agent: request.surface.agent, scope: request.scope) + guard case .skill(_, let mode, _) = linked.payload, mode != .edit, + paired.id == occurrence.component, child.resources.count == 1 + else { + throw input.issue( + ["children", "skills"], .invalid, "generated native skill requires frozen content") + } + lowering = .init( + id: childID, format: "native/skill-resource@1", inputs: [occurrence.component], + resources: child.resources, deployments: [], layout: .init(), platform: platform.rawValue, + artifacts: []) + } else if child.kind == "mcpServer" { + let contribution = try NativeMCPLowering.lower( + linked, frozen: frozen, + request: .init(surface: request.surface, scope: request.scope == .user ? .user : .project) + ) + var value = contribution.lowering(id: childID, artifact: childID, platform: platform) + value.layout.object!["occurrences"] = .init(array: owners.map { .init(integer: $0) }) + lowering = value + } else { + let paired = try FrozenNativeIdentity.match( + linked, frozen: frozen, agent: request.surface.agent, scope: request.scope) + guard paired.id == occurrence.component else { + throw input.issue(["children"], .invalid, "frozen native member identity mismatch") + } + let childInput = ComponentRenderInput( + record: child, component: occurrence.component, request: request, occurrences: owners, + resources: [:], ledger: ledger, limits: .standard, inPlugin: true) + try childInput.validateProfile() + lowering = .init( + id: childID, format: NativeComponentLayoutsV1.format(request.surface), + inputs: [occurrence.component], resources: child.resources, deployments: [], + layout: .init(object: [ + "surface": .init(request.surface.rawValue), "scope": .init(request.scope.rawValue), + "occurrences": .init(array: owners.map { .init(integer: $0) }), + "inPlugin": .init(boolean: true), + ]), platform: platform.rawValue, artifacts: []) + } + childLayouts.append(encode(lowering, owners: owners)) + } + return .init( + id: id, format: format(request.surface), inputs: inputs, resources: resources, + deployments: [], + layout: .init(object: [ + "surface": .init(request.surface.rawValue), "scope": .init(request.scope.rawValue), + "occurrences": .init(array: identity.occurrences.map { .init(integer: $0) }), + "members": .init(array: childLayouts), + ]), platform: platform.rawValue, artifacts: []) + } + + static func recipe(_ input: ComponentRenderInput) throws -> (NativeComponentRoute, String) { + switch input.request.surface { + case .claudeCode: return (.claudeSkillPlugin, ".claude-plugin/plugin.json") + case .cursorEditor where input.request.scope == .user: + return (.cursorLocalPlugin, ".cursor-plugin/plugin.json") + case .geminiCLI where input.request.scope == .user: + return (.geminiExtension, "gemini-extension.json") + default: + throw input.issue( + ["scope"], .unverified, + "generated native container registration is not established for this surface/scope") + } + } + + static func selectedChildren(_ input: ComponentRenderInput, platform: String) throws + -> [LedgerOccurrence] + { + var byID: [Int: LedgerOccurrence] = [:] + for occurrence in input.ledger.occurrences { + try input.budget.step() + guard byID.updateValue(occurrence, forKey: occurrence.id) == nil else { + throw input.issue(["occurrences"], .invalid, "duplicate frozen native occurrence identity") + } + } + var result: [LedgerOccurrence] = [] + for parent in input.occurrences { + try input.budget.step() + guard let owner = byID[parent], owner.component == input.component, + let expansion = owner.pluginExpansion, + ["native/claudePluginV1@1", "native/cursorPluginV1@1", "native/geminiExtensionV1@1"] + .contains(expansion.input.format), + expansion.input.adapterVersion == "1" + else { + throw input.issue( + ["children"], .invalid, "complete frozen native expansion evidence is required") + } + for id in expansion.children { + try input.budget.node(depth: 1) + try input.budget.step() + guard let child = byID[id], child.pluginMember?.parent == parent, + let record = input.ledger.components[child.component], + record.containerRoot.map({ Data($0.utf8) }) == Data(expansion.containerRoot.utf8), + record.source == expansion.source + else { throw input.issue(["children"], .invalid, "invalid frozen native member relation") } + if child.recipients.contains(input.request.surface.agent), + child.condition.scopes?.contains(input.request.scope) ?? true, + child.condition.platforms?.contains(platform) ?? true, + child.condition.agents?.contains(input.request.surface.agent) ?? true + { + result.append(child) + } + } + } + return result + } + + static func encode(_ lowering: LockedLowering, owners: [Int]) -> LedgerValue { + .init(object: [ + "id": .init(lowering.id), "format": .init(lowering.format), + "inputs": LedgerPayload.strings(lowering.inputs), + "resources": LedgerPayload.strings(lowering.resources), "layout": lowering.layout, + "occurrences": .init(array: owners.map { .init(integer: $0) }), + ]) + } + + static func decode( + _ lowering: LockedLowering, ledger: ResolvedLedger, limits: LedgerLimits + ) throws -> (ComponentRenderInput, [LockedLowering], [[Int]]) { + func invalid() -> CoreError { .invalidState("invalid sealed generated native plugin layout") } + guard let fields = lowering.layout.object, + Set(fields.keys) == ["surface", "scope", "occurrences", "members"], + let surface = fields["surface"]?.text.flatMap(NativeClientSurface.init(rawValue:)), + let scope = fields["scope"]?.text.flatMap(InstallScope.init(rawValue:)), + lowering.format == format(surface), let parent = lowering.inputs.first, + let record = ledger.components[parent], record.kind == "plugin", + record.payload.object?["mode"] == .init("components"), record.resources.isEmpty, + let ids = fields["occurrences"]?.array, ids.allSatisfy({ $0.kind == .integer }), + !ids.isEmpty, let encoded = fields["members"]?.array + else { throw invalid() } + let owners = ids.compactMap(\.integer) + let ownerSet = Set(owners) + guard ownerSet.count == owners.count, + owners + == ledger.occurrences.filter({ $0.component == parent && ownerSet.contains($0.id) }).map( + \.id), + ledger.occurrences.filter({ ownerSet.contains($0.id) }).allSatisfy({ + $0.recipients.contains(surface.agent) && ($0.condition.scopes?.contains(scope) ?? true) + && ($0.condition.agents?.contains(surface.agent) ?? true) + && ($0.condition.platforms?.contains(lowering.platform) ?? true) + }) + else { throw invalid() } + let input = ComponentRenderInput( + record: record, component: parent, request: .init(surface: surface, scope: scope), + occurrences: owners, resources: [:], ledger: ledger, limits: limits) + try input.validateProfile() + _ = try recipe(input) + // Charge the complete layout before indexing/copying child layouts. + try NativeGeneratedPluginContribution.admit(lowering.layout, budget: input.budget) + let closure = try selectedChildren(input, platform: lowering.platform) + let grouped = Dictionary(grouping: closure, by: \.component) + var expected: [String] = [] + var seen = Set() + for item in closure where seen.insert(item.component).inserted { + expected.append(item.component) + } + guard lowering.inputs == [parent] + expected, encoded.count == expected.count else { + throw invalid() + } + var nested: [LockedLowering] = [] + var memberOwners: [[Int]] = [] + var resources: [String] = [] + var resourceSet = Set() + for (index, value) in encoded.enumerated() { + let component = expected[index] + let record = ledger.components[component]! + let owners = grouped[component]!.map(\.id) + guard let child = value.object, + Set(child.keys) == ["id", "format", "inputs", "resources", "layout", "occurrences"], + child["id"] == .init(lowering.id + "/member/" + String(index)), + child["inputs"] == LedgerPayload.strings([component]), + child["resources"] == LedgerPayload.strings(record.resources), + child["occurrences"] == .init(array: owners.map { .init(integer: $0) }), + let format = child["format"]?.text, let layout = child["layout"] + else { throw invalid() } + let childLowering = LockedLowering( + id: child["id"]!.text!, format: format, inputs: [component], resources: record.resources, + deployments: [], layout: layout, platform: lowering.platform, artifacts: []) + if record.kind == "skills" { + guard format == "native/skill-resource@1", layout == .init(), record.resources.count == 1, + record.payload.object?["mode"] != .init("edit") + else { throw invalid() } + } else if record.kind == "mcpServer" { + let contribution = try MCPLayoutV1.contribution(childLowering, ledger: ledger) + guard contribution.occurrences == owners, + contribution.descriptor.request.surface == surface, + contribution.descriptor.request.scope == (scope == .user ? .user : .project) + else { throw invalid() } + } else { + let parsed = try NativeComponentLayoutsV1.input( + childLowering, ledger: ledger, limits: limits) + guard parsed.inPlugin, parsed.occurrences == owners, parsed.request == input.request, + ["command", "subagent", "hook", "lspServer"].contains(record.kind) + else { throw invalid() } + } + nested.append(childLowering) + memberOwners.append(owners) + for resource in record.resources where resourceSet.insert(resource).inserted { + resources.append(resource) + } + } + guard resources == lowering.resources else { throw invalid() } + return (input, nested, memberOwners) + } + + static func render( + _ lowering: LockedLowering, ledger: ResolvedLedger, resources: [String: URL], + limits: LedgerLimits + ) throws -> [ReplayedArtifact] { + let (input, members, _) = try decode(lowering, ledger: ledger, limits: limits) + let table = NativeComponentLayoutsV1.renderers(limits: limits).merging(MCPLayoutV1.renderers) { + a, _ in a + } + let values = try members.map { member -> LedgerValue in + if member.format == "native/skill-resource@1" { return .init() } + guard let renderer = table[member.format] else { + throw CoreError.invalidState("unknown native member renderer") + } + let artifacts = try renderer(member, ledger, resources) + guard artifacts.count == 1, artifacts[0].kind == .ownedValues, let value = artifacts[0].values + else { + throw CoreError.invalidState("invalid generated native member output") + } + return value + } + return [ + .init(name: lowering.id, kind: .ownedValues, values: try envelope(input, members: values)) + ] + } + static func envelope(_ input: ComponentRenderInput, members: [LedgerValue]) throws -> LedgerValue + { + let (route, manifest) = try recipe(input) + let metadata = try input.checkedNative(["version": .string, "description": .string]) + return .init(object: [ + "component": .init(input.component), "directory": .init(try input.filename()), + "route": .init(route.rawValue), "manifest": .init(manifest), + "metadata": .init(object: metadata), + "occurrences": .init(array: input.occurrences.map { .init(integer: $0) }), + "members": .init(array: members), + ]) + } + +} diff --git a/Sources/Components/NativeHookLayoutV1.swift b/Sources/Components/NativeHookLayoutV1.swift new file mode 100644 index 0000000..ab3702d --- /dev/null +++ b/Sources/Components/NativeHookLayoutV1.swift @@ -0,0 +1,103 @@ +import AgentsCore + +enum NativeHookLayoutV1 { + static func render(_ lowering: LockedLowering, _ input: ComponentRenderInput) throws + -> [ReplayedArtifact] + { + let events: Set + let route: NativeComponentRoute + switch input.request.surface { + case .codexCLI: + events = [ + "PreToolUse", "PermissionRequest", "PostToolUse", "PreCompact", "PostCompact", + "SessionStart", "SessionEnd", "UserPromptSubmit", "SubagentStart", "SubagentStop", "Stop", + "Interrupt", + ] + route = .codexHooks + case .geminiCLI: + events = [ + "BeforeTool", "AfterTool", "BeforeAgent", "Notification", "AfterAgent", "SessionStart", + "SessionEnd", + "PreCompress", "BeforeModel", "AfterModel", "BeforeToolSelection", + ] + route = .geminiSettings + default: + throw input.issue( + ["event"], .unverified, "the native event/runner contract is not established") + } + guard let event = input.fields["event"]?.object?["native"]?.text else { + throw input.issue( + ["event"], .unverified, + "portable event payload/output equivalence is not established; select an explicit native event" + ) + } + guard events.contains(event) else { + throw input.issue( + ["event"], .unsupported, "event is absent from the pinned native event enum") + } + if input.request.surface == .codexCLI, let matcher = input.fields["matcher"]?.text { + guard !["UserPromptSubmit", "Stop", "Interrupt"].contains(event) else { + throw input.issue(["matcher"], .unsupported, "this native event ignores matchers") + } + guard + matcher.isEmpty || matcher == "*" + || matcher.utf8.allSatisfy({ + (48...57).contains($0) || (65...90).contains($0) || (97...122).contains($0) || $0 == 95 + || $0 == 124 + }) + else { + throw input.issue( + ["matcher"], .unverified, + "exact Rust-regex syntax admission is required beyond the native literal/alternative matcher form" + ) + } + } + let native = try input.checkedNative( + input.request.surface == .geminiCLI ? ["sequential": .boolean] : [:]) + guard let run = input.fields["run"]?.object else { + throw input.issue(["run"], .invalid, "missing frozen hook program") + } + var program = run + program["executable"] = try NativeProgramV1.executable(run, input: input) + if run["workingDirectory"] != nil { + let index = run["executable"]?.text?.contains("/") == true ? 1 : 0 + guard input.record.resources.indices.contains(index) else { + throw input.issue(["run", "workingDirectory"], .invalid, "missing frozen hook directory") + } + program["workingDirectory"] = .init(object: ["resource": .init(input.record.resources[index])] + ) + } + try NativeProgramV1.validateLiterals(.init(object: program), input: input, path: ["run"]) + var hook: [String: LedgerValue] = [ + "type": .init("command"), "command": .init(object: ["program": .init(object: program)]), + ] + if let seconds = input.fields["timeoutSeconds"]?.integer { + let factor = input.request.surface == .geminiCLI ? 1000 : 1 + guard seconds > 0, seconds <= Int.max / factor else { + throw input.issue( + ["timeoutSeconds"], .invalid, "native timeout is outside its representable range") + } + if input.request.surface == .codexCLI, ["SessionEnd", "Interrupt"].contains(event), + seconds > 3 + { + throw input.issue( + ["timeoutSeconds"], .unsupported, + "the pinned native teardown hook clamps its timeout to three seconds") + } + if input.request.surface == .geminiCLI, seconds * factor > 2_147_483_647 { + throw input.issue( + ["timeoutSeconds"], .invalid, + "native Node timer milliseconds exceed its representable range") + } + hook["timeout"] = .init(integer: seconds * factor) + } + var group: [String: LedgerValue] = ["hooks": .init(array: [.init(object: hook)])] + group["matcher"] = input.fields["matcher"] + group["sequential"] = native["sequential"] + return try input.emitted( + lowering, + input.envelope( + route: route, + keys: ["hooks", event], selection: "hookGroup", value: .init(object: group))) + } +} diff --git a/Sources/Components/NativeIgnoreLayoutV1.swift b/Sources/Components/NativeIgnoreLayoutV1.swift new file mode 100644 index 0000000..d992cf7 --- /dev/null +++ b/Sources/Components/NativeIgnoreLayoutV1.swift @@ -0,0 +1,17 @@ +import AgentsCore + +/// Patterns form an ordered managed-block contribution for E's ignore preparation. +/// This renderer does not own a second ignore editor or infer ownership from matching lines. +enum NativeIgnoreLayoutV1 { + static func patterns(_ input: ComponentRenderInput) throws -> [String] { + try (input.fields["patterns"]?.array ?? []).enumerated().map { index, value in + guard let pattern = value.text, !pattern.isEmpty, + !pattern.utf8.contains(0), !pattern.utf8.contains(10), !pattern.utf8.contains(13) + else { + throw input.issue( + ["patterns", String(index)], .invalid, "ignore pattern must occupy one nonempty line") + } + return pattern + } + } +} diff --git a/Sources/Components/NativeLSPLayoutV1.swift b/Sources/Components/NativeLSPLayoutV1.swift new file mode 100644 index 0000000..74c80c7 --- /dev/null +++ b/Sources/Components/NativeLSPLayoutV1.swift @@ -0,0 +1,108 @@ +import AgentsCore + +enum NativeLSPLayoutV1 { + static let openCodeNativeFields: [String: MCPNativeField] = [ + "extensions": .strings, "disabled": .boolean, + ] + + static func claude(_ lowering: LockedLowering, _ input: ComponentRenderInput) throws + -> [ReplayedArtifact] + { + let name = try input.filename() + guard NativePluginFieldsV1.validClaudeName(name) else { + throw input.issue( + ["name"], .invalid, "generated native plugin identifier contains a forbidden character") + } + guard let languages = input.fields["languages"]?.object, !languages.isEmpty, + languages.allSatisfy({ $0.key.hasPrefix(".") && $0.value.text?.isEmpty == false }) + else { + throw input.issue( + ["languages"], .invalid, + "native extensionToLanguage requires nonempty dot-prefixed extensions and language IDs") + } + guard let run = input.fields["run"]?.object else { + throw input.issue(["run"], .invalid, "missing native LSP program") + } + guard run["workingDirectory"] == nil else { + throw input.issue( + ["run", "workingDirectory"], .unsupported, + "native LSP workspaceFolder is not a process working-directory setting") + } + var config = try input.checkedNative([ + "transport": .oneOf(["stdio", "socket"]), "workspaceFolder": .string, + "startupTimeout": .positiveInteger, "shutdownTimeout": .positiveInteger, + "requestTimeout": .positiveInteger, "restartOnCrash": .boolean, "diagnostics": .boolean, + "maxRestarts": .nonnegativeInteger, "settings": .object, + ]) + config["command"] = try NativeProgramV1.executable(run, input: input) + if let command = config["command"]?.text, command.contains(" ") && !command.hasPrefix("/") { + throw input.issue( + ["run", "executable"], .invalid, "native LSP command with spaces must be absolute") + } + config["args"] = run["arguments"] + config["env"] = run["environment"] + config["extensionToLanguage"] = .init(object: languages) + config["initializationOptions"] = input.fields["initializationOptions"] + try NativeProgramV1.validateLiterals(.init(object: config), input: input, path: []) + for key in ["command", "args", "env"] { + if let value = config[key] { try validateExpansion(value, input, path: ["run", key]) } + } + let manifest: LedgerValue = .init(object: [ + "name": .init(name), "lspServers": .init(object: [name: .init(object: config)]), + ]) + return try input.emitted( + lowering, + input.envelope( + route: .claudeSkillPlugin, path: name, selection: "generatedPlugin", + value: .init(object: [".claude-plugin/plugin.json": manifest]))) + } + + private static func validateExpansion( + _ value: LedgerValue, _ input: ComponentRenderInput, path: [String] + ) throws { + if let text = value.text, value.kind == .string || value.kind == .literal, text.contains("${") { + throw input.issue( + path, .unverified, + "literal preservation across native LSP placeholders needs an exact representation") + } + for (index, child) in (value.array ?? []).enumerated() { + try validateExpansion(child, input, path: path + [String(index)]) + } + for (key, child) in value.object ?? [:] { + try validateExpansion(child, input, path: path + [key]) + } + } + + static func openCode(_ lowering: LockedLowering, _ input: ComponentRenderInput) throws + -> [ReplayedArtifact] + { + guard input.fields["languages"]?.object?.isEmpty ?? true else { + throw input.issue( + ["languages"], .unverified, + "native extensions do not encode extension-to-language IDs; runtime equivalence is not established" + ) + } + var fields = try input.checkedNative(openCodeNativeFields) + guard let run = input.fields["run"]?.object else { + throw input.issue(["run"], .invalid, "missing frozen LSP executable") + } + guard run["workingDirectory"] == nil else { + throw input.issue( + ["run", "workingDirectory"], .unsupported, + "the pinned LSP schema has no working-directory field") + } + fields["command"] = .init( + array: [try NativeProgramV1.executable(run, input: input)] + (run["arguments"]?.array ?? [])) + if let environment = run["environment"]?.object, !environment.isEmpty { + fields["env"] = .init(object: environment) + } + fields["initialization"] = input.fields["initializationOptions"] + // OpenCode performs raw JSON substitution on every string in the native document. + try NativeProgramV1.validateLiterals(.init(object: fields), input: input, path: []) + return try input.emitted( + lowering, + input.envelope( + route: .openCodeConfig, + keys: ["lsp", input.record.name], selection: "lsp", value: .init(object: fields))) + } +} diff --git a/Sources/Components/NativePluginFieldsV1.swift b/Sources/Components/NativePluginFieldsV1.swift new file mode 100644 index 0000000..ebf810a --- /dev/null +++ b/Sources/Components/NativePluginFieldsV1.swift @@ -0,0 +1,756 @@ +import AgentsCore +import Foundation +import NativeDocuments + +/// Validates documented native container fields against the frozen bundle. Native source +/// bytes and discovery precedence are preserved; this is not decomposition or installation. +struct NativePluginFieldsV1 { + let surface: NativeClientSurface + let document: String + let entries: [LedgerEntry] + let budget: NativeDocumentBudget + let readJSON: (String, [String]) throws -> NativeValue + var issue: ([String], String, NativeAdapterIssue.Reason) -> Error + var claude: Bool { surface == .claudeCode } + + init(input: ComponentRenderInput, resource: LedgerResource, root: URL) { + surface = input.request.surface + document = surface == .claudeCode ? ".claude-plugin/plugin.json" : ".cursor-plugin/plugin.json" + entries = resource.entries + budget = input.budget + issue = { input.issue(["manifest"] + $0, $2, $1) } + readJSON = { relative, field in + try input.budget.step(resource.entries.count) + guard let entry = resource.entries.first(where: { $0.path == relative }), + entry.kind == .file, let size = entry.byteCount, size <= input.limits.resourceBytes + else { + throw input.issue( + ["manifest"] + field, .invalid, "native JSON resource is not a bounded frozen file") + } + try input.budget.allocate(size, stage: "native plugin JSON") + try input.budget.step(size) + let bytes = try Data(contentsOf: PathSafety.resolvedChild(base: root, subpath: relative)) + guard bytes.count == size else { + throw input.issue(["manifest"] + field, .invalid, "native JSON resource size changed") + } + do { + let document = try NativeDocument(bytes: bytes, format: .json, budget: input.budget) + guard let value = try document.read(.init(keys: []))?.value else { + throw input.issue( + ["manifest"] + field, .invalid, "native JSON resource has no root value") + } + return value + } catch NativeDocumentError.invalidDocument { + throw input.issue(["manifest"] + field, .invalid, "native JSON resource is malformed") + } + } + } + + init( + surface: NativeClientSurface, document: String, fieldPrefix: [String] = [], + entries: [LedgerEntry], + budget: NativeDocumentBudget, + documents: [String: NativeValue] + ) { + self.surface = surface + self.document = document + self.entries = entries + self.budget = budget + issue = { + NativeComponentFieldIssue(document: document, field: fieldPrefix + $0, reason: $2, detail: $1) + } + readJSON = { relative, field in + guard entries.contains(where: { $0.path == relative && $0.kind == .file }), + let value = documents[relative] + else { + throw NativeComponentFieldIssue( + document: document, field: fieldPrefix + field, reason: .invalid, + detail: "referenced native JSON document was not supplied" + ) + } + return value + } + } + static func validClaudeName(_ name: String) -> Bool { + !name.isEmpty + && name.unicodeScalars.allSatisfy { + !CharacterSet.whitespacesAndNewlines.contains($0) + && !"@:/\\".unicodeScalars.contains($0) && $0.properties.generalCategory != .control + && ![0x61C, 0x200E, 0x200F].contains($0.value) + && !(0x202A...0x202E).contains($0.value) && !(0x2066...0x2069).contains($0.value) + } + } + + func fail(_ path: [String], _ detail: String, _ reason: NativeAdapterIssue.Reason = .invalid) + -> Error + { + issue(path, detail, reason) + } + + func text(_ value: NativeValue, _ path: [String]) throws -> String { + guard case .string(let text) = value, !text.utf8.contains(0) else { + throw fail(path, "native field requires a string without NUL") + } + return text + } + + func strings(_ value: NativeValue, _ path: [String]) throws { + guard case .array(let values) = value else { + throw fail(path, "native field requires an array of strings") + } + for (index, value) in values.enumerated() { _ = try text(value, path + [String(index)]) } + } + + func path( + _ value: NativeValue, _ field: [String], kind: LedgerEntry.Kind? = nil, suffix: String? = nil + ) throws -> String { + let authored = try text(value, field) + if claude, !authored.hasPrefix("./"), !(field.first == "skills" && authored == ".") { + throw fail(field, "native Claude component paths require a dot-slash prefix") + } + if authored.contains("\\") { + throw fail( + field, "native backslash paths need exact frozen resource-path identity", .unverified) + } + let relative: String + do { + relative = try PathSafety.sanitizeSubpath(authored) + guard !authored.hasPrefix("/"), !authored.split(separator: "/").contains(".."), + !authored.contains("://") + else { throw CoreError.invalidState("invalid path") } + } catch { throw fail(field, "native component path must remain inside its frozen plugin root") } + if relative == ".", kind != .file, suffix == nil { return relative } + try budget.step(entries.count) + guard let entry = entries.first(where: { $0.path == relative }) else { + try budget.step(entries.count) + if entries.contains(where: { + $0.kind == .symlink && relative.hasPrefix($0.path + "/") + }) { + throw fail( + field, "native referenced symlink requires E's contained resource closure", + .integrationRequired) + } + throw fail(field, "native component path is absent from the frozen bundle") + } + guard entry.kind != .symlink else { + throw fail( + field, "native referenced symlink requires E's final contained resource closure", + .integrationRequired) + } + guard kind == nil || entry.kind == kind, suffix == nil || relative.hasSuffix(suffix!) else { + throw fail(field, "native component path has the wrong file or directory kind") + } + return relative + } + + func paths( + _ value: NativeValue, _ field: [String], kind: LedgerEntry.Kind? = nil, suffix: String? = nil + ) throws { + if case .array(let values) = value { + for (index, value) in values.enumerated() { + _ = try path(value, field + [String(index)], kind: kind, suffix: suffix) + } + } else { + _ = try path(value, field, kind: kind, suffix: suffix) + } + } + + func json(_ relative: String, field: [String]) throws -> NativeValue { + try readJSON(relative, field) + } + + func validate(_ fields: [String: NativeValue]) throws { + if claude { + guard Self.validClaudeName(try text(fields["name"] ?? .null, ["name"])) else { + throw fail(["name"], "native plugin identifier contains a forbidden character") + } + } else { + let name = try text(fields["name"] ?? .null, ["name"]) + guard + name.range(of: #"^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$"#, options: .regularExpression) != nil + else { + throw fail( + ["name"], + "Cursor native plugin name must be a lowercase alphanumeric/hyphen/period identifier") + } + } + if !claude, case .string(let version) = fields["version"] { + do { + guard try SourceRequirement.exact(version).canonicalized() == .exact(version) else { + throw fail(["version"], "native plugin version must be canonical SemVer") + } + } catch { + throw fail(["version"], "native plugin version must be canonical SemVer") + } + } + for (key, value) in fields.sorted(by: { $0.key < $1.key }) { + try budget.step() + switch key { + case "name", "version", "description", "homepage", "repository", "license": + _ = try text(value, [key]) + case "displayName" where claude: _ = try text(value, [key]) + case "keywords": try strings(value, [key]) + case "author": + guard case .object(let author) = value, author["name"] != nil else { + throw fail([key], "native author requires a name") + } + for (field, value) in author { + guard ["name", "email"].contains(field) || (claude && field == "url") else { + throw fail([key, field], "native author field is not established", .unverified) + } + _ = try text(value, [key, field]) + } + case "metadata" where claude: + guard case .object = value else { throw fail([key], "native metadata requires an object") } + case "defaultEnabled" where claude: + guard case .boolean = value else { + throw fail([key], "native defaultEnabled requires a boolean") + } + case "commands": + if claude, case .object(let commands) = value { + for (name, value) in commands { + guard case .object(let command) = value, + (command["source"] == nil) != (command["content"] == nil) + else { + throw fail([key, name], "native command requires exactly one source or content") + } + for (field, value) in command { + switch field { + case "source": _ = try path(value, [key, name, field], kind: .file, suffix: ".md") + case "content", "description", "argumentHint", "model": + _ = try text(value, [key, name, field]) + case "allowedTools": try strings(value, [key, name, field]) + default: + throw fail( + [key, name, field], "unknown native command field would lose intent", .unverified) + } + } + } + } else { + try paths(value, [key]) + } + case "agents": + try paths(value, [key], kind: claude ? .file : nil, suffix: claude ? ".md" : nil) + case "skills": try paths(value, [key], kind: claude ? .directory : nil) + case "rules" where !claude: try paths(value, [key]) + case "hooks", "mcpServers": try configurations(value, field: key) + case "lspServers" where claude: try configurations(value, field: key) + case "variables" where !claude: + try variables(value, field: [key], root: true) + case "userConfig" where claude: + try userConfig(value) + case "dependencies" where claude: + throw fail( + [key], + "native plugin dependencies require linked/frozen dependency closure rather than native installer resolution", + .integrationRequired) + case "logo" where !claude: + let logo = try text(value, [key]) + if !logo.hasPrefix("https://") && !logo.hasPrefix("http://") { + _ = try path(value, [key], kind: .file) + } + default: + throw fail( + [key], "native field needs its exact container/registration contract", .unverified) + } + } + // Native defaults retain their own merge/replacement behavior. They are not rewritten. + let defaults = try NativeComponentFieldsV1.pluginDefaults( + surface: surface, document: document, explicitFields: Set(fields.keys)) + try budget.step(entries.count * 3) + for field in claude ? ["hooks", "mcpServers", "lspServers"] : ["hooks", "mcpServers"] { + guard let file = defaults[field], entries.contains(where: { $0.path == file }) else { + continue + } + try configurationFile(file, field: field, coordinate: [field]) + } + } + + /// The reference is located in the current document; values loaded through it are + /// located in the referenced document, regardless of later native merge winners. + func configurationFile(_ relative: String, field: String, coordinate: [String]) throws { + let value = try json(relative, field: coordinate) + var validator = self + validator.issue = { path, detail, reason in + let original = self.issue(path, detail, reason) + guard original is NativeComponentFieldIssue else { return original } + let local = field == "lspServers" && path.first == field ? Array(path.dropFirst()) : path + return NativeComponentFieldIssue( + document: relative, field: local, reason: reason, detail: detail) + } + try validator.configuration(value, field: field, wrapped: true) + } + + func configurations(_ value: NativeValue, field: String, coordinate: [String]? = nil) throws { + try budget.step() + let coordinate = coordinate ?? [field] + if case .array(let values) = value { + guard claude || field == "mcpServers" else { + throw fail(coordinate, "native hooks do not accept an array of configuration sources") + } + for (index, value) in values.enumerated() { + try configurations(value, field: field, coordinate: coordinate + [String(index)]) + } + } else if case .string = value { + if claude, field == "mcpServers" { + let source = try text(value, coordinate) + if source.hasSuffix(".mcpb") || source.hasSuffix(".dxt") { + throw fail( + coordinate, + "native MCP bundle extraction and registration require frozen typed children and closed E/D routes", + .integrationRequired) + } + } + let relative = try path(value, coordinate, kind: .file, suffix: ".json") + try configurationFile(relative, field: field, coordinate: coordinate) + } else { + guard claude else { + throw fail( + coordinate, + "the exact inline Cursor container wrapper requires a primary schema/example beyond its documented object type", + .unverified) + } + var validator = self + validator.issue = { path, detail, reason in + self.issue(coordinate + path.dropFirst(), detail, reason) + } + try validator.configuration(value, field: field, wrapped: false) + } + } + + func configuration(_ value: NativeValue, field: String, wrapped: Bool) throws { + guard case .object(let root) = value else { + throw fail(wrapped ? [] : [field], "native config requires an object") + } + let map: [String: NativeValue] + if wrapped && field != "lspServers" { + let allowed: Set + if field == "mcpServers" { + allowed = [field, "$schema"] + } else { + allowed = claude ? [field, "description"] : [field, "version"] + } + if let unknown = root.keys.sorted().first(where: { !allowed.contains($0) }) { + throw fail( + [unknown], "native file root contains fields outside the captured wrapper profile", + .unverified) + } + guard case .object(let entries) = root[field] else { + throw fail( + [field], "native file requires its component wrapper", + field == "mcpServers" ? .unverified : .invalid) + } + if let description = root["description"] { + _ = try text(description, ["description"]) + } + if let schema = root["$schema"] { _ = try text(schema, ["$schema"]) } + if let version = root["version"] { + let one: Bool + switch version { + case .integer(let value): one = value == 1 + case .decimal(let value): one = Double(value) == 1 + default: one = false + } + guard one else { + throw fail( + ["version"], "native hook file version is outside the fixed version-one profile", + .unverified) + } + } + map = entries + } else { + map = root + } + switch field { + case "hooks": try hooks(map) + case "lspServers": + for (name, value) in map { try lsp(value, field: [field, name]) } + case "mcpServers": + for (name, value) in map { try mcp(value, field: [field, name]) } + default: throw fail([field], "unknown native config profile") + } + } + + func hooks(_ events: [String: NativeValue]) throws { + for (event, value) in events { + try budget.step() + guard + (claude ? NativeDocumentedHooksV1.claudeEvents : NativeDocumentedHooksV1.cursorEvents) + .contains(event), case .array(let entries) = value + else { + throw fail(["hooks", event], "native hook event or handler array is invalid") + } + for (index, entry) in entries.enumerated() { + let path = ["hooks", event, String(index)] + guard case .object(let object) = entry else { + throw fail(path, "native hook entry requires an object") + } + if claude { + guard Set(object.keys).isSubset(of: ["matcher", "hooks"]), + case .array(let handlers) = object["hooks"] + else { + throw fail(path, "Claude hook group requires matcher/hooks fields") + } + if let matcher = object["matcher"] { + let pattern = try text(matcher, path + ["matcher"]) + guard NativeDocumentedHooksV1.admittedMatcher(pattern) else { + throw fail( + path + ["matcher"], + "exact native JavaScript regex admission is required beyond this fragment profile", + .unverified) + } + guard !NativeDocumentedHooksV1.claudeWithoutMatcher.contains(event) else { + throw fail( + path + ["matcher"], "this native event ignores matchers", .unsupported) + } + } + for (handlerIndex, handler) in handlers.enumerated() { + try handlerFields(handler, event: event, path: path + ["hooks", String(handlerIndex)]) + } + } else { + try handlerFields(entry, event: event, path: path) + } + } + } + } + + func handlerFields(_ value: NativeValue, event: String, path: [String]) throws { + try budget.step() + guard case .object(let handler) = value else { + throw fail(path, "native handler requires an object") + } + let type = try text( + handler["type"] ?? (claude ? .null : .string("command")), path + ["type"]) + guard + claude + ? ["command", "http", "prompt", "agent", "mcp_tool"].contains(type) : type == "command" + else { + throw fail( + path + ["type"], + claude ? "native handler type is not established" : "Cursor plugin hooks are command-only", + .unsupported) + } + if claude { + let promptAndAgentEvents: Set = [ + "PermissionDenied", "PostToolBatch", "PostToolUse", "PostToolUseFailure", "PreToolUse", + "Stop", "SubagentStop", "TaskCompleted", "TaskCreated", "TeammateIdle", + "UserPromptExpansion", "UserPromptSubmit", + ] + if (type == "agent" && !promptAndAgentEvents.contains(event)) + || (type == "prompt" && !promptAndAgentEvents.contains(event) + && event != "PermissionRequest") + || (type == "http" && ["SessionStart", "Setup"].contains(event)) + { + throw fail( + path + ["type"], "native event skips this handler type", .unsupported) + } + } + let required: [String] + switch type { + case "command": required = ["command"] + case "http": required = ["url"] + case "prompt", "agent": required = ["prompt"] + default: required = ["server", "tool"] + } + for key in required { _ = try text(handler[key] ?? .null, path + [key]) } + let specific: Set + switch type { + case "command": + specific = + claude + ? ["command", "args", "async", "asyncRewake", "shell", "onFailure"] + : ["command", "matcher", "failClosed", "loop_limit"] + case "http": specific = ["url", "headers", "allowedEnvVars", "onFailure"] + case "prompt", "agent": specific = ["prompt", "model"] + default: specific = ["server", "tool", "input"] + } + for (key, value) in handler { + let field = path + [key] + guard + specific.contains(key) + || (claude ? ["type", "if", "timeout", "statusMessage"] : ["type", "timeout"]).contains( + key) + else { + throw fail(field, "native handler field is not established for its type", .unverified) + } + switch key { + case "type", "command", "url", "prompt", "model", "server", "tool": _ = try text(value, field) + case "headers": + guard case .object(let headers) = value else { + throw fail(field, "native HTTP headers require a string map") + } + for (name, value) in headers { + let header = try text(value, field + [name]) + guard !header.utf8.contains(13), !header.utf8.contains(10) else { + throw fail(field + [name], "native header contains a line break") + } + } + case "allowedEnvVars": try strings(value, field) + case "input": + guard case .object = value else { + throw fail(field, "native MCP tool input requires an object") + } + case "args" where claude: try strings(value, field) + case "statusMessage" where claude: _ = try text(value, field) + case "if" where claude: + _ = try text(value, field) + guard + [ + "PreToolUse", "PostToolUse", "PostToolUseFailure", "PermissionRequest", + "PermissionDenied", + ].contains(event) + else { throw fail(field, "native if filters never run on this event", .unsupported) } + case "matcher" where !claude: + let pattern = try text(value, field) + guard NativeDocumentedHooksV1.admittedMatcher(pattern) else { + throw fail( + field, + "exact native JavaScript regex admission is required beyond this fragment profile", + .unverified) + } + guard NativeDocumentedHooksV1.cursorMatcherEvents.contains(event) else { + throw fail(field, "native matcher target is not established for this event", .unverified) + } + case "async" where claude, "asyncRewake" where claude: + guard case .boolean = value else { throw fail(field, "native flag requires a boolean") } + case "failClosed" where !claude: + guard case .boolean = value else { throw fail(field, "native flag requires a boolean") } + if event == "sessionStart", value == .boolean(true) { + throw fail(field, "native sessionStart cannot block creation", .unsupported) + } + case "timeout": + guard MCPNativeField.positiveNumber.accepts(value) else { + throw fail(field, "native timeout requires positive seconds") + } + let seconds: Double + switch value { + case .integer(let number): seconds = Double(number) + case .decimal(let number): seconds = Double(number) ?? 0 + default: seconds = 0 + } + if claude, event == "SessionEnd", seconds > 60 { + throw fail(field, "native SessionEnd budget is capped at sixty seconds", .unsupported) + } + case "loop_limit" where !claude: + guard ["stop", "subagentStop"].contains(event), MCPNativeField.numberOrNull.accepts(value) + else { + throw fail( + field, "loop_limit applies only to stop/subagentStop and requires a number or null") + } + case "shell" where claude: + guard [.string("bash"), .string("powershell")].contains(value) else { + throw fail(field, "invalid native shell") + } + if handler["args"] != nil { + throw fail(field, "exec-form native hooks ignore shell", .unsupported) + } + case "onFailure" where claude: + guard [.string("continue"), .string("block")].contains(value) else { + throw fail(field, "invalid native failure policy") + } + if ["Stop", "SubagentStop", "TaskCompleted", "TeammateIdle"].contains(event) + || handler["async"] == .boolean(true) || handler["asyncRewake"] == .boolean(true) + { + throw fail(field, "native hook ignores this failure policy", .unsupported) + } + default: + throw fail(field, "native handler field is not established by this profile", .unverified) + } + } + if claude, type == "mcp_tool", ["SessionStart", "Setup"].contains(event) { + throw fail( + path + ["type"], "MCP hook availability is not guaranteed during native startup", + .unverified) + } + if claude, handler["timeout"] != nil, + handler["async"] == .boolean(true) || handler["asyncRewake"] == .boolean(true) + { + throw fail( + path + ["timeout"], "native background hook ignores timeout", .unsupported) + } + } + + func lsp(_ value: NativeValue, field: [String]) throws { + try budget.step() + guard case .object(let config) = value, let command = config["command"], + case .object(let languages) = config["extensionToLanguage"], !languages.isEmpty + else { + throw fail(field, "native LSP requires command and nonempty extensionToLanguage") + } + let executable = try text(command, field + ["command"]) + guard !executable.isEmpty, !executable.contains(" ") || executable.hasPrefix("/") else { + throw fail(field + ["command"], "native executable with spaces must be absolute") + } + for (ext, value) in languages { + guard ext.hasPrefix("."), !(try text(value, field + ["extensionToLanguage", ext])).isEmpty + else { + throw fail( + field + ["extensionToLanguage"], + "native extensions require a dot prefix and a language ID") + } + } + let rules: [String: MCPNativeField] = [ + "command": .string, "args": .strings, "extensionToLanguage": .object, + "transport": .oneOf(["stdio", "socket"]), "env": .object, + "initializationOptions": .object, "settings": .object, "workspaceFolder": .string, + "startupTimeout": .positiveInteger, "shutdownTimeout": .positiveInteger, + "requestTimeout": .positiveInteger, "restartOnCrash": .boolean, + "maxRestarts": .nonnegativeInteger, "diagnostics": .boolean, + ] + for (key, value) in config { + guard let rule = rules[key] else { + throw fail(field + [key], "unknown strict native LSP field", .unverified) + } + guard rule.accepts(value) else { + throw fail(field + [key], "invalid native LSP field type or range") + } + if key == "env", case .object(let env) = value { + for (name, value) in env { _ = try text(value, field + [key, name]) } + } + } + } + + func mcp(_ value: NativeValue, field: [String]) throws { + try budget.step() + guard case .object(let server) = value, (server["command"] == nil) != (server["url"] == nil) + else { + throw fail(field, "native MCP needs exactly one command or URL") + } + for (key, value) in server { + switch key { + case "command", "url": _ = try text(value, field + [key]) + case "cwd" where !claude: _ = try text(value, field + [key]) + case "args": try strings(value, field + [key]) + case "env", "headers": + guard case .object(let fields) = value else { + throw fail(field + [key], "native MCP requires a string map") + } + for (name, value) in fields { _ = try text(value, field + [key, name]) } + case "type" where claude: + guard + (server["command"] != nil ? [.string("stdio")] : [.string("http"), .string("sse")]) + .contains(value) + else { + throw fail(field + [key], "native MCP transport profile is not established", .unverified) + } + default: + throw fail( + field + [key], "native MCP field/selector requires an exact source contract", .unverified) + } + } + } + + func variables(_ value: NativeValue, field: [String], root: Bool = false) throws { + try budget.step() + guard case .object(let schema) = value else { + throw fail(field, "native variables require a schema object") + } + if root, schema["type"] != .string("object") { + throw fail(field, "native variable schema root must have object type") + } + if root { + guard case .object = schema["properties"] else { + throw fail(field, "native variable schema root requires properties") + } + } + for (key, value) in schema { + switch key { + case "type": + guard + [ + .string("object"), .string("string"), .string("number"), .string("integer"), + .string("boolean"), .string("array"), .string("null"), + ].contains(value) + else { throw fail(field + [key], "native variable schema type is invalid") } + case "title", "description": _ = try text(value, field + [key]) + case "required": try strings(value, field + [key]) + case "properties": + guard case .object(let properties) = value else { + throw fail(field + [key], "native schema properties require an object") + } + for (name, value) in properties { try variables(value, field: field + [key, name]) } + case "items": try variables(value, field: field + [key]) + case "enum": + guard case .array = value else { + throw fail(field + [key], "native schema enum requires an array") + } + case "default", "const": break + default: + throw fail( + field + [key], "native variable schema keyword is not in the captured fixed profile", + .unverified) + } + } + } + + func userConfig(_ value: NativeValue) throws { + guard case .object(let entries) = value else { + throw fail(["userConfig"], "native userConfig requires an object") + } + for (name, value) in entries { + try budget.step() + let field = ["userConfig", name] + guard MCPReferenceSyntax.isName(name), case .object(let option) = value, + case .string(let type) = option["type"], + ["string", "number", "boolean", "directory", "file"].contains(type) + else { throw fail(field, "native userConfig requires an identifier and a supported type") } + _ = try text(option["title"] ?? .null, field + ["title"]) + _ = try text(option["description"] ?? .null, field + ["description"]) + for (key, value) in option { + switch key { + case "type", "title", "description": _ = try text(value, field + [key]) + case "required", "multiple", "sensitive": + guard case .boolean = value else { + throw fail(field + [key], "native option flag requires a boolean") + } + if key == "multiple", type != "string" { + throw fail(field + [key], "multiple applies only to string options", .unsupported) + } + case "min", "max": + guard type == "number", case .integer = value else { + if type == "number", case .decimal(let number) = value, Double(number)?.isFinite == true + { + continue + } + throw fail( + field + [key], "native numeric bounds require a number option and a finite number") + } + case "options": + guard type == "string", option["multiple"] != .boolean(true), + option["sensitive"] != .boolean(true), case .array(let options) = value + else { + throw fail(field + [key], "native picker options require a non-sensitive single string") + } + for value in options { + let label = try text(value, field + [key]) + guard (1...64).contains(label.utf16.count) else { + throw fail(field + [key], "native picker label is outside its documented length") + } + } + if let fallback = option["default"], !options.contains(fallback) { + throw fail(field + ["default"], "native picker default must be a listed option") + } + if option["default"] == nil, option["required"] != .boolean(true) { + throw fail(field + [key], "native picker needs a listed default or required selection") + } + case "default": + if option["sensitive"] == .boolean(true), value != .string("") { + throw fail( + field + [key], "sensitive native defaults cannot enter frozen public resources", + .integrationRequired) + } + switch value { + case .string, .integer, .boolean: break + case .decimal(let number): + guard Double(number)?.isFinite == true else { + throw fail(field + [key], "native default must be finite") + } + case .array: try strings(value, field + [key]) + default: throw fail(field + [key], "native default has an unsupported value type") + } + default: throw fail(field + [key], "unknown strict native userConfig field") + } + } + } + } +} diff --git a/Sources/Components/NativePluginLayoutV1.swift b/Sources/Components/NativePluginLayoutV1.swift new file mode 100644 index 0000000..0bcc914 --- /dev/null +++ b/Sources/Components/NativePluginLayoutV1.swift @@ -0,0 +1,106 @@ +import AgentsCore +import Foundation +import NativeDocuments + +/// Opaque native preservation is confined to a verified native container and one recipient. +/// Decomposition consumes G's typed children, not a second parser hidden in a renderer. +enum NativePluginLayoutV1 { + static func render(_ lowering: LockedLowering, _ input: ComponentRenderInput) throws + -> [ReplayedArtifact] + { + _ = try input.checkedNative([:]) + guard input.fields["mode"]?.text == "native" else { + throw input.issue( + ["mode"], .integrationRequired, + "decomposed plugins require the frozen-member generated plugin renderer format" + ) + } + guard input.record.recipients == [input.request.surface.agent] else { + throw input.issue( + ["recipients"], .invalid, + "opaque native plugin preservation requires exactly one native recipient") + } + guard input.fields["select"] == nil, input.fields["exclude"]?.array?.isEmpty ?? true else { + throw input.issue( + ["select", "exclude"], .invalid, + "native container preservation cannot filter child components") + } + let route: NativeComponentRoute + let manifest: String + switch input.request.surface { + case .claudeCode: + route = .claudeSkillPlugin + manifest = ".claude-plugin/plugin.json" + case .geminiCLI where input.request.scope == .user: + route = .geminiExtension + manifest = "gemini-extension.json" + case .cursorEditor where input.request.scope == .user: + route = .cursorLocalPlugin + manifest = ".cursor-plugin/plugin.json" + default: + throw input.issue( + ["scope"], .unverified, + "native container registration/loading is not established for this surface/scope") + } + let name = try input.filename() + guard input.record.resources.count == 1, let id = input.record.resources.first, + let record = input.ledger.resources[id], let root = input.resources[id], + let entry = record.entries.first(where: { $0.path == manifest }), entry.kind == .file, + let size = entry.byteCount, size <= input.limits.resourceBytes + else { + throw input.issue( + ["path"], .invalid, "frozen native plugin requires its exact container manifest") + } + if input.request.surface == .geminiCLI, + record.entries.contains(where: { + [".gemini-extension-install.json", ".env"].contains($0.path) + }) + { + throw input.issue( + ["path"], .invalid, "runtime-local extension metadata/settings cannot be vendor resources") + } + try input.budget.allocate(size, stage: "native plugin manifest") + try input.budget.step(size) + let bytes = try Data(contentsOf: PathSafety.resolvedChild(base: root, subpath: manifest)) + let document = try NativeDocument(bytes: bytes, format: .json, budget: input.budget) + guard bytes.count == size, + case .object(let manifestFields) = try document.read(.init(keys: []))?.value + else { + throw input.issue(["path"], .invalid, "native plugin manifest is not an exact JSON object") + } + if input.request.surface == .geminiCLI { + for (key, value) in manifestFields { + guard ["name", "version"].contains(key) else { + throw input.issue( + ["manifest", key], .unverified, + "this native manifest field's registration/path semantics are not captured by the fixed profile" + ) + } + guard case .string(let text) = value, !text.utf8.contains(0) else { + throw input.issue(["manifest", key], .invalid, "native metadata must be a string") + } + } + } else { + try NativePluginFieldsV1(input: input, resource: record, root: root).validate(manifestFields) + } + guard try document.read(.init(keys: ["name"]))?.value == .string(name) else { + throw input.issue( + ["name"], .invalid, "native manifest name does not match the frozen component") + } + if input.request.surface == .geminiCLI { + guard name.range(of: #"^[a-zA-Z0-9-]+$"#, options: .regularExpression) != nil else { + throw input.issue( + ["name"], .invalid, "native extension name requires alphanumeric characters and hyphens") + } + guard case .string(let version) = manifestFields["version"], !version.isEmpty else { + throw input.issue( + ["manifest", "version"], .invalid, "native extension requires a version string") + } + } + let envelope = input.envelope( + route: route, path: name, selection: "nativePlugin", + value: .init(object: ["resource": .init(id), "manifest": .init(manifest)])) + return try input.emitted(lowering, envelope) + + [.init(name: lowering.id + "/bundle", kind: .tree, tree: root)] + } +} diff --git a/Sources/Components/NativeProgramV1.swift b/Sources/Components/NativeProgramV1.swift new file mode 100644 index 0000000..0b564e5 --- /dev/null +++ b/Sources/Components/NativeProgramV1.swift @@ -0,0 +1,281 @@ +import AgentsCore +import Foundation +import NativeDocuments + +/// Native command strings use the pinned clients' POSIX shell runner on supported platforms. +/// Each argument is quoted as one word. Source scripts remain frozen files, never inline code. +package enum NativeProgramV1 { + /// E supplies this only after verifying the native client's command runner, independently + /// of the applying process's environment. Gemini's pinned Unix runner selects bash itself. + package enum CommandShell { case posix } + + /// Frozen program shape is still the typed declaration's run, not native settings data. + static func validateFrozenRun(_ input: ComponentRenderInput) throws { + guard let run = input.fields["run"]?.object, + Set(run.keys).subtracting(["workingDirectory", "executableSource"]) == [ + "executable", "arguments", "environment", + ], + run["executable"]?.kind == .string, run["executable"]?.text?.isEmpty == false, + let arguments = run["arguments"]?.array, arguments.allSatisfy({ $0.kind == .string }), + let environment = run["environment"]?.object, + environment.allSatisfy({ + !$0.key.isEmpty && !$0.key.contains("=") && !$0.key.utf8.contains(0) + && [.literal, .environment, .secret].contains($0.value.kind) + && ($0.value.kind == .literal || $0.value.text?.isEmpty == false) + }) + else { throw input.issue(["run"], .invalid, "invalid frozen typed native program") } + if let source = run["executableSource"] { + guard source.kind == .string, source.text?.isEmpty == false, + run["executable"]!.text!.contains("/") + else { + throw input.issue( + ["run", "executableSource"], .invalid, "invalid executable source coordinate") + } + } + if let cwd = run["workingDirectory"] { + guard let fields = cwd.object, Set(fields.keys).isSubset(of: ["path", "source"]), + fields["path"]?.kind == .string, fields["path"]?.text?.isEmpty == false, + fields["source"] == nil || fields["source"]?.kind == .string + else { + throw input.issue( + ["run", "workingDirectory"], .invalid, "invalid frozen directory resource") + } + } + } + + static func executable(_ run: [String: LedgerValue], input: ComponentRenderInput) throws + -> LedgerValue + { + guard let executable = run["executable"]?.text, !executable.isEmpty else { + throw input.issue(["run", "executable"], .invalid, "missing native executable") + } + if executable.contains("/") { + guard let resource = input.record.resources.first else { + throw input.issue(["run", "executable"], .invalid, "missing frozen executable resource") + } + return .init(object: ["resource": .init(resource)]) + } + try input.literal(executable, field: ["run", "executable"]) + return .init(executable) + } + + static func validateLiterals(_ value: LedgerValue, input: ComponentRenderInput, path: [String]) + throws + { + if value.kind == .string || value.kind == .literal { + try input.literal(value.text!, field: path) + } + for (index, item) in (value.array ?? []).enumerated() { + try validateLiterals(item, input: input, path: path + [String(index)]) + } + for (key, item) in value.object ?? [:] { + try input.literal(key, field: path + ["key"]) + try validateLiterals(item, input: input, path: path + [key]) + } + } + + /// The strict contribution decoder supplies the envelope; package callers use its typed value. + static func stagedValue( + _ envelope: LedgerValue, bindings: RuntimeBindingValues, + environment: RuntimeEnvironment, resourcePaths: [String: String], budget: NativeDocumentBudget, + codexCommandShell: CommandShell? = nil, cursorCommandShell: CommandShell? = nil + ) throws -> NativeValue { + guard let metadata = envelope.object, + let surface = metadata["surface"]?.text.flatMap(NativeClientSurface.init(rawValue:)), + let scope = metadata["scope"]?.text.flatMap(InstallScope.init(rawValue:)), + let kind = metadata["kind"]?.text, let component = metadata["name"]?.text, + let value = metadata["value"], let selection = metadata["selection"]?.text, + ["hookGroup", "cursorHook", "antigravityHook", "lsp", "generatedPlugin"].contains(selection) + else { throw CoreError.invalidState("invalid staged native program intention") } + func issue(_ path: [String], _ detail: String, _ reason: NativeAdapterIssue.Reason = .invalid) + -> NativeComponentIssue + { + .init( + request: .init(surface: surface, scope: scope), kind: kind, component: component, + field: path, reason: reason, detail: detail) + } + if surface == .codexCLI { + guard codexCommandShell == .posix + else { + throw NativeComponentIssue( + request: .init(surface: surface, scope: scope), kind: kind, + component: component, field: ["run"], reason: .integrationRequired, + detail: + "E must supply the verified native POSIX command-shell contract; the apply environment is not that evidence" + ) + } + } + if [.cursorEditor, .cursorCLI, .cursorCloud].contains(surface), cursorCommandShell != .posix { + throw NativeComponentIssue( + request: .init(surface: surface, scope: scope), kind: kind, + component: component, field: ["run"], reason: .integrationRequired, + detail: + "E must supply the verified native POSIX command-shell contract for this Cursor surface") + } + func check(_ text: String, path: [String]) throws -> String { + try budget.allocate(text.utf8.count, stage: "native program string") + try budget.step(text.utf8.count) + guard !text.utf8.contains(0) else { throw issue(path, "NUL is not a native string") } + if surface == .openCodeCLI, text.contains("{env:") || text.contains("{file:") { + throw issue(path, "literal cannot cross native interpolation exactly") + } + if surface == .claudeCode, text.contains("${"), + selection == "hookGroup" + || (selection == "generatedPlugin" && path.count >= 4 + && ["command", "args", "env"].contains(path[3])) + { + throw issue(path, "literal cannot cross native placeholders exactly", .unverified) + } + if [.cursorEditor, .cursorCLI, .cursorCloud].contains(surface), text.contains("${") { + throw issue( + path, "exact literal preservation across Cursor command preprocessing needs evidence", + .unverified) + } + // Settings expand environment tokens before the hook runner sees shell quoting. + if surface == .geminiCLI, + text.range(of: #"\$(?:[A-Za-z0-9_]+|\{[^}]+?(?::-[^}]*)?\})"#, options: .regularExpression) + != nil + { + throw issue(path, "literal cannot cross native settings interpolation exactly") + } + return text + } + func string(_ value: LedgerValue, path: [String]) throws -> String { + if let resource = value.object?["resource"]?.text { + guard let final = resourcePaths[resource], !final.isEmpty else { + throw issue(path, "final registered resource placement is required") + } + return try check(final, path: path) + } + switch value.kind { + case .string, .literal: return try check(value.text!, path: path) + case .environment: + guard let text = environment.environment[value.text!] else { + throw issue(path, "required environment value is unavailable") + } + return try check(text, path: path) + case .secret: + let data: Data + do { data = try bindings.value(for: value.text!) } catch { + throw issue(path, "required binding is unavailable") + } + try budget.allocate(data.count, stage: "native program UTF8") + guard let text = String(data: data, encoding: .utf8) else { + throw issue(path, "native binding is not UTF8") + } + return try check(text, path: path) + default: throw issue(path, "expected native program string") + } + } + func quote(_ text: String) throws -> String { + guard text.utf8.count <= (Int.max - 2) / 4 else { + throw issue(["run"], "native command exceeds budget") + } + try budget.allocate(text.utf8.count * 4 + 2, stage: "native shell word") + return "'" + text.replacingOccurrences(of: "'", with: "'\\''") + "'" + } + func program(_ run: [String: LedgerValue]) throws -> String { + var words: [String] = [] + if let cwd = run["workingDirectory"] { + // Working directories are frozen resources; original authored paths never become native paths. + guard let resource = cwd.object?["resource"]?.text, let final = resourcePaths[resource], + !final.isEmpty + else { + throw issue( + ["run", "workingDirectory"], "final registered directory placement is required") + } + words.append( + "cd -- " + (try quote(check(final, path: ["run", "workingDirectory"]))) + " &&") + } + if let env = run["environment"]?.object, !env.isEmpty { + words.append("env") + for (key, value) in env.sorted(by: { $0.key < $1.key }) { + guard MCPReferenceSyntax.isName(key) else { + throw issue(["run", "environment"], "native environment key is invalid") + } + words.append(try quote(key + "=" + string(value, path: ["run", "environment", key]))) + } + } + guard let executable = run["executable"] else { + throw issue(["run", "executable"], "missing executable") + } + words.append(try quote(string(executable, path: ["run", "executable"]))) + for (index, argument) in (run["arguments"]?.array ?? []).enumerated() { + words.append(try quote(string(argument, path: ["run", "arguments", String(index)]))) + } + var size = 0 + for word in words { + guard word.utf8.count < Int.max - size else { + throw issue(["run"], "native command exceeds budget") + } + size += word.utf8.count + 1 + } + try budget.allocate(size, stage: "native command") + return words.joined(separator: " ") + } + let namedHookCommand = + selection == "antigravityHook" + ? AntigravityAdapter.commandPath(in: value) : nil + func convert(_ value: LedgerValue, path: [String], depth: Int) throws -> NativeValue { + try budget.node(depth: depth) + try budget.step() + if (selection == "hookGroup" && path == ["hooks", "0", "command"]) + || path == namedHookCommand + { + guard let run = value.object?["program"]?.object else { + throw issue(path, "missing native hook program") + } + return .string(try program(run)) + } + if selection == "cursorHook", path == ["command"] { + guard let run = value.object?["program"]?.object else { + throw issue(path, "missing native Cursor hook program") + } + return .string(try program(run)) + } + let generatedLSP = + selection == "generatedPlugin" + && path.count >= 3 + && Array(path.prefix(3)) == [".claude-plugin/plugin.json", "lspServers", component] + if generatedLSP, path == [".claude-plugin/plugin.json", "lspServers", component, "command"], + value.object?["resource"] != nil + { + return .string(try string(value, path: path)) + } + if selection == "lsp", path == ["command", "0"], value.object?["resource"] != nil { + return .string(try string(value, path: path)) + } + if value.kind == .environment || value.kind == .secret { + guard + (selection == "lsp" && path.count == 2 && path.first == "env") + || (generatedLSP && path.count == 5 && path[3] == "env") + else { + throw issue(path, "symbolic binding is outside a native environment slot") + } + return .string(try string(value, path: path)) + } + switch value.kind { + case .string, .literal: return .string(try string(value, path: path)) + case .integer: return .integer(value.integer!) + case .boolean: return .boolean(value.boolean!) + case .decimal: return .decimal(value.text!) + case .null: return .null + case .array: + return .array( + try value.array!.enumerated().map { + try convert($0.element, path: path + [String($0.offset)], depth: depth + 1) + }) + case .object: + var fields: [String: NativeValue] = [:] + for (key, value) in value.object!.sorted(by: { $0.key < $1.key }) { + try budget.allocate(key.utf8.count, stage: "native program key") + try budget.step(key.utf8.count) + fields[key] = try convert(value, path: path + [key], depth: depth + 1) + } + return .object(fields) + case .environment, .secret: throw issue(path, "invalid symbolic value") + } + } + return try convert(value, path: [], depth: 0) + } +} diff --git a/Sources/Components/NativePromptAudit.swift b/Sources/Components/NativePromptAudit.swift new file mode 100644 index 0000000..fa78a99 --- /dev/null +++ b/Sources/Components/NativePromptAudit.swift @@ -0,0 +1,163 @@ +import AgentsCore +import Foundation +import NativeDocuments + +package enum NativePromptAudit { + package enum Format: Equatable, Sendable { + case codexAgent, geminiCommand, claudeHooks, cursorHooks, commandHooks, antigravityHooks + case openCodeJSON, openCodeJSONC + package var isTOML: Bool { self == .codexAgent || self == .geminiCommand } + } + + package struct Field { + package let text: String + package let pointer: String + package let sourceRange: Range? + package let managed: Bool + } + + package struct Readback { + package let fields: [Field] + package let ownershipVerified: Bool + } + + package enum Failure: Error { + case unsupported(offset: Int?, field: String?) + } + + package static func read( + _ bytes: Data, format: Format, authorities: [LedgerNativeOwnedRegion] + ) throws -> Readback { + let limits = LedgerLimits.standard + let document: NativeDocument + do { + document = try NativeDocument( + bytes: bytes, + format: format.isTOML + ? .toml : format == .openCodeJSONC ? .jsonc(trailingCommas: true) : .json, + budget: NativeDocumentBudget( + limits: .init( + storage: limits.resourceBytes, work: limits.encodedBytes, nodes: limits.nodes, + depth: limits.depth, uninterruptedBytes: limits.resourceBytes))) + } catch NativeDocumentError.invalidDocument(_, let range) { + throw Failure.unsupported(offset: range?.lowerBound, field: nil) + } + let root = document.promptRoot + guard root.isObject else { throw Failure.unsupported(offset: 0, field: nil) } + + var selected: [(node: NativePromptNode, pointer: String)] = [] + var rootKeys = Set() + func select(_ node: NativePromptNode, at pointer: String) throws { + guard node.string != nil else { + throw Failure.unsupported(offset: node.sourceRange?.lowerBound, field: pointer) + } + selected.append((node, pointer)) + } + switch format { + case .codexAgent, .geminiCommand: + let key = format == .codexAgent ? "developer_instructions" : "prompt" + if let value = root[key] { try select(value, at: "/" + key) } + rootKeys.insert(key) + case .openCodeJSON, .openCodeJSONC: + for (section, key) in [("commands", "template"), ("agents", "system")] { + guard let entries = root[section] else { continue } + guard entries.isObject else { + throw Failure.unsupported(offset: entries.sourceRange?.lowerBound, field: "/" + section) + } + rootKeys.insert(section) + for (name, entry) in entries.fields { + if let value = entry[key] { + try select(value, at: "/" + section + "/" + pointerToken(name) + "/" + key) + } + } + } + case .antigravityHooks: + break + case .claudeHooks, .cursorHooks, .commandHooks: + if let hooks = root["hooks"] { + rootKeys.insert("hooks") + guard hooks.isObject else { + throw Failure.unsupported(offset: hooks.sourceRange?.lowerBound, field: "/hooks") + } + for (event, handlers) in hooks.fields { + let path = "/hooks/" + pointerToken(event) + guard handlers.isArray else { + throw Failure.unsupported(offset: handlers.sourceRange?.lowerBound, field: path) + } + for (index, handler) in handlers.elements.enumerated() { + let position = path + "/" + String(index) + if format == .cursorHooks { + try collect(handler, at: position, types: ["prompt"], select: select) + } else if let group = handler["hooks"] { + guard group.isArray else { + throw Failure.unsupported( + offset: group.sourceRange?.lowerBound, field: position + "/hooks") + } + if format == .claudeHooks { + for (child, hook) in group.elements.enumerated() { + try collect( + hook, at: position + "/hooks/" + String(child), types: ["prompt", "agent"], + select: select) + } + } + } else { + throw Failure.unsupported(offset: handler.sourceRange?.lowerBound, field: position) + } + } + } + } + } + guard !selected.isEmpty else { return .init(fields: [], ownershipVerified: true) } + + // Regional claims are meaningful for the native document generation they describe. + var ranges: [Range] = [] + var verified = true + for authority in authorities { + guard case .key(let key)? = authority.path.first, rootKeys.contains(key) + else { continue } + do { + let region = try NativeAuthorityComposition.region( + authority.path, document: document, arrays: []) + guard let readback = try document.promptNode(at: region), + let range = readback.sourceRange + else { + verified = false + continue + } + ranges.append(range) + } catch { + verified = false + } + } + let fields = selected.compactMap { entry -> Field? in + guard let value = entry.node.string else { return nil } + let range = entry.node.sourceRange + return Field( + text: value, pointer: entry.pointer, sourceRange: range, + managed: range.map { leaf in + ranges.contains { $0.lowerBound <= leaf.lowerBound && $0.upperBound >= leaf.upperBound } + } ?? false + ) + } + return .init(fields: fields, ownershipVerified: verified) + } + + private static func pointerToken(_ value: String) -> String { + value.replacingOccurrences(of: "~", with: "~0").replacingOccurrences(of: "/", with: "~1") + } + + private static func collect( + _ handler: NativePromptNode, at position: String, types: Set, + select: (NativePromptNode, String) throws -> Void + ) throws { + guard handler.isObject, handler["hooks"] == nil else { + throw Failure.unsupported(offset: handler.sourceRange?.lowerBound, field: position) + } + guard let type = handler["type"]?.string, types.contains(type) else { return } + let pointer = position + "/prompt" + guard let prompt = handler["prompt"] else { + throw Failure.unsupported(offset: handler.sourceRange?.lowerBound, field: pointer) + } + try select(prompt, pointer) + } +} diff --git a/Sources/Components/PluginExpansion.swift b/Sources/Components/PluginExpansion.swift new file mode 100644 index 0000000..7f59622 --- /dev/null +++ b/Sources/Components/PluginExpansion.swift @@ -0,0 +1,262 @@ +import AgentsCore +import Foundation + +extension Expansion { + func plugin( + _ declaration: ComponentDeclaration, context: LinkingDocument, group: String?, + condition: DeclarationCondition, chain: [SourceSpan], position: SourceMapEntry?, + dependencies: [SourceSnapshotID] + ) throws { + guard + case .plugin( + let name, let path, let alias, let mode, let select, let exclude, + let agents, let authoredCondition, let authoredNative) = declaration + else { return } + guard active.count + pluginDepth < 64 else { throw LinkError.budget("active references") } + let componentKey = key(name, kind: .plugin, context: context, group: group) + let address = try linking.address(alias, in: context, chain: chain) + let view: SourceSnapshot + if linking.directPins[componentKey] == nil, + let selected = try linking.view(address, pin: choices[address.id]) + { + view = selected + } else { + view = try selectedView(address, key: componentKey) + } + let container = try view.relativePath( + PathSafety.resolvedChild(base: view.directory(), subpath: path)) + let recipients = condition.recipients( + requested: agents ?? context.declaration.defaultAgents, + scope: linking.store.scope, platform: linking.platform) + if mode == .native { + guard recipients.count == 1, select == nil, exclude.isEmpty else { + throw LinkError.invalid("native plugin requires one recipient and no filters", chain) + } + try append( + key: componentKey, snapshot: view.snapshot, pin: view.pin, + payload: .declaration(declaration), context: context, group: group, + condition: condition, recipients: recipients, chatGPT: false, + resources: [resource(path, in: view, chain: chain)], chain: chain, position: position, + dependencies: dependencies + [view.snapshot]) + return + } + let profiles: [(SourceImportProfile, String)] = [ + (.claudePluginV1, ".claude-plugin/plugin.json"), + (.cursorPluginV1, ".cursor-plugin/plugin.json"), + (.geminiExtensionV1, "gemini-extension.json"), + ] + let entries = try profiles.compactMap { profile, suffix -> (SourceImportProfile, String)? in + let document = container == "." ? suffix : container + "/" + suffix + let file = try view.resource(document) + return FileManager.default.fileExists(atPath: file.path) ? (profile, document) : nil + } + guard entries.count == 1, let (profile, document) = entries.first else { + throw LinkError.invalid("plugin requires one supported native container manifest", chain) + } + let proposal = try SourceImport.preview( + .init(profile: profile, root: view.root, document: document)) + if let failure = proposal.diagnostics.first(where: { + ![.unconverted, .credentialBinding].contains($0.code) + }) { + throw LinkError.invalid( + "native plugin \(failure.code.rawValue) at \(failure.location.document)\(failure.location.pointer)", + chain) + } + var effective = declaration + if profile == .geminiExtensionV1, let metadata = proposal.packageMetadata { + guard let version = metadata.version, let versionLocation = metadata.versionLocation, + proposal.profile == profile, + [metadata.nameLocation, versionLocation].allSatisfy({ + $0.document.utf8.elementsEqual(document.utf8) + && $0.span?.document.rawValue.utf8.elementsEqual(document.utf8) == true + }) + else { + throw LinkError.invalid("native package metadata has different producer coordinates", chain) + } + if authoredNative[AgentID.geminiCLI.rawValue]?["version"] == nil { + var native = authoredNative + native[AgentID.geminiCLI.rawValue, default: [:]]["version"] = .string(version) + effective = .plugin( + name: name, path: path, source: alias, mode: mode, select: select, exclude: exclude, + agents: agents, condition: authoredCondition, native: native) + } + } + // G's aliases are read coordinates in the already selected immutable producer tree. + var aliases: [String: SourceSnapshot] = [:] + for source in proposal.sources { + try linking.budget.step() + guard source.declaration?.kind == .local, let path = source.producerPath else { + throw LinkError.invalid("native member has no contained producer coordinates", chain) + } + aliases[source.alias] = try SourceSnapshot( + snapshot: view.snapshot, pin: view.pin, root: view.root, discoveryPath: path, + packageIdentity: view.packageIdentity) + } + let namespace = pluginFrame?.root ?? view.discoveryPath + let input = LedgerInputProvenance( + format: "native/" + profile.rawValue + "@1", adapterVersion: "1") + let parentIndex = components.count + let parent = nextOccurrence + try append( + key: componentKey, snapshot: view.snapshot, pin: view.pin, + payload: .declaration(effective), context: context, group: group, + condition: condition, recipients: recipients, chatGPT: false, resources: [], + chain: chain, position: position, dependencies: dependencies + [view.snapshot]) + let actualRecipients = components[parentIndex].origins[0].recipients + components[parentIndex].origins[0].pluginExpansion = LinkedPluginExpansion( + snapshot: view.snapshot, root: namespace, containerRoot: container, + document: document, input: input, children: []) + let previous = pluginFrame + pluginDepth += 1 + defer { + pluginFrame = previous + pluginDepth -= 1 + } + let childView = try SourceSnapshot( + snapshot: view.snapshot, pin: view.pin, root: view.root, + discoveryPath: container, packageIdentity: view.packageIdentity) + var childContext = LinkingDocument( + declaration: context.declaration, document: context.document, + view: childView, manifestPath: document, producer: true) + childContext.importedSources = aliases + var documents = Set() + for path in [document] + proposal.components.map({ $0.origin.document }) + + proposal.resources.map({ $0.origin.document }) + where documents.insert(Data(path.utf8)).inserted { + let bytes = try Data(contentsOf: view.resource(path)) + try linking.budget.manifest(view.snapshot, path: path, bytes: bytes.count) + } + let exclusions = try Set( + exclude.map { + try linking.budget.step() + return try ResolvedLedgerCodec.bytes(LedgerPayload.reference($0)) + }) + var resourcesByDocument: [Data: [ImportResourceProposal]] = [:] + for resource in proposal.resources { + try linking.budget.step() + resourcesByDocument[Data(resource.origin.document.utf8), default: []].append(resource) + } + var selectors = Set() + for child in proposal.components { + if child.declaration.kind == .skills { + try linking.budget.step() + } else { + try spendNativeValue(LedgerPayload.component(child.declaration)) + } + guard let coordinate = child.member, + coordinate.containerRoot.utf8.elementsEqual(container.utf8) + else { + throw LinkError.invalid("native member lacks container coordinates", chain) + } + let selector = LedgerPayload.reference(coordinate.selector) + let bytes = try ResolvedLedgerCodec.bytes(selector) + guard selectors.insert(bytes).inserted else { + throw LinkError.invalid("duplicate native member selector", chain) + } + guard select?.contains(child.declaration.kind) ?? true, !exclusions.contains(bytes) + else { continue } + pluginFrame = PluginFrame( + parent: parent, selector: coordinate.selector, + root: namespace, containerRoot: container, origin: child.origin, + input: .init( + format: "native/" + coordinate.profile.rawValue + "@" + String(coordinate.formatVersion), + adapterVersion: "1", + pointer: child.origin.pointer), recipients: actualRecipients) + let condition = condition.intersecting(child.declaration.condition ?? .init()) + let start = components.count + try emitComponent( + child.declaration, in: childContext, group: nil, condition: condition, + chain: chain, + position: child.origin.span.map { + SourceMapEntry(pointer: child.origin.pointer, span: $0, origins: [], defaulted: false) + }, dependencies: dependencies + [view.snapshot]) + // Literal prompt payloads retain their selected safe native input, never a raw bundle. + if [.command, .subagent].contains(child.declaration.kind) { + let selected = (resourcesByDocument[Data(child.origin.document.utf8)] ?? []).filter { + ($0.kind == nil || $0.kind == child.declaration.kind) && !$0.requiresBindingRewrite + } + for entry in selected { + guard let path = entry.path, let source = aliases[entry.sourceAlias] else { + throw LinkError.invalid("native member resource lacks producer coordinates", chain) + } + let resource = try resource(path, in: source, chain: chain) + for index in start.. ComponentDeclaration + { + guard pluginFrame != nil else { return declaration } + func path(_ value: ResourceDeclaration) throws -> ResourceDeclaration { + let address = try linking.address(value.source, in: context, chain: []) + guard let view = address.contained else { + throw LinkError.invalid("unselected native resource", []) + } + return try ResourceDeclaration( + path: view.relativePath( + PathSafety.resolvedChild(base: view.directory(), subpath: value.path))) + } + func run(_ value: ExecutableDeclaration) throws -> ExecutableDeclaration { + var value = value + if value.executable.contains("/") { + let relative = try path(.init(path: value.executable, source: value.executableSource)).path + value.executable = relative.contains("/") ? relative : "./" + relative + value.executableSource = nil + } + value.workingDirectory = try value.workingDirectory.map(path) + return value + } + func prompt(_ value: PromptBody) throws -> PromptBody { + if case .file(let resource) = value { return try .file(path(resource)) } + return value + } + switch declaration { + case .mcpServer( + let name, .stdio(let invocation), let agents, let condition, let native, let registry): + return try .mcpServer( + name: name, transport: .stdio(run(invocation)), agents: agents, + condition: condition, native: native, registry: registry) + case .hook( + let name, let event, let invocation, let matcher, let timeout, let agents, let condition, + let native): + return try .hook( + name: name, event: event, run: run(invocation), matcher: matcher, + timeoutSeconds: timeout, agents: agents, condition: condition, native: native) + case .lspServer( + let name, let invocation, let languages, let options, let agents, let condition, let native): + return try .lspServer( + name: name, run: run(invocation), languages: languages, + initializationOptions: options, agents: agents, condition: condition, native: native) + case .command( + let name, let description, let body, let parameters, let agents, let condition, let native): + return try .command( + name: name, description: description, prompt: prompt(body), + parameters: parameters, agents: agents, condition: condition, native: native) + case .subagent( + let name, let description, let body, let model, let tools, let agents, let condition, + let native): + return try .subagent( + name: name, description: description, prompt: prompt(body), model: model, + tools: tools, agents: agents, condition: condition, native: native) + default: return declaration + } + } +} diff --git a/Sources/Components/SourceCatalog.swift b/Sources/Components/SourceCatalog.swift new file mode 100644 index 0000000..051f1c6 --- /dev/null +++ b/Sources/Components/SourceCatalog.swift @@ -0,0 +1,443 @@ +import AgentsCore +import AgentsInstructions +import AgentsManifest +import AgentsSkills +import Foundation + +/// An explicitly chosen adapter document, relative to the source's discovery root. +package struct SourceCatalogImport: Sendable { + package let profile: SourceImportProfile + package let document: String + package var selection: Set? = nil + package init(profile: SourceImportProfile, document: String, selection: Set? = nil) { + self.profile = profile + self.document = document + self.selection = selection + } +} + +/// Temporary source enumeration, with stable coordinates and no borrowed resource URLs. +/// Destination composition and publication belong to the captured-addition owner. +package struct SourceCatalog: Sendable { + package struct ID: Hashable, Sendable { + fileprivate let owner: UUID + fileprivate let index: Int + } + + package enum Unit: Sendable { + case skill(String) + case instruction(String) + case group(GroupUseDeclaration) + case nativePlugin(ComponentDeclaration) + case componentsPlugin(ComponentDeclaration) + /// One member is representable through typed kind selection and sibling exclusions. + case pluginMember(ComponentDeclaration, ComponentReferenceDeclaration) + /// Metadata is issued by the adapter; its key is never derived from the display label. + case importer(ImportChoiceMetadata) + } + + package struct ImportEffects: Sendable { + package let sources: [ImportedSource] + package let components: [ImportedComponent] + package let resources: [ImportResourceProposal] + package let diagnostics: [SourceImportDiagnostic] + } + + package struct Choice: Sendable { + package let id: ID + package let label: String + package let origin: ImportLocation + package let unit: Unit + /// Actual linked closure, including restrictions, pins, resources and repeated occurrences. + package let graph: LinkedComponents? + package let imported: ImportEffects? + package let artifact: LockedArtifact? + package let unavailableReason: String? + } + + package let alias: String + package let source: SourceDeclaration + package let snapshot: SourceSnapshotID + package let root: String + package let contentHash: String + package let choices: [Choice] + package let fixedEffects: ImportEffects? + package let requiredInputs: [ImportInputMetadata] + package let bindings: [ImportBindingRequirement] + package let producerSelections: [ImportProducerSelection] + package let importDocument: SourceCatalogImport? + private let owner: UUID + + /// Empty catalog selection is no addition. This resolves handles to representable units only; + /// it neither composes a declaration nor grants an unrestricted update capability. + package func selected(_ ids: [ID]) throws -> [Choice]? { + guard Set(ids).count == ids.count, + ids.allSatisfy({ $0.owner == owner && choices.indices.contains($0.index) }) + else { throw CoreError.invalidState("source choices belong to another inspection") } + guard !ids.isEmpty else { return nil } + let selected = ids.map { choices[$0.index] } + if let reason = selected.compactMap(\.unavailableReason).first { + throw CoreError.invalidSource(reason) + } + return selected + } + + package static func inspect( + alias: String, source: SourceDeclaration, store: StateStore, platform: DeclarationPlatform, + importing imported: SourceCatalogImport? = nil, sourcePolicy: EffectiveSourcePolicy = .init(), + organization: OrganizationPolicyEvaluator = .init(chains: []), + admitOrganization: @escaping @Sendable ([OrganizationPolicyFinding]) throws -> Void = { _ in } + ) throws -> SourceCatalog { + try Declaration(sources: [alias: source]).validate(environment: store.environment) + let owner = UUID() + let budget = LinkBudget() + if source.kind == .wellKnown { + _ = try store.environment.sourceAccess.requireDirectHTTP( + URL(string: source.location)!, policy: sourcePolicy) + guard imported == nil else { + throw CoreError.invalidSource("skill indexes do not contain adapter documents") + } + let skills = try SkillSnapshotReader.index( + source, sourcePolicy: sourcePolicy, sourceAccess: store.environment.sourceAccess, + requireOrigin: organization.artifactOriginCheck(admitOrganization)) + let hash = FileHash.sha256Hex( + data: try JSONEncoder().encode(skills.map { [$0.name, $0.artifact.digest] })) + let snapshot = try SourceSnapshotID( + source: source.identity(environment: store.environment), revision: "sha256:" + hash) + try budget.snapshot(snapshot) + let choices = try SourceResolutionSession.withTemporaryRead( + store: store, sourcePolicy: sourcePolicy + ) { session in + try skills.enumerated().map { index, skill in + let graph = try capturedIndexSkill( + skill, alias: alias, source: source, store: store, platform: platform, + session: session, budget: budget) + return Choice( + id: .init(owner: owner, index: index), label: label("Skill", skill.name), + origin: .init(document: skill.name, pointer: ""), unit: .skill(skill.name), + graph: graph, imported: nil, artifact: skill.artifact, unavailableReason: nil) + } + } + return .init( + alias: alias, source: source, snapshot: snapshot, root: source.path ?? ".", + contentHash: hash, choices: choices, fixedEffects: nil, requiredInputs: [], bindings: [], + producerSelections: [], importDocument: nil, owner: owner) + } + return try SourceResolutionSession.withTemporaryRead( + store: store, sourcePolicy: sourcePolicy, + requireRecordedTransport: organization.requiresRecordedGitOrigin + ) { session in + try session.requireSource(source) + let view: SourceSnapshot + if try source.requirement != nil || session.isGitSource(source) { + let identity = + try organization.active + ? OrganizationPolicyIdentity(.declared(source, in: store.environment), root: source.path) + : OrganizationPolicyIdentity(.missing) + let admission = organization.requirements(for: identity) + let requirements = + (admission.overrides ? [] : [source.requirement]) + + admission.constraints.map(Optional.some) + guard + let pin = try session.candidates( + for: source, requirements: requirements, spending: budget.step + ).first + else { + if !admission.constraints.isEmpty { + try admitOrganization( + organization.version( + nil, identity: identity, authored: [source.requirement].compactMap { $0 }, + available: false)) + } + throw CoreError.invalidSource("source has no matching revision") + } + view = try session.snapshot(source, at: pin) + } else { + view = try session.localSnapshot(source) + } + try budget.snapshot(view.snapshot) + let hash = try FileHash.folderHash(view.directory()) + func admitManifest(_ path: String) throws { + let handle = try FileHandle(forReadingFrom: view.resource(path)) + defer { try? handle.close() } + let bytes = try handle.read(upToCount: SourceImportLimits().documentBytes + 1) ?? Data() + try budget.manifest(view.snapshot, path: path, bytes: bytes.count) + } + var choices: [Choice] = [] + func issue( + _ unit: Unit, label: String, origin: ImportLocation, graph: LinkedComponents? = nil, + effects: ImportEffects? = nil, unavailable: String? = nil + ) throws { + try budget.contribution(chain: 0) + choices.append( + .init( + id: .init(owner: owner, index: choices.count), label: label, origin: origin, + unit: unit, graph: graph, imported: effects, artifact: nil, + unavailableReason: unavailable)) + } + func linked(_ component: ComponentDeclaration?, use: GroupUseDeclaration? = nil) throws + -> LinkedComponents + { + let declaration = Declaration( + sources: [alias: source], components: component.map { [$0] } ?? [], + uses: use.map { [$0] } ?? []) + let identity = DocumentIdentity("catalog/agents.yaml") + let bytes = + try DeclarationEditPlan.bytes( + replacing: Declaration(), with: declaration, in: nil, identity: identity, + environment: store.environment) ?? Array("version: 1\n".utf8) + let linker = Linking( + document: try DeclarationDocument(bytes: bytes, identity: identity), store: store, + platform: platform, session: session, directPins: [:], retainedLedger: nil, + organization: organization, admitOrganization: admitOrganization, budget: budget + ) + return try linker.solve(preserving: view.pin.map { [view.snapshot.source: $0] } ?? [:]) + } + func resolved( + _ unit: Unit, component: ComponentDeclaration? = nil, use: GroupUseDeclaration? = nil, + label: String, origin: ImportLocation, unavailable: String? = nil + ) throws { + do { + try issue( + unit, label: label, origin: origin, graph: linked(component, use: use), + unavailable: unavailable) + } catch is CancellationError { throw CancellationError() } catch let error as LinkError { + if case .budget = error { throw error } + try issue(unit, label: label, origin: origin, unavailable: diagnostic(error, view: view)) + } catch { + try issue(unit, label: label, origin: origin, unavailable: diagnostic(error, view: view)) + } + } + if let imported { + let document = try view.relativePath( + PathSafety.resolvedChild(base: view.directory(), subpath: imported.document)) + var input = SourceImportInput( + profile: imported.profile, root: view.root, document: document, + selection: imported.selection) + try admitManifest(document) + let current = try SourceImport.preview(input) + input.selection = nil + input.enumerateChoices = true + let proposal = try SourceImport.preview(input) + func effects( + _ components: [Int], _ sources: [Int], _ resources: [Int], _ diagnostics: [Int] + ) + -> ImportEffects + { + .init( + sources: sources.map { stable(proposal.sources[$0], view: view) }, + components: components.map { proposal.components[$0] }, + resources: resources.map { proposal.resources[$0] }, + diagnostics: diagnostics.map { proposal.diagnostics[$0] }) + } + for (index, choice) in proposal.choices.enumerated() { + try issue( + .importer(choice), label: "Producer selection \(index + 1)", + origin: choice.locations.first ?? .init(document: document, pointer: ""), + effects: effects( + choice.components, choice.sources, choice.resources, choice.diagnostics)) + } + let components = Set(proposal.choices.flatMap(\.components)) + let sources = Set(proposal.choices.flatMap(\.sources)) + let resources = Set(proposal.choices.flatMap(\.resources)) + let diagnostics = Set(proposal.choices.flatMap(\.diagnostics)) + let fixed = effects( + proposal.components.indices.filter { !components.contains($0) }, + proposal.sources.indices.filter { !sources.contains($0) }, + proposal.resources.indices.filter { !resources.contains($0) }, + proposal.diagnostics.indices.filter { !diagnostics.contains($0) }) + return .init( + alias: alias, source: source, snapshot: view.snapshot, root: view.discoveryPath, + contentHash: hash, choices: choices, fixedEffects: fixed, + requiredInputs: proposal.requiredInputs, bindings: proposal.bindings, + producerSelections: current.selections, importDocument: imported, owner: owner) + } + for skill in try SkillSnapshotReader.read(view) { + try resolved( + .skill(skill.name), + component: .skills(source: alias, .init(select: .names([skill.name]))), + label: label("Skill", skill.name), origin: .init(document: skill.path, pointer: "")) + } + for instruction in try InstructionSnapshotReader.read(view) { + let component = ComponentDeclaration.instructions( + .init(sections: [alias + ":" + instruction.name])) + try resolved( + .instruction(instruction.name), component: component, + label: label("Instruction", instruction.name), + origin: .init(document: instruction.path, pointer: "")) + } + let manifest = try view.relativePath( + view.directory().appendingPathComponent( + view.directory().lastPathComponent == ".agent" ? "agents.yaml" : ".agent/agents.yaml")) + if FileManager.default.fileExists(atPath: try view.resource(manifest).path) { + let document = try DeclarationDocument( + bytes: Array("version: 1\n".utf8), identity: .init("catalog/agents.yaml")) + let linker = Linking( + document: document, store: store, platform: platform, session: session, + directPins: [:], retainedLedger: nil, budget: budget) + let producer = try linker.producer(view, chain: []) + for name in producer.declaration.exports { + let use = GroupUseDeclaration(name: name, source: alias) + try resolved( + .group(use), use: use, label: label("Group", name), + origin: .init(document: manifest, pointer: "/exports")) + } + } + var nativeBindings: [ImportBindingRequirement] = [] + var nativeInputs: [ImportInputMetadata] = [] + var nativeSelections: [ImportProducerSelection] = [] + for (profile, suffix, agent) in [ + (SourceImportProfile.claudePluginV1, ".claude-plugin/plugin.json", AgentID.claudeCode), + (.cursorPluginV1, ".cursor-plugin/plugin.json", .cursor), + (.geminiExtensionV1, "gemini-extension.json", .geminiCLI), + ] { + let document = try view.relativePath( + PathSafety.resolvedChild(base: view.directory(), subpath: suffix)) + guard FileManager.default.fileExists(atPath: try view.resource(document).path) else { + continue + } + try admitManifest(document) + let proposal = try SourceImport.preview( + .init(profile: profile, root: view.root, document: document)) + let nativeName = proposal.packageMetadata?.name + let native = ComponentDeclaration.plugin( + name: nativeName ?? alias, path: ".", source: alias, mode: .native, agents: [agent]) + try resolved( + .nativePlugin(native), component: native, label: "Native \(agent.rawValue) registration", + origin: proposal.packageMetadata?.nameLocation ?? .init(document: document, pointer: ""), + unavailable: nativeName == nil + ? "native registration requires adapter-issued container name metadata" : nil) + nativeBindings += proposal.bindings + nativeInputs += proposal.requiredInputs + nativeSelections += proposal.selections + let whole = ComponentDeclaration.plugin( + name: alias, path: ".", source: alias, mode: .components, agents: [agent]) + try resolved( + .componentsPlugin(whole), component: whole, + label: "Components \(agent.rawValue) container", + origin: .init(document: document, pointer: "")) + for member in proposal.components { + guard let selector = member.member?.selector else { continue } + let identity = try ResolvedLedgerCodec.bytes(LedgerPayload.reference(selector)) + try budget.step(proposal.components.count) + let siblings = proposal.components.filter { + $0.declaration.kind == member.declaration.kind + }.compactMap(\.member?.selector) + let exclusions = try siblings.filter { + try ResolvedLedgerCodec.bytes(LedgerPayload.reference($0)) != identity + } + let component = ComponentDeclaration.plugin( + name: alias, path: ".", source: alias, mode: .components, + select: [member.declaration.kind], exclude: exclusions, agents: [agent]) + try resolved( + .pluginMember(component, selector), component: component, + label: label(member.declaration.kind.rawValue, member.declaration.name ?? "member"), + origin: member.origin) + } + } + return .init( + alias: alias, source: source, snapshot: view.snapshot, root: view.discoveryPath, + contentHash: hash, choices: choices, fixedEffects: nil, requiredInputs: nativeInputs, + bindings: nativeBindings, producerSelections: nativeSelections, importDocument: nil, + owner: owner) + } + } + + private static func label(_ kind: String, _ name: String) -> String { + kind + " " + + String( + String.UnicodeScalarView( + name.unicodeScalars.map { + CharacterSet.controlCharacters.contains($0) ? UnicodeScalar(0xfffd)! : $0 + })) + } + + private static func diagnostic(_ error: any Error, view: SourceSnapshot) -> String { + String(describing: error) + .replacingOccurrences(of: view.root.path, with: view.snapshot.source) + .replacingOccurrences( + of: view.root.resolvingSymlinksInPath().path, with: view.snapshot.source) + } + + /// Relative imported coordinates remain anchored to the catalog snapshot, never its borrowed URL. + private static func stable(_ value: ImportedSource, view: SourceSnapshot) -> ImportedSource { + func relative(_ path: String?) -> String? { + guard let path, path.hasPrefix("/"), + PathSafety.isContained(URL(fileURLWithPath: path), in: view.root) + else { return path } + return PathSafety.relativePath(path, to: view.root.path) + } + var declaration = value.declaration + if let location = declaration?.location, declaration?.kind == .local, + location.hasPrefix("/"), + PathSafety.isContained(URL(fileURLWithPath: location), in: view.root) + { + declaration?.location = PathSafety.relativePath(location, to: view.root.path) + } + declaration?.environment = nil + return .init( + alias: value.alias, origin: value.origin, declaration: declaration, pin: value.pin, + requestedRef: value.requestedRef, producerPath: relative(value.producerPath), + producerIdentity: value.producerIdentity, registry: value.registry, + resolvedRef: value.resolvedRef, + resolvedURL: value.resolvedURL, developmentOnly: value.developmentOnly) + } +} + +extension SourceCatalog { + /// Interprets the already verified artifact through ordinary skill expansion, without fetching + /// again or promoting the borrowed extraction to a source identity. + private static func capturedIndexSkill( + _ skill: SnapshotIndexSkill, alias: String, source: SourceDeclaration, store: StateStore, + platform: DeclarationPlatform, session: SourceResolutionSession, budget: LinkBudget + ) throws -> LinkedComponents { + let id = try source.identity(environment: store.environment) + let view = try session.fileSnapshot( + source: id, revision: skill.artifact.digest, + files: skill.files, executableFlags: skill.executableFlags) + try budget.snapshot(view.snapshot) + let declaration = Declaration( + sources: [alias: source], + components: [ + .skills(source: alias, .init(select: .names([skill.name]))) + ]) + let identity = DocumentIdentity("catalog/agents.yaml") + let bytes = + try DeclarationEditPlan.bytes( + replacing: Declaration(), with: declaration, + in: nil, identity: identity, environment: store.environment) ?? Array("version: 1\n".utf8) + let document = try DeclarationDocument(bytes: bytes, identity: identity) + let root = store.scope == .user ? store.directory : store.environment.projectDirectory + let consumer = try SourceSnapshot( + snapshot: .init(source: "local:" + root.path, revision: "live"), + pin: nil, root: root, + localEnvironment: .init( + projectDirectory: root, + homeDirectory: store.environment.homeDirectory), liveRoot: root) + session.register(consumer) + let context = LinkingDocument( + declaration: declaration, document: document, view: consumer, + manifestPath: store.scope == .user ? "agents.yaml" : ".agent/agents.yaml", producer: false, + importedSources: [alias: view]) + try budget.manifest(consumer.snapshot, path: context.manifestPath, bytes: bytes.count) + let linking = Linking( + document: document, store: store, platform: platform, session: session, + directPins: [:], retainedLedger: nil, budget: budget) + linking.sourceUses = [.init(source: id, root: ".", requirement: source.requirement)] + let expansion = Expansion(linking: linking, choices: [:], emit: true) + try expansion.expandRoot(context) + let graph = try expansion.result() + return LinkedComponents( + components: graph.components.map { component in + var component = component + component.resources = component.resources.map { resource in + LinkedResource( + snapshot: resource.snapshot, path: resource.path, hash: resource.hash, + executableFlags: resource.executableFlags, artifact: skill.artifact) + } + return component + }, references: graph.references, constraints: graph.constraints, selections: graph.selections, + sourceSnapshots: graph.sourceSnapshots, sourceUses: graph.sourceUses, + declaringSnapshots: graph.declaringSnapshots) + } +} diff --git a/Sources/Components/SourceCatalogSelection.swift b/Sources/Components/SourceCatalogSelection.swift new file mode 100644 index 0000000..076aca8 --- /dev/null +++ b/Sources/Components/SourceCatalogSelection.swift @@ -0,0 +1,199 @@ +import AgentsCore +import AgentsManifest +import Foundation + +extension SourceCatalog { + /// Combines member recipes by container, preserving typed exclusions and byte-exact selectors. + package func additions( + _ ids: [ID], agents: [AgentID]?, condition: DeclarationCondition?, mode: InstallMode? + ) throws -> Declaration { + guard let selected = try selected(ids) else { return Declaration() } + var result = Declaration(sources: [alias: source]) + var plugins: [(Data, ComponentDeclaration, [ComponentReferenceDeclaration]?)] = [] + for choice in selected { + switch choice.unit { + case .skill(let name): + result.components.append( + .skills( + source: alias, + .init( + select: .names([name]), agents: agents, mode: mode, condition: condition))) + case .instruction(let name): + result.components.append( + .instructions( + .init( + agents: agents, sections: [alias + ":" + name], condition: condition))) + case .group(var use): + var restriction = condition + if let agents { + restriction = restriction ?? .init() + let existingAgents = restriction?.agents + restriction?.agents = + existingAgents.map { existing in agents.filter { existing.contains($0) } } ?? agents + } + use.condition = restriction + result.uses.append(use) + case .nativePlugin(let declaration), .componentsPlugin(let declaration): + try addPlugin(declaration, member: nil) + case .pluginMember(let declaration, let selector): + try addPlugin(declaration, member: selector) + case .importer: + throw CoreError.invalidState("importer choices require adapter conversion") + } + } + for (_, declaration, members) in plugins { + guard + case .plugin( + let name, let path, let source, let strategy, _, _, let defaults, _, let native) = + declaration + else { continue } + let recipients = agents ?? defaults + if strategy == .native, recipients?.count != 1 { + throw CoreError.invalidState("native registration requires exactly one recipient") + } + var kinds: [DeclaredComponentKind]? = nil + var exclusions: [ComponentReferenceDeclaration] = [] + if let members { + let identities = try Set(members.map(Self.referenceIdentity)) + let recipes = choices.compactMap { + choice -> (ComponentDeclaration, ComponentReferenceDeclaration)? in + if case .pluginMember(let recipe, let selector) = choice.unit { + return (recipe, selector) + } + return nil + } + kinds = [] + for (recipe, selector) in recipes { + guard case .plugin(_, let p, let s, _, let select, _, let a, _, _) = recipe, + try containerIdentity(path: p, source: s, agents: a) + == containerIdentity(path: path, source: source, agents: defaults) + else { continue } + if try identities.contains(Self.referenceIdentity(selector)) { + for kind in select ?? [] where !kinds!.contains(kind) { kinds!.append(kind) } + } + } + for (recipe, selector) in recipes { + guard case .plugin(_, let p, let s, _, let select, _, let a, _, _) = recipe, + try containerIdentity(path: p, source: s, agents: a) + == containerIdentity(path: path, source: source, agents: defaults), + select?.contains(where: { kinds!.contains($0) }) == true, + try !identities.contains(Self.referenceIdentity(selector)) + else { continue } + exclusions.append(selector) + } + } + result.components.append( + .plugin( + name: name, path: path, source: source, mode: strategy, + select: kinds, exclude: exclusions, agents: recipients, condition: condition, + native: native)) + } + return result + + func addPlugin(_ declaration: ComponentDeclaration, member: ComponentReferenceDeclaration?) + throws + { + guard + case .plugin(_, let path, let source, let strategy, _, _, let agents, _, _) = declaration + else { return } + let key = try containerIdentity(path: path, source: source, agents: agents) + if let index = plugins.firstIndex(where: { $0.0 == key }) { + guard case .plugin(_, _, _, let existing, _, _, _, _, _) = plugins[index].1, + existing == strategy + else { throw CoreError.invalidState("incompatible plugin strategies") } + if let member, plugins[index].2 != nil { + plugins[index].2!.append(member) + } else { + plugins[index].2 = nil + } + } else { + plugins.append((key, declaration, member.map { [$0] })) + } + } + func containerIdentity(path: String, source: String, agents: [AgentID]?) throws -> Data { + try JSONEncoder().encode([source, path] + (agents ?? []).map(\.rawValue)) + } + } + + private static func referenceIdentity(_ value: ComponentReferenceDeclaration) throws -> Data { + Data(try ResolvedLedgerCodec.bytes(LedgerPayload.reference(value))) + } + + /// Runs the adapter inside an owned, freshly verified snapshot. No borrowed path is returned. + package func conversion( + keys: Set, bindings: [String: RuntimeBinding], sources: [String: SourceDeclaration], + content: [String: String], store: StateStore + ) throws -> (Declaration, SourceImportProposal) { + guard let imported = importDocument else { + throw CoreError.invalidState("not an importer catalog") + } + let budget = LinkBudget() + let policy = try SourcePolicySnapshot(store: store) + return try SourceResolutionSession.withTemporaryRead( + store: store, sourcePolicy: policy.effective + ) { session in + let view: SourceSnapshot + if try source.requirement != nil || session.isGitSource(source) { + guard + let pin = try session.candidates( + for: source, requirements: [source.requirement], spending: budget.step + ).first + else { + throw CoreError.invalidSource("source has no matching revision") + } + view = try session.snapshot(source, at: pin) + } else { + view = try session.localSnapshot(source) + } + try budget.snapshot(view.snapshot) + guard view.snapshot == snapshot, try FileHash.folderHash(view.directory()) == contentHash + else { + throw CoreError.invalidState("catalog source changed; refresh inspection") + } + let document = try view.relativePath( + PathSafety.resolvedChild(base: view.directory(), subpath: imported.document)) + var input = SourceImportInput( + profile: imported.profile, root: view.root, document: document, + selection: keys, sourceDeclarations: sources, installedSkills: content) + input.bindingReferences = bindings + var proposal = try SourceImport.preview(input) + guard proposal.diagnostics.isEmpty, proposal.bindings.isEmpty, + !proposal.resources.contains(where: { + $0.selected + && ($0.requiresBindingRewrite + || ($0.producerIntegrity != nil && $0.observedHash == nil)) + }) + else { + throw CoreError.invalidState( + "import has unresolved conversion, binding or preserved resource requirements") + } + var declaration = Declaration() + for index in proposal.sources.indices { + let imported = proposal.sources[index] + guard var coordinate = imported.declaration else { + throw CoreError.invalidSource("import lacks canonical source coordinates") + } + if coordinate.kind == .local { + let local = coordinate.localURL( + environment: .init( + projectDirectory: view.root, homeDirectory: view.root, environment: [:])) + let relative = try view.relativePath(local) + coordinate = source + coordinate.path = relative + if let pin = view.pin { coordinate.requirement = .revision(pin.revision) } + coordinate.environment = source.environment + } + declaration.sourceDeclarations.append(.init(name: imported.alias, source: coordinate)) + proposal.sources[index] = .init( + alias: imported.alias, origin: imported.origin, declaration: coordinate, + pin: imported.pin, requestedRef: imported.requestedRef, producerPath: nil, + producerIdentity: imported.producerIdentity, registry: imported.registry, + resolvedRef: imported.resolvedRef, resolvedURL: imported.resolvedURL, + developmentOnly: imported.developmentOnly) + } + declaration.components = proposal.components.map(\.declaration) + try policy.validate() + return (declaration, proposal) + } + } +} diff --git a/Sources/NativeDocuments/JSONParser.swift b/Sources/NativeDocuments/JSONParser.swift new file mode 100644 index 0000000..18f6908 --- /dev/null +++ b/Sources/NativeDocuments/JSONParser.swift @@ -0,0 +1,190 @@ +import Foundation + +struct JSONParser { + let bytes: [UInt8] + let format: NativeDocumentFormat + let budget: NativeDocumentBudget + var i: Int = 0 + var comments: [Range] = [] + var allowsComments: Bool { if case .jsonc = format { true } else { false } } + var trailing: Bool { if case .jsonc(let allowed) = format { allowed } else { false } } + + mutating func parse() throws -> Node { + if bytes.starts(with: [0xef, 0xbb, 0xbf]) { i = 3 } + try trivia() + let node = try value(depth: 0) + try trivia() + guard i == bytes.count else { throw invalid() } + return node + } + func invalid() -> NativeDocumentError { + .invalidDocument(code: "jsonSyntax", range: i.. (String, Range) { + let start = i + guard i < bytes.count, bytes[i] == 34 else { throw invalid() } + i += 1 + while i < bytes.count { + try budget.step() + let ch = bytes[i] + i += 1 + if ch == 34 { + try budget.allocate(i - start, stage: "decoded string") + let data = Data(bytes[start.. Node { + try budget.node(depth: depth) + try trivia() + guard i < bytes.count else { throw invalid() } + let start = i + switch bytes[i] { + case 123, 91: + let object = bytes[i] == 123 + let close: UInt8 = object ? 125 : 93 + let node = Node(object ? .object : .array) + node.inline = true + i += 1 + try trivia() + if i < bytes.count && bytes[i] == close { + i += 1 + node.range = start..? + if object { + let parsedKey = try string() + key = parsedKey.0 + keyRange = parsedKey.1 + guard try node.member(key, budget: budget) == nil else { + throw NativeDocumentError.invalidDocument(code: "duplicateKey", range: entryStart..? + if i < bytes.count && bytes[i] == 44 { + comma = i..= 49 && bytes[i] <= 57 else { throw invalid() } + try digits() + } + var decimal = false + if i < bytes.count && bytes[i] == 46 { + decimal = true + i += 1 + try requiredDigits() + } + if i < bytes.count && [69, 101].contains(bytes[i]) { + decimal = true + i += 1 + if i < bytes.count && [43, 45].contains(bytes[i]) { i += 1 } + try requiredDigits() + } + try budget.allocate(i - start, stage: "numeric lexeme") + let raw = String(decoding: bytes[start..= 48 && bytes[i] <= 57 { + try budget.step() + i += 1 + } + } + mutating func requiredDigits() throws { + let start = i + try digits() + guard i > start else { throw invalid() } + } +} diff --git a/Sources/NativeDocuments/Model.swift b/Sources/NativeDocuments/Model.swift new file mode 100644 index 0000000..92bb7db --- /dev/null +++ b/Sources/NativeDocuments/Model.swift @@ -0,0 +1,298 @@ +import AgentsCore +import Foundation +import TOMLSemantics + +package enum NativeDocumentFormat: Equatable { + case json + case jsonc(trailingCommas: Bool) + case toml +} + +package enum NativeDocumentError: Error, CustomStringConvertible { + package var description: String { + switch self { + case .invalidDocument(let code, _): "Invalid native document (\(code))." + case .ownershipMismatch: "Native region ownership does not match." + case .unsupportedEdit(let reason, _, _): "Unsupported native edit (\(reason))." + case .unrepresentableValue: "Value is not representable in the native format." + case .budgetExceeded(let stage): "Native document budget exceeded (\(stage))." + case .cancelled: "Native document operation cancelled." + } + } + case invalidDocument(code: String, range: Range?) + case ownershipMismatch(NativeRegion) + case unsupportedEdit(NativeUnsupportedEdit, NativeRegion, [Range]) + case unrepresentableValue(NativeDocumentFormat, NativeRegion, String) + case budgetExceeded(String) + case cancelled +} + +package enum NativeUnsupportedEdit { + case syntaxNotLocated, ambiguousOccurrence, ambiguousTrivia, wouldRewriteUnownedStructure, + overlappingEdits +} + +package struct NativeRegion: Equatable { + package let steps: [NativePathStep] + package init(_ steps: [NativePathStep]) { self.steps = steps } + package init(keys: [String]) { steps = keys.map(NativePathStep.key) } + package static func == (lhs: Self, rhs: Self) -> Bool { lhs.steps == rhs.steps } +} + +package enum NativePathStep: Equatable { + case key(String) + case occurrence(NativeOccurrenceEvidence) + package static func == (a: Self, b: Self) -> Bool { + switch (a, b) { + case (.key(let x), .key(let y)): return x.utf8.elementsEqual(y.utf8) + case (.occurrence(let x), .occurrence(let y)): return x == y + default: return false + } + } +} + +package struct NativeOccurrenceEvidence: Equatable { + package let idKey: String? + package let id: String? + /// Ephemeral semantic fingerprints contain value bytes and never grant adoption. + /// Keep the complete occurrence evidence in the current private operation; persisted + /// positions use versioned array digests or D-validated opaque private array tokens. + package let snapshot: Data? + /// Insertion ownership pins the complete semantic array and its position. Changed arrays + /// require fresh evidence from an authorized same-snapshot prepare, never duplicate reselection. + package let arraySnapshot: Data? + package let ordinal: Int? + package let previous: Data? + package let next: Data? + package init(idKey: String, id: String) { + self.idKey = idKey + self.id = id + snapshot = nil + arraySnapshot = nil + ordinal = nil + previous = nil + next = nil + } + package init( + snapshot: Data, ordinal: Int, previous: Data?, next: Data?, arraySnapshot: Data? = nil + ) { + idKey = nil + id = nil + self.snapshot = snapshot + self.arraySnapshot = arraySnapshot + self.ordinal = ordinal + self.previous = previous + self.next = next + } + package static func == (a: Self, b: Self) -> Bool { + func same(_ x: String?, _ y: String?) -> Bool { + switch (x, y) { + case (.some(let x), .some(let y)): x.utf8.elementsEqual(y.utf8) + case (.none, .none): true + default: false + } + } + return same(a.idKey, b.idKey) && same(a.id, b.id) && a.snapshot == b.snapshot + && a.arraySnapshot == b.arraySnapshot && a.ordinal == b.ordinal && a.previous == b.previous + && a.next == b.next + } +} + +package enum NativeProjectionFailure { + case canonicalKeyCollision + case nativeType(String) +} + +package struct NativeObservation { + package let region: NativeRegion + package let value: NativeValue? + package let nativeKind: String + package let numericLexeme: String? + package let projectionFailure: NativeProjectionFailure? + package let valueRange: Range? + package let entryRanges: [Range] + package let occurrences: [NativeOccurrenceEvidence] + let fingerprint: Data +} + +package enum NativeExpectedRegion { + case absent + case owned(NativeObservation) + /// Creation evidence authorizes only empty, comment-safe pruning, never a put. + case createdContainer(NativeObservation) +} + +package enum NativeRegionEdit { + case put(region: NativeRegion, expected: NativeExpectedRegion, value: NativeValue) + case remove(region: NativeRegion, expected: NativeExpectedRegion) + /// Appends a distinct occurrence even when an equal unmanaged value exists. The precondition + /// observes the original array, or its absence. Several appends retain caller order. + case append(region: NativeRegion, expected: NativeExpectedRegion, value: NativeValue) + /// The caller must hold durable creation authority for this object or array. The observation + /// must match the preimage; removal is conditional on emptiness after all descendant edits. + /// Unowned comments or ambiguous removal syntax retain the container. + case pruneCreatedContainer(region: NativeRegion, observed: NativeObservation) + var region: NativeRegion { + switch self { + case .put(let r, _, _), .append(let r, _, _), .remove(let r, _), + .pruneCreatedContainer(let r, _): + r + } + } + var expected: NativeExpectedRegion { + switch self { + case .put(_, let e, _), .append(_, let e, _), .remove(_, let e): e + case .pruneCreatedContainer(_, let observation): .createdContainer(observation) + } + } + var isAppend: Bool { + if case .append = self { true } else { false } + } + var isConditionalPrune: Bool { + if case .pruneCreatedContainer = self { true } else { false } + } +} + +/// Versioned native semantics, not a NativeValue projection. The caller decides whether +/// this digest is public-safe; private-array digests belong only in D's private receipt. +package struct NativeArrayDigest: Equatable, CustomStringConvertible, CustomDebugStringConvertible { + package static let currentFormat = "native-array@1" + package let format: String + package let digest: String + package init(format: String, digest: String) { + self.format = format + self.digest = digest + } + package var description: String { "Native array semantic evidence." } + package var debugDescription: String { description } +} + +/// Index refers to the caller's retaining observations. Nil means that the admitted edit +/// removed the region or replaced its ancestry, so its old authority cannot be rematched. +package struct NativeRegionRemap { + package let index: Int + package let observation: NativeObservation? +} + +/// Index refers to trackingArrays. A present final region/digest does not confer ownership. +/// Only canRetainToken proves unchanged structure, durable address and exact semantics. +/// All fields remain private-operation evidence until E/D classify and encode them. +package struct NativeArrayTransition { + package let index: Int + package let region: NativeRegion? + package let digest: NativeArrayDigest? + package let canRetainToken: Bool +} + +package struct PreparedNativeChange { + package let bytes: Data + package let changedRegions: [NativeRegion] + package let observations: [NativeObservation] + package let createdContainers: [NativeRegion] + /// Input edit index associates each inserted owner with its final, rematchable observation. + package let appendedOccurrences: [NativeAppendedOccurrence] + package let survivingRegions: [NativeRegionRemap] + package let arrayTransitions: [NativeArrayTransition] +} + +package struct NativeAppendedOccurrence { + package let editIndex: Int + package let observation: NativeObservation +} + +struct Member { + var key: String + var node: Node + var entry: Range? + var comma: Range? + var keyRange: Range? = nil +} + +final class Node { + enum Kind: String { case object, array, string, integer, decimal, boolean, null, atom } + // Parsed document nodes are immutable; expected edit copies never inherit this cache. + var cachedArrayDigest: NativeArrayDigest? + var kind: Kind + var text: String + var raw: String + var atomType: String? + var range: Range? + var entry: Range? + var members: [Member] = [] + var elements: [Node] = [] + var headers: [Range] = [] + var insertion: Int? + var inline = false + // Dotted descendants own entries inside these braces, not a separately extensible table. + weak var enclosingInline: Node? + var inlineKeyPath: [String] = [] + var aot = false + var syntaxLocated = false + var commas: [Range] = [] + init(_ kind: Kind, text: String = "", raw: String = "", range: Range? = nil) { + self.kind = kind + self.text = text + self.raw = raw + self.range = range + } + func member(_ key: String, budget: NativeDocumentBudget) throws -> Int? { + for i in members.indices { + try budget.step() + if try budget.equal(members[i].key, key) { return i } + } + return nil + } + func inlineEntries(_ budget: NativeDocumentBudget) throws -> [(parent: Node, index: Int)] { + var result: [(parent: Node, index: Int)] = [] + func collect(_ node: Node, depth: Int) throws { + try budget.enter(depth) + for i in node.members.indices { + try budget.step() + if node.members[i].entry != nil { + try budget.allocate(1, stage: "inline entries") + result.append((node, i)) + } else { + try collect(node.members[i].node, depth: depth + 1) + } + } + } + try collect(self, depth: 0) + try budget.allocate(result.count, stage: "inline entry order") + return try result.sorted { + try budget.step() + return $0.parent.members[$0.index].entry!.lowerBound + < $1.parent.members[$1.index].entry!.lowerBound + } + } + func copy(_ budget: NativeDocumentBudget, depth: Int = 0) throws -> Node { + try budget.node(depth: depth) + let result = Node(kind, text: text, raw: raw, range: range) + result.entry = entry + result.atomType = atomType + result.headers = headers + result.insertion = insertion + result.inline = inline + result.aot = aot + result.syntaxLocated = syntaxLocated + result.commas = commas + for member in members { + try budget.allocate(1, stage: "expected member") + result.members.append( + Member( + key: member.key, node: try member.node.copy(budget, depth: depth + 1), + entry: member.entry, comma: member.comma, keyRange: member.keyRange)) + } + for element in elements { result.elements.append(try element.copy(budget, depth: depth + 1)) } + return result + } +} + +func translated(_ body: () throws -> T) throws -> T { + do { return try body() } catch SemanticBudget.Failure.exceeded(let stage) { + throw NativeDocumentError.budgetExceeded(stage) + } catch SemanticBudget.Failure.cancelled { throw NativeDocumentError.cancelled } catch let error + as NativeDocumentError + { throw error } catch { + throw NativeDocumentError.invalidDocument(code: "invalidSyntaxOrValue", range: nil) + } +} diff --git a/Sources/NativeDocuments/NativeDocument.swift b/Sources/NativeDocuments/NativeDocument.swift new file mode 100644 index 0000000..edf0d8d --- /dev/null +++ b/Sources/NativeDocuments/NativeDocument.swift @@ -0,0 +1,870 @@ +import AgentsCore +import Foundation +import TOMLSemantics + +package typealias NativeDocumentBudget = SemanticBudget + +package struct NativeDocument { + package let bytes: Data + package let format: NativeDocumentFormat + let budget: NativeDocumentBudget + let root: Node + let source: [UInt8] + let comments: [Range] + let located: Bool + + package init(bytes: Data, format: NativeDocumentFormat, budget: NativeDocumentBudget) throws { + self = try translated { + try budget.allocate(bytes.count, stage: "input bytes") + // Admission and cooperative work precede copies, decoder and parser construction. + for _ in bytes { try budget.step() } + try budget.allocate(bytes.count, stage: "UTF8 validation") + guard String(data: bytes, encoding: .utf8) != nil else { + throw NativeDocumentError.invalidDocument(code: "utf8", range: nil) + } + let source = Array(bytes) + let root: Node + let comments: [Range] + let located: Bool + if format == .toml { + var parser = TOMLIndex(bytes: source, budget: budget) + root = try parser.parse() + comments = parser.comments + located = parser.located + } else { + var parser = JSONParser(bytes: source, format: format, budget: budget) + root = try parser.parse() + comments = parser.comments + located = true + } + return Self( + bytes: bytes, format: format, budget: budget, root: root, source: source, + comments: comments, located: located) + } + } + + private init( + bytes: Data, format: NativeDocumentFormat, budget: NativeDocumentBudget, root: Node, + source: [UInt8], comments: [Range], located: Bool + ) { + self.bytes = bytes + self.format = format + self.budget = budget + self.root = root + self.source = source + self.comments = comments + self.located = located + } + + package func read(_ region: NativeRegion) throws -> NativeObservation? { + try translated { + guard let node = try resolve(region, on: root) else { return nil } + return try observation(node, region: region) + } + } + + /// Hashes the full native array with bounded, versioned semantics. No value-bearing + /// fingerprint bytes escape this operation; callers must keep private digests private. + package func arrayDigest(_ region: NativeRegion) throws -> NativeArrayDigest { + try translated { + guard let array = try resolve(region, on: root), array.kind == .array else { + throw NativeDocumentError.ownershipMismatch(region) + } + return try array.arrayDigest(budget) + } + } + + /// Validates the entire same-preimage array before selecting any persisted ordinal. + /// Returned selectors contain private snapshots and remain ephemeral, never ledger data. + package func validatedOccurrences( + in region: NativeRegion, matching digest: NativeArrayDigest, ordinals: [Int] + ) throws -> [NativeRegion] { + try translated { + try budget.check() + guard digest.format.utf8.elementsEqual(NativeArrayDigest.currentFormat.utf8), + digest.digest.utf8.count == 64, + digest.digest.utf8.allSatisfy({ (48...57).contains($0) || (97...102).contains($0) }), + let array = try resolve(region, on: root), array.kind == .array, + try array.arrayDigest(budget) == digest + else { throw NativeDocumentError.ownershipMismatch(region) } + for ordinal in ordinals { + try budget.step() + guard ordinal >= 0 && ordinal < array.elements.count else { + throw NativeDocumentError.ownershipMismatch(region) + } + } + let snapshot = try array.fingerprint(budget) + var result: [NativeRegion] = [] + for ordinal in ordinals { + try budget.allocate(region.steps.count + 2, stage: "validated occurrence") + let evidence = try insertionEvidence(in: array, ordinal: ordinal, arraySnapshot: snapshot) + result.append(NativeRegion(region.steps + [.occurrence(evidence)])) + } + return result + } + } + + /// retaining contains fresh, already authorized observations; trackingArrays contains + /// every admitted receipt array, including foreign scopes. Neither input grants authority. + package func prepare( + _ edits: [NativeRegionEdit], retaining: [NativeObservation] = [], + trackingArrays: [NativeRegion] = [] + ) throws -> PreparedNativeChange { + try translated { + try budget.check() + var addresses: [[AddressStep]] = [] + for edit in edits { + guard !edit.region.steps.isEmpty else { + throw NativeDocumentError.unsupportedEdit(.wouldRewriteUnownedStructure, edit.region, []) + } + let address = try address(edit.region) + for (index, previous) in addresses.enumerated() { + try budget.step(address.reduce(0) { $0 + $1.work } + previous.reduce(0) { $0 + $1.work }) + let conditionalAncestor = + (edit.isConditionalPrune && previous.count > address.count + && previous.starts(with: address)) + || (edits[index].isConditionalPrune && address.count > previous.count + && address.starts(with: previous)) + let orderedAppend = + (edit.isAppend && previous.starts(with: address) + && (previous.count > address.count || edits[index].isAppend)) + || (edits[index].isAppend && address.count > previous.count + && address.starts(with: previous)) + if !conditionalAncestor && !orderedAppend + && (address.starts(with: previous) || previous.starts(with: address)) + { + throw NativeDocumentError.unsupportedEdit(.overlappingEdits, edit.region, []) + } + } + let existing = try resolve(edit.region, on: root) + if edit.isAppend, let existing, existing.kind != .array { + throw NativeDocumentError.ownershipMismatch(edit.region) + } + if case .createdContainer = edit.expected { + if edit.isConditionalPrune { + guard let existing, existing.kind == .object || existing.kind == .array else { + throw NativeDocumentError.ownershipMismatch(edit.region) + } + } else { + guard case .remove = edit, let existing, existing.kind == .object, + existing.members.isEmpty + else { throw NativeDocumentError.ownershipMismatch(edit.region) } + } + } + switch edit.expected { + case .absent: + guard existing == nil else { throw NativeDocumentError.ownershipMismatch(edit.region) } + case .owned(let observation), .createdContainer(let observation): + try budget.step(observation.fingerprint.count) + guard let existing, try sameRegion(observation.region, edit.region), + try existing.fingerprint(budget) == observation.fingerprint + else { throw NativeDocumentError.ownershipMismatch(edit.region) } + } + addresses.append(address) + } + var retainedAddresses: [[AddressStep]] = [] + for observation in retaining { + try budget.step(observation.fingerprint.count) + guard let node = try resolve(observation.region, on: root), + try node.fingerprint(budget) == observation.fingerprint + else { throw NativeDocumentError.ownershipMismatch(observation.region) } + try budget.allocate(1, stage: "retained region address") + retainedAddresses.append(try address(observation.region)) + } + var arrayAddresses: [[AddressStep]] = [] + var arrayDigests: [NativeArrayDigest] = [] + for region in trackingArrays { + let path = try address(region) + for previous in arrayAddresses { + try budget.step(path.reduce(0) { $0 + $1.work } + previous.reduce(0) { $0 + $1.work }) + guard path != previous else { throw NativeDocumentError.ownershipMismatch(region) } + } + guard let array = try resolve(region, on: root), array.kind == .array else { + throw NativeDocumentError.ownershipMismatch(region) + } + try budget.allocate(path.count + 2, stage: "tracked array") + arrayAddresses.append(path) + arrayDigests.append(try array.arrayDigest(budget)) + } + if !edits.isEmpty && !located { + throw NativeDocumentError.unsupportedEdit(.syntaxNotLocated, edits[0].region, []) + } + var current = self + var changed: [NativeRegion] = [] + var created: [(region: NativeRegion, address: [AddressStep])] = [] + var observed: [Int] = [] + var appended: [(editIndex: Int, ordinal: Int)] = [] + var removed: [([AddressStep], Int)] = [] + var effects: [(address: [AddressStep], removal: Bool, append: Bool)] = [] + try budget.allocate(edits.count, stage: "native edit order") + var prunes: [Int] = [] + var appends: [Int] = [] + var order: [Int] = [] + for index in edits.indices { + try budget.step() + if edits[index].isConditionalPrune { + prunes.append(index) + } else if edits[index].isAppend { + appends.append(index) + } else { + order.append(index) + } + } + try prunes.sort { + try budget.step() + return addresses[$0].count == addresses[$1].count + ? $0 < $1 : addresses[$0].count > addresses[$1].count + } + try budget.allocate(prunes.count, stage: "conditional prune order") + order.append(contentsOf: appends) + order.append(contentsOf: prunes) + for editIndex in order { + let edit = edits[editIndex] + try budget.step() + let effective = try current.region(edit.region, at: addresses[editIndex], removed: removed) + let old = try current.resolve(effective, on: current.root) + if edit.isConditionalPrune { + guard let old else { + // Dotted TOML parents can disappear with their last owned entry. + changed.append(edit.region) + continue + } + guard + (old.kind == .object && old.members.isEmpty) + || (old.kind == .array && old.elements.isEmpty) + else { continue } + if try current.hasComments(old) { continue } + } + let desired: Node? + var appendedValue: Node? + switch edit { + case .put(_, _, let value), .append(_, _, let value): + let text = try NativeRenderer(format: format, budget: budget, region: edit.region).render( + value) + if format == .toml { + let parsed = try NativeDocument( + bytes: Data(("value = " + text).utf8), format: .toml, budget: budget) + appendedValue = parsed.root.members.first?.node + } else { + let parsed = try NativeDocument(bytes: Data(text.utf8), format: .json, budget: budget) + appendedValue = parsed.root + } + if edit.isAppend { + guard let element = appendedValue else { + throw NativeDocumentError.ownershipMismatch(edit.region) + } + if old == nil { try budget.node(depth: effective.steps.count) } + let array = try old?.copy(budget) ?? Node(.array) + try budget.allocate(1, stage: "appended occurrence") + array.elements.append(element) + desired = array + } else { + desired = appendedValue + appendedValue = nil + } + case .remove, .pruneCreatedContainer: + desired = nil + } + if let old, let desired, try old.equal(to: desired, budget: budget) { + observed.append(editIndex) + continue + } + guard old != nil || desired != nil else { + throw NativeDocumentError.ownershipMismatch(edit.region) + } + if let old, desired == nil, old.kind == .object && old.members.isEmpty { + guard case .createdContainer = edit.expected else { + throw NativeDocumentError.ownershipMismatch(edit.region) + } + guard try !current.hasComments(old) else { + throw NativeDocumentError.unsupportedEdit(.ambiguousTrivia, edit.region, old.headers) + } + } + var editCreated: [NativeRegion] = [] + if edit.isAppend && old == nil { + try budget.allocate(effective.steps.count + 1, stage: "created array evidence") + editCreated.append(effective) + } + try current.createdObjects( + old: old, new: desired, path: effective.steps, into: &editCreated) + let expected = try current.root.copy(budget) + try current.change( + expected, steps: effective.steps[...], desired: desired, region: effective, + created: &editCreated) + var editor = PatchBuilder(document: current, region: effective) + let checked: NativeDocument + do { + if let appendedValue, old != nil { + try editor.appendOccurrence(appendedValue, path: effective.steps) + } else if let old, let desired { + try editor.diff(old, desired: desired, path: effective.steps) + } else if let old { + try editor.remove(old, path: effective.steps) + } else if let desired { + try editor.insert(path: effective.steps, value: desired, root: current.root) + } + let candidate = try editor.apply() + checked = try NativeDocument(bytes: candidate, format: format, budget: budget) + } catch NativeDocumentError.invalidDocument { + if edit.isConditionalPrune { continue } + throw NativeDocumentError.unsupportedEdit( + .wouldRewriteUnownedStructure, edit.region, editor.patches.map(\.range)) + } catch NativeDocumentError.unsupportedEdit(let reason, _, _) + where edit.isConditionalPrune + && [.ambiguousTrivia, .syntaxNotLocated, .wouldRewriteUnownedStructure].contains(reason) + { + continue + } + var nextRemoved = removed + if desired == nil, case .element(let ordinal) = addresses[editIndex].last { + try budget.allocate(removed.count + 1, stage: "removed occurrence addresses") + try budget.allocate(addresses[editIndex].count, stage: "removed occurrence path") + nextRemoved.append((Array(addresses[editIndex].dropLast()), ordinal)) + } + try current.removeVanishedContainers( + expected, checked: checked, edits: edits, prunes: prunes, addresses: addresses, + removed: nextRemoved) + guard try checked.root.equal(to: expected, budget: budget) else { + if edit.isConditionalPrune { continue } + throw NativeDocumentError.unsupportedEdit( + .wouldRewriteUnownedStructure, edit.region, editor.patches.map(\.range)) + } + // Creation paths share the admitted edit's original address. Any suffix is a + // newly created object member, so no snapshot selector is reselected by value. + for container in editCreated { + let shared = min(container.steps.count, edit.region.steps.count) + try budget.allocate(container.steps.count * 2 + 1, stage: "created container address") + var address = Array(addresses[editIndex].prefix(shared)) + let suffix = container.steps.dropFirst(shared) + for step in suffix { + guard case .key(let key) = step else { + throw NativeDocumentError.ownershipMismatch(container) + } + try budget.allocate(key.utf8.count, stage: "created member address") + address.append(.key(Data(key.utf8))) + } + created.append((NativeRegion(Array(edit.region.steps.prefix(shared)) + suffix), address)) + } + if edit.isAppend { + var ordinal = old?.elements.count ?? 0 + for (path, _) in removed { + try budget.step(path.reduce(0) { $0 + $1.work }) + if path == addresses[editIndex] { ordinal += 1 } + } + try budget.allocate(1, stage: "insertion identity") + appended.append((editIndex, ordinal)) + } else if desired != nil { + observed.append(editIndex) + } + try budget.allocate(addresses[editIndex].count + 1, stage: "native structural transition") + effects.append((addresses[editIndex], desired == nil, edit.isAppend)) + removed = nextRemoved + current = checked + changed.append(edit.region) + } + var observations: [NativeObservation] = [] + for index in observed { + let region = try current.region(edits[index].region, at: addresses[index], removed: removed) + if let node = try current.resolve(region, on: current.root) { + observations.append(try current.observation(node, region: region)) + } + } + var appendedOccurrences: [NativeAppendedOccurrence] = [] + for insertion in appended { + let index = insertion.editIndex + let parent = try current.region(edits[index].region, at: addresses[index], removed: removed) + guard let array = try current.resolve(parent, on: current.root) else { + throw NativeDocumentError.ownershipMismatch(parent) + } + var ordinal = insertion.ordinal + for (path, _) in removed { + try budget.step(path.reduce(0) { $0 + $1.work }) + if path == addresses[index] { ordinal -= 1 } + } + guard ordinal >= 0 && ordinal < array.elements.count else { + throw NativeDocumentError.ownershipMismatch(parent) + } + let evidence = try current.insertionEvidence(in: array, ordinal: ordinal) + let region = NativeRegion(parent.steps + [.occurrence(evidence)]) + try budget.allocate(region.steps.count + 1, stage: "insertion observation") + appendedOccurrences.append( + NativeAppendedOccurrence( + editIndex: index, + observation: try current.observation(array.elements[ordinal], region: region))) + } + var createdContainers: [NativeRegion] = [] + for container in created { + var deleted = false + for (parent, ordinal) in removed { + try budget.step(parent.reduce(0) { $0 + $1.work } + container.address.count) + if container.address.count > parent.count, + container.address.starts(with: parent), + container.address[parent.count] == .element(ordinal) + { + deleted = true + break + } + } + if deleted { continue } + let region = try current.region( + container.region, at: container.address, removed: removed) + if try current.resolve(region, on: current.root) != nil { + try budget.allocate(region.steps.count + 1, stage: "final created container evidence") + createdContainers.append(region) + } + } + var survivingRegions: [NativeRegionRemap] = [] + for (index, observation) in retaining.enumerated() { + let path = retainedAddresses[index] + let lost = try effects.contains { effect in + try budget.step( + path.reduce(0) { $0 + $1.work } + effect.address.reduce(0) { $0 + $1.work }) + return !effect.append && path.starts(with: effect.address) + && (effect.removal || path.count > effect.address.count) + } + var final: NativeObservation? + if !lost { + let region = try current.region( + observation.region, at: path, removed: removed, anchored: true) + if let node = try current.resolve(region, on: current.root) { + final = try current.observation(node, region: region) + } + } + try budget.allocate(1, stage: "surviving region remap") + survivingRegions.append(.init(index: index, observation: final)) + } + var arrayTransitions: [NativeArrayTransition] = [] + for (index, original) in trackingArrays.enumerated() { + let path = arrayAddresses[index] + var removedAncestor = false + var touched = false + for effect in effects { + try budget.step( + path.reduce(0) { $0 + $1.work } + effect.address.reduce(0) { $0 + $1.work }) + let ancestor = path.starts(with: effect.address) + let ancestorAppend = ancestor && effect.append && effect.address.count < path.count + if (ancestor && !ancestorAppend) || effect.address.starts(with: path) { touched = true } + if ancestor && effect.removal { removedAncestor = true } + } + var region: NativeRegion? + var digest: NativeArrayDigest? + var sameAddress = true + if !removedAncestor { + let final: NativeRegion? + do { + final = try current.region(original, at: path, removed: removed, anchored: true) + } catch NativeDocumentError.ownershipMismatch { + final = nil + } + if let final, let node = try current.resolve(final, on: current.root), node.kind == .array + { + region = final + digest = try node.arrayDigest(budget) + let finalAddress = try current.address(final) + for (stepIndex, step) in original.steps.enumerated() { + if case .occurrence(let evidence) = step, evidence.idKey != nil { + if step != final.steps[stepIndex] { sameAddress = false } + } else if path[stepIndex] != finalAddress[stepIndex] { + sameAddress = false + } + } + } + } + try budget.allocate(1, stage: "array transition result") + arrayTransitions.append( + .init( + index: index, region: region, digest: digest, + canRetainToken: region != nil && !touched && sameAddress + && digest == arrayDigests[index])) + } + return PreparedNativeChange( + bytes: current.bytes, changedRegions: changed, observations: observations, + createdContainers: createdContainers, appendedOccurrences: appendedOccurrences, + survivingRegions: survivingRegions, arrayTransitions: arrayTransitions) + } + } + + /// A dotted TOML object has no independent syntax to retain after its last entry goes away. + /// Only explicitly authorized conditional containers may disappear from the expected tree. + private func removeVanishedContainers( + _ expected: Node, checked: NativeDocument, edits: [NativeRegionEdit], prunes: [Int], + addresses: [[AddressStep]], removed: [([AddressStep], Int)] + ) throws { + guard format == .toml else { return } + for index in prunes { + try budget.step() + var deleted = false + for (parent, ordinal) in removed { + try budget.step( + parent.reduce(0) { $0 + $1.work } + addresses[index].reduce(0) { $0 + $1.work }) + if addresses[index].count > parent.count, + addresses[index].prefix(parent.count).elementsEqual(parent), + addresses[index][parent.count] == .element(ordinal) + { + deleted = true + break + } + } + if deleted { continue } + let original = edits[index].region + let region: NativeRegion + do { + region = try self.region(original, at: addresses[index], removed: removed, on: expected) + } catch NativeDocumentError.ownershipMismatch { + // An earlier conditional prune may already have removed an enclosing occurrence. + continue + } + guard let node = try resolve(region, on: expected), node.kind == .object, + node.members.isEmpty, node.range == nil, node.headers.isEmpty, node.entry == nil + else { continue } + let actual = try checked.region(original, at: addresses[index], removed: removed) + guard try checked.resolve(actual, on: checked.root) == nil else { continue } + var created: [NativeRegion] = [] + try change( + expected, steps: region.steps[...], desired: nil, region: region, created: &created) + } + } + + private func sameRegion(_ a: NativeRegion, _ b: NativeRegion) throws -> Bool { + guard a.steps.count == b.steps.count else { return false } + for (a, b) in zip(a.steps, b.steps) { + switch (a, b) { + case (.key(let a), .key(let b)): if try !budget.equal(a, b) { return false } + case (.occurrence(let a), .occurrence(let b)): + let aSize = + (a.idKey?.utf8.count ?? 0) + (a.id?.utf8.count ?? 0) + (a.snapshot?.count ?? 0) + + (a.arraySnapshot?.count ?? 0) + + (a.previous?.count ?? 0) + (a.next?.count ?? 0) + let bSize = + (b.idKey?.utf8.count ?? 0) + (b.id?.utf8.count ?? 0) + (b.snapshot?.count ?? 0) + + (b.arraySnapshot?.count ?? 0) + + (b.previous?.count ?? 0) + (b.next?.count ?? 0) + try budget.step(aSize + bSize + 1) + if a != b { return false } + default: return false + } + } + return true + } + + private enum AddressStep: Equatable { + case key(Data) + case element(Int) + case append(Data, Data) + var work: Int { + switch self { + case .key(let bytes): bytes.count + case .element: 1 + case .append(let key, let id): key.count + id.count + 1 + } + } + } + + private func address(_ region: NativeRegion) throws -> [AddressStep] { + try budget.enter(region.steps.count) + var node: Node? = root + var result: [AddressStep] = [] + for step in region.steps { + try budget.step() + switch step { + case .key(let key): + try budget.allocate(key.utf8.count + 1, stage: "region address") + result.append(.key(Data(key.utf8))) + if let current = node, let i = try current.member(key, budget: budget) { + node = current.members[i].node + } else { + node = nil + } + case .occurrence(let evidence): + guard let current = node else { throw NativeDocumentError.ownershipMismatch(region) } + do { + let i = try occurrence(evidence, in: current, region: region) + result.append(.element(i)) + node = current.elements[i] + } catch NativeDocumentError.ownershipMismatch { + guard current.kind == .array, let key = evidence.idKey, let id = evidence.id, + result.count == region.steps.count - 1 + else { throw NativeDocumentError.ownershipMismatch(region) } + try budget.allocate(key.utf8.count + id.utf8.count + 1, stage: "new occurrence address") + result.append(.append(Data(key.utf8), Data(id.utf8))) + node = nil + } + } + } + return result + } + + /// Addresses refer to the original snapshot. Only removals can shift other owned occurrences. + private func region( + _ original: NativeRegion, at address: [AddressStep], removed: [([AddressStep], Int)], + on startingRoot: Node? = nil, anchored: Bool = false + ) throws -> NativeRegion { + var node: Node? = startingRoot ?? root + var steps: [NativePathStep] = [] + for (index, step) in original.steps.enumerated() { + try budget.step() + switch step { + case .key(let key): + steps.append(step) + if let current = node, let i = try current.member(key, budget: budget) { + node = current.members[i].node + } else { + node = nil + } + case .occurrence(let evidence): + if case .append = address[index] { + steps.append(step) + node = nil + continue + } + guard let current = node, case .element(let ordinal) = address[index] else { + throw NativeDocumentError.ownershipMismatch(original) + } + let prefix = Array(address.prefix(index)) + var shift = 0 + for (parent, deleted) in removed { + try budget.step(prefix.reduce(0) { $0 + $1.work } + parent.reduce(0) { $0 + $1.work }) + if parent == prefix && deleted < ordinal { shift += 1 } + } + let i = ordinal - shift + guard i >= 0 && i < current.elements.count else { + throw NativeDocumentError.ownershipMismatch(original) + } + let element = current.elements[i] + let next: NativeOccurrenceEvidence + if evidence.arraySnapshot != nil || (anchored && evidence.idKey == nil) { + next = try insertionEvidence(in: current, ordinal: i) + } else if let key = evidence.idKey, let m = try element.member(key, budget: budget), + element.members[m].node.kind == .string + { + next = .init(idKey: key, id: element.members[m].node.text) + } else { + next = .init( + snapshot: try element.fingerprint(budget), ordinal: i, + previous: i > 0 ? try current.elements[i - 1].fingerprint(budget) : nil, + next: i + 1 < current.elements.count + ? try current.elements[i + 1].fingerprint(budget) : nil) + } + // Newly ambiguous evidence cannot become a later ownership capability. + guard try occurrence(next, in: current, region: original) == i else { + throw NativeDocumentError.unsupportedEdit(.ambiguousOccurrence, original, []) + } + steps.append(.occurrence(next)) + node = element + } + } + return NativeRegion(steps) + } + + func hasComments(_ node: Node) throws -> Bool { + for comment in comments { + try budget.step() + if let range = node.range, range.overlaps(comment) { return true } + for header in node.headers { + try budget.step() + if comment.lowerBound >= header.lowerBound + && comment.lowerBound < (node.insertion ?? header.upperBound) + { + return true + } + } + } + return false + } + + private func insertionEvidence(in array: Node, ordinal: Int, arraySnapshot: Data? = nil) throws + -> NativeOccurrenceEvidence + { + .init( + snapshot: try array.elements[ordinal].fingerprint(budget), ordinal: ordinal, + previous: ordinal > 0 ? try array.elements[ordinal - 1].fingerprint(budget) : nil, + next: ordinal + 1 < array.elements.count + ? try array.elements[ordinal + 1].fingerprint(budget) : nil, + arraySnapshot: try arraySnapshot ?? array.fingerprint(budget)) + } + + func occurrence(_ evidence: NativeOccurrenceEvidence, in node: Node, region: NativeRegion) throws + -> Int + { + guard node.kind == .array else { throw NativeDocumentError.ownershipMismatch(region) } + if let arraySnapshot = evidence.arraySnapshot { + try budget.step(arraySnapshot.count + (evidence.snapshot?.count ?? 0)) + guard let ordinal = evidence.ordinal, let snapshot = evidence.snapshot, + ordinal >= 0 && ordinal < node.elements.count, + try node.fingerprint(budget) == arraySnapshot, + try node.elements[ordinal].fingerprint(budget) == snapshot + else { throw NativeDocumentError.ownershipMismatch(region) } + return ordinal + } + var matches: [Int] = [] + for (i, element) in node.elements.enumerated() { + try budget.step() + if let key = evidence.idKey, let id = evidence.id, + let m = try element.member(key, budget: budget), element.members[m].node.kind == .string + { + if try budget.equal(element.members[m].node.text, id) { matches.append(i) } + } else if let snapshot = evidence.snapshot { + try budget.step(snapshot.count) + if try element.fingerprint(budget) == snapshot { matches.append(i) } + } + } + if evidence.idKey == nil && matches.count > 1 { + var contextual: [Int] = [] + func same(_ a: Data?, _ b: Data?) throws -> Bool { + switch (a, b) { + case (.some(let a), .some(let b)): + try budget.step(a.count + b.count) + return a == b + case (.none, .none): return true + default: return false + } + } + for i in matches { + let previous = i > 0 ? try node.elements[i - 1].fingerprint(budget) : nil + let next = i + 1 < node.elements.count ? try node.elements[i + 1].fingerprint(budget) : nil + if try same(previous, evidence.previous) && same(next, evidence.next) { + contextual.append(i) + } + } + matches = contextual + } + guard !matches.isEmpty else { throw NativeDocumentError.ownershipMismatch(region) } + guard matches.count == 1, let match = matches.first else { + throw NativeDocumentError.unsupportedEdit(.ambiguousOccurrence, region, []) + } + return match + } + + func resolve(_ region: NativeRegion, on root: Node) throws -> Node? { + var node = root + for step in region.steps { + try budget.step() + switch step { + case .key(let key): + guard node.kind == .object, let i = try node.member(key, budget: budget) else { return nil } + node = node.members[i].node + case .occurrence(let evidence): + do { + node = node.elements[try occurrence(evidence, in: node, region: region)] + } catch NativeDocumentError.ownershipMismatch { return nil } + } + } + return node + } + + private func entryRanges(_ node: Node) throws -> [Range] { + try budget.step() + if let entry = node.entry { + try budget.allocate(1, stage: "observation ranges") + return [entry] + } + try budget.allocate(node.headers.count, stage: "observation ranges") + var ranges = node.headers + for member in node.members { + let children = try entryRanges(member.node) + try budget.allocate(children.count, stage: "observation ranges") + ranges += children + } + for element in node.elements { + let children = try entryRanges(element) + try budget.allocate(children.count, stage: "observation ranges") + ranges += children + } + return ranges + } + + private func observation(_ node: Node, region: NativeRegion) throws -> NativeObservation { + var occurrences: [NativeOccurrenceEvidence] = [] + if node.kind == .array { + var prints: [Data] = [] + for e in node.elements { prints.append(try e.fingerprint(budget)) } + for i in prints.indices { + occurrences.append( + .init( + snapshot: prints[i], ordinal: i, previous: i > 0 ? prints[i - 1] : nil, + next: i + 1 < prints.count ? prints[i + 1] : nil)) + } + } + return NativeObservation( + region: region, value: try node.project(budget), + nativeKind: node.atomType ?? node.kind.rawValue, + numericLexeme: node.kind == .integer || node.kind == .decimal ? node.raw : nil, + projectionFailure: try node.projectionFailure(budget), + valueRange: node.range, entryRanges: try entryRanges(node), + occurrences: occurrences, fingerprint: try node.fingerprint(budget)) + } + + private func createdObjects( + old: Node?, new: Node?, path: [NativePathStep], into result: inout [NativeRegion] + ) throws { + guard let new, new.kind == .object else { return } + try budget.step() + if old?.kind != .object { + try budget.allocate(path.count + 1, stage: "created container evidence") + result.append(NativeRegion(path)) + } + for member in new.members { + let previous = try old?.member(member.key, budget: budget).map { old!.members[$0].node } + try budget.allocate(path.count + 1, stage: "created container path") + try createdObjects( + old: previous, new: member.node, path: path + [.key(member.key)], into: &result) + } + } + + private func change( + _ node: Node, steps: ArraySlice, desired: Node?, region: NativeRegion, + created: inout [NativeRegion], offset: Int = 0 + ) throws { + try budget.enter(offset) + guard let step = steps.first else { throw NativeDocumentError.ownershipMismatch(region) } + let tail = steps.dropFirst() + switch step { + case .key(let key): + guard node.kind == .object else { throw NativeDocumentError.ownershipMismatch(region) } + let m = try node.member(key, budget: budget) + if tail.isEmpty { + if let m { + if let desired { node.members[m].node = desired } else { node.members.remove(at: m) } + } else if let desired { + node.members.append(Member(key: key, node: desired)) + } + } else { + let child: Node + if let m { + child = node.members[m].node + } else { + guard desired != nil else { throw NativeDocumentError.ownershipMismatch(region) } + try budget.node(depth: offset) + child = Node(.object) + node.members.append(Member(key: key, node: child)) + created.append(NativeRegion(Array(region.steps.prefix(offset + 1)))) + } + try change( + child, steps: tail, desired: desired, region: region, created: &created, + offset: offset + 1) + } + case .occurrence(let evidence): + let i: Int + do { i = try occurrence(evidence, in: node, region: region) } catch NativeDocumentError + .ownershipMismatch + { + guard node.kind == .array, tail.isEmpty, let desired, desired.kind == .object, + let key = evidence.idKey, let id = evidence.id, + let field = try desired.member(key, budget: budget), + desired.members[field].node.kind == .string, + try budget.equal(desired.members[field].node.text, id) + else { throw NativeDocumentError.ownershipMismatch(region) } + try budget.allocate(1, stage: "new occurrence") + node.elements.append(desired) + return + } + if tail.isEmpty { + if let desired { node.elements[i] = desired } else { node.elements.remove(at: i) } + } else { + try change( + node.elements[i], steps: tail, desired: desired, region: region, created: &created, + offset: offset + 1) + } + } + } +} diff --git a/Sources/NativeDocuments/NativePromptReadback.swift b/Sources/NativeDocuments/NativePromptReadback.swift new file mode 100644 index 0000000..fcd2979 --- /dev/null +++ b/Sources/NativeDocuments/NativePromptReadback.swift @@ -0,0 +1,25 @@ +import Foundation + +/// A read-only view onto the parser's indexed nodes. This avoids projecting unrelated +/// settings or constructing occurrence fingerprints during prompt field discovery. +package struct NativePromptNode { + fileprivate let node: Node + package var isObject: Bool { node.kind == .object } + package var isArray: Bool { node.kind == .array } + package var string: String? { node.kind == .string ? node.text : nil } + package var sourceRange: Range? { node.range } + package var fields: [(String, Self)] { node.members.map { ($0.key, .init(node: $0.node)) } } + package var elements: [Self] { node.elements.map { .init(node: $0) } } + + package subscript(_ key: String) -> Self? { + node.members.first { $0.key.utf8.elementsEqual(key.utf8) }.map { .init(node: $0.node) } + } +} + +extension NativeDocument { + package var promptRoot: NativePromptNode { .init(node: root) } + + package func promptNode(at region: NativeRegion) throws -> NativePromptNode? { + try resolve(region, on: root).map { .init(node: $0) } + } +} diff --git a/Sources/NativeDocuments/PatchBuilder.swift b/Sources/NativeDocuments/PatchBuilder.swift new file mode 100644 index 0000000..67608f9 --- /dev/null +++ b/Sources/NativeDocuments/PatchBuilder.swift @@ -0,0 +1,612 @@ +import Foundation + +struct BytePatch { + let range: Range + let bytes: [UInt8] +} + +struct PatchBuilder { + struct InlineChange { + let container: Node + var additions: [String] + } + let document: NativeDocument + let region: NativeRegion + var patches: [BytePatch] = [] + var inlineChanges: [InlineChange] = [] + var budget: NativeDocumentBudget { document.budget } + var toml: Bool { document.format == .toml } + var newline: String { + get throws { + var lf = false + var crlf = false + for i in document.source.indices where document.source[i] == 10 { + try budget.step() + if i > 0 && document.source[i - 1] == 13 { crlf = true } else { lf = true } + } + if lf && crlf { throw NativeDocumentError.unsupportedEdit(.ambiguousTrivia, region, []) } + return crlf ? "\r\n" : "\n" + } + } + mutating func patch(_ range: Range, _ text: String = "") throws { + try budget.allocate(text.utf8.count + 1, stage: "patch") + try budget.step(text.utf8.count) + patches.append(BytePatch(range: range, bytes: Array(text.utf8))) + } + func encoded(_ node: Node) throws -> String { + let renderer = NativeRenderer(format: document.format, budget: budget, region: region) + try budget.step() + switch node.kind { + case .string: return try renderer.string(node.text) + case .integer, .decimal, .boolean, .null: return node.raw.isEmpty ? node.text : node.raw + case .array: + var values: [String] = [] + for e in node.elements { values.append(try encoded(e)) } + return try nativeJoin(values, prefix: "[", suffix: "]", separator: ", ", budget: budget) + case .object: + var values: [String] = [] + for m in node.members { + values.append(try renderer.string(m.key) + (toml ? " = " : ": ") + encoded(m.node)) + } + return try nativeJoin(values, prefix: "{", suffix: "}", separator: ", ", budget: budget) + case .atom: + throw NativeDocumentError.unrepresentableValue(document.format, region, "nativeAtom") + } + } + mutating func diff(_ old: Node, desired: Node, path: [NativePathStep]) throws { + if try old.equal(to: desired, budget: budget) { return } + if old.kind == .object && desired.kind == .object { + var retained: [Int] = [] + var added: [Member] = [] + for (i, m) in old.members.enumerated() { + if let next = try desired.member(m.key, budget: budget) { + retained.append(i) + try diff(m.node, desired: desired.members[next].node, path: path + [.key(m.key)]) + } else { + try eraseMember(m, parent: old) + } + } + if toml, let container = old.inline ? old : old.enclosingInline { + try recordInlineChange(in: container) + } else if old.inline && retained.count != old.members.count { + let keepCommas = Set(retained.dropLast().compactMap { old.members[$0].comma?.lowerBound }) + for m in old.members { + if let comma = m.comma, !keepCommas.contains(comma.lowerBound) { try patch(comma) } + } + } + for m in desired.members where try old.member(m.key, budget: budget) == nil { + added.append(m) + } + if !added.isEmpty { + try insertMembers( + added, in: old, path: path, remaining: retained.count, + survivors: retained.map { old.members[$0] }) + } + return + } + if old.kind == .array && desired.kind == .array && old.aot { + if desired.elements.contains(where: { $0.kind != .object }) { + for element in old.elements { try eraseTable(element) } + try arrayAssignment(path: path, rendered: encoded(desired)) + return + } + let common = min(old.elements.count, desired.elements.count) + for i in 0.. common { + try budget.allocate(desired.elements.count - common, stage: "AoT append") + try appendTables(Array(desired.elements.dropFirst(common)), path: path) + } + return + } + guard let range = old.range else { + throw NativeDocumentError.unsupportedEdit(.wouldRewriteUnownedStructure, region, old.headers) + } + if try document.hasComments(old) { + throw NativeDocumentError.unsupportedEdit(.ambiguousTrivia, region, [range]) + } + try patch(range, encoded(desired)) + } + mutating func eraseMember(_ member: Member, parent: Node) throws { + if let entry = member.entry { + if try document.comments.contains(where: { + try budget.step() + return entry.overlaps($0) + }) { + throw NativeDocumentError.unsupportedEdit(.ambiguousTrivia, region, [entry]) + } + try patch(entry) + } else if toml && (!parent.inline || member.node.enclosingInline === parent) { + try eraseTable(member.node) + } else { + throw NativeDocumentError.unsupportedEdit(.syntaxNotLocated, region, []) + } + } + mutating func eraseTable(_ node: Node) throws { + for header in node.headers { try patch(header) } + for m in node.members { + if let entry = m.entry { + if try document.comments.contains(where: { + try budget.step() + return entry.overlaps($0) + }) { + throw NativeDocumentError.unsupportedEdit(.ambiguousTrivia, region, [entry]) + } + try patch(entry) + } else { + try eraseTable(m.node) + } + } + if node.aot { for e in node.elements { try eraseTable(e) } } + } + mutating func remove(_ node: Node, path: [NativePathStep]) throws { + let parentPath = NativeRegion(Array(path.dropLast())) + guard let parent = try document.resolve(parentPath, on: document.root), let last = path.last + else { throw NativeDocumentError.ownershipMismatch(region) } + switch last { + case .key(let key): + guard let i = try parent.member(key, budget: budget) else { + throw NativeDocumentError.ownershipMismatch(region) + } + try eraseMember(parent.members[i], parent: parent) + if toml, let container = parent.inline ? parent : parent.enclosingInline { + try recordInlineChange(in: container) + } else if parent.inline { + if let comma = parent.members[i].comma { + try patch(comma) + } else if i > 0, let comma = parent.members[i - 1].comma { + try patch(comma) + } + } + case .occurrence(let evidence): + let i = try document.occurrence(evidence, in: parent, region: region) + if parent.aot { + try eraseTable(node) + if parent.elements.count == 1 { try arrayAssignment(path: Array(path.dropLast())) } + } else { + guard let range = node.range else { + throw NativeDocumentError.unsupportedEdit(.syntaxNotLocated, region, []) + } + if try document.hasComments(node) { + throw NativeDocumentError.unsupportedEdit(.ambiguousTrivia, region, [range]) + } + try patch(range) + if i < parent.commas.count { + try patch(parent.commas[i]) + } else if i > 0 && i - 1 < parent.commas.count { + try patch(parent.commas[i - 1]) + } + } + } + } + private func entryRemoved(_ member: Member) throws -> Bool { + guard let entry = member.entry else { return false } + return try patches.contains { + try budget.step() + return $0.bytes.isEmpty && $0.range.lowerBound <= entry.lowerBound + && $0.range.upperBound >= entry.upperBound + } + } + private func survivingInlineMembers(in container: Node) throws -> [Member] { + var surviving: [Member] = [] + for entry in try container.inlineEntries(budget) { + let member = entry.parent.members[entry.index] + if try !entryRemoved(member) { + try budget.allocate(1, stage: "inline survivors") + surviving.append(member) + } + } + return surviving + } + private mutating func recordInlineChange(in container: Node, additions: [String] = []) throws { + guard let range = container.range else { + throw NativeDocumentError.unsupportedEdit(.syntaxNotLocated, region, []) + } + for i in inlineChanges.indices { + try budget.step() + if inlineChanges[i].container.range == range { + try budget.allocate(additions.count, stage: "inline additions") + inlineChanges[i].additions.append(contentsOf: additions) + return + } + } + try budget.allocate(additions.count + 1, stage: "inline changes") + inlineChanges.append(InlineChange(container: container, additions: additions)) + } + private mutating func pruneInlineCommas(in container: Node) throws { + let surviving = try survivingInlineMembers(in: container) + for entry in try container.inlineEntries(budget) { + let member = entry.parent.members[entry.index] + if let comma = member.comma, + try entryRemoved(member) || member.entry == surviving.last?.entry + { + try patch(comma) + } + } + } + mutating func insert(path: [NativePathStep], value: Node, root: Node) throws { + var parent = root + var existing: [NativePathStep] = [] + for (i, step) in path.enumerated() { + switch step { + case .occurrence(let evidence): + do { + parent = parent.elements[try document.occurrence(evidence, in: parent, region: region)] + existing.append(step) + } catch NativeDocumentError.ownershipMismatch { + guard i == path.count - 1 else { throw NativeDocumentError.ownershipMismatch(region) } + if parent.aot { + try appendTables([value], path: existing) + } else { + try appendValues([value], in: parent) + } + return + } + case .key(let key): + if let m = try parent.member(key, budget: budget) { + parent = parent.members[m].node + existing.append(step) + continue + } + let remainder = Array(path.dropFirst(i + 1)) + var new = value + for step in remainder.reversed() { + guard case .key(let key) = step else { + throw NativeDocumentError.unsupportedEdit(.ambiguousOccurrence, region, []) + } + try budget.node(depth: remainder.count) + let container = Node(.object) + container.members = [Member(key: key, node: new)] + new = container + } + try insertMembers( + [Member(key: key, node: new)], in: parent, path: existing, remaining: parent.members.count + ) + return + } + } + throw NativeDocumentError.ownershipMismatch(region) + } + mutating func appendOccurrence(_ value: Node, path: [NativePathStep]) throws { + guard let array = try document.resolve(NativeRegion(path), on: document.root), + array.kind == .array + else { throw NativeDocumentError.ownershipMismatch(region) } + if array.aot { + try appendTables([value], path: path) + } else { + try appendValues([value], in: array) + } + } + + private mutating func arrayAssignment(path: [NativePathStep], rendered: String = "[]") throws { + guard case .key(let key) = path.last, + let parent = try document.resolve(NativeRegion(Array(path.dropLast())), on: document.root) + else { throw NativeDocumentError.unsupportedEdit(.wouldRewriteUnownedStructure, region, []) } + let renderer = NativeRenderer(format: document.format, budget: budget, region: region) + let nl = try newline + let at: Int + let assignmentKey: String + if let insertion = parent.insertion { + at = insertion + assignmentKey = try renderer.string(key) + } else { + at = document.root.insertion ?? 0 + var keys: [String] = [] + for step in path { + guard case .key(let key) = step else { + throw NativeDocumentError.unsupportedEdit(.wouldRewriteUnownedStructure, region, []) + } + keys.append(try renderer.string(key)) + } + assignmentKey = keys.joined(separator: ".") + } + try patch( + at.. 0 && document.source[at - 1] != 10 ? nl : "") + assignmentKey + " = " + rendered + nl) + } + + private mutating func appendTables(_ values: [Node], path: [NativePathStep]) throws { + let renderer = NativeRenderer(format: document.format, budget: budget, region: region) + var keys: [String] = [] + var current = document.root + for step in path { + switch step { + case .key(let key): + keys.append(try renderer.string(key)) + if let i = try current.member(key, budget: budget) { current = current.members[i].node } + case .occurrence(let evidence): + let i = try document.occurrence(evidence, in: current, region: region) + guard i == current.elements.count - 1 else { + throw NativeDocumentError.unsupportedEdit(.wouldRewriteUnownedStructure, region, []) + } + current = current.elements[i] + } + } + let nl = try newline + var blocks: [String] = [] + for value in values { + guard value.kind == .object else { + throw NativeDocumentError.unrepresentableValue(document.format, region, "arrayTableElement") + } + var pairs: [String] = [] + for member in value.members { + pairs.append(try renderer.string(member.key) + " = " + encoded(member.node)) + } + blocks.append( + try nativeJoin( + pairs, prefix: "[[" + keys.joined(separator: ".") + "]]" + nl, suffix: "", separator: nl, + budget: budget)) + } + let at = document.source.count + try patch( + at.. 0 && document.source[at - 1] != 10 ? nl : "") + + (try nativeJoin(blocks, prefix: "", suffix: nl, separator: nl, budget: budget))) + } + + private mutating func appendValues(_ values: [Node], in array: Node) throws { + guard array.kind == .array, let range = array.range else { + throw NativeDocumentError.unsupportedEdit(.syntaxNotLocated, region, []) + } + let at = range.upperBound - 1 + var pieces: [String] = [] + for value in values { pieces.append(try encoded(value)) } + let comma = !array.elements.isEmpty && array.commas.count < array.elements.count + if document.source[range].contains(10), let closeIndent = try indentation(at: at) { + let nl = try newline + var indent = closeIndent + " " + if let first = array.elements.first?.range, let local = try indentation(at: first.lowerBound) + { + indent = local + } + if comma, let end = array.elements.last?.range?.upperBound { try patch(end.. range.lowerBound + 1 && [9, 32].contains(document.source[insertion - 1]) { + try budget.step() + insertion -= 1 + } + let separator = array.elements.count > 1 ? " " : "" + try patch( + insertion.. String { + let fallback = toml ? " = " : ": " + let first: Member? + if toml && parent.inline { + first = try parent.inlineEntries(budget).first.map { $0.parent.members[$0.index] } + } else { + first = parent.members.first(where: { $0.keyRange != nil }) + } + guard let first, let key = first.keyRange, let value = first.node.range else { return fallback } + let gap = document.source[key.upperBound.. String? { + var start = position + while start > 0 && document.source[start - 1] != 10 { + try budget.step() + start -= 1 + } + let prefix = document.source[start.. lower + && (document.source[insertion - 1] == 9 || document.source[insertion - 1] == 32) + { + try budget.step() + insertion -= 1 + } + let text = try nativeJoin( + pieces, prefix: (remaining > 0 && !hasComma ? "," : "") + separator, suffix: "", + separator: "," + separator, budget: budget) + try patch(insertion.. 0 && document.source[at - 1] != 10 ? nl : "" + try patch(at.. 0 && document.source[at - 1] != 10 ? nl : "" + var blocks: [String] = [] + var rootPairs: [String] = [] + for m in members { + let full = keys + [try renderer.string(m.key)] + if m.node.kind == .object { + var pairs: [String] = [] + for child in m.node.members { + pairs.append(try renderer.string(child.key) + " = " + encoded(child.node)) + } + blocks.append("[" + full.joined(separator: ".") + "]" + nl + pairs.joined(separator: nl)) + } else { + // A dotted assignment belongs in the root block, before the first header. + rootPairs.append(full.joined(separator: ".") + " = " + (try encoded(m.node))) + } + } + if !rootPairs.isEmpty { + let rootAt = document.root.insertion ?? 0 + try patch( + rootAt.. Data { + // Resolve each physical inline delta after all recursive entry removals are known. + for change in inlineChanges { + try pruneInlineCommas(in: change.container) + if !change.additions.isEmpty { + let surviving = try survivingInlineMembers(in: change.container) + try insertInlinePieces( + change.additions, in: change.container, surviving: surviving, remaining: surviving.count) + } + } + // Coalesce repeated deletions but reject any other overlap before allocating a result. + try budget.allocate(patches.count, stage: "patch order") + var ordered = try patches.sorted { + try budget.step() + if $0.range.lowerBound == $1.range.lowerBound { return $0.range.isEmpty && !$1.range.isEmpty } + return $0.range.lowerBound < $1.range.lowerBound + } + var merged: [BytePatch] = [] + for p in ordered { + try budget.step() + if let last = merged.last, p.range.lowerBound < last.range.upperBound || p.range == last.range + { + guard p.bytes.isEmpty && last.bytes.isEmpty else { + throw NativeDocumentError.unsupportedEdit( + .overlappingEdits, region, [p.range, last.range]) + } + merged.removeLast() + merged.append( + BytePatch( + range: last.range.lowerBound.. Bool { + try budget.step() + guard kind == other.kind else { return false } + if kind == .object { + guard members.count == other.members.count else { return false } + for member in members { + guard let i = try other.member(member.key, budget: budget), + try member.node.equal(to: other.members[i].node, budget: budget) + else { return false } + } + return true + } + if kind == .array { + guard elements.count == other.elements.count else { return false } + for (a, b) in zip(elements, other.elements) { + if try !a.equal(to: b, budget: budget) { return false } + } + return true + } + return try budget.equal(text, other.text) + } + + func fingerprint(_ budget: NativeDocumentBudget, exactScalars: Bool = false) throws -> Data { + var data = Data() + func append(_ text: String) throws { + try budget.allocate(text.utf8.count + 24, stage: "observation") + try budget.step(text.utf8.count) + data.append(contentsOf: "\(text.utf8.count):".utf8) + data.append(contentsOf: text.utf8) + } + try append(kind.rawValue) + if kind == .object { + try append(String(members.count)) + var sorted: [Member] = [] + for m in members { + var index = 0 + while index < sorted.count { + try budget.step(m.key.utf8.count + sorted[index].key.utf8.count) + if m.key.utf8.lexicographicallyPrecedes(sorted[index].key.utf8) { break } + index += 1 + } + try budget.allocate(1, stage: "observation members") + sorted.insert(m, at: index) + } + for m in sorted { + try append(m.key) + let child = try m.node.fingerprint(budget, exactScalars: exactScalars) + try budget.allocate(child.count, stage: "observation subtree") + data.append(child) + } + } else if kind == .array { + try append(String(elements.count)) + for e in elements { + let child = try e.fingerprint(budget, exactScalars: exactScalars) + try budget.allocate(child.count, stage: "observation subtree") + data.append(child) + } + } else { + try append(text) + if exactScalars { + if kind == .integer || kind == .decimal { try append(raw) } + if kind == .atom { try append(atomType ?? "nativeAtom") } + } + } + return data + } + + func arrayDigest(_ budget: NativeDocumentBudget) throws -> NativeArrayDigest { + try budget.check() + if let cachedArrayDigest { return cachedArrayDigest } + let semantic = try fingerprint(budget, exactScalars: true) + let domain = NativeArrayDigest.currentFormat + "\0" + try budget.allocate(domain.utf8.count + semantic.count + 192, stage: "native array digest") + try budget.step(domain.utf8.count + semantic.count) + var bytes = Data(domain.utf8) + bytes.append(semantic) + let result = NativeArrayDigest( + format: NativeArrayDigest.currentFormat, digest: FileHash.sha256Hex(data: bytes)) + cachedArrayDigest = result + return result + } + + func projectionFailure(_ budget: NativeDocumentBudget) throws -> NativeProjectionFailure? { + try budget.step() + if kind == .atom { return .nativeType(atomType ?? "nativeAtom") } + if kind == .object { + var keys: Set = [] + for member in members { + try budget.allocate(member.key.utf8.count, stage: "projection key") + try budget.step(member.key.utf8.count) + if !keys.insert(member.key).inserted { return .canonicalKeyCollision } + if let failure = try member.node.projectionFailure(budget) { return failure } + } + } + for element in elements { + if let failure = try element.projectionFailure(budget) { return failure } + } + return nil + } + + func project(_ budget: NativeDocumentBudget) throws -> NativeValue? { + try budget.step() + switch kind { + case .object: + var result: [String: NativeValue] = [:] + for m in members { + try budget.allocate(m.key.utf8.count + 1, stage: "projection") + // Core dictionaries use canonical equivalence; refuse this projection rather than collapse keys. + guard result[m.key] == nil, let value = try m.node.project(budget) else { return nil } + result[m.key] = value + } + return .object(result) + case .array: + var values: [NativeValue] = [] + for e in elements { + guard let v = try e.project(budget) else { return nil } + values.append(v) + } + return .array(values) + case .string: return .string(text) + case .integer: return Int(text).map(NativeValue.integer) ?? .decimal(raw) + case .decimal: return .decimal(text) + case .boolean: return .boolean(text == "true") + case .null: return .null + case .atom: return nil + } + } +} + +struct NativeRenderer { + let format: NativeDocumentFormat + let budget: NativeDocumentBudget + let region: NativeRegion + var toml: Bool { format == .toml } + func string(_ value: String) throws -> String { + guard value.utf8.count <= (Int.max - 2) / 6 else { + throw NativeDocumentError.budgetExceeded("string encoding") + } + try budget.allocate(value.utf8.count * 6 + 2, stage: "string encoding") + try budget.step(value.utf8.count) + let encoder = JSONEncoder() + encoder.outputFormatting = [.withoutEscapingSlashes] + let bytes = try encoder.encode(value) + try budget.allocate(bytes.count, stage: "encoded string") + if toml { + try budget.allocate(bytes.count, stage: "TOML string escaping") + var escaped: [UInt8] = [] + for byte in bytes { + try budget.step() + if byte == 127 { + try budget.allocate(6, stage: "TOML string escaping") + escaped.append(contentsOf: "\\u007F".utf8) + } else { + escaped.append(byte) + } + } + return String(decoding: escaped, as: UTF8.self) + } + return String(decoding: bytes, as: UTF8.self) + } + func render(_ value: NativeValue, depth: Int = 0) throws -> String { + try budget.node(depth: depth) + switch value { + case .string(let value): return try string(value) + case .integer(let value): return String(value) + case .decimal(let raw): + try budget.allocate(raw.utf8.count, stage: "decimal input") + var parser = JSONParser(bytes: Array(raw.utf8), format: .json, budget: budget) + let node: Node + do { node = try parser.parse() } catch let failure as TOMLSemantics.SemanticBudget.Failure { + throw failure + } catch { throw NativeDocumentError.unrepresentableValue(format, region, "decimal") } + guard node.kind == .integer || node.kind == .decimal, node.range == 0.. String { + try budget.allocate(prefix.utf8.count + suffix.utf8.count, stage: "rendered container") + for part in parts { + try budget.step(part.utf8.count) + try budget.allocate(part.utf8.count + separator.utf8.count, stage: "rendered container") + } + return prefix + parts.joined(separator: separator) + suffix +} diff --git a/Sources/NativeDocuments/TOMLIndex.swift b/Sources/NativeDocuments/TOMLIndex.swift new file mode 100644 index 0000000..2bb2f46 --- /dev/null +++ b/Sources/NativeDocuments/TOMLIndex.swift @@ -0,0 +1,287 @@ +import Foundation +import TOMLSemantics +import TreeSitter +import TreeSitterTOML + +private struct ParseInput { + let bytes: UnsafePointer + let count: Int + let budget: NativeDocumentBudget + var failure: (any Error)? +} + +struct TOMLIndex { + let bytes: [UInt8] + let budget: NativeDocumentBudget + var comments: [Range] = [] + var located = true + var offset: Int { bytes.starts(with: [0xef, 0xbb, 0xbf]) ? 3 : 0 } + + mutating func parse() throws -> Node { + try budget.allocate(bytes.count, stage: "TOML string") + guard let source = String(bytes: bytes.dropFirst(offset), encoding: .utf8) else { + throw NativeDocumentError.invalidDocument(code: "utf8", range: nil) + } + let semantics = try SemanticDocument(source: source, budget: budget) + let root = try convert(semantics.root, depth: 0) + root.syntaxLocated = true + // The admitted whole envelope includes long comments and whitespace absent from semantic tokens. + try budget.admitCST(bytes: bytes.count) + guard bytes.count <= Int(UInt32.max), let parser = ts_parser_new() else { + throw NativeDocumentError.budgetExceeded("CST input") + } + defer { ts_parser_delete(parser) } + guard ts_parser_set_language(parser, tree_sitter_toml()) else { + throw NativeDocumentError.invalidDocument(code: "parserABI", range: nil) + } + var failure: (any Error)? + let tree = bytes.withUnsafeBytes { raw -> OpaquePointer? in + var empty: CChar = 0 + return withUnsafePointer(to: &empty) { emptyPointer in + var state = ParseInput( + bytes: raw.baseAddress?.assumingMemoryBound(to: CChar.self).advanced(by: offset) + ?? emptyPointer, count: bytes.count - offset, budget: budget) + return withUnsafeMutablePointer(to: &state) { pointer in + let input = TSInput( + payload: UnsafeMutableRawPointer(pointer), + read: { payload, index, _, count in + let state = payload!.assumingMemoryBound(to: ParseInput.self).pointee + let offset = min(Int(index), state.count) + count!.pointee = UInt32(state.count - offset) + return state.bytes.advanced(by: offset) + }, encoding: TSInputEncodingUTF8, decode: nil) + let options = TSParseOptions( + payload: UnsafeMutableRawPointer(pointer), + progress_callback: { progress in + let state = progress!.pointee.payload!.assumingMemoryBound(to: ParseInput.self) + do { + try state.pointee.budget.step() + return false + } catch { + state.pointee.failure = error + return true + } + }) + let tree = ts_parser_parse_with_options(parser, nil, input, options) + failure = pointer.pointee.failure + return tree + } + } + } + if let failure { + if let tree { ts_tree_delete(tree) } + throw failure + } + guard let tree else { + throw NativeDocumentError.invalidDocument(code: "parserFailure", range: nil) + } + defer { ts_tree_delete(tree) } + try budget.check() + let syntax = ts_tree_root_node(tree) + if ts_node_has_error(syntax) { + located = false + return root + } + let top = try children(syntax) + root.insertion = + top.first(where: { type($0) == "table" || type($0) == "table_array_element" }).map { + span($0).lowerBound + } ?? bytes.count + var active = root + for child in top { + try budget.step() + switch type(child) { + case "comment": comments.append(span(child)) + case "pair": try pair(child, in: root) + case "table", "table_array_element": + let parts = try children(child) + guard let key = parts.first(where: { type($0) != "comment" }) else { + located = false + continue + } + let keys = try keyParts(key) + let isArray = type(child) == "table_array_element" + active = try table(root, keys: keys, aot: isArray) + let start = span(child).lowerBound + var end = span(key).upperBound + while end < bytes.count && bytes[end] != 93 { + try budget.step() + end += 1 + } + guard end < bytes.count else { + located = false + continue + } + end += isArray ? 2 : 1 + active.syntaxLocated = true + active.headers.append(start.. Node { + try budget.node(depth: depth) + switch value { + case .object(let entries): + let n = Node(.object) + for e in entries { + n.members.append(Member(key: e.key, node: try convert(e.value, depth: depth + 1))) + } + return n + case .array(let elements): + let n = Node(.array) + for e in elements { n.elements.append(try convert(e, depth: depth + 1)) } + return n + case .scalar(let kind, let decoded, let raw, let range): + let k: Node.Kind + switch kind { + case .string: k = .string + case .boolean: k = .boolean + case .integer: k = .integer + case .float: + k = ["inf", "+inf", "-inf", "nan", "+nan", "-nan"].contains(raw) ? .atom : .decimal + case .dateTime: k = .atom + } + let node = Node( + k, text: k == .atom ? raw : decoded, raw: raw, + range: (range.lowerBound + offset)..<(range.upperBound + offset) + ) + if k == .atom { node.atomType = kind == .dateTime ? "dateTime" : "nonFiniteFloat" } + return node + } + } + func span(_ node: TSNode) -> Range { + (Int(ts_node_start_byte(node)) + offset)..<(Int(ts_node_end_byte(node)) + offset) + } + func type(_ node: TSNode) -> String { String(cString: ts_node_type(node)) } + func children(_ node: TSNode) throws -> [TSNode] { + var result: [TSNode] = [] + for i in 0.. [String] { + try budget.step() + if type(node) == "dotted_key" { + var keys: [String] = [] + for c in try children(node) { keys += try keyParts(c) } + return keys + } + try budget.allocate(span(node).count, stage: "CST key copy") + return [try SemanticDocument.decodeKey(Array(bytes[span(node)]), budget: budget)] + } + func table(_ root: Node, keys: [String], aot: Bool) throws -> Node { + var current = root + for (i, key) in keys.enumerated() { + guard let m = try current.member(key, budget: budget) else { + throw NativeDocumentError.invalidDocument(code: "syntaxSemanticMismatch", range: nil) + } + current = current.members[m].node + if current.kind == .array { + if i == keys.count - 1 && aot { + current.aot = true + guard let next = current.elements.first(where: { $0.headers.isEmpty }) else { + throw NativeDocumentError.invalidDocument(code: "arrayTableIndex", range: nil) + } + current = next + } else { + guard let latest = current.elements.last(where: { !$0.headers.isEmpty }) else { + throw NativeDocumentError.invalidDocument(code: "arrayTableScope", range: nil) + } + current = latest + } + } + } + return current + } + mutating func pair(_ syntax: TSNode, in parent: Node) throws { + let nodes = try children(syntax).filter { type($0) != "comment" } + guard nodes.count >= 2 else { + located = false + return + } + let keys = try keyParts(nodes[0]) + var current = parent + let enclosingInline = parent.inline ? parent : parent.enclosingInline + var inlineKeyPath = parent.inline ? [] : parent.inlineKeyPath + for key in keys.dropLast() { + guard let m = try current.member(key, budget: budget) else { + located = false + return + } + current = current.members[m].node + if let enclosingInline { + try budget.allocate(key.utf8.count + inlineKeyPath.count + 1, stage: "inline key path") + inlineKeyPath.append(key) + current.enclosingInline = enclosingInline + current.inlineKeyPath = inlineKeyPath + } + } + guard let key = keys.last, let m = try current.member(key, budget: budget) else { + located = false + return + } + let value = nodes[1] + current.members[m].entry = span(nodes[0]).lowerBound.. Important: Offset date-time in TOML is defined by RFC 3339, +/// > which interprets the date with proleptic Gregorian calendar. +/// > This is different from Foundation's usage of the Gregorian calendar, +/// > which follows the Julian calendar up to 1582-10-04, +/// > then transitions to the Gregorian calendar after that. +/// > This means for ancient dates, +/// > ``OffsetDateTime`` may disagree with `Foundation.Date` on how much time has passed since a reference date. +/// > For modern dates, there's no difference between the two. +public struct OffsetDateTime: Equatable, Hashable, Sendable, Codable, CustomStringConvertible { + /// The date component of the offset date-time. + public var date: LocalDate + /// The time component of the offset date-time. + public var time: LocalTime + /// The offset from UTC in minutes, valid range is [-1440, 1440]. + public var offset: Int16 + /// Details about the formatting of the date-time string. + /// For example, whether the 'T' connecting the date and time is lowercase or uppercase. + /// Or whether 00:00 offset is represented as 'Z' or '+00:00'. + public var features: Features + + /// Create a new offset date-time from it's members. + /// + /// This initializer does not validate the components. + /// Use ``isValid`` to check if the offset date-time is valid. + /// + /// - Parameters: + /// - date: The date component of the offset date-time. + /// - time: The time component of the offset date-time. + /// - offset: The offset from UTC in minutes, valid range is [-1440, 1440]. + /// - features: Details about the formatting of the date-time string. + public init(date: LocalDate, time: LocalTime, offset: Int16, features: Features) { + self.date = date + self.time = time + self.offset = offset + self.features = features + } + + /// Create a new offset date-time from it's members. + /// + /// This initializer validates the components. + /// A invalid component causes a error to be thrown. + /// + /// - Parameters: + /// - date: The date component of the offset date-time. + /// - time: The time component of the offset date-time. + /// - offset: The offset from UTC in minutes, valid range is [-1440, 1440]. + /// - features: Details about the formatting of the date-time string. + public init(validatingDate date: LocalDate, time: LocalTime, offset: Int16, features: Features) + throws + { + self.init(date: date, time: time, offset: offset, features: features) + guard date.isValid else { + throw TOMLError(.invalidDateTimeComponents("Invalid local date: \(date)")) + } + guard time.isValid else { + throw TOMLError(.invalidDateTimeComponents("Invalid local time: \(time)")) + } + guard offsetIsValid else { + throw TOMLError(.invalidDateTimeComponents("Invalid offset: \(offset)")) + } + guard featuresAreValid else { + throw TOMLError(.invalidDateTimeComponents("Invalid features: \(features)")) + } + } + + /// Check if the offset date-time is valid. + public var isValid: Bool { + guard date.isValid, time.isValid, offsetIsValid else { + return false + } + + return featuresAreValid + } + + private var offsetIsValid: Bool { + offset >= -1440 && offset <= 1440 + } + + private var featuresAreValid: Bool { + if features.contains(.lowercaseZ) || features.contains(.uppercaseZ) { + return offset == 0 + } + + return true + } + + /// Number of seconds since 2001-01-01T00:00:00Z according to the proleptic Gregorian calendar. + /// + /// > Important: This is similar to `Foundation.Date.timeIntervalSinceReferenceDate`. + /// But for ancient dates, this result may disagree with `Foundation.Date` on how much time has passed. + /// this is because Foundation's Gregorian calendar follows the Julian calendar up to 1582-10-04, + /// then the Gregorian calendar after that. According to the TOML specification, + /// an offset date-time should follow the proleptic Gregorian calendar, + /// which extends the Gregorian calendar backwards to year 1. + public var timeIntervalSince2001: Double { + timeIntervalSince1970 - 978_307_200 + } + + /// Number of seconds since 1970-01-01T00:00:00Z according to the proleptic Gregorian calendar. + /// + /// > Important: This is similar to `Foundation.Date.timeIntervalSinceReferenceDate`. + /// But for ancient dates, this result may disagree with `Foundation.Date` on how much time has passed. + /// this is because Foundation's Gregorian calendar follows the Julian calendar up to 1582-10-04, + /// then the Gregorian calendar after that. According to the TOML specification, + /// an offset date-time should follow the proleptic Gregorian calendar, + /// which extends the Gregorian calendar backwards to year 1. + public var timeIntervalSince1970: Double { + let year = Int64(date.year) + let month = Int64(date.month) + let day = Int64(date.day) + let hour = Int64(time.hour) + let minute = Int64(time.minute) + let second = Int64(time.second) + let nanosecond = Int64(time.nanosecond) + let offsetInSeconds = Int64(offset) * 60 + + var y = year + if month <= 2 { y -= 1 } + + let era = (y >= 0 ? y : y - 399) / 400 + let yoe = y - era * 400 + let doy = (153 * (month + (month > 2 ? -3 : 9)) + 2) / 5 + day - 1 + let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy + let epochOffset = Int64(719_468) + let dayCounts = era * 146_097 + doe - epochOffset + let secondOfDay = hour * 3600 + minute * 60 + second + let totalSeconds = dayCounts * 86400 + secondOfDay - offsetInSeconds + + return Double(totalSeconds) + Double(nanosecond) / 1_000_000_000 + } + + /// The string representation of the offset date-time. + /// + /// If a value has precision up to 1 nanosecond, + /// and it does not require superfluous trailing zeros in its fraction seconds, + /// this value can be recreated exactly. + public var description: String { + let dateString = date.description + let timeString = time.description + let separator = + if features.contains(.lowercaseT) { + "t" + } else if features.contains(.uppercaseT) { + "T" + } else { + " " + } + + if features.contains(.lowercaseZ) { + return "\(dateString)\(separator)\(timeString)z" + } else if features.contains(.uppercaseZ) { + return "\(dateString)\(separator)\(timeString)Z" + } else { + let sign = offset >= 0 ? "+" : "-" + let absOffset = abs(offset) + let hours = absOffset / 60 + let minutes = absOffset % 60 + let hoursStr = hours < 10 ? "0\(hours)" : "\(hours)" + let minutesStr = minutes < 10 ? "0\(minutes)" : "\(minutes)" + return "\(dateString)\(separator)\(timeString)\(sign)\(hoursStr):\(minutesStr)" + } + } + + /// Presentation details for string representation of the offset date-time. + /// + /// A parser can preserve features of a offset date-time string with this type. + /// If neither lowercase nor uppercase 'T' is present, the date-time seprator is a space, which is allowed by TOML. + public struct Features: OptionSet, Hashable, Sendable, Codable { + /// The raw value of the features. + public let rawValue: UInt8 + + /// Create a new features from it's raw value. + public init(rawValue: UInt8) { + self.rawValue = rawValue + } + + /// Indicates the date-time seprator is a lowercase 't'. + public static let lowercaseT = Features(rawValue: 1 << 1) + + /// Indicates the date-time seprator is a uppercase 'T'. + public static let uppercaseT = Features(rawValue: 1 << 2) + + /// Indicates the offset is represented as a lowercase 'z'. + /// This should not be present if the offset is non-zero, + /// or if it's +00:00. + public static let lowercaseZ = Features(rawValue: 1 << 3) + + /// Indicates the offset is represented as a uppercase 'Z'. + /// This should not be present if the offset is non-zero, + /// or if it's +00:00. + public static let uppercaseZ = Features(rawValue: 1 << 4) + } +} + +/// A local date-time as defined by TOML. +/// +/// ``LocalDateTime`` stores fractional seconds to the nanosecond precision. +public struct LocalDateTime: Equatable, Hashable, Sendable, Codable, CustomStringConvertible { + /// The date component of the local date-time. + public var date: LocalDate + /// The time component of the local date-time. + public var time: LocalTime + + /// Create a new local date-time from it's members. + /// + /// This initializer does not validate the components. + /// Use ``isValid`` to check if the local date-time is valid. + /// - Parameters: + /// - date: The date component of the local date-time. + /// - time: The time component of the local date-time. + public init(date: LocalDate, time: LocalTime) { + self.date = date + self.time = time + } + + /// Create a new local date-time from it's members. + /// + /// This initializer validates the components. + /// A invalid component causes a error to be thrown. + /// + /// - Parameters: + /// - date: The date component of the local date-time. + /// - time: The time component of the local date-time. + public init(validatingDate date: LocalDate, time: LocalTime) throws { + self.init(date: date, time: time) + guard date.isValid else { + throw TOMLError(.invalidDateTimeComponents("Invalid local date: \(date)")) + } + guard time.isValid else { + throw TOMLError(.invalidDateTimeComponents("Invalid local time: \(time)")) + } + } + + /// Check if the local date-time is valid. + public var isValid: Bool { + date.isValid && time.isValid + } + + /// The string representation of the local date-time. + public var description: String { + "\(date.description)T\(time.description)" + } +} + +/// A local time as defined by TOML. +/// +/// ``LocalTime`` stores fractional seconds to the nanosecond precision. +public struct LocalTime: Equatable, Hashable, Sendable, Codable, CustomStringConvertible { + /// The hour component of the local time. + public var hour: UInt8 + /// The minute component of the local time. + public var minute: UInt8 + /// The second component of the local time. + public var second: UInt8 + /// The fractional second component of the local time in nanoseconds. + public var nanosecond: UInt32 + + /// Create a new local time from it's members. + /// + /// This initializer validates the components. + /// A invalid component causes a error to be thrown. + /// + /// - Parameters: + /// - hour: The hour component of the local time. + /// - minute: The minute component of the local time. + /// - second: The second component of the local time. + /// - nanosecond: The fractional second component of the local time in nanoseconds. + public init(validatingHour hour: UInt8, minute: UInt8, second: UInt8, nanosecond: UInt32 = 0) + throws + { + self.init(hour: hour, minute: minute, second: second, nanosecond: nanosecond) + guard isValid else { + throw TOMLError( + .invalidDateTimeComponents( + "Invalid local time components: \(hour):\(minute):\(second).\(nanosecond)")) + } + } + + /// Create a new local time from it's members. + /// + /// This initializer does not validate the components. + /// Use ``isValid`` to check if the local time is valid. + /// + /// - Parameters: + /// - hour: The hour component of the local time. + /// - minute: The minute component of the local time. + /// - second: The second component of the local time. + /// - nanosecond: The fractional second component of the local time in nanoseconds. + public init(hour: UInt8, minute: UInt8, second: UInt8, nanosecond: UInt32 = 0) { + self.hour = hour + self.minute = minute + self.second = second + self.nanosecond = nanosecond + } + + /// Check if the local time is valid. + public var isValid: Bool { + hour < 24 && minute < 60 && second < 60 && nanosecond < 1_000_000_000 + } + + /// The string representation of the local time. + public var description: String { + let hourStr = hour < 10 ? "0\(hour)" : "\(hour)" + let minuteStr = minute < 10 ? "0\(minute)" : "\(minute)" + let secondStr = second < 10 ? "0\(second)" : "\(second)" + + if nanosecond == 0 { + return "\(hourStr):\(minuteStr):\(secondStr)" + } else { + let nanosecondStr = String(nanosecond).padded(to: 9, with: "0") + let trimmedFractional = nanosecondStr.trimmingSuffix("0") + let finalFractional = trimmedFractional.isEmpty ? "0" : trimmedFractional + return "\(hourStr):\(minuteStr):\(secondStr).\(finalFractional)" + } + } +} + +/// A local date as defined by TOML. +/// +/// ``LocalDate`` stores the year, month, and day components of a date. +public struct LocalDate: Equatable, Hashable, Sendable, Codable, CustomStringConvertible { + /// The year component of the local date. + /// Valid range is [1, 9999]. + public var year: UInt16 + + /// The month component of the local date. + /// Valid range is [1, 12]. + public var month: UInt8 + + /// The day component of the local date. + /// Valid range is depends on the month and year. + public var day: UInt8 + + /// Create a new local date from it's members. + /// + /// This initializer validates the components. + /// A invalid component causes a error to be thrown. + /// + /// - Parameters: + /// - year: The year component of the local date. + /// - month: The month component of the local date. + /// - day: The day component of the local date. + public init(validatingYear year: UInt16, month: UInt8, day: UInt8) throws { + self.init(year: year, month: month, day: day) + guard isValid else { + throw TOMLError( + .invalidDateTimeComponents("Invalid local date components: \(year)-\(month)-\(day)")) + } + } + + /// Create a new local date from it's members. + /// + /// This initializer does not validate the components. + /// Use ``isValid`` to check if the local date is valid. + /// + /// - Parameters: + /// - year: The year component of the local date. + /// - month: The month component of the local date. + /// - day: The day component of the local date. + public init(year: UInt16, month: UInt8, day: UInt8) { + self.year = year + self.month = month + self.day = day + } + + /// Check if the local date is valid. + public var isValid: Bool { + guard month >= 1, month <= 12 else { return false } + guard day >= 1 else { return false } + + let daysInMonth: UInt8 + switch month { + case 1, 3, 5, 7, 8, 10, 12: + daysInMonth = 31 + case 4, 6, 9, 11: + daysInMonth = 30 + case 2: + let isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) + daysInMonth = isLeapYear ? 29 : 28 + default: + return false + } + + return day <= daysInMonth + } + + /// The string representation of the local date. + public var description: String { + let yearStr = String(year).padded(to: 4, with: "0") + let monthStr = month < 10 ? "0\(month)" : "\(month)" + let dayStr = day < 10 ? "0\(day)" : "\(day)" + return "\(yearStr)-\(monthStr)-\(dayStr)" + } +} + +extension String { + fileprivate func padded(to length: Int, with character: Character) -> String { + if count >= length { + return self + } + return String(repeating: character, count: length - count) + self + } + + fileprivate func trimmingSuffix(_ suffix: Character) -> String { + var result = self + while result.last == suffix { + result.removeLast() + } + return result + } +} diff --git a/Sources/TOMLSemantics/LICENSE b/Sources/TOMLSemantics/LICENSE new file mode 100644 index 0000000..a30b4e4 --- /dev/null +++ b/Sources/TOMLSemantics/LICENSE @@ -0,0 +1,9 @@ +The MIT License (MIT) + +Copyright (c) 2019 TOMLDecoder contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/Sources/TOMLSemantics/PATCHES.md b/Sources/TOMLSemantics/PATCHES.md new file mode 100644 index 0000000..7992b38 --- /dev/null +++ b/Sources/TOMLSemantics/PATCHES.md @@ -0,0 +1,47 @@ +# TOML semantic source subset + +Source: TOMLDecoder 0.4.5, revision +`a2bbd2796fe3064e107de18cb56031052c4fa899`, MIT. `provenance.json` +records each copied file's original path and SHA256. `upstream.patch` records +the complete zero-context differences for those exact hashed files, including +repository formatting. +`SemanticBudget.swift` and `SemanticDocument.swift` are package-owned seams. + +The subset contains the parser, token/model/constants, scalar/date validators, +key context and errors. General Decodable containers, public table/array +accessors, Dictionary/Any conversion, executables, tests, documentation, +benchmarks and build plugins are not included. + +Local changes are limited to: + +- Per-operation budget/cancellation propagation through construction, capacity + reservation, recursive descent, token/trivia scans, key comparisons, lazy + scalar decoding and ordered traversal. Original typed throws become ordinary + throwing calls so budget and cancellation errors propagate without casts. + Dotted-key descent admits depth before recursion, cumulatively with enclosing + inline tables and arrays. +- Exact decoded UTF-8 key comparison, including sampled-hash collisions. Unused + key-transform and String-key Dictionary/Any access paths are removed. Keyed + model types do not synthesize String equality. +- Stable entry source positions for ordered typed traversal. Scalar syntax is + classified before invoking its standard validator. Overflowing integers do + not retry as floating point. Raw numeric lexemes and native atoms remain + separate from Core projection. Date/time atoms require one of the four valid + date/time/offset combinations. Finite decimal projection removes only TOML + separators and a leading plus, with no floating-point formatting. +- Actual EOF guards after fractional-time scanning and before the month/day + delimiter. Multiline basic-string closing delimiters use backslash parity + with cooperative scan checks. No source terminator, sentinel or synthetic + newline is appended. +- Required string helper budget propagation and quoted-key validation through + the same standard validators. Decoder-specific date initializers and unused + Foundation date conversion extensions are omitted with the decoder product. +- Inline-table closure is enforced while traversing ancestors. Static arrays + containing inline tables retain a distinct kind from declared arrays of + tables, so headers cannot extend them. +- Repository Swift formatting. + +NativeDocuments owns the JSON syntax, source index, ownership expectations, +patches and full-candidate comparison. This target has no library product and +performs no I/O. Standard-validator failures are translated into safe document +codes by NativeDocuments; upstream error descriptions are never preview text. diff --git a/Sources/TOMLSemantics/Parsing/Constants.swift b/Sources/TOMLSemantics/Parsing/Constants.swift new file mode 100644 index 0000000..34a168c --- /dev/null +++ b/Sources/TOMLSemantics/Parsing/Constants.swift @@ -0,0 +1,109 @@ +enum CodeUnits { + static let escape: UTF8.CodeUnit = 27 + static let equal: UTF8.CodeUnit = 61 + static let comma: UTF8.CodeUnit = 44 + static let lbrace: UTF8.CodeUnit = 123 + static let rbrace: UTF8.CodeUnit = 125 + static let lbracket: UTF8.CodeUnit = 91 + static let rbracket: UTF8.CodeUnit = 93 + static let pound: UTF8.CodeUnit = 35 + static let backslash: UTF8.CodeUnit = 92 + static let backspace: UTF8.CodeUnit = 8 + static let cr: UTF8.CodeUnit = 13 + static let colon: UTF8.CodeUnit = 58 + static let dot: UTF8.CodeUnit = 46 + static let doubleQuote: UTF8.CodeUnit = 34 + static let formfeed: UTF8.CodeUnit = 12 + static let lf: UTF8.CodeUnit = 10 + static let minus: UTF8.CodeUnit = 45 + static let plus: UTF8.CodeUnit = 43 + static let singleQuote: UTF8.CodeUnit = 39 + static let space: UTF8.CodeUnit = 32 + static let tab: UTF8.CodeUnit = 9 + static let underscore: UTF8.CodeUnit = 95 + + static let number0: UTF8.CodeUnit = 48 + static let number1: UTF8.CodeUnit = 49 + static let number7: UTF8.CodeUnit = 55 + static let number9: UTF8.CodeUnit = 57 + + static let lowerA: UTF8.CodeUnit = 97 + static let lowerB: UTF8.CodeUnit = 98 + static let lowerI: UTF8.CodeUnit = 105 + static let lowerE: UTF8.CodeUnit = 101 + static let lowerF: UTF8.CodeUnit = 102 + static let lowerL: UTF8.CodeUnit = 108 + static let lowerS: UTF8.CodeUnit = 115 + static let lowerN: UTF8.CodeUnit = 110 + static let lowerO: UTF8.CodeUnit = 111 + static let lowerR: UTF8.CodeUnit = 114 + static let lowerT: UTF8.CodeUnit = 116 + static let lowerU: UTF8.CodeUnit = 117 + static let lowerX: UTF8.CodeUnit = 120 + static let lowerZ: UTF8.CodeUnit = 122 + static let upperA: UTF8.CodeUnit = 65 + static let upperE: UTF8.CodeUnit = 69 + static let upperF: UTF8.CodeUnit = 70 + static let upperT: UTF8.CodeUnit = 84 + static let upperU: UTF8.CodeUnit = 85 + static let upperZ: UTF8.CodeUnit = 90 + + nonisolated(unsafe) static let isBareKeyChar: UnsafePointer = { + let ptr = UnsafeMutablePointer.allocate(capacity: 256) + ptr.initialize(repeating: false, count: 256) + for i in 0..<256 { + let ch = UTF8.CodeUnit(i) + if (ch >= CodeUnits.lowerA && ch <= CodeUnits.lowerZ) + || (ch >= CodeUnits.upperA && ch <= CodeUnits.upperZ) + || (ch >= CodeUnits.number0 && ch <= CodeUnits.number9) || ch == CodeUnits.underscore + || ch == CodeUnits.minus + { + ptr[i] = true + } + } + return UnsafePointer(ptr) + }() + + nonisolated(unsafe) static let isValueChar: UnsafePointer = { + let ptr = UnsafeMutablePointer.allocate(capacity: 256) + ptr.initialize(repeating: false, count: 256) + for i in 0..<256 { + let ch = UTF8.CodeUnit(i) + if (ch >= CodeUnits.lowerA && ch <= CodeUnits.lowerZ) + || (ch >= CodeUnits.upperA && ch <= CodeUnits.upperZ) + || (ch >= CodeUnits.number0 && ch <= CodeUnits.number9) || ch == CodeUnits.underscore + || ch == CodeUnits.minus || ch == CodeUnits.plus || ch == CodeUnits.dot + { + ptr[i] = true + } + } + return UnsafePointer(ptr) + }() + + nonisolated(unsafe) static let isBasicStringBodyChar: UnsafePointer = { + let ptr = UnsafeMutablePointer.allocate(capacity: 256) + ptr.initialize(repeating: true, count: 256) + ptr[Int(CodeUnits.backslash)] = false + ptr[Int(CodeUnits.doubleQuote)] = false + ptr[Int(CodeUnits.lf)] = false + return UnsafePointer(ptr) + }() + + static let null: UTF8.CodeUnit = 0x00 + static let unitSeparator: UTF8.CodeUnit = 0x1F + static let delete: UTF8.CodeUnit = 0x7F +} + +extension UTF8.CodeUnit { + @_transparent + var isDecimalDigit: Bool { + CodeUnits.number0 <= self && self <= CodeUnits.number9 + } + + @_transparent + var isHexDigit: Bool { + isDecimalDigit + || CodeUnits.lowerA <= self && self <= CodeUnits.lowerF + || CodeUnits.upperA <= self && self <= CodeUnits.upperF + } +} diff --git a/Sources/TOMLSemantics/Parsing/Parser+Finish.swift b/Sources/TOMLSemantics/Parsing/Parser+Finish.swift new file mode 100644 index 0000000..eafd32d --- /dev/null +++ b/Sources/TOMLSemantics/Parsing/Parser+Finish.swift @@ -0,0 +1,24 @@ +extension Parser { + consuming func finish(source: String) -> TOMLDocument { + var tables: [InternalTOMLTable] = [] + var arrays: [InternalTOMLArray] = [] + var keyTables: [KeyTablePair] = [] + var keyArrays: [KeyArrayPair] = [] + var keyValues: [KeyValuePair] = [] + + swap(&tables, &self.tables) + swap(&arrays, &self.arrays) + swap(&keyTables, &self.keyTables) + swap(&keyArrays, &self.keyArrays) + swap(&keyValues, &self.keyValues) + + return TOMLDocument( + source: source, + tables: tables, + arrays: arrays, + keyTables: keyTables, + keyArrays: keyArrays, + keyValues: keyValues + ) + } +} diff --git a/Sources/TOMLSemantics/Parsing/Parser.swift b/Sources/TOMLSemantics/Parsing/Parser.swift new file mode 100644 index 0000000..462a042 --- /dev/null +++ b/Sources/TOMLSemantics/Parsing/Parser.swift @@ -0,0 +1,2696 @@ +struct Parser: ~Copyable { + let budget: SemanticBudget + var depth = 0 + var token = Token.empty + var cursor = 0 + var currentLineNumber = 1 + var currentTable = 0 + var currentTableIsKeyed = false + var tablePath: [(key: String, keyHash: Int)] = [] + var tables: [InternalTOMLTable] = [] + var arrays: [InternalTOMLArray] = [] + var keyTables: [KeyTablePair] = [] + var keyArrays: [KeyArrayPair] = [] + var keyValues: [KeyValuePair] = [] + + mutating func parse(bytes: UnsafeBufferPointer) throws { + try budget.node(depth: 0) + tables.append(InternalTOMLTable()) + let estimatedKeyValues = max(32, bytes.count / 48) + let estimatedNodes = max(8, estimatedKeyValues / 8) + try budget.allocate(max(8, estimatedNodes), stage: "semantic storage") + tables.reserveCapacity(max(8, estimatedNodes)) + try budget.allocate(estimatedNodes, stage: "semantic storage") + arrays.reserveCapacity(estimatedNodes) + try budget.allocate(estimatedNodes, stage: "semantic storage") + keyTables.reserveCapacity(estimatedNodes) + try budget.allocate(estimatedNodes, stage: "semantic storage") + keyArrays.reserveCapacity(estimatedNodes) + try budget.allocate(estimatedKeyValues, stage: "semantic storage") + keyValues.reserveCapacity(estimatedKeyValues) + try budget.allocate(8, stage: "semantic storage") + tablePath.reserveCapacity(8) + + while token.kind != .eof { + try budget.step() + switch token.kind { + case .newline: + try nextToken(bytes: bytes, isDotSpecial: true) + case .string, .bareKey: + try parseKeyValue(bytes: bytes, tableIndex: currentTable, isKeyed: currentTableIsKeyed) + if token.kind != .newline, token.kind != .eof { + throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "extra chars after value")) + } + if token.kind == .newline { + try eatToken(bytes: bytes, kind: .newline, isDotSpecial: true) + } + case .lbracket: + try parseSelect(bytes: bytes) + default: + throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "syntax error")) + } + } + } + + mutating func nextToken(bytes: UnsafeBufferPointer, isDotSpecial: Bool) throws { + let lineNumber = currentLineNumber + var position = cursor + + @inline(__always) + func emitToken(kind: Token.Kind, start: Int, end: Int, newlines: Int = 0) throws { + try budget.node(depth: depth) + token = Token(budget: budget, kind: kind, lineNumber: lineNumber, text: start..= CodeUnits.null && commentChar <= CodeUnits.backspace) + || (commentChar >= CodeUnits.lf && commentChar <= CodeUnits.unitSeparator) + || commentChar == CodeUnits.delete + { + if commentChar == CodeUnits.cr { + let nextPosition = position + 1 + if nextPosition < count, bytes[nextPosition] == CodeUnits.lf { + // Allow CRLF sequence + } else { + throw TOMLError( + .syntax( + lineNumber: lineNumber, + message: "control characters are not allowed in comments" + ) + ) + } + } else { + throw TOMLError( + .syntax( + lineNumber: lineNumber, + message: "control characters are not allowed in comments" + ) + ) + } + } + position += 1 + } + continue + case CodeUnits.space, CodeUnits.tab: + // ignore white spaces + position += 1 + while position < count { + try budget.step() + let ws = bytes[position] + if ws != CodeUnits.space, ws != CodeUnits.tab { + break + } + position += 1 + } + continue + case CodeUnits.dot where isDotSpecial: + try emitToken(kind: .dot, start: position, end: position + 1) + return + case CodeUnits.comma: + try emitToken(kind: .comma, start: position, end: position + 1) + return + case CodeUnits.equal: + try emitToken(kind: .equal, start: position, end: position + 1) + return + case CodeUnits.lbrace: + try emitToken(kind: .lbrace, start: position, end: position + 1) + return + case CodeUnits.rbrace: + try emitToken(kind: .rbrace, start: position, end: position + 1) + return + case CodeUnits.lbracket: + try emitToken(kind: .lbracket, start: position, end: position + 1) + return + case CodeUnits.rbracket: + try emitToken(kind: .rbracket, start: position, end: position + 1) + return + case CodeUnits.lf: + try emitToken(kind: .newline, start: position, end: position + 1, newlines: 1) + return + case CodeUnits.cr: + // Check if this is part of a CRLF sequence + let nextPosition = position + 1 + if nextPosition < count, bytes[nextPosition] == CodeUnits.lf { + // This is CRLF, treat as newline + try emitToken(kind: .newline, start: position, end: nextPosition + 1, newlines: 1) + return + } + // Bare CR is invalid + throw TOMLError( + .syntax( + lineNumber: lineNumber, + message: "bare carriage return is not allowed" + ) + ) + default: + break + } + + func scanString(range: Range, lineNumber: Int) throws { + let start = range.lowerBound + let end = range.upperBound + let head = bytes[start] + if (head >= CodeUnits.lowerA && head <= CodeUnits.lowerZ) + || (head >= CodeUnits.upperA && head <= CodeUnits.upperZ) || head == CodeUnits.underscore + { + let isBareKeyChar = CodeUnits.isBareKeyChar + var index = start + 1 + while index < end { + try budget.step() + let ch = bytes[index] + if isBareKeyChar[Int(ch)] { + index += 1 + continue + } + break + } + try emitToken(kind: .bareKey, start: start, end: index) + return + } + + if head == CodeUnits.singleQuote { + if start + 3 <= end, + bytes[start + 1] == CodeUnits.singleQuote, + bytes[start + 2] == CodeUnits.singleQuote + { + var i = start + 3 + var newlinesInToken = 0 + + while i < end { + try budget.step() + if bytes[i] == CodeUnits.lf { + newlinesInToken += 1 + } + if i + 3 <= end, + bytes[i] == CodeUnits.singleQuote, + bytes[i + 1] == CodeUnits.singleQuote, + bytes[i + 2] == CodeUnits.singleQuote + { + if i + 3 >= end || bytes[i + 3] != CodeUnits.singleQuote { + break + } + } + i += 1 + } + + guard i < end else { + throw TOMLError( + .syntax(lineNumber: lineNumber, message: "unterminated triple-s-quote") + ) + } + + try emitToken(kind: .string, start: start, end: i + 3, newlines: newlinesInToken) + return + } + + var i = start + 1 + while i < end { + try budget.step() + let ch = bytes[i] + if ch == CodeUnits.singleQuote || ch == CodeUnits.lf { + break + } + i += 1 + } + + if i >= end || bytes[i] != CodeUnits.singleQuote { + throw TOMLError( + .syntax(lineNumber: lineNumber, message: "unterminated s-quote") + ) + } + + try emitToken(kind: .string, start: start, end: i + 1) + return + } + + if head == CodeUnits.doubleQuote { + if start + 3 < end, + bytes[start + 1] == CodeUnits.doubleQuote, + bytes[start + 2] == CodeUnits.doubleQuote + { + var i = start + 3 + var newlinesInToken = 0 + + while i < end { + try budget.step() + if bytes[i] == CodeUnits.lf { + newlinesInToken += 1 + } + if i + 3 <= end, + bytes[i] == CodeUnits.doubleQuote, + bytes[i + 1] == CodeUnits.doubleQuote, + bytes[i + 2] == CodeUnits.doubleQuote + { + if i + 3 >= end || bytes[i + 3] != CodeUnits.doubleQuote { + var backslashStart = i + while backslashStart > start + 3 + && bytes[backslashStart - 1] == CodeUnits.backslash + { + try budget.step() + backslashStart -= 1 + } + if (i - backslashStart) % 2 != 0 { + i += 1 + continue + } + break + } + } + i += 1 + } + + guard i < end else { + throw TOMLError( + .syntax(lineNumber: lineNumber, message: "unterminated triple-d-quote") + ) + } + + try emitToken(kind: .string, start: start, end: i + 3, newlines: newlinesInToken) + return + } + + var i = start + 1 + let isBasicStringBodyChar = CodeUnits.isBasicStringBodyChar + let baseAddress = bytes.baseAddress! + while i + 8 <= end { + try budget.step() + let chunk = UnsafeRawPointer(baseAddress.advanced(by: i)).loadUnaligned( + as: UInt64.self + ) + if chunkContainsDoubleQuotedStopByte(chunk) { + break + } + i += 8 + } + + while i < end { + try budget.step() + let ch = bytes[i] + if isBasicStringBodyChar[Int(ch)] { + i += 1 + continue + } + if ch == CodeUnits.backslash { + i += 1 + if i < end { + i += 1 + continue + } + break + } + + break + } + + if i >= end || bytes[i] != CodeUnits.doubleQuote { + throw TOMLError( + .syntax(lineNumber: lineNumber, message: "unterminated quote") + ) + } + + try emitToken(kind: .string, start: start, end: i + 1) + return + } + + if !isDotSpecial { + var index = start + var dateEnder: Int? + // Fast path: Dates must produce YYYY-MM-DD, so checks for the dash + if start + 4 < end && bytes[start + 4] == CodeUnits.minus { + dateEnder = scanDate(bytes: bytes, range: range)?.3 + } + + if let dateEnder, dateEnder < end, + bytes[dateEnder] == CodeUnits.upperT || bytes[dateEnder] == CodeUnits.lowerT + || bytes[dateEnder] == CodeUnits.space + { + let timeStarter = dateEnder + 1 + if let timeEnder = scanTime( + bytes: bytes, range: timeStarter.. start { + if index < end { + if bytes[index] == CodeUnits.dot { + index += 1 + while index < end, bytes[index] >= CodeUnits.number0, + bytes[index] <= CodeUnits.number9 + { + try budget.step() + index += 1 + } + } + if index < end, bytes[index] == CodeUnits.upperZ || bytes[index] == CodeUnits.lowerZ { + index += 1 + } else if let timzoneEnder = scanTimezoneOffset( + bytes: bytes, range: index.. start, bytes[index - 1] == CodeUnits.space { + try budget.step() + index -= 1 + } + // tokenize + try emitToken(kind: .string, start: start, end: index) + return + } + } + + if isDotSpecial { + let isBareKeyChar = CodeUnits.isBareKeyChar + var index = start + while index < end, isBareKeyChar[Int(bytes[index])] { + try budget.step() + index += 1 + } + if index >= end || bytes[index] != CodeUnits.plus { + try emitToken(kind: .bareKey, start: start, end: index) + return + } + + index += 1 + while index < end { + try budget.step() + let ch = bytes[index] + if isBareKeyChar[Int(ch)] || ch == CodeUnits.plus { + index += 1 + continue + } + break + } + try emitToken(kind: .string, start: start, end: index) + } else { + let isValueChar = CodeUnits.isValueChar + var index = start + while index < end { + try budget.step() + let ch = bytes[index] + if isValueChar[Int(ch)] { + index += 1 + continue + } + break + } + try emitToken(kind: .string, start: start, end: index) + } + } + + try scanString(range: position.., kind: Token.Kind, isDotSpecial: Bool) + throws + { + if token.kind != kind { + throw TOMLError(.internalError(lineNumber: token.lineNumber)) + } + try nextToken(bytes: bytes, isDotSpecial: isDotSpecial) + } + + mutating func createKeyValue( + bytes: UnsafeBufferPointer, + token: Token, + value: Token, + inTable tableIndex: Int, + isKeyed: Bool + ) throws { + let (key, keyHash) = try normalizeKeyAndHash(bytes: bytes, token: token) + if try tableValue(tableIndex: tableIndex, keyed: isKeyed, key: key, keyHash: keyHash) != nil { + throw TOMLError(.badKey(lineNumber: token.lineNumber)) + } + let index = keyValues.count + try budget.node(depth: depth) + keyValues.append( + KeyValuePair(key: key, keyHash: keyHash, sourcePosition: token.text.lowerBound, value: value)) + + if isKeyed { + if keyTables[tableIndex].table.keyValues.isEmpty { + try budget.allocate(8, stage: "semantic storage") + keyTables[tableIndex].table.keyValues.reserveCapacity(8) + } + try budget.node(depth: depth) + keyTables[tableIndex].table.keyValues.append(index) + keyTables[tableIndex].table.recordKeyHash(keyHash) + } else { + if tables[tableIndex].keyValues.isEmpty { + try budget.allocate(8, stage: "semantic storage") + tables[tableIndex].keyValues.reserveCapacity(8) + } + try budget.node(depth: depth) + tables[tableIndex].keyValues.append(index) + tables[tableIndex].recordKeyHash(keyHash) + } + } + + mutating func createKeyTable( + bytes: UnsafeBufferPointer, token: Token, inTable tableIndex: Int, isKeyed: Bool, + implicit: Bool = false + ) throws -> Int { + let (key, keyHash) = try normalizeKeyAndHash(bytes: bytes, token: token) + return try createKeyTable( + normalizedKey: key, + keyHash: keyHash, + lineNumber: token.lineNumber, + inTable: tableIndex, + isKeyed: isKeyed, + implicit: implicit + ) + } + + mutating func createKeyTable( + normalizedKey key: String, keyHash: Int, lineNumber: Int, inTable tableIndex: Int, + isKeyed: Bool, implicit: Bool = false + ) throws -> Int { + // Check if parent table is readOnly (inline table) + if isKeyed ? keyTables[tableIndex].table.readOnly : tables[tableIndex].readOnly { + throw TOMLError(.syntax(lineNumber: lineNumber, message: "cannot add to inline table")) + } + + switch try tableValue(tableIndex: tableIndex, keyed: isKeyed, key: key, keyHash: keyHash) { + case .table(let existingTableIndex): + if keyTables[existingTableIndex].table.implicit { + if keyTables[existingTableIndex].table.definedByDottedKey { + throw TOMLError(.keyExists(lineNumber: lineNumber)) + } + keyTables[existingTableIndex].table.implicit = false + return existingTableIndex + } + throw TOMLError(.keyExists(lineNumber: lineNumber)) + case .keyValue, .array: + throw TOMLError(.keyExists(lineNumber: lineNumber)) + case nil: + break + } + let index = keyTables.count + var newTable = InternalTOMLTable() + newTable.implicit = implicit + newTable.definedByDottedKey = implicit + try budget.node(depth: depth) + keyTables.append( + KeyTablePair( + key: key, keyHash: keyHash, sourcePosition: token.text.lowerBound, table: newTable)) + + if isKeyed { + if keyTables[tableIndex].table.tables.isEmpty { + try budget.allocate(8, stage: "semantic storage") + keyTables[tableIndex].table.tables.reserveCapacity(8) + } + try budget.node(depth: depth) + keyTables[tableIndex].table.tables.append(index) + keyTables[tableIndex].table.recordKeyHash(keyHash) + } else { + if tables[tableIndex].tables.isEmpty { + try budget.allocate(8, stage: "semantic storage") + tables[tableIndex].tables.reserveCapacity(8) + } + try budget.node(depth: depth) + tables[tableIndex].tables.append(index) + tables[tableIndex].recordKeyHash(keyHash) + } + return index + } + + mutating func createKeyArray( + bytes: UnsafeBufferPointer, token: Token, inTable tableIndex: Int, isKeyed: Bool, + kind: InternalTOMLArray.Kind? = nil + ) throws -> Int { + let (key, keyHash) = try normalizeKeyAndHash(bytes: bytes, token: token) + return try createKeyArray( + normalizedKey: key, + keyHash: keyHash, + lineNumber: token.lineNumber, + inTable: tableIndex, + isKeyed: isKeyed, + kind: kind + ) + } + + mutating func createKeyArray( + normalizedKey key: String, keyHash: Int, lineNumber: Int, inTable tableIndex: Int, + isKeyed: Bool, kind: InternalTOMLArray.Kind? = nil + ) throws -> Int { + if try tableValue(tableIndex: tableIndex, keyed: isKeyed, key: key, keyHash: keyHash) != nil { + throw TOMLError(.keyExists(lineNumber: lineNumber)) + } + + let index = keyArrays.count + var array = InternalTOMLArray(kind: kind) + if kind == .table { + try budget.allocate(8, stage: "semantic storage") + array.elements.reserveCapacity(8) + } + try budget.node(depth: depth) + keyArrays.append( + KeyArrayPair(key: key, keyHash: keyHash, sourcePosition: token.text.lowerBound, array: array)) + if isKeyed { + if keyTables[tableIndex].table.arrays.isEmpty { + try budget.allocate(8, stage: "semantic storage") + keyTables[tableIndex].table.arrays.reserveCapacity(8) + } + try budget.node(depth: depth) + keyTables[tableIndex].table.arrays.append(index) + keyTables[tableIndex].table.recordKeyHash(keyHash) + } else { + if tables[tableIndex].arrays.isEmpty { + try budget.allocate(8, stage: "semantic storage") + tables[tableIndex].arrays.reserveCapacity(8) + } + try budget.node(depth: depth) + tables[tableIndex].arrays.append(index) + tables[tableIndex].recordKeyHash(keyHash) + } + return index + } + + @inline(__always) + mutating func skipNewlines(bytes: UnsafeBufferPointer, isDotSpecial: Bool) throws { + if token.kind != .newline { + return + } + + let count = bytes.count + var position = cursor + var lineNumber = currentLineNumber + + while position < count { + try budget.step() + let ch = bytes[position] + if ch == CodeUnits.space || ch == CodeUnits.tab { + // 8x unrolling for space/tab skipping + while position + 8 <= count { + try budget.step() + let c0 = bytes[position] + let c1 = bytes[position + 1] + let c2 = bytes[position + 2] + let c3 = bytes[position + 3] + let c4 = bytes[position + 4] + let c5 = bytes[position + 5] + let c6 = bytes[position + 6] + let c7 = bytes[position + 7] + + if c0 == CodeUnits.space || c0 == CodeUnits.tab, + c1 == CodeUnits.space || c1 == CodeUnits.tab, + c2 == CodeUnits.space || c2 == CodeUnits.tab, + c3 == CodeUnits.space || c3 == CodeUnits.tab, + c4 == CodeUnits.space || c4 == CodeUnits.tab, + c5 == CodeUnits.space || c5 == CodeUnits.tab, + c6 == CodeUnits.space || c6 == CodeUnits.tab, + c7 == CodeUnits.space || c7 == CodeUnits.tab + { + position += 8 + } else { + break + } + } + + while position < count { + try budget.step() + let ws = bytes[position] + if ws != CodeUnits.space, ws != CodeUnits.tab { + break + } + position += 1 + } + continue + } + switch ch { + case CodeUnits.lf: + lineNumber += 1 + position += 1 + case CodeUnits.cr: + if position + 1 < count, bytes[position + 1] == CodeUnits.lf { + lineNumber += 1 + position += 2 + } else { + // Bare CR, let nextToken handle error + cursor = position + currentLineNumber = lineNumber + try nextToken(bytes: bytes, isDotSpecial: isDotSpecial) + return + } + case CodeUnits.pound: + // Comment + position += 1 + while position < count { + try budget.step() + let c = bytes[position] + if c == CodeUnits.lf { + break // Leave LF for next iteration to handle line number + } + if (c >= CodeUnits.null && c <= CodeUnits.backspace) + || (c >= CodeUnits.lf && c <= CodeUnits.unitSeparator) || c == CodeUnits.delete + { + if c == CodeUnits.cr { + if position + 1 < count, bytes[position + 1] == CodeUnits.lf { + // CRLF ends comment + break + } + } + // Let nextToken throw the error + cursor = position + currentLineNumber = lineNumber + try nextToken(bytes: bytes, isDotSpecial: isDotSpecial) + return + } + position += 1 + } + default: + // Found something else, stop skipping + cursor = position + currentLineNumber = lineNumber + try nextToken(bytes: bytes, isDotSpecial: isDotSpecial) + return + } + } + + // If we hit EOF or loop finishes + cursor = position + currentLineNumber = lineNumber + try nextToken(bytes: bytes, isDotSpecial: isDotSpecial) + } + + mutating func parseKeyedInlineTable(bytes: UnsafeBufferPointer, tableIndex: Int) throws { + try budget.enter(depth + 1) + depth += 1 + defer { depth -= 1 } + try eatToken(bytes: bytes, kind: .lbrace, isDotSpecial: true) + + while true { + try budget.step() + try skipNewlines(bytes: bytes, isDotSpecial: false) + + if token.kind == .rbrace { + break + } + + if token.kind != .string, token.kind != .bareKey { + throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "expect a string")) + } + + try parseKeyValue(bytes: bytes, tableIndex: tableIndex, isKeyed: true) + + try skipNewlines(bytes: bytes, isDotSpecial: false) + + if token.kind == .comma { + try eatToken(bytes: bytes, kind: .comma, isDotSpecial: true) + continue + } + break + } + + try eatToken(bytes: bytes, kind: .rbrace, isDotSpecial: true) + + keyTables[tableIndex].table.readOnly = true + } + + mutating func parseInlineTable(bytes: UnsafeBufferPointer, tableIndex: Int) throws { + try budget.enter(depth + 1) + depth += 1 + defer { depth -= 1 } + try eatToken(bytes: bytes, kind: .lbrace, isDotSpecial: true) + + while true { + try budget.step() + try skipNewlines(bytes: bytes, isDotSpecial: false) + + if token.kind == .rbrace { + break + } + + if token.kind != .string, token.kind != .bareKey { + throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "expect a string")) + } + + try parseKeyValue(bytes: bytes, tableIndex: tableIndex, isKeyed: false) + + try skipNewlines(bytes: bytes, isDotSpecial: false) + + if token.kind == .comma { + try eatToken(bytes: bytes, kind: .comma, isDotSpecial: true) + continue + } + break + } + + try eatToken(bytes: bytes, kind: .rbrace, isDotSpecial: true) + + tables[tableIndex].readOnly = true + } + + mutating func parseKeyedArray(bytes: UnsafeBufferPointer, arrayIndex: Int) throws { + try budget.enter(depth + 1) + depth += 1 + defer { depth -= 1 } + try eatToken(bytes: bytes, kind: .lbracket, isDotSpecial: false) + + while true { + try budget.step() + try skipNewlines(bytes: bytes, isDotSpecial: false) + + if token.kind == .rbracket { + break + } + if keyArrays[arrayIndex].array.elements.isEmpty { + try budget.allocate(8, stage: "semantic storage") + keyArrays[arrayIndex].array.elements.reserveCapacity(8) + } + + switch token.kind { + case .string, .bareKey: + if keyArrays[arrayIndex].array.kind == nil { + keyArrays[arrayIndex].array.kind = .value + } else if keyArrays[arrayIndex].array.kind != .value { + keyArrays[arrayIndex].array.kind = .mixed + } + + try budget.node(depth: depth) + keyArrays[arrayIndex].array.elements.append(.leaf(token)) + + try nextToken(bytes: bytes, isDotSpecial: true) + + case .lbracket: // Nested array + if keyArrays[arrayIndex].array.kind == nil { + keyArrays[arrayIndex].array.kind = .array + } else if keyArrays[arrayIndex].array.kind != .array { + keyArrays[arrayIndex].array.kind = .mixed + } + + let newArrayIndex = arrays.count + try budget.node(depth: depth) + arrays.append(InternalTOMLArray()) + try budget.node(depth: depth) + keyArrays[arrayIndex].array.elements.append( + .array(lineNumber: token.lineNumber, newArrayIndex)) + + try parseArray(bytes: bytes, arrayIndex: newArrayIndex) + + case .lbrace: // Nested table + if keyArrays[arrayIndex].array.kind == nil { + keyArrays[arrayIndex].array.kind = .inlineTable + } else if keyArrays[arrayIndex].array.kind != .inlineTable { + keyArrays[arrayIndex].array.kind = .mixed + } + + let newTableIndex = tables.count + try budget.node(depth: depth) + tables.append(InternalTOMLTable()) + try budget.node(depth: depth) + keyArrays[arrayIndex].array.elements.append( + .table(lineNumber: token.lineNumber, newTableIndex)) + + try parseInlineTable(bytes: bytes, tableIndex: newTableIndex) + + default: + throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "syntax error")) + } + + try skipNewlines(bytes: bytes, isDotSpecial: false) + + if token.kind == .comma { + try eatToken(bytes: bytes, kind: .comma, isDotSpecial: false) + continue + } + break + } + + try eatToken(bytes: bytes, kind: .rbracket, isDotSpecial: true) + } + + mutating func parseArray(bytes: UnsafeBufferPointer, arrayIndex: Int) throws { + try budget.enter(depth + 1) + depth += 1 + defer { depth -= 1 } + try eatToken(bytes: bytes, kind: .lbracket, isDotSpecial: false) + + while true { + try budget.step() + try skipNewlines(bytes: bytes, isDotSpecial: false) + + if token.kind == .rbracket { + break + } + if arrays[arrayIndex].elements.isEmpty { + try budget.allocate(8, stage: "semantic storage") + arrays[arrayIndex].elements.reserveCapacity(8) + } + + switch token.kind { + case .string, .bareKey: + if arrays[arrayIndex].kind == nil { + arrays[arrayIndex].kind = .value + } else if arrays[arrayIndex].kind != .value { + arrays[arrayIndex].kind = .mixed + } + + try budget.node(depth: depth) + arrays[arrayIndex].elements.append(.leaf(token)) + + try nextToken(bytes: bytes, isDotSpecial: true) + + case .lbracket: // Nested array + if arrays[arrayIndex].kind == nil { + arrays[arrayIndex].kind = .array + } else if arrays[arrayIndex].kind != .array { + arrays[arrayIndex].kind = .mixed + } + + let newArrayIndex = arrays.count + try budget.node(depth: depth) + arrays.append(InternalTOMLArray()) + try budget.node(depth: depth) + arrays[arrayIndex].elements.append(.array(lineNumber: token.lineNumber, newArrayIndex)) + + try parseArray(bytes: bytes, arrayIndex: newArrayIndex) + + case .lbrace: // Nested table + if arrays[arrayIndex].kind == nil { + arrays[arrayIndex].kind = .inlineTable + } else if arrays[arrayIndex].kind != .inlineTable { + arrays[arrayIndex].kind = .mixed + } + + let newTableIndex = tables.count + try budget.node(depth: depth) + tables.append(InternalTOMLTable()) + try budget.node(depth: depth) + arrays[arrayIndex].elements.append(.table(lineNumber: token.lineNumber, newTableIndex)) + + try parseInlineTable(bytes: bytes, tableIndex: newTableIndex) + + default: + throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "syntax error")) + } + + try skipNewlines(bytes: bytes, isDotSpecial: false) + + if token.kind == .comma { + try eatToken(bytes: bytes, kind: .comma, isDotSpecial: false) + continue + } + break + } + + try eatToken(bytes: bytes, kind: .rbracket, isDotSpecial: true) + } + + mutating func parseKeyValue(bytes: UnsafeBufferPointer, tableIndex: Int, isKeyed: Bool) + throws + { + if isKeyed ? keyTables[tableIndex].table.readOnly : tables[tableIndex].readOnly { + throw TOMLError( + .syntax( + lineNumber: token.lineNumber, message: "cannot insert new entry into existing table")) + } + + let key = token + try nextToken(bytes: bytes, isDotSpecial: true) + + if token.kind == .dot { + try budget.enter(depth + 1) + depth += 1 + defer { depth -= 1 } + let (subTableKey, subTableHash) = try normalizeKeyAndHash( + bytes: bytes, + token: key + ) + let subTableIndex: Int + + if let existingTableIndex = try lookupTable( + in: tableIndex, keyed: isKeyed, key: subTableKey, keyHash: subTableHash) + { + // Check if the existing table is explicitly defined (not implicit) + if !keyTables[existingTableIndex].table.implicit { + throw TOMLError( + .syntax( + lineNumber: token.lineNumber, + message: "cannot add to explicitly defined table using dotted keys")) + } + subTableIndex = existingTableIndex + } else { + subTableIndex = try createKeyTable( + normalizedKey: subTableKey, + keyHash: subTableHash, + lineNumber: key.lineNumber, + inTable: tableIndex, + isKeyed: isKeyed, + implicit: true + ) + } + + try nextToken(bytes: bytes, isDotSpecial: true) + try parseKeyValue(bytes: bytes, tableIndex: subTableIndex, isKeyed: true) + return + } + + if token.kind != .equal { + throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "missing =")) + } + + try nextToken(bytes: bytes, isDotSpecial: false) + + if token.kind == .string || token.kind == .bareKey { + try createKeyValue( + bytes: bytes, token: key, value: token, inTable: tableIndex, isKeyed: isKeyed) + try nextToken(bytes: bytes, isDotSpecial: false) + return + } + + if token.kind == .lbracket { + let index = try createKeyArray( + bytes: bytes, token: key, inTable: tableIndex, isKeyed: isKeyed) + try parseKeyedArray(bytes: bytes, arrayIndex: index) + return + } + + if token.kind == .lbrace { + let index = try createKeyTable( + bytes: bytes, token: key, inTable: tableIndex, isKeyed: isKeyed) + try parseKeyedInlineTable(bytes: bytes, tableIndex: index) + return + } + + throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "syntax error")) + } + + mutating func fillTablePath(bytes: UnsafeBufferPointer, clearPath: Bool = true) throws -> ( + key: String, + keyHash: Int, + token: Token + ) { + let lineNumber = token.lineNumber + if clearPath { + tablePath.removeAll(keepingCapacity: true) + } + + while true { + try budget.step() + if token.kind != .string, token.kind != .bareKey { + throw TOMLError(.syntax(lineNumber: lineNumber, message: "invalid or missing key")) + } + + let currentToken = token + let (key, keyHash) = try normalizeKeyAndHash(bytes: bytes, token: token) + try nextToken(bytes: bytes, isDotSpecial: true) + + if token.kind == .rbracket { + return (key: key, keyHash: keyHash, token: currentToken) + } + + try budget.node(depth: depth) + tablePath.append((key: key, keyHash: keyHash)) + + if token.kind != .dot { + throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "invalid key")) + } + + try nextToken(bytes: bytes, isDotSpecial: true) + } + } + + mutating func parseSelect(bytes: UnsafeBufferPointer) throws { + assert(token.kind == .lbracket) + let nextIndex = token.text.lowerBound + 1 + let llb = nextIndex < bytes.count && bytes[nextIndex] == CodeUnits.lbracket + if llb { + cursor = nextIndex + 1 + try nextToken(bytes: bytes, isDotSpecial: true) + } else { + try eatToken(bytes: bytes, kind: .lbracket, isDotSpecial: true) + } + + if token.kind != .string, token.kind != .bareKey { + throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "invalid or missing key")) + } + + let firstToken = token + let firstIsBare = firstToken.kind == .bareKey + let firstKey: String? + let firstKeyHash: Int + if firstIsBare { + firstKey = nil + firstKeyHash = fastKeyHash(bytes: bytes, range: firstToken.text) + } else { + let normalized = try normalizeKeyAndHash( + bytes: bytes, + token: firstToken + ) + firstKey = normalized.key + firstKeyHash = normalized.keyHash + } + try nextToken(bytes: bytes, isDotSpecial: true) + + if token.kind == .rbracket { + currentTable = 0 + currentTableIsKeyed = false + if !llb { + let key = try firstKey ?? makeString(budget: budget, bytes: bytes, range: firstToken.text) + currentTable = try createKeyTable( + normalizedKey: key, + keyHash: firstKeyHash, + lineNumber: firstToken.lineNumber, + inTable: currentTable, + isKeyed: currentTableIsKeyed + ) + currentTableIsKeyed = true + } else { + let arrayIndex: Int + if firstIsBare { + if let existingArrayIndex = try lookupArray( + in: currentTable, + keyed: currentTableIsKeyed, + bytes: bytes, + token: firstToken, + keyHash: firstKeyHash + ) { + arrayIndex = existingArrayIndex + } else { + let key = try makeString(budget: budget, bytes: bytes, range: firstToken.text) + arrayIndex = try createKeyArray( + normalizedKey: key, + keyHash: firstKeyHash, + lineNumber: firstToken.lineNumber, + inTable: currentTable, + isKeyed: currentTableIsKeyed, + kind: .table + ) + } + } else { + let key = firstKey! + if let existingArrayIndex = try lookupArray( + in: currentTable, + keyed: currentTableIsKeyed, + key: key, + keyHash: firstKeyHash + ) { + arrayIndex = existingArrayIndex + } else { + arrayIndex = try createKeyArray( + normalizedKey: key, + keyHash: firstKeyHash, + lineNumber: firstToken.lineNumber, + inTable: currentTable, + isKeyed: currentTableIsKeyed, + kind: .table + ) + } + } + if keyArrays[arrayIndex].array.kind != .table { + throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "array mismatch")) + } + + let newTableIndex = tables.count + try budget.node(depth: depth) + tables.append(InternalTOMLTable()) + try budget.node(depth: depth) + keyArrays[arrayIndex].array.elements.append( + .table(lineNumber: token.lineNumber, newTableIndex)) + currentTable = newTableIndex + currentTableIsKeyed = false + } + } else { + if token.kind != .dot { + throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "invalid key")) + } + + let firstPathKey = + try firstKey ?? makeString(budget: budget, bytes: bytes, range: firstToken.text) + var pathTableIndex = 0 + var pathTableIsKeyed = false + try advanceTablePathSegment( + tableIndex: &pathTableIndex, + isKeyed: &pathTableIsKeyed, + key: firstPathKey, + keyHash: firstKeyHash + ) + + try nextToken(bytes: bytes, isDotSpecial: true) + if token.kind != .string, token.kind != .bareKey { + throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "invalid or missing key")) + } + + let secondToken = token + let (secondKey, secondKeyHash) = try normalizeKeyAndHash( + bytes: bytes, + token: secondToken + ) + try nextToken(bytes: bytes, isDotSpecial: true) + + let key: String + let keyHash: Int + let keyToken: Token + + if token.kind == .rbracket { + currentTable = pathTableIndex + currentTableIsKeyed = pathTableIsKeyed + key = secondKey + keyHash = secondKeyHash + keyToken = secondToken + } else { + tablePath.removeAll(keepingCapacity: true) + try budget.node(depth: depth) + tablePath.append((key: secondKey, keyHash: secondKeyHash)) + if token.kind != .dot { + throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "invalid key")) + } + try nextToken(bytes: bytes, isDotSpecial: true) + + let terminal = try fillTablePath(bytes: bytes, clearPath: false) + key = terminal.key + keyHash = terminal.keyHash + keyToken = terminal.token + try walkTablePath(startTable: pathTableIndex, startKeyed: pathTableIsKeyed) + } + + if !llb { + currentTable = try createKeyTable( + normalizedKey: key, + keyHash: keyHash, + lineNumber: keyToken.lineNumber, + inTable: currentTable, + isKeyed: currentTableIsKeyed + ) + currentTableIsKeyed = true + } else { + let arrayIndex: Int = + if let existingArrayIndex = try lookupArray( + in: currentTable, + keyed: currentTableIsKeyed, + key: key, + keyHash: keyHash + ) { + existingArrayIndex + } else { + try createKeyArray( + normalizedKey: key, + keyHash: keyHash, + lineNumber: keyToken.lineNumber, + inTable: currentTable, + isKeyed: currentTableIsKeyed, + kind: .table + ) + } + if keyArrays[arrayIndex].array.kind != .table { + throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "array mismatch")) + } + + let newTableIndex = tables.count + try budget.node(depth: depth) + tables.append(InternalTOMLTable()) + try budget.node(depth: depth) + keyArrays[arrayIndex].array.elements.append( + .table(lineNumber: token.lineNumber, newTableIndex)) + currentTable = newTableIndex + currentTableIsKeyed = false + } + } + + if token.kind != .rbracket { + throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "expects ]")) + } + + if llb { + guard cursor < bytes.count, bytes[cursor] == CodeUnits.rbracket else { + throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "expects ]]")) + } + cursor += 1 + try nextToken(bytes: bytes, isDotSpecial: true) + } else { + try eatToken(bytes: bytes, kind: .rbracket, isDotSpecial: true) + } + + if token.kind != .newline, token.kind != .eof { + throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "extra chars after ] or ]]")) + } + } +} + +extension Token { + func unpackBool(bytes: UnsafeBufferPointer, context: TOMLKey) throws -> Bool { + try budget.allocate(text.count, stage: "scalar decode") + try budget.step(text.count) + if text.count == 4, + bytes[text.lowerBound] == CodeUnits.lowerT, + bytes[text.lowerBound + 1] == CodeUnits.lowerR, + bytes[text.lowerBound + 2] == CodeUnits.lowerU, + bytes[text.lowerBound + 3] == CodeUnits.lowerE + { + return true + } else if text.count == 5, + bytes[text.lowerBound] == CodeUnits.lowerF, + bytes[text.lowerBound + 1] == CodeUnits.lowerA, + bytes[text.lowerBound + 2] == CodeUnits.lowerL, + bytes[text.lowerBound + 3] == CodeUnits.lowerS, + bytes[text.lowerBound + 4] == CodeUnits.lowerE + { + return false + } + + throw TOMLError(.invalidBool(context: context, lineNumber: lineNumber)) + } + + func unpackFloat(bytes: UnsafeBufferPointer, context: TOMLKey) throws -> Double { + try budget.allocate(text.count, stage: "scalar decode") + try budget.step(text.count) + var resultCodeUnits: [UTF8.CodeUnit] = [] + var index = text.lowerBound + if bytes[index] == CodeUnits.plus || bytes[index] == CodeUnits.minus { + try budget.allocate(1, stage: "decoded scalar storage") + resultCodeUnits.append(bytes[index]) + index += 1 + } + guard index < text.upperBound else { + throw TOMLError( + .invalidFloat( + context: context, lineNumber: lineNumber, reason: "expected digit, nan or inf after sign") + ) + } + + if !bytes[index].isDecimalDigit { + let nameEnd = index + 3 + guard nameEnd == text.upperBound, + (bytes[index] == CodeUnits.lowerN && bytes[index + 1] == CodeUnits.lowerA + && bytes[index + 2] == CodeUnits.lowerN) + || (bytes[index] == CodeUnits.lowerI && bytes[index + 1] == CodeUnits.lowerN + && bytes[index + 2] == CodeUnits.lowerF) + else { + throw TOMLError( + .invalidFloat( + context: context, lineNumber: lineNumber, + reason: "Expected nan or inf, found \(bytes[index])")) + } + try budget.allocate(1, stage: "decoded scalar storage") + resultCodeUnits.append(bytes[index]) + try budget.allocate(1, stage: "decoded scalar storage") + resultCodeUnits.append(bytes[index + 1]) + try budget.allocate(1, stage: "decoded scalar storage") + resultCodeUnits.append(bytes[index + 2]) + } else { + let nextIndex = index + 1 + if bytes[index] == CodeUnits.number0, + nextIndex < text.upperBound, + case let next = bytes[nextIndex], + next != CodeUnits.dot, next != CodeUnits.lowerE, next != CodeUnits.upperE + { + throw TOMLError( + .invalidFloat( + context: context, lineNumber: lineNumber, + reason: "Float begins with 0 must be followed by a '.', 'e' or 'E'")) + } + + while index < text.upperBound { + try budget.step() + let ch = bytes[index] + index += 1 + + if ch == CodeUnits.underscore { + guard + let last = resultCodeUnits.last, + last.isDecimalDigit + else { + throw TOMLError( + .invalidFloat( + context: context, lineNumber: lineNumber, reason: "'_' must be preceded by a digit") + ) + } + + guard + index < text.upperBound, + case let next = bytes[index], + next.isDecimalDigit + else { + throw TOMLError( + .invalidFloat( + context: context, lineNumber: lineNumber, reason: "'_' must be follewed by a digit") + ) + } + + continue + } else if ch == CodeUnits.dot { + if resultCodeUnits.isEmpty { + throw TOMLError( + .invalidFloat( + context: context, lineNumber: lineNumber, + reason: "First digit of floats cannot be '.'")) + } + + if !resultCodeUnits.last!.isDecimalDigit { + throw TOMLError( + .invalidFloat( + context: context, lineNumber: lineNumber, + reason: "'.' must be preceded by a decimal digit")) + } + + guard index < text.upperBound, bytes[index].isDecimalDigit else { + throw TOMLError( + .invalidFloat( + context: context, lineNumber: lineNumber, reason: "A digit must follow '.'")) + } + + } else if ch == CodeUnits.upperE || ch == CodeUnits.lowerE { + } else if !ch.isDecimalDigit, ch != CodeUnits.plus, ch != CodeUnits.minus { + throw TOMLError( + .invalidFloat( + context: context, lineNumber: lineNumber, reason: "invalid character for float")) + } + + try budget.allocate(1, stage: "decoded scalar storage") + resultCodeUnits.append(ch) + } + } + + guard let double = Double(String(decoding: resultCodeUnits, as: UTF8.self)) else { + throw TOMLError( + .invalidFloat(context: context, lineNumber: lineNumber, reason: "not a float")) + } + + return double + } + + func unpackString(bytes: UnsafeBufferPointer, context: TOMLKey) throws -> String { + try budget.allocate(text.count, stage: "scalar decode") + try budget.step(text.count) + var multiline = false + + if bytes.count == 0 { + throw TOMLError( + .invalidString(context: context, lineNumber: lineNumber, reason: "missing closing quote")) + } + + let quoteChar = bytes[text.lowerBound] + if quoteChar != CodeUnits.doubleQuote, quoteChar != CodeUnits.singleQuote { + throw TOMLError(.typeMismatch(context: context, lineNumber: lineNumber, expected: "string")) + } + var index = text.lowerBound + var endIndex = text.upperBound + + if endIndex - index >= 3 && bytes[index] == CodeUnits.doubleQuote + && bytes[index + 1] == CodeUnits.doubleQuote && bytes[index + 2] == CodeUnits.doubleQuote + || endIndex - index >= 3 && bytes[index] == CodeUnits.singleQuote + && bytes[index + 1] == CodeUnits.singleQuote && bytes[index + 2] == CodeUnits.singleQuote + { + multiline = true + index += 3 + endIndex -= 3 + + if index < endIndex, bytes[index] == CodeUnits.lf { + index += 1 + } else if endIndex - index >= 2, bytes[index] == CodeUnits.cr, + bytes[index + 1] == CodeUnits.lf + { + index += 2 + } + } else { + index = index + 1 + endIndex = endIndex - 1 + guard endIndex >= 0, bytes[endIndex] == quoteChar else { + throw TOMLError( + .invalidString(context: context, lineNumber: lineNumber, reason: "missing closing quote")) + } + } + + if quoteChar == CodeUnits.singleQuote { + return try literalString( + budget: budget, bytes: bytes, range: index.., context: TOMLKey) throws -> Int64 { + try budget.allocate(text.count, stage: "scalar decode") + try budget.step(text.count) + @_transparent + func isValidDigit(_ codeUnit: UTF8.CodeUnit, base: Int) -> Bool { + switch base { + case 10: + codeUnit.isDecimalDigit + case 16: + codeUnit.isHexDigit + case 2: + codeUnit == CodeUnits.number0 || codeUnit == CodeUnits.number1 + case 8: + CodeUnits.number0 <= codeUnit && codeUnit <= CodeUnits.number7 + default: + false + } + } + + var resultCodeUnits: [UTF8.CodeUnit] = [] + var index = text.lowerBound + var base = 10 + var hasSign = false + if bytes[index] == CodeUnits.plus || bytes[index] == CodeUnits.minus { + hasSign = true + try budget.allocate(1, stage: "decoded scalar storage") + resultCodeUnits.append(bytes[index]) + index = text.index(after: index) + } + guard index < text.upperBound else { + throw TOMLError( + .invalidInteger( + context: context, lineNumber: lineNumber, reason: "expected digit after sign")) + } + + if bytes[index] == CodeUnits.underscore { + throw TOMLError( + .invalidInteger(context: context, lineNumber: lineNumber, reason: "cannot start with a '_'") + ) + } + + if bytes[index] == CodeUnits.number0 { + let nextIndex = index + 1 + if nextIndex < text.upperBound { + if bytes[nextIndex] == CodeUnits.lowerX { + if hasSign { + throw TOMLError( + .invalidInteger( + context: context, lineNumber: lineNumber, + reason: "hexadecimal integers cannot have explicit signs")) + } + base = 16 + index += 2 + } else if bytes[nextIndex] == CodeUnits.lowerO { + if hasSign { + throw TOMLError( + .invalidInteger( + context: context, lineNumber: lineNumber, + reason: "octal integers cannot have explicit signs")) + } + base = 8 + index += 2 + } else if bytes[nextIndex] == CodeUnits.lowerB { + if hasSign { + throw TOMLError( + .invalidInteger( + context: context, lineNumber: lineNumber, + reason: "binary integers cannot have explicit signs")) + } + base = 2 + index += 2 + } else if bytes[nextIndex].isDecimalDigit || bytes[nextIndex] == CodeUnits.underscore { + throw TOMLError( + .invalidInteger( + context: context, lineNumber: lineNumber, + reason: "decimal integers cannot have leading zeros")) + } + } + // Single zero is allowed to continue to the main loop + } + guard index < text.upperBound else { + throw TOMLError( + .invalidInteger( + context: context, lineNumber: lineNumber, reason: "expected digit after base prefix")) + } + + while index < text.upperBound { + try budget.step() + let ch = bytes[index] + index += 1 + + if ch == CodeUnits.underscore { + guard + let last = resultCodeUnits.last, + isValidDigit(last, base: base) + else { + throw TOMLError( + .invalidInteger( + context: context, lineNumber: lineNumber, + reason: "cannot use '_' adjacent to a non-digit")) + } + + if index >= text.endIndex { + throw TOMLError( + .invalidInteger( + context: context, lineNumber: lineNumber, reason: "cannot end with a '_'")) + } + + let next = bytes[index] + if next == CodeUnits.underscore { + throw TOMLError( + .invalidInteger( + context: context, lineNumber: lineNumber, reason: "cannot contain consecutive '_'")) + } + guard isValidDigit(next, base: base) else { + throw TOMLError( + .invalidInteger( + context: context, lineNumber: lineNumber, + reason: "cannot use '_' adjacent to a non-digit")) + } + continue + } + + guard isValidDigit(ch, base: base) else { + throw TOMLError( + .invalidInteger( + context: context, lineNumber: lineNumber, reason: "invalid digit for base \(base)")) + } + + try budget.allocate(1, stage: "decoded scalar storage") + resultCodeUnits.append(ch) + } + + let s = String(decoding: resultCodeUnits, as: UTF8.self) + guard let i = Int64(s, radix: base) else { + throw TOMLError( + .invalidInteger( + context: context, lineNumber: lineNumber, + reason: "\(s) is a invalid integer of base \(base)")) + } + return i + } + + func unpackDateTime(bytes: UnsafeBufferPointer, context: TOMLKey) throws + -> DateTimeComponents + { + try budget.allocate(text.count, stage: "scalar decode") + try budget.step(text.count) + var mustParseTime = false + var date: (year: Int, month: Int, day: Int)? + var time: (hour: Int, minute: Int, second: Int)? + + var index = text.lowerBound + if let (year, month, day, _) = scanDate(bytes: bytes, range: text) { + // Validate date components + if month < 1 || month > 12 { + throw TOMLError( + .invalidDateTime3( + context: context, lineNumber: lineNumber, reason: "month must be between 01 and 12")) + } + if day < 1 { + throw TOMLError( + .invalidDateTime3( + context: context, lineNumber: lineNumber, reason: "day must be between 01 and 31")) + } + + // Validate days per month and leap years + let isLeapYear = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) + let maxDaysInMonth: Int = + switch month { + case 2: + isLeapYear ? 29 : 28 + case 4, 6, 9, 11: + 30 + default: + 31 + } + + if day > maxDaysInMonth { + if month == 2, !isLeapYear { + throw TOMLError( + .invalidDateTime3( + context: context, lineNumber: lineNumber, + reason: "February only has 28 days in non-leap years")) + } else if month == 2, isLeapYear { + throw TOMLError( + .invalidDateTime3( + context: context, lineNumber: lineNumber, + reason: "February only has 29 days in leap years")) + } else { + throw TOMLError( + .invalidDateTime3( + context: context, lineNumber: lineNumber, + reason: "day \(day) is invalid for month \(month)")) + } + } + + date = (year, month, day) + index += 10 + } + + var features: OffsetDateTime.Features = [] + var nanoseconds: UInt32? + if index < text.upperBound { + if date != nil { + let isSeparatorLowerT = bytes[index] == CodeUnits.lowerT + let isSeparatorUpperT = bytes[index] == CodeUnits.upperT + guard isSeparatorLowerT || isSeparatorUpperT || bytes[index] == CodeUnits.space else { + throw TOMLError( + .invalidDateTime3( + context: context, lineNumber: lineNumber, + reason: "expected 'T' or 't' or space to separate date and time")) + } + if isSeparatorLowerT { + features.insert(.lowercaseT) + } else if isSeparatorUpperT { + features.insert(.uppercaseT) + } + mustParseTime = true + index += 1 + } else { + // For standalone time values, don't advance index + mustParseTime = true + } + if let (hour, minute, second, newIndex) = scanTime( + bytes: bytes, range: index.. 23 { + throw TOMLError( + .invalidDateTime3( + context: context, lineNumber: lineNumber, reason: "hour must be between 00 and 23")) + } + if minute > 59 { + throw TOMLError( + .invalidDateTime3( + context: context, lineNumber: lineNumber, reason: "minute must be between 00 and 59")) + } + if second > 59 { + throw TOMLError( + .invalidDateTime3( + context: context, lineNumber: lineNumber, reason: "second must be between 00 and 59")) + } + + time = (hour, minute, second) + + index = newIndex + if index < text.upperBound, bytes[index] == CodeUnits.dot { + index += 1 + let beforeNanoIndex = index + nanoseconds = try parseNanoSeconds( + budget: budget, bytes: bytes, range: index.. 24 { + throw TOMLError( + .invalidDateTime3( + context: context, lineNumber: lineNumber, + reason: "timezone offset hour must be between 00 and 24")) + } + if offsetMinute > 59 { + throw TOMLError( + .invalidDateTime3( + context: context, lineNumber: lineNumber, + reason: "timezone offset minute must be between 00 and 59")) + } + + let offsetInMinutes = offsetHour * 60 + offsetMinute + timeOffset = Int16(offsetIsNegative ? -offsetInMinutes : offsetInMinutes) + index += consumedLength + } catch let parseError { + if let tomlError = parseError as? TOMLError { + switch tomlError.reason { + case .invalidDateTime(_, let reason): + throw TOMLError( + .invalidDateTime3(context: context, lineNumber: lineNumber, reason: reason)) + default: + throw tomlError + } + } else { + throw TOMLError( + .invalidDateTime3( + context: context, lineNumber: lineNumber, reason: "timezone parsing error")) + } + } + } + } + + if index < text.upperBound { + throw TOMLError( + .invalidDateTime3( + context: context, lineNumber: lineNumber, reason: "extra character after date time")) + } + + return DateTimeComponents( + date: date.map { + LocalDate(year: .init($0.year), month: .init($0.month), day: .init($0.day)) + }, + time: time.map { + LocalTime( + hour: .init($0.hour), minute: .init($0.minute), second: .init($0.second), + nanosecond: nanoseconds ?? 0) + }, + offset: timeOffset, + features: features + ) + } + +} + +func parseTimezoneOffset(bytes: UnsafeBufferPointer, range: Range, lineNumber: Int) + throws -> (hour: Int, minute: Int, consumedLength: Int) +{ + guard range.count >= 2 else { + throw TOMLError( + .invalidDateTime( + lineNumber: lineNumber, reason: "timezone offset must have at least 2 digits for hour")) + } + + var index = range.lowerBound + + // Parse hour digits (exactly 2 required) + guard + index < range.upperBound, + bytes[index].isDecimalDigit, + case let firstHourDigit = bytes[index], + case let nextIndex = index + 1, + nextIndex < range.upperBound, + bytes[nextIndex].isDecimalDigit, + case let secondHourDigit = bytes[nextIndex] + else { + throw TOMLError( + .invalidDateTime( + lineNumber: lineNumber, reason: "timezone offset hour must be exactly 2 digits")) + } + + let offsetHour = + Int(firstHourDigit - CodeUnits.number0) * 10 + Int(secondHourDigit - CodeUnits.number0) + index += 2 + var consumedLength = 2 + + // Parse required minute digits (timezone offset must include minutes) + guard index < range.upperBound, bytes[index] == CodeUnits.colon else { + throw TOMLError( + .invalidDateTime( + lineNumber: lineNumber, reason: "timezone offset must include minutes (format: ±HH:MM)")) + } + + index += 1 + consumedLength += 1 + + guard + index < range.upperBound, + bytes[index].isDecimalDigit, + case let firstMinuteDigit = bytes[index], + case let nextMinuteIndex = index + 1, + nextMinuteIndex < range.upperBound, + bytes[nextMinuteIndex].isDecimalDigit, + case let secondMinuteDigit = bytes[nextMinuteIndex] + else { + throw TOMLError( + .invalidDateTime( + lineNumber: lineNumber, reason: "timezone offset minute must be exactly 2 digits")) + } + + let offsetMinute = + Int(firstMinuteDigit - CodeUnits.number0) * 10 + Int(secondMinuteDigit - CodeUnits.number0) + consumedLength += 2 + + return (offsetHour, offsetMinute, consumedLength) +} + +func literalString( + budget: SemanticBudget, bytes: UnsafeBufferPointer, range: Range, multiline: Bool +) throws -> String { + var resultCodeUnits: [UTF8.CodeUnit] = [] + var consecutiveQuotes = 0 + + for index in range { + try budget.step() + let codeUnit = bytes[index] + if codeUnit >= CodeUnits.null && codeUnit <= CodeUnits.backspace + || codeUnit >= CodeUnits.lf && codeUnit <= CodeUnits.unitSeparator + || codeUnit == CodeUnits.delete + { + if multiline, codeUnit == CodeUnits.lf { + // Allow LF in multiline literal strings + } else if multiline, codeUnit == CodeUnits.cr { + // Only allow CR if followed by LF (CRLF sequence) + let nextIndex = index + 1 + if nextIndex < range.upperBound, bytes[nextIndex] == CodeUnits.lf { + // Allow CRLF sequence - will be processed as separate characters + } else { + throw TOMLError(.invalidCharacter(codeUnit)) + } + } else { + throw TOMLError(.invalidCharacter(codeUnit)) + } + } + + if multiline, codeUnit == CodeUnits.singleQuote { + consecutiveQuotes += 1 + if consecutiveQuotes > 2 { + throw TOMLError( + .syntax( + lineNumber: 0, + message: + "literal multiline strings cannot contain more than 2 consecutive single quotes")) + } + } else { + consecutiveQuotes = 0 + } + + try budget.allocate(1, stage: "decoded scalar storage") + resultCodeUnits.append(codeUnit) + } + return String(decoding: resultCodeUnits, as: UTF8.self) +} + +func basicString( + budget: SemanticBudget, bytes: UnsafeBufferPointer, range: Range, multiline: Bool +) throws -> String { + let startIndex = range.lowerBound + let endIndex = range.upperBound + var resultCodeUnits: [UTF8.CodeUnit] = [] + try budget.allocate(range.count, stage: "decoded string capacity") + resultCodeUnits.reserveCapacity(range.count) + var consecutiveQuotes = 0 + var index = startIndex + while true { + try budget.step() + if index >= endIndex { + break + } + + var ch = bytes[index] + index += 1 + if ch != CodeUnits.backslash { + if ch >= CodeUnits.null && ch <= CodeUnits.backspace + || ch >= CodeUnits.lf && ch <= CodeUnits.unitSeparator || ch == CodeUnits.delete + { + if multiline, ch == CodeUnits.lf { + // Allow LF in multiline basic strings + } else if multiline, ch == CodeUnits.cr { + // Only allow CR if followed by LF (CRLF sequence) + if index < endIndex, bytes[index] == CodeUnits.lf { + // Allow CRLF sequence - will be processed as separate characters + } else { + throw TOMLError(.invalidCharacter(ch)) + } + } else { + throw TOMLError(.invalidCharacter(ch)) + } + } + + if multiline, ch == CodeUnits.doubleQuote { + consecutiveQuotes += 1 + if consecutiveQuotes > 2 { + throw TOMLError( + .syntax( + lineNumber: 0, + message: + "basic multiline strings cannot contain more than 2 consecutive double quotes" + ) + ) + } + } else { + consecutiveQuotes = 0 + } + + try budget.allocate(1, stage: "decoded scalar storage") + resultCodeUnits.append(ch) + continue + } + + if index >= endIndex { + throw TOMLError(.invalidCharacter(CodeUnits.backslash)) + } + + func indexAfterSkippingCharacters(start: Int, endIndex: Int, characters: [UTF8.CodeUnit]) + throws -> Int + { + var index = start + while index < endIndex { + try budget.step() + if characters.contains(bytes[index]) { + index += 1 + } else { + break + } + } + return index + } + + if multiline { + let afterWhitespace = try indexAfterSkippingCharacters( + start: index, endIndex: endIndex, + characters: [CodeUnits.space, CodeUnits.tab, CodeUnits.cr] + ) + if afterWhitespace < endIndex, bytes[afterWhitespace] == CodeUnits.lf { + index = try indexAfterSkippingCharacters( + start: index, endIndex: endIndex, + characters: [CodeUnits.space, CodeUnits.tab, CodeUnits.cr, CodeUnits.lf] + ) + continue + } + } + + ch = bytes[index] + index += 1 + + if ch == CodeUnits.lowerU || ch == CodeUnits.upperU || ch == CodeUnits.lowerX { + let hexCount = + switch ch { + case CodeUnits.lowerU: 4 + case CodeUnits.upperU: 8 + case CodeUnits.lowerX: 2 + default: fatalError("Unsupported CodeUnit: \(ch)") + } + var ucs: UInt32 = 0 + for _ in 0..= endIndex { + throw TOMLError(.expectedHexCharacters(ch, hexCount)) + } + ch = bytes[index] + index += 1 + let v: Int32 = + ch.isDecimalDigit + ? Int32(ch - CodeUnits.number0) + : (ch >= CodeUnits.upperA && ch <= CodeUnits.upperF) + ? Int32(ch - CodeUnits.upperA + 10) + : (ch >= CodeUnits.lowerA && ch <= CodeUnits.lowerF) + ? Int32(ch - CodeUnits.lowerA + 10) + : -1 + if v == -1 { + throw TOMLError(.invalidHexCharacters(ch)) + } + ucs = ucs * 16 + UInt32(v) + } + guard let scalar = Unicode.Scalar(ucs) else { + throw TOMLError(.illegalUCSCode(ucs)) + } + try budget.allocate(1, stage: "decoded scalar storage") + resultCodeUnits.append(contentsOf: scalar.utf8) + continue + } else if ch == CodeUnits.lowerB { + ch = CodeUnits.backspace + } else if ch == CodeUnits.lowerT { + ch = CodeUnits.tab + } else if ch == CodeUnits.lowerF { + ch = CodeUnits.formfeed + } else if ch == CodeUnits.lowerR { + ch = CodeUnits.cr + } else if ch == CodeUnits.lowerN { + ch = CodeUnits.lf + } else if ch == CodeUnits.lowerE { + ch = CodeUnits.escape + } else if ch != CodeUnits.doubleQuote, ch != CodeUnits.backslash { + throw TOMLError(.illegalEscapeCharacter(ch)) + } + + consecutiveQuotes = 0 // Reset count after escape sequence + try budget.allocate(1, stage: "decoded scalar storage") + resultCodeUnits.append(ch) + } + return String(decoding: resultCodeUnits, as: UTF8.self) +} + +func scanDate(bytes: UnsafeBufferPointer, range: Range) -> (Int, Int, Int, Int)? { + guard let year = scanDigits(bytes: bytes, range: range, n: 4) else { + return nil + } + + var index = range.lowerBound + index += 4 + + guard index < range.upperBound, bytes[index] == CodeUnits.minus else { + return nil + } + + index += 1 + guard let month = scanDigits(bytes: bytes, range: index.., range: Range, n: Int) -> Int? { + var result = 0 + var n = n + var index = range.lowerBound + while n > 0, index < range.upperBound, bytes[index].isDecimalDigit { + result = 10 * result + Int(bytes[index]) - Int(CodeUnits.number0) + index += 1 + n -= 1 + } + return n != 0 ? nil : result +} + +func scanTime(bytes: UnsafeBufferPointer, range: Range) -> (Int, Int, Int, Int)? { + guard let hour = scanDigits(bytes: bytes, range: range, n: 2) else { + return nil + } + + var index = range.lowerBound + + index += 2 + guard index < range.upperBound, bytes[index] == CodeUnits.colon else { + return nil + } + + index += 1 + guard let minute = scanDigits(bytes: bytes, range: index.., range: Range, + updatedIndex: inout Int +) throws -> UInt32 { + var unit: Double = 100_000_000 + var result: Double = 0 + var index = range.lowerBound + while index < range.upperBound, bytes[index].isDecimalDigit { + try budget.step() + result += Double(bytes[index] - CodeUnits.number0) * unit + index += 1 + unit /= 10 + } + updatedIndex = index + return UInt32(result) +} + +func scanTimezoneOffset(bytes: UnsafeBufferPointer, range: Range) -> Int? { + var index = range.lowerBound + guard index < range.upperBound, bytes[index] == CodeUnits.plus || bytes[index] == CodeUnits.minus + else { + return nil + } + + index += 1 + guard scanDigits(bytes: bytes, range: index.. Bool { + let ones: UInt64 = 0x0101_0101_0101_0101 + let highBits: UInt64 = 0x8080_8080_8080_8080 + + @inline(__always) + func hasByte(_ bytePattern: UInt64) -> Bool { + let xor = chunk ^ bytePattern + return ((xor &- ones) & ~xor & highBits) != 0 + } + + return hasByte(0x2222_2222_2222_2222) + || hasByte(0x5C5C_5C5C_5C5C_5C5C) + || hasByte(0x0A0A_0A0A_0A0A_0A0A) +} + +func normalizeKeyAndHash(bytes: UnsafeBufferPointer, token: Token) throws -> ( + key: String, keyHash: Int +) { + let budget = token.budget! + try budget.allocate(token.text.count, stage: "decoded key") + var start = token.text.lowerBound + var end = token.text.upperBound + if token.kind == .bareKey { + let str = try makeString(budget: budget, bytes: bytes, range: start..= CodeUnits.number0 && byte <= CodeUnits.number9 // 0-9 + || byte >= CodeUnits.upperA && byte <= CodeUnits.upperZ // A-Z + || byte >= CodeUnits.lowerA && byte <= CodeUnits.lowerZ // a-z + || byte == CodeUnits.underscore // _ + || byte == CodeUnits.minus // - + { + continue + } + throw TOMLError(.badKey(lineNumber: token.lineNumber)) + } + + let key = try makeString(budget: budget, bytes: bytes, range: start.., range: Range) -> Int { + let count = range.upperBound - range.lowerBound + if count == 0 { + return 0 + } + let start = bytes.baseAddress!.advanced(by: range.lowerBound) + if count <= 8 { + return Int(truncatingIfNeeded: packedKeyHash(UnsafeBufferPointer(start: start, count: count))) + } + return Int(truncatingIfNeeded: sampledKeyHash(start: start, count: count)) +} + +@inline(__always) +func fastKeyHash(_ key: String) -> Int { + if let hash = key.utf8.withContiguousStorageIfAvailable({ buffer -> UInt64 in + if buffer.count <= 8 { + return packedKeyHash(buffer) + } + if let start = buffer.baseAddress { + return sampledKeyHash(start: start, count: buffer.count) + } + return 0 + }) { + return Int(truncatingIfNeeded: hash) + } + + let offsetBasis: UInt64 = 14_695_981_039_346_656_037 + let prime: UInt64 = 1_099_511_628_211 + var hash = offsetBasis + var packed: UInt64 = 0 + var count = 0 + for byte in key.utf8 { + if count < 8 { + packed |= UInt64(byte) << (UInt64(count) * 8) + } + hash ^= UInt64(byte) + hash &*= prime + count += 1 + } + return Int(truncatingIfNeeded: count <= 8 ? packed : hash) +} + +@inline(__always) +private func sampledKeyHash(start: UnsafePointer, count: Int) -> UInt64 { + let prefix = packedKeyHash(UnsafeBufferPointer(start: start, count: 8)) + let suffix = packedKeyHash(UnsafeBufferPointer(start: start.advanced(by: count - 8), count: 8)) + let rotatedSuffix = (suffix << 1) | (suffix >> 63) + return prefix ^ rotatedSuffix ^ (UInt64(truncatingIfNeeded: count) &* 0x9E37_79B1_85EB_CA87) +} + +@inline(__always) +private func packedKeyHash(_ buffer: UnsafeBufferPointer) -> UInt64 { + var packed: UInt64 = 0 + switch buffer.count { + case 8: + packed |= UInt64(buffer[7]) << 56 + fallthrough + case 7: + packed |= UInt64(buffer[6]) << 48 + fallthrough + case 6: + packed |= UInt64(buffer[5]) << 40 + fallthrough + case 5: + packed |= UInt64(buffer[4]) << 32 + fallthrough + case 4: + packed |= UInt64(buffer[3]) << 24 + fallthrough + case 3: + packed |= UInt64(buffer[2]) << 16 + fallthrough + case 2: + packed |= UInt64(buffer[1]) << 8 + fallthrough + case 1: + packed |= UInt64(buffer[0]) + default: + break + } + return packed +} + +@inline(__always) +private func makeString( + budget: SemanticBudget, bytes: UnsafeBufferPointer, range: Range +) throws -> String { + try budget.allocate(range.count, stage: "decoded key copy") + try budget.step(range.count) + let count = range.upperBound - range.lowerBound + if count == 0 { + return "" + } + let start = bytes.baseAddress!.advanced(by: range.lowerBound) + return String(decoding: UnsafeBufferPointer(start: start, count: count), as: UTF8.self) +} + +extension Parser { + @inline(__always) + func matchKeyValue(in indices: borrowing [Int], key: borrowing String, keyHash: Int) throws + -> Int? + { + if indices.isEmpty { + return nil + } + return try keyValues.withUnsafeBufferPointer { keyValueBuffer -> Int? in + guard let keyValueBase = keyValueBuffer.baseAddress else { + return nil + } + let indexCount = indices.count + var i = 0 + while i < indexCount { + try budget.step() + let keyValueIndex = indices[i] + let keyValuePair = keyValueBase.advanced(by: keyValueIndex).pointee + if keyValuePair.keyHash == keyHash, try budget.equal(keyValuePair.key, key) { + return keyValueIndex + } + i += 1 + } + return nil + } + } + + @inline(__always) + func matchKeyArray(in indices: borrowing [Int], key: borrowing String, keyHash: Int) throws + -> Int? + { + if indices.isEmpty { + return nil + } + return try keyArrays.withUnsafeBufferPointer { keyArrayBuffer -> Int? in + guard let keyArrayBase = keyArrayBuffer.baseAddress else { + return nil + } + let indexCount = indices.count + var i = 0 + while i < indexCount { + try budget.step() + let keyArrayIndex = indices[i] + let keyArrayPair = keyArrayBase.advanced(by: keyArrayIndex).pointee + if keyArrayPair.keyHash == keyHash, try budget.equal(keyArrayPair.key, key) { + return keyArrayIndex + } + i += 1 + } + return nil + } + } + + @inline(__always) + func keyMatchesToken(bytes: UnsafeBufferPointer, token: Token, key: borrowing String) + throws -> Bool + { + let range = token.text + let count = range.upperBound - range.lowerBound + + if let matches = try key.utf8.withContiguousStorageIfAvailable({ keyBuffer -> Bool in + if keyBuffer.count != count { + return false + } + + var keyIndex = 0 + var byteIndex = range.lowerBound + while keyIndex < count { + try budget.step() + if keyBuffer[keyIndex] != bytes[byteIndex] { + return false + } + keyIndex += 1 + byteIndex += 1 + } + return true + }) { + return matches + } + + var index = range.lowerBound + for byte in key.utf8 { + try budget.step() + if index >= range.upperBound || bytes[index] != byte { + return false + } + index += 1 + } + return index == range.upperBound + } + + @inline(__always) + func matchKeyArray( + in indices: borrowing [Int], + bytes: UnsafeBufferPointer, + token: Token, + keyHash: Int + ) throws -> Int? { + if indices.isEmpty { + return nil + } + return try keyArrays.withUnsafeBufferPointer { keyArrayBuffer -> Int? in + guard let keyArrayBase = keyArrayBuffer.baseAddress else { + return nil + } + let indexCount = indices.count + var i = 0 + while i < indexCount { + try budget.step() + let keyArrayIndex = indices[i] + let keyArrayPair = keyArrayBase.advanced(by: keyArrayIndex).pointee + if keyArrayPair.keyHash == keyHash, + try keyMatchesToken(bytes: bytes, token: token, key: keyArrayPair.key) + { + return keyArrayIndex + } + i += 1 + } + return nil + } + } + + @inline(__always) + func matchKeyTable(in indices: borrowing [Int], key: borrowing String, keyHash: Int) throws + -> Int? + { + if indices.isEmpty { + return nil + } + return try keyTables.withUnsafeBufferPointer { keyTableBuffer -> Int? in + guard let keyTableBase = keyTableBuffer.baseAddress else { + return nil + } + let indexCount = indices.count + var i = 0 + while i < indexCount { + try budget.step() + let keyTableIndex = indices[i] + let keyTablePair = keyTableBase.advanced(by: keyTableIndex).pointee + if keyTablePair.keyHash == keyHash, try budget.equal(keyTablePair.key, key) { + return keyTableIndex + } + i += 1 + } + return nil + } + } + + @inline(__always) + func tableValue( + tableIndex: Int, + keyed: Bool, + key: borrowing String, + keyHash: Int + ) throws -> InternalTOMLTable.Value? { + if keyed { + if !keyTables[tableIndex].table.mightContainKeyHash(keyHash) { + return nil + } + } else if !tables[tableIndex].mightContainKeyHash(keyHash) { + return nil + } + + if keyed { + if let keyValueIndex = try matchKeyValue( + in: keyTables[tableIndex].table.keyValues, key: key, keyHash: keyHash) + { + return .keyValue(keyValueIndex) + } + + if let keyArrayIndex = try matchKeyArray( + in: keyTables[tableIndex].table.arrays, key: key, keyHash: keyHash) + { + return .array(keyArrayIndex) + } + + if let keyTableIndex = try matchKeyTable( + in: keyTables[tableIndex].table.tables, key: key, keyHash: keyHash) + { + return .table(keyTableIndex) + } + return nil + } + + if let keyValueIndex = try matchKeyValue( + in: tables[tableIndex].keyValues, key: key, keyHash: keyHash) + { + return .keyValue(keyValueIndex) + } + + if let keyArrayIndex = try matchKeyArray( + in: tables[tableIndex].arrays, key: key, keyHash: keyHash) + { + return .array(keyArrayIndex) + } + + if let keyTableIndex = try matchKeyTable( + in: tables[tableIndex].tables, key: key, keyHash: keyHash) + { + return .table(keyTableIndex) + } + + return nil + } + + @inline(__always) + func lookupTable(in tableIndex: Int, keyed: Bool, key: borrowing String, keyHash: Int) throws + -> Int? + { + if keyed { + if !keyTables[tableIndex].table.mightContainKeyHash(keyHash) { + return nil + } + return try matchKeyTable(in: keyTables[tableIndex].table.tables, key: key, keyHash: keyHash) + } + if !tables[tableIndex].mightContainKeyHash(keyHash) { + return nil + } + return try matchKeyTable(in: tables[tableIndex].tables, key: key, keyHash: keyHash) + } + + @inline(__always) + func lookupArray(in tableIndex: Int, keyed: Bool, key: borrowing String, keyHash: Int) throws + -> Int? + { + if keyed { + if !keyTables[tableIndex].table.mightContainKeyHash(keyHash) { + return nil + } + return try matchKeyArray(in: keyTables[tableIndex].table.arrays, key: key, keyHash: keyHash) + } + if !tables[tableIndex].mightContainKeyHash(keyHash) { + return nil + } + return try matchKeyArray(in: tables[tableIndex].arrays, key: key, keyHash: keyHash) + } + + @inline(__always) + func lookupArray( + in tableIndex: Int, + keyed: Bool, + bytes: UnsafeBufferPointer, + token: Token, + keyHash: Int + ) throws -> Int? { + if keyed { + if !keyTables[tableIndex].table.mightContainKeyHash(keyHash) { + return nil + } + return try matchKeyArray( + in: keyTables[tableIndex].table.arrays, + bytes: bytes, + token: token, + keyHash: keyHash + ) + } + if !tables[tableIndex].mightContainKeyHash(keyHash) { + return nil + } + return try matchKeyArray( + in: tables[tableIndex].arrays, + bytes: bytes, + token: token, + keyHash: keyHash + ) + } + + mutating func advanceTablePathSegment( + tableIndex: inout Int, + isKeyed: inout Bool, + key: String, + keyHash: Int + ) throws { + if isKeyed ? keyTables[tableIndex].table.readOnly : tables[tableIndex].readOnly { + throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "cannot add to inline table")) + } + switch try tableValue(tableIndex: tableIndex, keyed: isKeyed, key: key, keyHash: keyHash) { + case .table(let index): + guard !keyTables[index].table.readOnly else { + throw TOMLError( + .syntax(lineNumber: token.lineNumber, message: "cannot add to inline table")) + } + tableIndex = index + isKeyed = true + case .array(let arrayIndex): + let array = keyArrays[arrayIndex].array + guard case .table = array.kind else { + throw TOMLError( + .syntax(lineNumber: token.lineNumber, message: "array element is not a table")) + } + + if array.elements.isEmpty { + throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "empty array")) + } + + guard case .table(_, let index) = array.elements.last else { + throw TOMLError( + .syntax(lineNumber: token.lineNumber, message: "array element is not a table")) + } + + tableIndex = index + isKeyed = false + case .keyValue: + throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "key-value already exists")) + default: + let newTableAddress = keyTables.count + var newTable = InternalTOMLTable() + newTable.implicit = true + newTable.definedByDottedKey = false + try budget.node(depth: depth) + keyTables.append( + KeyTablePair( + key: key, keyHash: keyHash, sourcePosition: token.text.lowerBound, table: newTable)) + + if isKeyed { + if keyTables[tableIndex].table.tables.isEmpty { + try budget.allocate(8, stage: "semantic storage") + keyTables[tableIndex].table.tables.reserveCapacity(8) + } + try budget.node(depth: depth) + keyTables[tableIndex].table.tables.append(newTableAddress) + keyTables[tableIndex].table.recordKeyHash(keyHash) + } else { + if tables[tableIndex].tables.isEmpty { + try budget.allocate(8, stage: "semantic storage") + tables[tableIndex].tables.reserveCapacity(8) + } + try budget.node(depth: depth) + tables[tableIndex].tables.append(newTableAddress) + tables[tableIndex].recordKeyHash(keyHash) + } + tableIndex = newTableAddress + isKeyed = true + } + } + + mutating func walkTablePath(startTable: Int = 0, startKeyed: Bool = false) throws { + var tableIndex = startTable + var isKeyed = startKeyed + for (key, keyHash) in tablePath { + try budget.step() + try advanceTablePathSegment( + tableIndex: &tableIndex, + isKeyed: &isKeyed, + key: key, + keyHash: keyHash + ) + } + currentTable = tableIndex + currentTableIsKeyed = isKeyed + } +} diff --git a/Sources/TOMLSemantics/Parsing/TOMLDocument.swift b/Sources/TOMLSemantics/Parsing/TOMLDocument.swift new file mode 100644 index 0000000..142dc61 --- /dev/null +++ b/Sources/TOMLSemantics/Parsing/TOMLDocument.swift @@ -0,0 +1,187 @@ +import Foundation + +struct TOMLDocument { + let tables: [InternalTOMLTable] + let arrays: [InternalTOMLArray] + let keyTables: [KeyTablePair] + let keyArrays: [KeyArrayPair] + let keyValues: [KeyValuePair] + + let source: String + + init( + source: String, + tables: [InternalTOMLTable], + arrays: [InternalTOMLArray], + keyTables: [KeyTablePair], + keyArrays: [KeyArrayPair], + keyValues: [KeyValuePair] + ) { + self.source = source + self.tables = tables + self.arrays = arrays + self.keyTables = keyTables + self.keyArrays = keyArrays + self.keyValues = keyValues + } + +} + +struct InternalTOMLArray: Equatable { + var kind: Kind? + var elements: [Element] + + init(kind: Kind? = nil, elements: [Element] = []) { + self.kind = kind + self.elements = elements + } + + enum Element: Equatable { + case leaf(Token) + case array(lineNumber: Int, Int) + case table(lineNumber: Int, Int) + + var lineNumber: Int { + switch self { + case .leaf(let token): + token.lineNumber + case .array(let lineNumber, _): + lineNumber + case .table(let lineNumber, _): + lineNumber + } + } + + static func == (lhs: Element, rhs: Element) -> Bool { + switch (lhs, rhs) { + case (.leaf(let lhsToken), .leaf(let rhsToken)): + lhsToken == rhsToken + case (.array(let lhsLineNumber, let lhsIndex), .array(let rhsLineNumber, let rhsIndex)): + lhsLineNumber == rhsLineNumber && lhsIndex == rhsIndex + case (.table(let lhsLineNumber, let lhsIndex), .table(let rhsLineNumber, let rhsIndex)): + lhsLineNumber == rhsLineNumber && lhsIndex == rhsIndex + default: + false + } + } + } + + enum Kind: UInt8 { + case value + case array + case table + case inlineTable + case mixed + } +} + +struct KeyTablePair { + let key: String + let keyHash: Int + let sourcePosition: Int + var table: InternalTOMLTable +} + +struct KeyArrayPair { + let key: String + let keyHash: Int + let sourcePosition: Int + var array: InternalTOMLArray +} + +struct KeyValuePair { + let key: String + let keyHash: Int + let sourcePosition: Int + var value: Token +} + +struct InternalTOMLTable: Equatable { + var implicit: Bool = false + var readOnly: Bool = false + var definedByDottedKey: Bool = false + var keyHashBloom: UInt64 = 0 + var keyValues: [Int] = [] + var arrays: [Int] = [] + var tables: [Int] = [] + + @inline(__always) + mutating func recordKeyHash(_ keyHash: Int) { + keyHashBloom |= keyHashBloomMask(keyHash) + } + + @inline(__always) + func mightContainKeyHash(_ keyHash: Int) -> Bool { + let mask = keyHashBloomMask(keyHash) + return (keyHashBloom & mask) == mask + } + + enum Value { + case keyValue(Int) + case array(Int) + case table(Int) + } +} + +@inline(__always) +private func keyHashBloomMask(_ keyHash: Int) -> UInt64 { + let raw = UInt(bitPattern: keyHash) + let bit0 = UInt64(1) << UInt64(raw & 63) + let bit1 = UInt64(1) << UInt64((raw >> 6) & 63) + return bit0 | bit1 +} + +struct DateTimeComponents: Equatable { + let date: LocalDate? + let time: LocalTime? + let offset: Int16? + let features: OffsetDateTime.Features + + @inline(__always) + func localDate(exactMatch: Bool = true) -> LocalDate? { + switch (date, time, offset) { + case (.some(let date), .none, .none): + date + case (.some(let date), _, _) where !exactMatch: + date + default: + nil + } + } + + @inline(__always) + func localTime(exactMatch: Bool = true) -> LocalTime? { + switch (date, time, offset) { + case (.none, .some(let time), .none): + time + case (_, .some(let time), _) where !exactMatch: + time + default: + nil + } + } + + @inline(__always) + func localDateTime(exactMatch: Bool = true) -> LocalDateTime? { + switch (date, time, offset) { + case (.some(let date), .some(let time), .none): + LocalDateTime(date: date, time: time) + case (.some(let date), .some(let time), .some) where !exactMatch: + LocalDateTime(date: date, time: time) + default: + nil + } + } +} + +extension TOMLDocument { + @inline(__always) + func table(at index: Int, keyed: Bool) -> InternalTOMLTable { + keyed ? keyTables[index].table : tables[index] + } + + @inline(__always) + func array(at index: Int, keyed: Bool) -> InternalTOMLArray { + keyed ? keyArrays[index].array : arrays[index] + } +} diff --git a/Sources/TOMLSemantics/Parsing/Token.swift b/Sources/TOMLSemantics/Parsing/Token.swift new file mode 100644 index 0000000..a73f890 --- /dev/null +++ b/Sources/TOMLSemantics/Parsing/Token.swift @@ -0,0 +1,27 @@ +struct Token: Equatable { + enum Kind: UInt8 { + case dot + case comma + case equal + case lbrace + case rbrace + case newline + case lbracket + case rbracket + case string + case bareKey + case eof + } + + var budget: SemanticBudget! = nil + + let kind: Kind + let lineNumber: Int + let text: Range + + static func == (lhs: Token, rhs: Token) -> Bool { + lhs.kind == rhs.kind && lhs.lineNumber == rhs.lineNumber && lhs.text == rhs.text + } + + static var empty: Token { Token(kind: .newline, lineNumber: 1, text: 0..<0) } +} diff --git a/Sources/TOMLSemantics/SemanticBudget.swift b/Sources/TOMLSemantics/SemanticBudget.swift new file mode 100644 index 0000000..b48e8b3 --- /dev/null +++ b/Sources/TOMLSemantics/SemanticBudget.swift @@ -0,0 +1,93 @@ +import Foundation + +/// One serial operation's cumulative admission. Units bound logical storage/work, not RSS. +package final class SemanticBudget { + package struct Limits { + package var storage: Int + package var work: Int + package var nodes: Int + package var depth: Int + package var uninterruptedBytes: Int + + package init(storage: Int, work: Int, nodes: Int, depth: Int, uninterruptedBytes: Int) { + self.storage = storage + self.work = work + self.nodes = nodes + self.depth = depth + self.uninterruptedBytes = uninterruptedBytes + } + } + + package enum Failure: Error { + case exceeded(String) + case cancelled + } + private var storage: Int + private var work: Int + private var nodes: Int + package let limits: Limits + private let cancellation: () -> Bool + + package init(limits: Limits, cancellation: @escaping () -> Bool = { false }) { + self.limits = limits + self.storage = limits.storage + self.work = limits.work + self.nodes = limits.nodes + self.cancellation = cancellation + } + + package func check() throws { + if cancellation() || Task.isCancelled { throw Failure.cancelled } + } + + package func step(_ amount: Int = 1) throws { + try check() + guard amount >= 0, amount <= work else { throw Failure.exceeded("work") } + work -= amount + } + + package func allocate(_ amount: Int, stage: String) throws { + try check() + guard amount >= 0, amount <= storage else { throw Failure.exceeded(stage) } + storage -= amount + } + + package func enter(_ depth: Int) throws { + try check() + guard depth <= limits.depth else { throw Failure.exceeded("depth") } + } + + package func node(depth: Int) throws { + try enter(depth) + guard nodes > 0 else { throw Failure.exceeded("nodes") } + nodes -= 1 + try allocate(1, stage: "node") + } + + package func equal(_ a: String, _ b: String) throws -> Bool { + guard a.utf8.count == b.utf8.count else { + try step() + return false + } + for (x, y) in zip(a.utf8, b.utf8) { + try step() + if x != y { return false } + } + return true + } + + /// The whole admitted envelope bounds every CST lexical run, including skipped trivia. + package func admitCST(bytes: Int) throws { + try check() + guard bytes <= limits.uninterruptedBytes else { + throw Failure.exceeded("CST uninterrupted input") + } + try step(bytes) + guard bytes <= (Int.max - 1) / 4 else { throw Failure.exceeded("CST nodes") } + let admittedNodes = bytes * 4 + 1 + guard admittedNodes <= nodes else { throw Failure.exceeded("CST nodes") } + nodes -= admittedNodes + try allocate(admittedNodes, stage: "CST nodes") + try allocate(bytes, stage: "CST input") + } +} diff --git a/Sources/TOMLSemantics/SemanticDocument.swift b/Sources/TOMLSemantics/SemanticDocument.swift new file mode 100644 index 0000000..6586a1c --- /dev/null +++ b/Sources/TOMLSemantics/SemanticDocument.swift @@ -0,0 +1,181 @@ +import Foundation + +package enum SemanticScalarKind: String { case string, boolean, integer, float, dateTime } + +package struct SemanticEntry { + package let key: String + package let value: SemanticValue + package init(key: String, value: SemanticValue) { + self.key = key + self.value = value + } +} + +package indirect enum SemanticValue { + case object([SemanticEntry]) + case array([SemanticValue]) + case scalar(kind: SemanticScalarKind, decoded: String, raw: String, range: Range) +} + +package struct SemanticDocument { + package let root: SemanticValue + + package init(source: String, budget: SemanticBudget) throws { + try budget.allocate(source.utf8.count, stage: "semantic input") + var parser = Parser(budget: budget) + try source.utf8.withContiguousStorageIfAvailable { try parser.parse(bytes: $0) } + .unwrapStorage() + let document = parser.finish(source: source) + root = try Self.table(document.tables[0], document: document, budget: budget, depth: 0) + } + + private static func table( + _ table: InternalTOMLTable, document: TOMLDocument, budget: SemanticBudget, depth: Int + ) throws -> SemanticValue { + try budget.node(depth: depth) + var entries: [(Int, SemanticEntry)] = [] + for i in table.keyValues { + try budget.step() + let pair = document.keyValues[i] + try budget.allocate(1, stage: "ordered entry") + entries.append( + ( + pair.sourcePosition, + SemanticEntry( + key: pair.key, value: try scalar(pair.value, source: document.source, budget: budget)) + )) + } + for i in table.arrays { + try budget.step() + let pair = document.keyArrays[i] + try budget.allocate(1, stage: "ordered entry") + entries.append( + ( + pair.sourcePosition, + SemanticEntry( + key: pair.key, + value: try array(pair.array, document: document, budget: budget, depth: depth + 1)) + )) + } + for i in table.tables { + try budget.step() + let pair = document.keyTables[i] + try budget.allocate(1, stage: "ordered entry") + entries.append( + ( + pair.sourcePosition, + SemanticEntry( + key: pair.key, + value: try Self.table(pair.table, document: document, budget: budget, depth: depth + 1)) + )) + } + try budget.allocate(entries.count, stage: "ordered entries") + let ordered = try entries.sorted { + try budget.step() + return $0.0 < $1.0 + } + return .object(ordered.map(\.1)) + } + + private static func array( + _ array: InternalTOMLArray, document: TOMLDocument, budget: SemanticBudget, depth: Int + ) throws -> SemanticValue { + try budget.node(depth: depth) + var values: [SemanticValue] = [] + for element in array.elements { + try budget.step() + try budget.allocate(1, stage: "ordered element") + switch element { + case .leaf(let token): + values.append(try scalar(token, source: document.source, budget: budget)) + case .array(_, let i): + values.append( + try Self.array(document.arrays[i], document: document, budget: budget, depth: depth + 1)) + case .table(_, let i): + values.append( + try table(document.tables[i], document: document, budget: budget, depth: depth + 1)) + } + } + return .array(values) + } + + private static func scalar(_ token: Token, source: String, budget: SemanticBudget) throws + -> SemanticValue + { + try budget.node(depth: 0) + try budget.allocate(token.text.count, stage: "scalar lexeme") + return try source.utf8.withContiguousStorageIfAvailable { bytes in + try budget.step(token.text.count) + let raw = String(decoding: bytes[token.text], as: UTF8.self) + let kind: SemanticScalarKind + let decoded: String + let first = bytes[token.text.lowerBound] + var dot = false + var exponent = false + var colon = false + for byte in bytes[token.text] { + try budget.step() + dot = dot || byte == 46 + exponent = exponent || byte == 101 || byte == 69 + colon = colon || byte == 58 + } + if first == 34 || first == 39 { + kind = .string + decoded = try token.unpackString(bytes: bytes, context: .super) + } else if first == 116 || first == 102 { + kind = .boolean + decoded = try token.unpackBool(bytes: bytes, context: .super) ? "true" : "false" + } else if colon || (token.text.count > 4 && bytes[token.text.lowerBound + 4] == 45) { + kind = .dateTime + let components = try token.unpackDateTime(bytes: bytes, context: .super) + switch (components.date, components.time, components.offset) { + case (.some, .some, .some), (.some, .some, .none), (.some, .none, .none), + (.none, .some, .none): + break + default: + throw TOMLError(.invalidValueInTable(context: .super, lineNumber: token.lineNumber)) + } + decoded = raw + } else { + // Base-prefixed integers can contain e/E hex digits. Classification precedes validation. + let numeric = (first == 43 || first == 45) ? String(raw.dropFirst()) : raw + if !numeric.hasPrefix("0x") && !numeric.hasPrefix("0o") && !numeric.hasPrefix("0b") + && (dot || exponent || numeric == "inf" || numeric == "nan") + { + kind = .float + _ = try token.unpackFloat(bytes: bytes, context: .super) + try budget.allocate(token.text.count, stage: "decimal projection") + var projection: [UInt8] = [] + for (i, byte) in bytes[token.text].enumerated() { + try budget.step() + if byte != 95 && !(i == 0 && byte == 43) { projection.append(byte) } + } + decoded = String(decoding: projection, as: UTF8.self) + } else { + kind = .integer + decoded = String(try token.unpackInteger(bytes: bytes, context: .super)) + } + } + return .scalar(kind: kind, decoded: decoded, raw: raw, range: token.text) + }.unwrapStorage() + } + + package static func decodeKey(_ bytes: [UInt8], budget: SemanticBudget) throws -> String { + try budget.allocate(bytes.count, stage: "key input") + if bytes.first == 34 || bytes.first == 39 { + return try bytes.withUnsafeBufferPointer { + let token = Token(budget: budget, kind: .string, lineNumber: 1, text: 0.. Wrapped { + guard let self else { throw TOMLError(.invalidUTF8) } + return self + } +} diff --git a/Sources/TOMLSemantics/TOMLError.swift b/Sources/TOMLSemantics/TOMLError.swift new file mode 100644 index 0000000..c54c7f3 --- /dev/null +++ b/Sources/TOMLSemantics/TOMLError.swift @@ -0,0 +1,147 @@ +/// An error originated from parsing the TOML document. +/// +/// This error provides details for invalid values, +/// or formatting issues in the TOML document. +/// It comes from the parsing phase. +/// Read to learn more. +public struct TOMLError: Error { + let reason: Reason + + init(_ reason: Reason) { + self.reason = reason + } + + enum Reason { + case arrayOutOfBound(index: Int, bound: Int) + case badKey(lineNumber: Int) + case expectedHexCharacters(UTF8.CodeUnit, Int) + case illegalEscapeCharacter(UTF8.CodeUnit) + case illegalUCSCode(UInt32) + case internalError(lineNumber: Int) + case invalidBool(context: TOMLKey, lineNumber: Int) + case invalidCharacter(UTF8.CodeUnit) + case invalidDateTime(lineNumber: Int?, reason: String) + case invalidDateTime3(context: TOMLKey, lineNumber: Int, reason: String) + case invalidDateTimeComponents(String) + case invalidFloat(context: TOMLKey, lineNumber: Int, reason: String) + case invalidHexCharacters(UTF8.CodeUnit) + case invalidInteger(context: TOMLKey, lineNumber: Int, reason: String) + case invalidNumber(reason: String) + case invalidString(context: TOMLKey, lineNumber: Int, reason: String) + case invalidUTF8 + case invalidValueInTable(context: TOMLKey, lineNumber: Int) + case keyExists(lineNumber: Int) + case keyNotFoundInTable(key: String, expected: String) + case notReallyCodable + case syntax(lineNumber: Int, message: String) + case typeMismatch(context: TOMLKey, lineNumber: Int, expected: String) + case typeMismatchInArray(lineNumber: Int, index: Int, expected: String) + case typeMismatchInTable(key: String, expected: String) + } +} + +extension TOMLError: CustomStringConvertible { + public var description: String { + switch reason { + case .arrayOutOfBound(let index, let bound): + "Array index \(index) is out of bounds (0..<\(bound))." + case .badKey(let lineNumber): + "(Line \(lineNumber)) Ill-formed key." + case .expectedHexCharacters(let codeUnit, let hexCount): + "Expected \(hexCount) hexadecimal characters after '\(String(UnicodeScalar(codeUnit))).'." + case .illegalEscapeCharacter(let codeUnit): + "Illegal escape character '\(String(UnicodeScalar(codeUnit)))'." + case .illegalUCSCode(let ucs): + "Illegal UCS code '\(ucs)'." + case .internalError(let lineNumber): + "(Line \(lineNumber)) Internal error." + case .invalidBool(let context, let lineNumber): + switch context { + case .string(let key): + "(Line \(lineNumber)) Invalid boolean value for key '\(key)'." + case .int(let index): + "(Line \(lineNumber)) Invalid boolean value for index \(index)." + case .super: + "(Line \(lineNumber)) Invalid boolean value for 'super'." + } + case .invalidCharacter(let codeUnit): + "Invalid character '\(String(UnicodeScalar(codeUnit)))'." + case .invalidDateTime(let lineNumber, let reason): + "\(lineNumber.map { "(Line \($0)) " } ?? "")Invalid date-time: \(reason)." + case .invalidDateTime3(let context, let lineNumber, let reason): + switch context { + case .string(let key): + "(Line \(lineNumber)) Invalid date-time value for key '\(key)': \(reason)." + case .int(let index): + "(Line \(lineNumber)) Invalid date-time value for index \(index)': \(reason)." + case .super: + "(Line \(lineNumber)) Invalid date-time value for 'super': \(reason)." + } + case .invalidDateTimeComponents(let components): + "Invalid date-time components: \(components)." + case .invalidFloat(let context, let lineNumber, let reason): + switch context { + case .string(let key): + "(Line \(lineNumber)) Invalid float value for key '\(key)': \(reason)." + case .int(let index): + "(Line \(lineNumber)) Invalid float value for index \(index)': \(reason)." + case .super: + "(Line \(lineNumber)) Invalid float value for 'super': \(reason)." + } + case .invalidHexCharacters(let codeUnit): + "Invalid hexadecimal characters '\(String(UnicodeScalar(codeUnit)))'." + case .invalidInteger(let context, let lineNumber, let reason): + switch context { + case .string(let key): + "(Line \(lineNumber)) Invalid integer value for key '\(key)': \(reason)." + case .int(let index): + "(Line \(lineNumber)) Invalid integer value for index \(index)': \(reason)." + case .super: + "(Line \(lineNumber)) Invalid integer value for 'super': \(reason)." + } + case .invalidNumber(let reason): + "Invalid number: \(reason)." + case .invalidString(let context, let lineNumber, let reason): + switch context { + case .string(let key): + "(Line \(lineNumber)) Invalid string value for key '\(key)': \(reason)." + case .int(let index): + "(Line \(lineNumber)) Invalid string value for index \(index)': \(reason)." + case .super: + "(Line \(lineNumber)) Invalid string value for 'super': \(reason)." + } + case .invalidUTF8: + "The given data was not valid UTF8." + case .invalidValueInTable(let context, let lineNumber): + switch context { + case .string(let key): + "(Line \(lineNumber)) Invalid value in table for key '\(key)'." + case .int(let index): + "(Line \(lineNumber)) Invalid value in table for index \(index)." + case .super: + "(Line \(lineNumber)) Invalid value in table for 'super'." + } + case .keyExists(let lineNumber): + "(Line \(lineNumber)) Key already exists." + case .keyNotFoundInTable(let key, let expected): + "Key '\(key)' not found in table while looking for \(expected)." + case .notReallyCodable: + "This type is not generally codable. Use TOMLDecoder to decode it as part of a larger Codable." + case .syntax(let lineNumber, let message): + "(Line \(lineNumber)) Syntax error: \(message)." + case .typeMismatch(let context, let lineNumber, let expected): + switch context { + case .string(let key): + "(Line \(lineNumber)) Type mismatch at table key '\(key)': expected \(expected)." + case .int(let index): + "(Line \(lineNumber)) Type mismatch at array index \(index): expected \(expected)." + case .super: + "(Line \(lineNumber)) Type mismatch at 'super': expected \(expected)." + } + case .typeMismatchInArray(let lineNumber, let index, let expected): + "(Line \(lineNumber)) Type mismatch at array index \(index): expected \(expected)." + case .typeMismatchInTable(let key, let expected): + "Type mismatch at table key '\(key)': expected \(expected)." + } + } +} diff --git a/Sources/TOMLSemantics/TOMLKey.swift b/Sources/TOMLSemantics/TOMLKey.swift new file mode 100644 index 0000000..d358984 --- /dev/null +++ b/Sources/TOMLSemantics/TOMLKey.swift @@ -0,0 +1,33 @@ +enum TOMLKey: CodingKey { + case string(String) + case int(Int) + case `super` + + init(stringValue: String) { + self = .string(stringValue) + } + + init(intValue: Int) { + self = .int(intValue) + } + + var stringValue: String { + switch self { + case .string(let string): + string + case .int(let int): + "Index \(int)" + case .super: + "super" + } + } + + var intValue: Int? { + switch self { + case .int(let int): + int + default: + nil + } + } +} diff --git a/Sources/TOMLSemantics/provenance.json b/Sources/TOMLSemantics/provenance.json new file mode 100644 index 0000000..de272da --- /dev/null +++ b/Sources/TOMLSemantics/provenance.json @@ -0,0 +1,48 @@ +{ + "upstream": "https://github.com/dduan/TOMLDecoder.git", + "revision": "a2bbd2796fe3064e107de18cb56031052c4fa899", + "files": { + "Parsing/Parser.swift": { + "source": "Sources/TOMLDecoder/Parsing/Parser.swift", + "sha256": "262c1a417325008fc2cefb0ce449bb6bb5189310ff154322bf1ff3a5cf837da5" + }, + "Parsing/Parser+Finish.swift": { + "source": "Sources/TOMLDecoder/Parsing/Parser+Finish.swift", + "sha256": "8e1ce8317624b9f2b9544399e09dfd4df944400bfe0c8a24e6577d4241f04f36" + }, + "Parsing/Token.swift": { + "source": "Sources/TOMLDecoder/Parsing/Token.swift", + "sha256": "f78a3e37ab5991195f3b82e092aae2d12f69c137f88447ce15ee49b8da7b0385" + }, + "Parsing/TOMLDocument.swift": { + "source": "Sources/TOMLDecoder/Parsing/TOMLDocument.swift", + "sha256": "9b92cc3127bcdba696fa51e3983da8d9fd25c16b9ae5aea0cd87569a058bf57d" + }, + "Parsing/Constants.swift": { + "source": "Sources/TOMLDecoder/Parsing/Constants.swift", + "sha256": "47adaa2e74ae68094fbd3d0da44fd0db28846b60a587e98cb95ce3f112485612" + }, + "DateTime.swift": { + "source": "Sources/TOMLDecoder/DateTime.swift", + "sha256": "c22cc93a4ea0ce8b7dac5c00c916ab24974b5df23d1c2645ca96ac61ebdeb6aa" + }, + "TOMLKey.swift": { + "source": "Sources/TOMLDecoder/TOMLKey.swift", + "sha256": "ccf76e6622ab7e585fb7e0fb2e812c48c42b96d5761a9970866f3d8bf90b4f1e" + }, + "TOMLError.swift": { + "source": "Sources/TOMLDecoder/TOMLError.swift", + "sha256": "b7f18d5a666d4e64fa9c12c0de73a0a53a506262be093e99d7f50b52156c6417" + }, + "LICENSE": { + "source": "LICENSE.md", + "sha256": "ee59f20a0a5550b0b071a0d9edb31c29629ce4bad2d8f5d0467ee7d574b541cf" + } + }, + "patches": { + "description": "PATCHES.md", + "diff": "upstream.patch", + "sha256": "b7522712c6d4879493b89f84596452a6e2b2a2b2cc3cac7fa4a13ca1bdc6c986", + "context_lines": 0 + } +} diff --git a/Sources/TOMLSemantics/upstream.patch b/Sources/TOMLSemantics/upstream.patch new file mode 100644 index 0000000..4cf520b --- /dev/null +++ b/Sources/TOMLSemantics/upstream.patch @@ -0,0 +1,6993 @@ +--- Sources/TOMLDecoder/Parsing/Parser.swift ++++ Sources/TOMLDecoder/Parsing/Parser.swift +@@ -2,31 +2,202 @@ +- var token = Token.empty +- var cursor = 0 +- var currentLineNumber = 1 +- var currentTable = 0 +- var currentTableIsKeyed = false +- var tablePath: [(key: String, keyHash: Int)] = [] +- var tables: [InternalTOMLTable] = [InternalTOMLTable()] +- var arrays: [InternalTOMLArray] = [] +- var keyTables: [KeyTablePair] = [] +- var keyArrays: [KeyArrayPair] = [] +- var keyValues: [KeyValuePair] = [] +- var keyTransform: (@Sendable (String) -> String)? +- +- mutating func parse(bytes: UnsafeBufferPointer) throws(TOMLError) { +- let estimatedKeyValues = max(32, bytes.count / 48) +- let estimatedNodes = max(8, estimatedKeyValues / 8) +- tables.reserveCapacity(max(8, estimatedNodes)) +- arrays.reserveCapacity(estimatedNodes) +- keyTables.reserveCapacity(estimatedNodes) +- keyArrays.reserveCapacity(estimatedNodes) +- keyValues.reserveCapacity(estimatedKeyValues) +- tablePath.reserveCapacity(8) +- +- while token.kind != .eof { +- switch token.kind { +- case .newline: +- try nextToken(bytes: bytes, isDotSpecial: true) +- case .string, .bareKey: +- try parseKeyValue(bytes: bytes, tableIndex: currentTable, isKeyed: currentTableIsKeyed) +- if token.kind != .newline, token.kind != .eof { +- throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "extra chars after value")) ++ let budget: SemanticBudget ++ var depth = 0 ++ var token = Token.empty ++ var cursor = 0 ++ var currentLineNumber = 1 ++ var currentTable = 0 ++ var currentTableIsKeyed = false ++ var tablePath: [(key: String, keyHash: Int)] = [] ++ var tables: [InternalTOMLTable] = [] ++ var arrays: [InternalTOMLArray] = [] ++ var keyTables: [KeyTablePair] = [] ++ var keyArrays: [KeyArrayPair] = [] ++ var keyValues: [KeyValuePair] = [] ++ ++ mutating func parse(bytes: UnsafeBufferPointer) throws { ++ try budget.node(depth: 0) ++ tables.append(InternalTOMLTable()) ++ let estimatedKeyValues = max(32, bytes.count / 48) ++ let estimatedNodes = max(8, estimatedKeyValues / 8) ++ try budget.allocate(max(8, estimatedNodes), stage: "semantic storage") ++ tables.reserveCapacity(max(8, estimatedNodes)) ++ try budget.allocate(estimatedNodes, stage: "semantic storage") ++ arrays.reserveCapacity(estimatedNodes) ++ try budget.allocate(estimatedNodes, stage: "semantic storage") ++ keyTables.reserveCapacity(estimatedNodes) ++ try budget.allocate(estimatedNodes, stage: "semantic storage") ++ keyArrays.reserveCapacity(estimatedNodes) ++ try budget.allocate(estimatedKeyValues, stage: "semantic storage") ++ keyValues.reserveCapacity(estimatedKeyValues) ++ try budget.allocate(8, stage: "semantic storage") ++ tablePath.reserveCapacity(8) ++ ++ while token.kind != .eof { ++ try budget.step() ++ switch token.kind { ++ case .newline: ++ try nextToken(bytes: bytes, isDotSpecial: true) ++ case .string, .bareKey: ++ try parseKeyValue(bytes: bytes, tableIndex: currentTable, isKeyed: currentTableIsKeyed) ++ if token.kind != .newline, token.kind != .eof { ++ throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "extra chars after value")) ++ } ++ if token.kind == .newline { ++ try eatToken(bytes: bytes, kind: .newline, isDotSpecial: true) ++ } ++ case .lbracket: ++ try parseSelect(bytes: bytes) ++ default: ++ throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "syntax error")) ++ } ++ } ++ } ++ ++ mutating func nextToken(bytes: UnsafeBufferPointer, isDotSpecial: Bool) throws { ++ let lineNumber = currentLineNumber ++ var position = cursor ++ ++ @inline(__always) ++ func emitToken(kind: Token.Kind, start: Int, end: Int, newlines: Int = 0) throws { ++ try budget.node(depth: depth) ++ token = Token(budget: budget, kind: kind, lineNumber: lineNumber, text: start..= CodeUnits.null && commentChar <= CodeUnits.backspace) ++ || (commentChar >= CodeUnits.lf && commentChar <= CodeUnits.unitSeparator) ++ || commentChar == CodeUnits.delete ++ { ++ if commentChar == CodeUnits.cr { ++ let nextPosition = position + 1 ++ if nextPosition < count, bytes[nextPosition] == CodeUnits.lf { ++ // Allow CRLF sequence ++ } else { ++ throw TOMLError( ++ .syntax( ++ lineNumber: lineNumber, ++ message: "control characters are not allowed in comments" ++ ) ++ ) ++ } ++ } else { ++ throw TOMLError( ++ .syntax( ++ lineNumber: lineNumber, ++ message: "control characters are not allowed in comments" ++ ) ++ ) ++ } ++ } ++ position += 1 ++ } ++ continue ++ case CodeUnits.space, CodeUnits.tab: ++ // ignore white spaces ++ position += 1 ++ while position < count { ++ try budget.step() ++ let ws = bytes[position] ++ if ws != CodeUnits.space, ws != CodeUnits.tab { ++ break ++ } ++ position += 1 ++ } ++ continue ++ case CodeUnits.dot where isDotSpecial: ++ try emitToken(kind: .dot, start: position, end: position + 1) ++ return ++ case CodeUnits.comma: ++ try emitToken(kind: .comma, start: position, end: position + 1) ++ return ++ case CodeUnits.equal: ++ try emitToken(kind: .equal, start: position, end: position + 1) ++ return ++ case CodeUnits.lbrace: ++ try emitToken(kind: .lbrace, start: position, end: position + 1) ++ return ++ case CodeUnits.rbrace: ++ try emitToken(kind: .rbrace, start: position, end: position + 1) ++ return ++ case CodeUnits.lbracket: ++ try emitToken(kind: .lbracket, start: position, end: position + 1) ++ return ++ case CodeUnits.rbracket: ++ try emitToken(kind: .rbracket, start: position, end: position + 1) ++ return ++ case CodeUnits.lf: ++ try emitToken(kind: .newline, start: position, end: position + 1, newlines: 1) ++ return ++ case CodeUnits.cr: ++ // Check if this is part of a CRLF sequence ++ let nextPosition = position + 1 ++ if nextPosition < count, bytes[nextPosition] == CodeUnits.lf { ++ // This is CRLF, treat as newline ++ try emitToken(kind: .newline, start: position, end: nextPosition + 1, newlines: 1) ++ return ++ } ++ // Bare CR is invalid ++ throw TOMLError( ++ .syntax( ++ lineNumber: lineNumber, ++ message: "bare carriage return is not allowed" ++ ) ++ ) ++ default: ++ break ++ } ++ ++ func scanString(range: Range, lineNumber: Int) throws { ++ let start = range.lowerBound ++ let end = range.upperBound ++ let head = bytes[start] ++ if (head >= CodeUnits.lowerA && head <= CodeUnits.lowerZ) ++ || (head >= CodeUnits.upperA && head <= CodeUnits.upperZ) || head == CodeUnits.underscore ++ { ++ let isBareKeyChar = CodeUnits.isBareKeyChar ++ var index = start + 1 ++ while index < end { ++ try budget.step() ++ let ch = bytes[index] ++ if isBareKeyChar[Int(ch)] { ++ index += 1 ++ continue ++ } ++ break ++ } ++ try emitToken(kind: .bareKey, start: start, end: index) ++ return ++ } ++ ++ if head == CodeUnits.singleQuote { ++ if start + 3 <= end, ++ bytes[start + 1] == CodeUnits.singleQuote, ++ bytes[start + 2] == CodeUnits.singleQuote ++ { ++ var i = start + 3 ++ var newlinesInToken = 0 ++ ++ while i < end { ++ try budget.step() ++ if bytes[i] == CodeUnits.lf { ++ newlinesInToken += 1 ++ } ++ if i + 3 <= end, ++ bytes[i] == CodeUnits.singleQuote, ++ bytes[i + 1] == CodeUnits.singleQuote, ++ bytes[i + 2] == CodeUnits.singleQuote ++ { ++ if i + 3 >= end || bytes[i + 3] != CodeUnits.singleQuote { ++ break +@@ -34,2 +205,65 @@ +- if token.kind == .newline { +- try eatToken(bytes: bytes, kind: .newline, isDotSpecial: true) ++ } ++ i += 1 ++ } ++ ++ guard i < end else { ++ throw TOMLError( ++ .syntax(lineNumber: lineNumber, message: "unterminated triple-s-quote") ++ ) ++ } ++ ++ try emitToken(kind: .string, start: start, end: i + 3, newlines: newlinesInToken) ++ return ++ } ++ ++ var i = start + 1 ++ while i < end { ++ try budget.step() ++ let ch = bytes[i] ++ if ch == CodeUnits.singleQuote || ch == CodeUnits.lf { ++ break ++ } ++ i += 1 ++ } ++ ++ if i >= end || bytes[i] != CodeUnits.singleQuote { ++ throw TOMLError( ++ .syntax(lineNumber: lineNumber, message: "unterminated s-quote") ++ ) ++ } ++ ++ try emitToken(kind: .string, start: start, end: i + 1) ++ return ++ } ++ ++ if head == CodeUnits.doubleQuote { ++ if start + 3 < end, ++ bytes[start + 1] == CodeUnits.doubleQuote, ++ bytes[start + 2] == CodeUnits.doubleQuote ++ { ++ var i = start + 3 ++ var newlinesInToken = 0 ++ ++ while i < end { ++ try budget.step() ++ if bytes[i] == CodeUnits.lf { ++ newlinesInToken += 1 ++ } ++ if i + 3 <= end, ++ bytes[i] == CodeUnits.doubleQuote, ++ bytes[i + 1] == CodeUnits.doubleQuote, ++ bytes[i + 2] == CodeUnits.doubleQuote ++ { ++ if i + 3 >= end || bytes[i + 3] != CodeUnits.doubleQuote { ++ var backslashStart = i ++ while backslashStart > start + 3 ++ && bytes[backslashStart - 1] == CodeUnits.backslash ++ { ++ try budget.step() ++ backslashStart -= 1 ++ } ++ if (i - backslashStart) % 2 != 0 { ++ i += 1 ++ continue ++ } ++ break +@@ -37,4 +271,2 @@ +- case .lbracket: +- try parseSelect(bytes: bytes) +- default: +- throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "syntax error")) ++ } ++ i += 1 +@@ -42,15 +274,362 @@ +- } +- } +- +- mutating func nextToken(bytes: UnsafeBufferPointer, isDotSpecial: Bool) throws(TOMLError) { +- let lineNumber = currentLineNumber +- var position = cursor +- +- @inline(__always) +- func emitToken(kind: Token.Kind, start: Int, end: Int, newlines: Int = 0) { +- token = Token(kind: kind, lineNumber: lineNumber, text: start ..< end) +- cursor = end +- currentLineNumber = lineNumber + newlines +- } +- +- let count = bytes.count ++ ++ guard i < end else { ++ throw TOMLError( ++ .syntax(lineNumber: lineNumber, message: "unterminated triple-d-quote") ++ ) ++ } ++ ++ try emitToken(kind: .string, start: start, end: i + 3, newlines: newlinesInToken) ++ return ++ } ++ ++ var i = start + 1 ++ let isBasicStringBodyChar = CodeUnits.isBasicStringBodyChar ++ let baseAddress = bytes.baseAddress! ++ while i + 8 <= end { ++ try budget.step() ++ let chunk = UnsafeRawPointer(baseAddress.advanced(by: i)).loadUnaligned( ++ as: UInt64.self ++ ) ++ if chunkContainsDoubleQuotedStopByte(chunk) { ++ break ++ } ++ i += 8 ++ } ++ ++ while i < end { ++ try budget.step() ++ let ch = bytes[i] ++ if isBasicStringBodyChar[Int(ch)] { ++ i += 1 ++ continue ++ } ++ if ch == CodeUnits.backslash { ++ i += 1 ++ if i < end { ++ i += 1 ++ continue ++ } ++ break ++ } ++ ++ break ++ } ++ ++ if i >= end || bytes[i] != CodeUnits.doubleQuote { ++ throw TOMLError( ++ .syntax(lineNumber: lineNumber, message: "unterminated quote") ++ ) ++ } ++ ++ try emitToken(kind: .string, start: start, end: i + 1) ++ return ++ } ++ ++ if !isDotSpecial { ++ var index = start ++ var dateEnder: Int? ++ // Fast path: Dates must produce YYYY-MM-DD, so checks for the dash ++ if start + 4 < end && bytes[start + 4] == CodeUnits.minus { ++ dateEnder = scanDate(bytes: bytes, range: range)?.3 ++ } ++ ++ if let dateEnder, dateEnder < end, ++ bytes[dateEnder] == CodeUnits.upperT || bytes[dateEnder] == CodeUnits.lowerT ++ || bytes[dateEnder] == CodeUnits.space ++ { ++ let timeStarter = dateEnder + 1 ++ if let timeEnder = scanTime( ++ bytes: bytes, range: timeStarter.. start { ++ if index < end { ++ if bytes[index] == CodeUnits.dot { ++ index += 1 ++ while index < end, bytes[index] >= CodeUnits.number0, ++ bytes[index] <= CodeUnits.number9 ++ { ++ try budget.step() ++ index += 1 ++ } ++ } ++ if index < end, bytes[index] == CodeUnits.upperZ || bytes[index] == CodeUnits.lowerZ { ++ index += 1 ++ } else if let timzoneEnder = scanTimezoneOffset( ++ bytes: bytes, range: index.. start, bytes[index - 1] == CodeUnits.space { ++ try budget.step() ++ index -= 1 ++ } ++ // tokenize ++ try emitToken(kind: .string, start: start, end: index) ++ return ++ } ++ } ++ ++ if isDotSpecial { ++ let isBareKeyChar = CodeUnits.isBareKeyChar ++ var index = start ++ while index < end, isBareKeyChar[Int(bytes[index])] { ++ try budget.step() ++ index += 1 ++ } ++ if index >= end || bytes[index] != CodeUnits.plus { ++ try emitToken(kind: .bareKey, start: start, end: index) ++ return ++ } ++ ++ index += 1 ++ while index < end { ++ try budget.step() ++ let ch = bytes[index] ++ if isBareKeyChar[Int(ch)] || ch == CodeUnits.plus { ++ index += 1 ++ continue ++ } ++ break ++ } ++ try emitToken(kind: .string, start: start, end: index) ++ } else { ++ let isValueChar = CodeUnits.isValueChar ++ var index = start ++ while index < end { ++ try budget.step() ++ let ch = bytes[index] ++ if isValueChar[Int(ch)] { ++ index += 1 ++ continue ++ } ++ break ++ } ++ try emitToken(kind: .string, start: start, end: index) ++ } ++ } ++ ++ try scanString(range: position.., kind: Token.Kind, isDotSpecial: Bool) ++ throws ++ { ++ if token.kind != kind { ++ throw TOMLError(.internalError(lineNumber: token.lineNumber)) ++ } ++ try nextToken(bytes: bytes, isDotSpecial: isDotSpecial) ++ } ++ ++ mutating func createKeyValue( ++ bytes: UnsafeBufferPointer, ++ token: Token, ++ value: Token, ++ inTable tableIndex: Int, ++ isKeyed: Bool ++ ) throws { ++ let (key, keyHash) = try normalizeKeyAndHash(bytes: bytes, token: token) ++ if try tableValue(tableIndex: tableIndex, keyed: isKeyed, key: key, keyHash: keyHash) != nil { ++ throw TOMLError(.badKey(lineNumber: token.lineNumber)) ++ } ++ let index = keyValues.count ++ try budget.node(depth: depth) ++ keyValues.append( ++ KeyValuePair(key: key, keyHash: keyHash, sourcePosition: token.text.lowerBound, value: value)) ++ ++ if isKeyed { ++ if keyTables[tableIndex].table.keyValues.isEmpty { ++ try budget.allocate(8, stage: "semantic storage") ++ keyTables[tableIndex].table.keyValues.reserveCapacity(8) ++ } ++ try budget.node(depth: depth) ++ keyTables[tableIndex].table.keyValues.append(index) ++ keyTables[tableIndex].table.recordKeyHash(keyHash) ++ } else { ++ if tables[tableIndex].keyValues.isEmpty { ++ try budget.allocate(8, stage: "semantic storage") ++ tables[tableIndex].keyValues.reserveCapacity(8) ++ } ++ try budget.node(depth: depth) ++ tables[tableIndex].keyValues.append(index) ++ tables[tableIndex].recordKeyHash(keyHash) ++ } ++ } ++ ++ mutating func createKeyTable( ++ bytes: UnsafeBufferPointer, token: Token, inTable tableIndex: Int, isKeyed: Bool, ++ implicit: Bool = false ++ ) throws -> Int { ++ let (key, keyHash) = try normalizeKeyAndHash(bytes: bytes, token: token) ++ return try createKeyTable( ++ normalizedKey: key, ++ keyHash: keyHash, ++ lineNumber: token.lineNumber, ++ inTable: tableIndex, ++ isKeyed: isKeyed, ++ implicit: implicit ++ ) ++ } ++ ++ mutating func createKeyTable( ++ normalizedKey key: String, keyHash: Int, lineNumber: Int, inTable tableIndex: Int, ++ isKeyed: Bool, implicit: Bool = false ++ ) throws -> Int { ++ // Check if parent table is readOnly (inline table) ++ if isKeyed ? keyTables[tableIndex].table.readOnly : tables[tableIndex].readOnly { ++ throw TOMLError(.syntax(lineNumber: lineNumber, message: "cannot add to inline table")) ++ } ++ ++ switch try tableValue(tableIndex: tableIndex, keyed: isKeyed, key: key, keyHash: keyHash) { ++ case .table(let existingTableIndex): ++ if keyTables[existingTableIndex].table.implicit { ++ if keyTables[existingTableIndex].table.definedByDottedKey { ++ throw TOMLError(.keyExists(lineNumber: lineNumber)) ++ } ++ keyTables[existingTableIndex].table.implicit = false ++ return existingTableIndex ++ } ++ throw TOMLError(.keyExists(lineNumber: lineNumber)) ++ case .keyValue, .array: ++ throw TOMLError(.keyExists(lineNumber: lineNumber)) ++ case nil: ++ break ++ } ++ let index = keyTables.count ++ var newTable = InternalTOMLTable() ++ newTable.implicit = implicit ++ newTable.definedByDottedKey = implicit ++ try budget.node(depth: depth) ++ keyTables.append( ++ KeyTablePair( ++ key: key, keyHash: keyHash, sourcePosition: token.text.lowerBound, table: newTable)) ++ ++ if isKeyed { ++ if keyTables[tableIndex].table.tables.isEmpty { ++ try budget.allocate(8, stage: "semantic storage") ++ keyTables[tableIndex].table.tables.reserveCapacity(8) ++ } ++ try budget.node(depth: depth) ++ keyTables[tableIndex].table.tables.append(index) ++ keyTables[tableIndex].table.recordKeyHash(keyHash) ++ } else { ++ if tables[tableIndex].tables.isEmpty { ++ try budget.allocate(8, stage: "semantic storage") ++ tables[tableIndex].tables.reserveCapacity(8) ++ } ++ try budget.node(depth: depth) ++ tables[tableIndex].tables.append(index) ++ tables[tableIndex].recordKeyHash(keyHash) ++ } ++ return index ++ } ++ ++ mutating func createKeyArray( ++ bytes: UnsafeBufferPointer, token: Token, inTable tableIndex: Int, isKeyed: Bool, ++ kind: InternalTOMLArray.Kind? = nil ++ ) throws -> Int { ++ let (key, keyHash) = try normalizeKeyAndHash(bytes: bytes, token: token) ++ return try createKeyArray( ++ normalizedKey: key, ++ keyHash: keyHash, ++ lineNumber: token.lineNumber, ++ inTable: tableIndex, ++ isKeyed: isKeyed, ++ kind: kind ++ ) ++ } ++ ++ mutating func createKeyArray( ++ normalizedKey key: String, keyHash: Int, lineNumber: Int, inTable tableIndex: Int, ++ isKeyed: Bool, kind: InternalTOMLArray.Kind? = nil ++ ) throws -> Int { ++ if try tableValue(tableIndex: tableIndex, keyed: isKeyed, key: key, keyHash: keyHash) != nil { ++ throw TOMLError(.keyExists(lineNumber: lineNumber)) ++ } ++ ++ let index = keyArrays.count ++ var array = InternalTOMLArray(kind: kind) ++ if kind == .table { ++ try budget.allocate(8, stage: "semantic storage") ++ array.elements.reserveCapacity(8) ++ } ++ try budget.node(depth: depth) ++ keyArrays.append( ++ KeyArrayPair(key: key, keyHash: keyHash, sourcePosition: token.text.lowerBound, array: array)) ++ if isKeyed { ++ if keyTables[tableIndex].table.arrays.isEmpty { ++ try budget.allocate(8, stage: "semantic storage") ++ keyTables[tableIndex].table.arrays.reserveCapacity(8) ++ } ++ try budget.node(depth: depth) ++ keyTables[tableIndex].table.arrays.append(index) ++ keyTables[tableIndex].table.recordKeyHash(keyHash) ++ } else { ++ if tables[tableIndex].arrays.isEmpty { ++ try budget.allocate(8, stage: "semantic storage") ++ tables[tableIndex].arrays.reserveCapacity(8) ++ } ++ try budget.node(depth: depth) ++ tables[tableIndex].arrays.append(index) ++ tables[tableIndex].recordKeyHash(keyHash) ++ } ++ return index ++ } ++ ++ @inline(__always) ++ mutating func skipNewlines(bytes: UnsafeBufferPointer, isDotSpecial: Bool) throws { ++ if token.kind != .newline { ++ return ++ } ++ ++ let count = bytes.count ++ var position = cursor ++ var lineNumber = currentLineNumber ++ ++ while position < count { ++ try budget.step() ++ let ch = bytes[position] ++ if ch == CodeUnits.space || ch == CodeUnits.tab { ++ // 8x unrolling for space/tab skipping ++ while position + 8 <= count { ++ try budget.step() ++ let c0 = bytes[position] ++ let c1 = bytes[position + 1] ++ let c2 = bytes[position + 2] ++ let c3 = bytes[position + 3] ++ let c4 = bytes[position + 4] ++ let c5 = bytes[position + 5] ++ let c6 = bytes[position + 6] ++ let c7 = bytes[position + 7] ++ ++ if c0 == CodeUnits.space || c0 == CodeUnits.tab, ++ c1 == CodeUnits.space || c1 == CodeUnits.tab, ++ c2 == CodeUnits.space || c2 == CodeUnits.tab, ++ c3 == CodeUnits.space || c3 == CodeUnits.tab, ++ c4 == CodeUnits.space || c4 == CodeUnits.tab, ++ c5 == CodeUnits.space || c5 == CodeUnits.tab, ++ c6 == CodeUnits.space || c6 == CodeUnits.tab, ++ c7 == CodeUnits.space || c7 == CodeUnits.tab ++ { ++ position += 8 ++ } else { ++ break ++ } ++ } ++ +@@ -58,87 +637,39 @@ +- let ch = bytes[position] +- switch ch { +- case CodeUnits.pound: +- // skip comment, stop just before the \n. +- position += 1 +- while position < count, bytes[position] != CodeUnits.lf { +- let commentChar = bytes[position] +- // Validate comment characters - control characters are not allowed except CR when followed by LF (CRLF) +- if (commentChar >= CodeUnits.null && commentChar <= CodeUnits.backspace) +- || (commentChar >= CodeUnits.lf && commentChar <= CodeUnits.unitSeparator) +- || commentChar == CodeUnits.delete +- { +- if commentChar == CodeUnits.cr { +- let nextPosition = position + 1 +- if nextPosition < count, bytes[nextPosition] == CodeUnits.lf { +- // Allow CRLF sequence +- } else { +- throw TOMLError( +- .syntax( +- lineNumber: lineNumber, +- message: "control characters are not allowed in comments" +- ) +- ) +- } +- } else { +- throw TOMLError( +- .syntax( +- lineNumber: lineNumber, +- message: "control characters are not allowed in comments" +- ) +- ) +- } +- } +- position += 1 +- } +- continue +- case CodeUnits.space, CodeUnits.tab: +- // ignore white spaces +- position += 1 +- while position < count { +- let ws = bytes[position] +- if ws != CodeUnits.space, ws != CodeUnits.tab { +- break +- } +- position += 1 +- } +- continue +- case CodeUnits.dot where isDotSpecial: +- emitToken(kind: .dot, start: position, end: position + 1) +- return +- case CodeUnits.comma: +- emitToken(kind: .comma, start: position, end: position + 1) +- return +- case CodeUnits.equal: +- emitToken(kind: .equal, start: position, end: position + 1) +- return +- case CodeUnits.lbrace: +- emitToken(kind: .lbrace, start: position, end: position + 1) +- return +- case CodeUnits.rbrace: +- emitToken(kind: .rbrace, start: position, end: position + 1) +- return +- case CodeUnits.lbracket: +- emitToken(kind: .lbracket, start: position, end: position + 1) +- return +- case CodeUnits.rbracket: +- emitToken(kind: .rbracket, start: position, end: position + 1) +- return +- case CodeUnits.lf: +- emitToken(kind: .newline, start: position, end: position + 1, newlines: 1) +- return +- case CodeUnits.cr: +- // Check if this is part of a CRLF sequence +- let nextPosition = position + 1 +- if nextPosition < count, bytes[nextPosition] == CodeUnits.lf { +- // This is CRLF, treat as newline +- emitToken(kind: .newline, start: position, end: nextPosition + 1, newlines: 1) +- return +- } +- // Bare CR is invalid +- throw TOMLError( +- .syntax( +- lineNumber: lineNumber, +- message: "bare carriage return is not allowed" +- ) +- ) +- default: ++ try budget.step() ++ let ws = bytes[position] ++ if ws != CodeUnits.space, ws != CodeUnits.tab { ++ break ++ } ++ position += 1 ++ } ++ continue ++ } ++ switch ch { ++ case CodeUnits.lf: ++ lineNumber += 1 ++ position += 1 ++ case CodeUnits.cr: ++ if position + 1 < count, bytes[position + 1] == CodeUnits.lf { ++ lineNumber += 1 ++ position += 2 ++ } else { ++ // Bare CR, let nextToken handle error ++ cursor = position ++ currentLineNumber = lineNumber ++ try nextToken(bytes: bytes, isDotSpecial: isDotSpecial) ++ return ++ } ++ case CodeUnits.pound: ++ // Comment ++ position += 1 ++ while position < count { ++ try budget.step() ++ let c = bytes[position] ++ if c == CodeUnits.lf { ++ break // Leave LF for next iteration to handle line number ++ } ++ if (c >= CodeUnits.null && c <= CodeUnits.backspace) ++ || (c >= CodeUnits.lf && c <= CodeUnits.unitSeparator) || c == CodeUnits.delete ++ { ++ if c == CodeUnits.cr { ++ if position + 1 < count, bytes[position + 1] == CodeUnits.lf { ++ // CRLF ends comment +@@ -145,0 +677 @@ ++ } +@@ -147,247 +679,4 @@ +- +- func scanString(range: Range, lineNumber: Int) throws(TOMLError) { +- let start = range.lowerBound +- let end = range.upperBound +- let head = bytes[start] +- if (head >= CodeUnits.lowerA && head <= CodeUnits.lowerZ) || +- (head >= CodeUnits.upperA && head <= CodeUnits.upperZ) || +- head == CodeUnits.underscore +- { +- let isBareKeyChar = CodeUnits.isBareKeyChar +- var index = start + 1 +- while index < end { +- let ch = bytes[index] +- if isBareKeyChar[Int(ch)] { +- index += 1 +- continue +- } +- break +- } +- emitToken(kind: .bareKey, start: start, end: index) +- return +- } +- +- if head == CodeUnits.singleQuote { +- if start + 3 <= end, +- bytes[start + 1] == CodeUnits.singleQuote, +- bytes[start + 2] == CodeUnits.singleQuote +- { +- var i = start + 3 +- var newlinesInToken = 0 +- +- while i < end { +- if bytes[i] == CodeUnits.lf { +- newlinesInToken += 1 +- } +- if i + 3 <= end, +- bytes[i] == CodeUnits.singleQuote, +- bytes[i + 1] == CodeUnits.singleQuote, +- bytes[i + 2] == CodeUnits.singleQuote +- { +- if i + 3 >= end || bytes[i + 3] != CodeUnits.singleQuote { +- break +- } +- } +- i += 1 +- } +- +- guard i < end else { +- throw TOMLError( +- .syntax(lineNumber: lineNumber, message: "unterminated triple-s-quote") +- ) +- } +- +- emitToken(kind: .string, start: start, end: i + 3, newlines: newlinesInToken) +- return +- } +- +- var i = start + 1 +- while i < end { +- let ch = bytes[i] +- if ch == CodeUnits.singleQuote || ch == CodeUnits.lf { +- break +- } +- i += 1 +- } +- +- if i >= end || bytes[i] != CodeUnits.singleQuote { +- throw TOMLError( +- .syntax(lineNumber: lineNumber, message: "unterminated s-quote") +- ) +- } +- +- emitToken(kind: .string, start: start, end: i + 1) +- return +- } +- +- if head == CodeUnits.doubleQuote { +- if start + 3 < end, +- bytes[start + 1] == CodeUnits.doubleQuote, +- bytes[start + 2] == CodeUnits.doubleQuote +- { +- var i = start + 3 +- var newlinesInToken = 0 +- +- while i < end { +- if bytes[i] == CodeUnits.lf { +- newlinesInToken += 1 +- } +- if i + 3 <= end, +- bytes[i] == CodeUnits.doubleQuote, +- bytes[i + 1] == CodeUnits.doubleQuote, +- bytes[i + 2] == CodeUnits.doubleQuote +- { +- if i + 3 >= end || bytes[i + 3] != CodeUnits.doubleQuote { +- if bytes[i - 1] == CodeUnits.backslash { +- i += 1 +- continue +- } +- break +- } +- } +- i += 1 +- } +- +- guard i < end else { +- throw TOMLError( +- .syntax(lineNumber: lineNumber, message: "unterminated triple-d-quote") +- ) +- } +- +- emitToken(kind: .string, start: start, end: i + 3, newlines: newlinesInToken) +- return +- } +- +- var i = start + 1 +- let isBasicStringBodyChar = CodeUnits.isBasicStringBodyChar +- let baseAddress = bytes.baseAddress! +- while i + 8 <= end { +- let chunk = UnsafeRawPointer(baseAddress.advanced(by: i)).loadUnaligned( +- as: UInt64.self +- ) +- if chunkContainsDoubleQuotedStopByte(chunk) { +- break +- } +- i += 8 +- } +- +- while i < end { +- let ch = bytes[i] +- if isBasicStringBodyChar[Int(ch)] { +- i += 1 +- continue +- } +- if ch == CodeUnits.backslash { +- i += 1 +- if i < end { +- i += 1 +- continue +- } +- break +- } +- +- break +- } +- +- if i >= end || bytes[i] != CodeUnits.doubleQuote { +- throw TOMLError( +- .syntax(lineNumber: lineNumber, message: "unterminated quote") +- ) +- } +- +- emitToken(kind: .string, start: start, end: i + 1) +- return +- } +- +- if !isDotSpecial { +- var index = start +- var dateEnder: Int? +- // Fast path: Dates must produce YYYY-MM-DD, so checks for the dash +- if start + 4 < end && bytes[start + 4] == CodeUnits.minus { +- dateEnder = scanDate(bytes: bytes, range: range)?.3 +- } +- +- if let dateEnder, dateEnder < end, +- bytes[dateEnder] == CodeUnits.upperT || bytes[dateEnder] == CodeUnits.lowerT +- || bytes[dateEnder] == CodeUnits.space +- { +- let timeStarter = dateEnder + 1 +- if let timeEnder = scanTime( +- bytes: bytes, range: timeStarter ..< end +- )?.3 { +- index = timeEnder +- } +- } else if let dateEnder { +- index = dateEnder +- } else if start + 2 < end, bytes[start + 2] == CodeUnits.colon, +- let timeEnder = scanTime( +- bytes: bytes, range: start ..< end +- )?.3 +- { +- index = timeEnder +- } +- if index > start { +- if index < end { +- if bytes[index] == CodeUnits.dot { +- index += 1 +- while index < end, bytes[index] >= CodeUnits.number0, +- bytes[index] <= CodeUnits.number9 +- { +- index += 1 +- } +- } +- if bytes[index] == CodeUnits.upperZ || bytes[index] == CodeUnits.lowerZ { +- index += 1 +- } else if let timzoneEnder = scanTimezoneOffset( +- bytes: bytes, range: index ..< end +- ) { +- index = timzoneEnder +- } +- } +- // squeeze out any spaces at end of string +- while index > start, bytes[index - 1] == CodeUnits.space { +- index -= 1 +- } +- // tokenize +- emitToken(kind: .string, start: start, end: index) +- return +- } +- } +- +- if isDotSpecial { +- let isBareKeyChar = CodeUnits.isBareKeyChar +- var index = start +- while index < end, isBareKeyChar[Int(bytes[index])] { +- index += 1 +- } +- if index >= end || bytes[index] != CodeUnits.plus { +- emitToken(kind: .bareKey, start: start, end: index) +- return +- } +- +- index += 1 +- while index < end { +- let ch = bytes[index] +- if isBareKeyChar[Int(ch)] || ch == CodeUnits.plus { +- index += 1 +- continue +- } +- break +- } +- emitToken(kind: .string, start: start, end: index) +- } else { +- let isValueChar = CodeUnits.isValueChar +- var index = start +- while index < end { +- let ch = bytes[index] +- if isValueChar[Int(ch)] { +- index += 1 +- continue +- } +- break +- } +- emitToken(kind: .string, start: start, end: index) +- } +- } +- +- try scanString(range: position ..< count, lineNumber: lineNumber) ++ // Let nextToken throw the error ++ cursor = position ++ currentLineNumber = lineNumber ++ try nextToken(bytes: bytes, isDotSpecial: isDotSpecial) +@@ -395,236 +684,5 @@ +- } +- +- emitToken(kind: .eof, start: position, end: count) +- } +- +- mutating func eatToken(bytes: UnsafeBufferPointer, kind: Token.Kind, isDotSpecial: Bool) +- throws(TOMLError) +- { +- if token.kind != kind { +- throw TOMLError(.internalError(lineNumber: token.lineNumber)) +- } +- try nextToken(bytes: bytes, isDotSpecial: isDotSpecial) +- } +- +- mutating func createKeyValue( +- bytes: UnsafeBufferPointer, +- token: Token, +- value: Token, +- inTable tableIndex: Int, +- isKeyed: Bool +- ) throws(TOMLError) { +- let (key, keyHash) = try normalizeKeyAndHash(bytes: bytes, token: token, keyTransform: keyTransform) +- if tableValue(tableIndex: tableIndex, keyed: isKeyed, key: key, keyHash: keyHash) != nil { +- throw TOMLError(.badKey(lineNumber: token.lineNumber)) +- } +- let index = keyValues.count +- keyValues.append(KeyValuePair(key: key, keyHash: keyHash, value: value)) +- +- if isKeyed { +- if keyTables[tableIndex].table.keyValues.isEmpty { +- keyTables[tableIndex].table.keyValues.reserveCapacity(8) +- } +- keyTables[tableIndex].table.keyValues.append(index) +- keyTables[tableIndex].table.recordKeyHash(keyHash) +- } else { +- if tables[tableIndex].keyValues.isEmpty { +- tables[tableIndex].keyValues.reserveCapacity(8) +- } +- tables[tableIndex].keyValues.append(index) +- tables[tableIndex].recordKeyHash(keyHash) +- } +- } +- +- mutating func createKeyTable(bytes: UnsafeBufferPointer, token: Token, inTable tableIndex: Int, isKeyed: Bool, implicit: Bool = false) throws(TOMLError) -> Int { +- let (key, keyHash) = try normalizeKeyAndHash(bytes: bytes, token: token, keyTransform: keyTransform) +- return try createKeyTable( +- normalizedKey: key, +- keyHash: keyHash, +- lineNumber: token.lineNumber, +- inTable: tableIndex, +- isKeyed: isKeyed, +- implicit: implicit +- ) +- } +- +- mutating func createKeyTable(normalizedKey key: String, keyHash: Int, lineNumber: Int, inTable tableIndex: Int, isKeyed: Bool, implicit: Bool = false) throws(TOMLError) -> Int { +- // Check if parent table is readOnly (inline table) +- if isKeyed ? keyTables[tableIndex].table.readOnly : tables[tableIndex].readOnly { +- throw TOMLError(.syntax(lineNumber: lineNumber, message: "cannot add to inline table")) +- } +- +- switch tableValue(tableIndex: tableIndex, keyed: isKeyed, key: key, keyHash: keyHash) { +- case let .table(existingTableIndex): +- if keyTables[existingTableIndex].table.implicit { +- if keyTables[existingTableIndex].table.definedByDottedKey { +- throw TOMLError(.keyExists(lineNumber: lineNumber)) +- } +- keyTables[existingTableIndex].table.implicit = false +- return existingTableIndex +- } +- throw TOMLError(.keyExists(lineNumber: lineNumber)) +- case .keyValue, .array: +- throw TOMLError(.keyExists(lineNumber: lineNumber)) +- case nil: +- break +- } +- let index = keyTables.count +- var newTable = InternalTOMLTable() +- newTable.implicit = implicit +- newTable.definedByDottedKey = implicit +- keyTables.append(KeyTablePair(key: key, keyHash: keyHash, table: newTable)) +- +- if isKeyed { +- if keyTables[tableIndex].table.tables.isEmpty { +- keyTables[tableIndex].table.tables.reserveCapacity(8) +- } +- keyTables[tableIndex].table.tables.append(index) +- keyTables[tableIndex].table.recordKeyHash(keyHash) +- } else { +- if tables[tableIndex].tables.isEmpty { +- tables[tableIndex].tables.reserveCapacity(8) +- } +- tables[tableIndex].tables.append(index) +- tables[tableIndex].recordKeyHash(keyHash) +- } +- return index +- } +- +- mutating func createKeyArray(bytes: UnsafeBufferPointer, token: Token, inTable tableIndex: Int, isKeyed: Bool, kind: InternalTOMLArray.Kind? = nil) throws(TOMLError) -> Int { +- let (key, keyHash) = try normalizeKeyAndHash(bytes: bytes, token: token, keyTransform: keyTransform) +- return try createKeyArray( +- normalizedKey: key, +- keyHash: keyHash, +- lineNumber: token.lineNumber, +- inTable: tableIndex, +- isKeyed: isKeyed, +- kind: kind +- ) +- } +- +- mutating func createKeyArray(normalizedKey key: String, keyHash: Int, lineNumber: Int, inTable tableIndex: Int, isKeyed: Bool, kind: InternalTOMLArray.Kind? = nil) throws(TOMLError) -> Int { +- if tableValue(tableIndex: tableIndex, keyed: isKeyed, key: key, keyHash: keyHash) != nil { +- throw TOMLError(.keyExists(lineNumber: lineNumber)) +- } +- +- let index = keyArrays.count +- var array = InternalTOMLArray(kind: kind) +- if kind == .table { +- array.elements.reserveCapacity(8) +- } +- keyArrays.append(KeyArrayPair(key: key, keyHash: keyHash, array: array)) +- if isKeyed { +- if keyTables[tableIndex].table.arrays.isEmpty { +- keyTables[tableIndex].table.arrays.reserveCapacity(8) +- } +- keyTables[tableIndex].table.arrays.append(index) +- keyTables[tableIndex].table.recordKeyHash(keyHash) +- } else { +- if tables[tableIndex].arrays.isEmpty { +- tables[tableIndex].arrays.reserveCapacity(8) +- } +- tables[tableIndex].arrays.append(index) +- tables[tableIndex].recordKeyHash(keyHash) +- } +- return index +- } +- +- @inline(__always) +- mutating func skipNewlines(bytes: UnsafeBufferPointer, isDotSpecial: Bool) throws(TOMLError) { +- if token.kind != .newline { +- return +- } +- +- let count = bytes.count +- var position = cursor +- var lineNumber = currentLineNumber +- +- while position < count { +- let ch = bytes[position] +- if ch == CodeUnits.space || ch == CodeUnits.tab { +- // 8x unrolling for space/tab skipping +- while position + 8 <= count { +- let c0 = bytes[position] +- let c1 = bytes[position + 1] +- let c2 = bytes[position + 2] +- let c3 = bytes[position + 3] +- let c4 = bytes[position + 4] +- let c5 = bytes[position + 5] +- let c6 = bytes[position + 6] +- let c7 = bytes[position + 7] +- +- if c0 == CodeUnits.space || c0 == CodeUnits.tab, +- c1 == CodeUnits.space || c1 == CodeUnits.tab, +- c2 == CodeUnits.space || c2 == CodeUnits.tab, +- c3 == CodeUnits.space || c3 == CodeUnits.tab, +- c4 == CodeUnits.space || c4 == CodeUnits.tab, +- c5 == CodeUnits.space || c5 == CodeUnits.tab, +- c6 == CodeUnits.space || c6 == CodeUnits.tab, +- c7 == CodeUnits.space || c7 == CodeUnits.tab +- { +- position += 8 +- } else { +- break +- } +- } +- +- while position < count { +- let ws = bytes[position] +- if ws != CodeUnits.space, ws != CodeUnits.tab { +- break +- } +- position += 1 +- } +- continue +- } +- switch ch { +- case CodeUnits.lf: +- lineNumber += 1 +- position += 1 +- case CodeUnits.cr: +- if position + 1 < count, bytes[position + 1] == CodeUnits.lf { +- lineNumber += 1 +- position += 2 +- } else { +- // Bare CR, let nextToken handle error +- cursor = position +- currentLineNumber = lineNumber +- try nextToken(bytes: bytes, isDotSpecial: isDotSpecial) +- return +- } +- case CodeUnits.pound: +- // Comment +- position += 1 +- while position < count { +- let c = bytes[position] +- if c == CodeUnits.lf { +- break // Leave LF for next iteration to handle line number +- } +- if (c >= CodeUnits.null && c <= CodeUnits.backspace) || +- (c >= CodeUnits.lf && c <= CodeUnits.unitSeparator) || +- c == CodeUnits.delete +- { +- if c == CodeUnits.cr { +- if position + 1 < count, bytes[position + 1] == CodeUnits.lf { +- // CRLF ends comment +- break +- } +- } +- // Let nextToken throw the error +- cursor = position +- currentLineNumber = lineNumber +- try nextToken(bytes: bytes, isDotSpecial: isDotSpecial) +- return +- } +- position += 1 +- } +- default: +- // Found something else, stop skipping +- cursor = position +- currentLineNumber = lineNumber +- try nextToken(bytes: bytes, isDotSpecial: isDotSpecial) +- return +- } +- } +- +- // If we hit EOF or loop finishes ++ } ++ position += 1 ++ } ++ default: ++ // Found something else, stop skipping +@@ -634,10 +692,1081 @@ +- } +- +- mutating func parseKeyedInlineTable(bytes: UnsafeBufferPointer, tableIndex: Int) throws(TOMLError) { +- try eatToken(bytes: bytes, kind: .lbrace, isDotSpecial: true) +- +- while true { +- try skipNewlines(bytes: bytes, isDotSpecial: false) +- +- if token.kind == .rbrace { +- break ++ return ++ } ++ } ++ ++ // If we hit EOF or loop finishes ++ cursor = position ++ currentLineNumber = lineNumber ++ try nextToken(bytes: bytes, isDotSpecial: isDotSpecial) ++ } ++ ++ mutating func parseKeyedInlineTable(bytes: UnsafeBufferPointer, tableIndex: Int) throws { ++ try budget.enter(depth + 1) ++ depth += 1 ++ defer { depth -= 1 } ++ try eatToken(bytes: bytes, kind: .lbrace, isDotSpecial: true) ++ ++ while true { ++ try budget.step() ++ try skipNewlines(bytes: bytes, isDotSpecial: false) ++ ++ if token.kind == .rbrace { ++ break ++ } ++ ++ if token.kind != .string, token.kind != .bareKey { ++ throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "expect a string")) ++ } ++ ++ try parseKeyValue(bytes: bytes, tableIndex: tableIndex, isKeyed: true) ++ ++ try skipNewlines(bytes: bytes, isDotSpecial: false) ++ ++ if token.kind == .comma { ++ try eatToken(bytes: bytes, kind: .comma, isDotSpecial: true) ++ continue ++ } ++ break ++ } ++ ++ try eatToken(bytes: bytes, kind: .rbrace, isDotSpecial: true) ++ ++ keyTables[tableIndex].table.readOnly = true ++ } ++ ++ mutating func parseInlineTable(bytes: UnsafeBufferPointer, tableIndex: Int) throws { ++ try budget.enter(depth + 1) ++ depth += 1 ++ defer { depth -= 1 } ++ try eatToken(bytes: bytes, kind: .lbrace, isDotSpecial: true) ++ ++ while true { ++ try budget.step() ++ try skipNewlines(bytes: bytes, isDotSpecial: false) ++ ++ if token.kind == .rbrace { ++ break ++ } ++ ++ if token.kind != .string, token.kind != .bareKey { ++ throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "expect a string")) ++ } ++ ++ try parseKeyValue(bytes: bytes, tableIndex: tableIndex, isKeyed: false) ++ ++ try skipNewlines(bytes: bytes, isDotSpecial: false) ++ ++ if token.kind == .comma { ++ try eatToken(bytes: bytes, kind: .comma, isDotSpecial: true) ++ continue ++ } ++ break ++ } ++ ++ try eatToken(bytes: bytes, kind: .rbrace, isDotSpecial: true) ++ ++ tables[tableIndex].readOnly = true ++ } ++ ++ mutating func parseKeyedArray(bytes: UnsafeBufferPointer, arrayIndex: Int) throws { ++ try budget.enter(depth + 1) ++ depth += 1 ++ defer { depth -= 1 } ++ try eatToken(bytes: bytes, kind: .lbracket, isDotSpecial: false) ++ ++ while true { ++ try budget.step() ++ try skipNewlines(bytes: bytes, isDotSpecial: false) ++ ++ if token.kind == .rbracket { ++ break ++ } ++ if keyArrays[arrayIndex].array.elements.isEmpty { ++ try budget.allocate(8, stage: "semantic storage") ++ keyArrays[arrayIndex].array.elements.reserveCapacity(8) ++ } ++ ++ switch token.kind { ++ case .string, .bareKey: ++ if keyArrays[arrayIndex].array.kind == nil { ++ keyArrays[arrayIndex].array.kind = .value ++ } else if keyArrays[arrayIndex].array.kind != .value { ++ keyArrays[arrayIndex].array.kind = .mixed ++ } ++ ++ try budget.node(depth: depth) ++ keyArrays[arrayIndex].array.elements.append(.leaf(token)) ++ ++ try nextToken(bytes: bytes, isDotSpecial: true) ++ ++ case .lbracket: // Nested array ++ if keyArrays[arrayIndex].array.kind == nil { ++ keyArrays[arrayIndex].array.kind = .array ++ } else if keyArrays[arrayIndex].array.kind != .array { ++ keyArrays[arrayIndex].array.kind = .mixed ++ } ++ ++ let newArrayIndex = arrays.count ++ try budget.node(depth: depth) ++ arrays.append(InternalTOMLArray()) ++ try budget.node(depth: depth) ++ keyArrays[arrayIndex].array.elements.append( ++ .array(lineNumber: token.lineNumber, newArrayIndex)) ++ ++ try parseArray(bytes: bytes, arrayIndex: newArrayIndex) ++ ++ case .lbrace: // Nested table ++ if keyArrays[arrayIndex].array.kind == nil { ++ keyArrays[arrayIndex].array.kind = .inlineTable ++ } else if keyArrays[arrayIndex].array.kind != .inlineTable { ++ keyArrays[arrayIndex].array.kind = .mixed ++ } ++ ++ let newTableIndex = tables.count ++ try budget.node(depth: depth) ++ tables.append(InternalTOMLTable()) ++ try budget.node(depth: depth) ++ keyArrays[arrayIndex].array.elements.append( ++ .table(lineNumber: token.lineNumber, newTableIndex)) ++ ++ try parseInlineTable(bytes: bytes, tableIndex: newTableIndex) ++ ++ default: ++ throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "syntax error")) ++ } ++ ++ try skipNewlines(bytes: bytes, isDotSpecial: false) ++ ++ if token.kind == .comma { ++ try eatToken(bytes: bytes, kind: .comma, isDotSpecial: false) ++ continue ++ } ++ break ++ } ++ ++ try eatToken(bytes: bytes, kind: .rbracket, isDotSpecial: true) ++ } ++ ++ mutating func parseArray(bytes: UnsafeBufferPointer, arrayIndex: Int) throws { ++ try budget.enter(depth + 1) ++ depth += 1 ++ defer { depth -= 1 } ++ try eatToken(bytes: bytes, kind: .lbracket, isDotSpecial: false) ++ ++ while true { ++ try budget.step() ++ try skipNewlines(bytes: bytes, isDotSpecial: false) ++ ++ if token.kind == .rbracket { ++ break ++ } ++ if arrays[arrayIndex].elements.isEmpty { ++ try budget.allocate(8, stage: "semantic storage") ++ arrays[arrayIndex].elements.reserveCapacity(8) ++ } ++ ++ switch token.kind { ++ case .string, .bareKey: ++ if arrays[arrayIndex].kind == nil { ++ arrays[arrayIndex].kind = .value ++ } else if arrays[arrayIndex].kind != .value { ++ arrays[arrayIndex].kind = .mixed ++ } ++ ++ try budget.node(depth: depth) ++ arrays[arrayIndex].elements.append(.leaf(token)) ++ ++ try nextToken(bytes: bytes, isDotSpecial: true) ++ ++ case .lbracket: // Nested array ++ if arrays[arrayIndex].kind == nil { ++ arrays[arrayIndex].kind = .array ++ } else if arrays[arrayIndex].kind != .array { ++ arrays[arrayIndex].kind = .mixed ++ } ++ ++ let newArrayIndex = arrays.count ++ try budget.node(depth: depth) ++ arrays.append(InternalTOMLArray()) ++ try budget.node(depth: depth) ++ arrays[arrayIndex].elements.append(.array(lineNumber: token.lineNumber, newArrayIndex)) ++ ++ try parseArray(bytes: bytes, arrayIndex: newArrayIndex) ++ ++ case .lbrace: // Nested table ++ if arrays[arrayIndex].kind == nil { ++ arrays[arrayIndex].kind = .inlineTable ++ } else if arrays[arrayIndex].kind != .inlineTable { ++ arrays[arrayIndex].kind = .mixed ++ } ++ ++ let newTableIndex = tables.count ++ try budget.node(depth: depth) ++ tables.append(InternalTOMLTable()) ++ try budget.node(depth: depth) ++ arrays[arrayIndex].elements.append(.table(lineNumber: token.lineNumber, newTableIndex)) ++ ++ try parseInlineTable(bytes: bytes, tableIndex: newTableIndex) ++ ++ default: ++ throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "syntax error")) ++ } ++ ++ try skipNewlines(bytes: bytes, isDotSpecial: false) ++ ++ if token.kind == .comma { ++ try eatToken(bytes: bytes, kind: .comma, isDotSpecial: false) ++ continue ++ } ++ break ++ } ++ ++ try eatToken(bytes: bytes, kind: .rbracket, isDotSpecial: true) ++ } ++ ++ mutating func parseKeyValue(bytes: UnsafeBufferPointer, tableIndex: Int, isKeyed: Bool) ++ throws ++ { ++ if isKeyed ? keyTables[tableIndex].table.readOnly : tables[tableIndex].readOnly { ++ throw TOMLError( ++ .syntax( ++ lineNumber: token.lineNumber, message: "cannot insert new entry into existing table")) ++ } ++ ++ let key = token ++ try nextToken(bytes: bytes, isDotSpecial: true) ++ ++ if token.kind == .dot { ++ try budget.enter(depth + 1) ++ depth += 1 ++ defer { depth -= 1 } ++ let (subTableKey, subTableHash) = try normalizeKeyAndHash( ++ bytes: bytes, ++ token: key ++ ) ++ let subTableIndex: Int ++ ++ if let existingTableIndex = try lookupTable( ++ in: tableIndex, keyed: isKeyed, key: subTableKey, keyHash: subTableHash) ++ { ++ // Check if the existing table is explicitly defined (not implicit) ++ if !keyTables[existingTableIndex].table.implicit { ++ throw TOMLError( ++ .syntax( ++ lineNumber: token.lineNumber, ++ message: "cannot add to explicitly defined table using dotted keys")) ++ } ++ subTableIndex = existingTableIndex ++ } else { ++ subTableIndex = try createKeyTable( ++ normalizedKey: subTableKey, ++ keyHash: subTableHash, ++ lineNumber: key.lineNumber, ++ inTable: tableIndex, ++ isKeyed: isKeyed, ++ implicit: true ++ ) ++ } ++ ++ try nextToken(bytes: bytes, isDotSpecial: true) ++ try parseKeyValue(bytes: bytes, tableIndex: subTableIndex, isKeyed: true) ++ return ++ } ++ ++ if token.kind != .equal { ++ throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "missing =")) ++ } ++ ++ try nextToken(bytes: bytes, isDotSpecial: false) ++ ++ if token.kind == .string || token.kind == .bareKey { ++ try createKeyValue( ++ bytes: bytes, token: key, value: token, inTable: tableIndex, isKeyed: isKeyed) ++ try nextToken(bytes: bytes, isDotSpecial: false) ++ return ++ } ++ ++ if token.kind == .lbracket { ++ let index = try createKeyArray( ++ bytes: bytes, token: key, inTable: tableIndex, isKeyed: isKeyed) ++ try parseKeyedArray(bytes: bytes, arrayIndex: index) ++ return ++ } ++ ++ if token.kind == .lbrace { ++ let index = try createKeyTable( ++ bytes: bytes, token: key, inTable: tableIndex, isKeyed: isKeyed) ++ try parseKeyedInlineTable(bytes: bytes, tableIndex: index) ++ return ++ } ++ ++ throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "syntax error")) ++ } ++ ++ mutating func fillTablePath(bytes: UnsafeBufferPointer, clearPath: Bool = true) throws -> ( ++ key: String, ++ keyHash: Int, ++ token: Token ++ ) { ++ let lineNumber = token.lineNumber ++ if clearPath { ++ tablePath.removeAll(keepingCapacity: true) ++ } ++ ++ while true { ++ try budget.step() ++ if token.kind != .string, token.kind != .bareKey { ++ throw TOMLError(.syntax(lineNumber: lineNumber, message: "invalid or missing key")) ++ } ++ ++ let currentToken = token ++ let (key, keyHash) = try normalizeKeyAndHash(bytes: bytes, token: token) ++ try nextToken(bytes: bytes, isDotSpecial: true) ++ ++ if token.kind == .rbracket { ++ return (key: key, keyHash: keyHash, token: currentToken) ++ } ++ ++ try budget.node(depth: depth) ++ tablePath.append((key: key, keyHash: keyHash)) ++ ++ if token.kind != .dot { ++ throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "invalid key")) ++ } ++ ++ try nextToken(bytes: bytes, isDotSpecial: true) ++ } ++ } ++ ++ mutating func parseSelect(bytes: UnsafeBufferPointer) throws { ++ assert(token.kind == .lbracket) ++ let nextIndex = token.text.lowerBound + 1 ++ let llb = nextIndex < bytes.count && bytes[nextIndex] == CodeUnits.lbracket ++ if llb { ++ cursor = nextIndex + 1 ++ try nextToken(bytes: bytes, isDotSpecial: true) ++ } else { ++ try eatToken(bytes: bytes, kind: .lbracket, isDotSpecial: true) ++ } ++ ++ if token.kind != .string, token.kind != .bareKey { ++ throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "invalid or missing key")) ++ } ++ ++ let firstToken = token ++ let firstIsBare = firstToken.kind == .bareKey ++ let firstKey: String? ++ let firstKeyHash: Int ++ if firstIsBare { ++ firstKey = nil ++ firstKeyHash = fastKeyHash(bytes: bytes, range: firstToken.text) ++ } else { ++ let normalized = try normalizeKeyAndHash( ++ bytes: bytes, ++ token: firstToken ++ ) ++ firstKey = normalized.key ++ firstKeyHash = normalized.keyHash ++ } ++ try nextToken(bytes: bytes, isDotSpecial: true) ++ ++ if token.kind == .rbracket { ++ currentTable = 0 ++ currentTableIsKeyed = false ++ if !llb { ++ let key = try firstKey ?? makeString(budget: budget, bytes: bytes, range: firstToken.text) ++ currentTable = try createKeyTable( ++ normalizedKey: key, ++ keyHash: firstKeyHash, ++ lineNumber: firstToken.lineNumber, ++ inTable: currentTable, ++ isKeyed: currentTableIsKeyed ++ ) ++ currentTableIsKeyed = true ++ } else { ++ let arrayIndex: Int ++ if firstIsBare { ++ if let existingArrayIndex = try lookupArray( ++ in: currentTable, ++ keyed: currentTableIsKeyed, ++ bytes: bytes, ++ token: firstToken, ++ keyHash: firstKeyHash ++ ) { ++ arrayIndex = existingArrayIndex ++ } else { ++ let key = try makeString(budget: budget, bytes: bytes, range: firstToken.text) ++ arrayIndex = try createKeyArray( ++ normalizedKey: key, ++ keyHash: firstKeyHash, ++ lineNumber: firstToken.lineNumber, ++ inTable: currentTable, ++ isKeyed: currentTableIsKeyed, ++ kind: .table ++ ) ++ } ++ } else { ++ let key = firstKey! ++ if let existingArrayIndex = try lookupArray( ++ in: currentTable, ++ keyed: currentTableIsKeyed, ++ key: key, ++ keyHash: firstKeyHash ++ ) { ++ arrayIndex = existingArrayIndex ++ } else { ++ arrayIndex = try createKeyArray( ++ normalizedKey: key, ++ keyHash: firstKeyHash, ++ lineNumber: firstToken.lineNumber, ++ inTable: currentTable, ++ isKeyed: currentTableIsKeyed, ++ kind: .table ++ ) ++ } ++ } ++ if keyArrays[arrayIndex].array.kind != .table { ++ throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "array mismatch")) ++ } ++ ++ let newTableIndex = tables.count ++ try budget.node(depth: depth) ++ tables.append(InternalTOMLTable()) ++ try budget.node(depth: depth) ++ keyArrays[arrayIndex].array.elements.append( ++ .table(lineNumber: token.lineNumber, newTableIndex)) ++ currentTable = newTableIndex ++ currentTableIsKeyed = false ++ } ++ } else { ++ if token.kind != .dot { ++ throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "invalid key")) ++ } ++ ++ let firstPathKey = ++ try firstKey ?? makeString(budget: budget, bytes: bytes, range: firstToken.text) ++ var pathTableIndex = 0 ++ var pathTableIsKeyed = false ++ try advanceTablePathSegment( ++ tableIndex: &pathTableIndex, ++ isKeyed: &pathTableIsKeyed, ++ key: firstPathKey, ++ keyHash: firstKeyHash ++ ) ++ ++ try nextToken(bytes: bytes, isDotSpecial: true) ++ if token.kind != .string, token.kind != .bareKey { ++ throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "invalid or missing key")) ++ } ++ ++ let secondToken = token ++ let (secondKey, secondKeyHash) = try normalizeKeyAndHash( ++ bytes: bytes, ++ token: secondToken ++ ) ++ try nextToken(bytes: bytes, isDotSpecial: true) ++ ++ let key: String ++ let keyHash: Int ++ let keyToken: Token ++ ++ if token.kind == .rbracket { ++ currentTable = pathTableIndex ++ currentTableIsKeyed = pathTableIsKeyed ++ key = secondKey ++ keyHash = secondKeyHash ++ keyToken = secondToken ++ } else { ++ tablePath.removeAll(keepingCapacity: true) ++ try budget.node(depth: depth) ++ tablePath.append((key: secondKey, keyHash: secondKeyHash)) ++ if token.kind != .dot { ++ throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "invalid key")) ++ } ++ try nextToken(bytes: bytes, isDotSpecial: true) ++ ++ let terminal = try fillTablePath(bytes: bytes, clearPath: false) ++ key = terminal.key ++ keyHash = terminal.keyHash ++ keyToken = terminal.token ++ try walkTablePath(startTable: pathTableIndex, startKeyed: pathTableIsKeyed) ++ } ++ ++ if !llb { ++ currentTable = try createKeyTable( ++ normalizedKey: key, ++ keyHash: keyHash, ++ lineNumber: keyToken.lineNumber, ++ inTable: currentTable, ++ isKeyed: currentTableIsKeyed ++ ) ++ currentTableIsKeyed = true ++ } else { ++ let arrayIndex: Int = ++ if let existingArrayIndex = try lookupArray( ++ in: currentTable, ++ keyed: currentTableIsKeyed, ++ key: key, ++ keyHash: keyHash ++ ) { ++ existingArrayIndex ++ } else { ++ try createKeyArray( ++ normalizedKey: key, ++ keyHash: keyHash, ++ lineNumber: keyToken.lineNumber, ++ inTable: currentTable, ++ isKeyed: currentTableIsKeyed, ++ kind: .table ++ ) ++ } ++ if keyArrays[arrayIndex].array.kind != .table { ++ throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "array mismatch")) ++ } ++ ++ let newTableIndex = tables.count ++ try budget.node(depth: depth) ++ tables.append(InternalTOMLTable()) ++ try budget.node(depth: depth) ++ keyArrays[arrayIndex].array.elements.append( ++ .table(lineNumber: token.lineNumber, newTableIndex)) ++ currentTable = newTableIndex ++ currentTableIsKeyed = false ++ } ++ } ++ ++ if token.kind != .rbracket { ++ throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "expects ]")) ++ } ++ ++ if llb { ++ guard cursor < bytes.count, bytes[cursor] == CodeUnits.rbracket else { ++ throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "expects ]]")) ++ } ++ cursor += 1 ++ try nextToken(bytes: bytes, isDotSpecial: true) ++ } else { ++ try eatToken(bytes: bytes, kind: .rbracket, isDotSpecial: true) ++ } ++ ++ if token.kind != .newline, token.kind != .eof { ++ throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "extra chars after ] or ]]")) ++ } ++ } ++} ++ ++extension Token { ++ func unpackBool(bytes: UnsafeBufferPointer, context: TOMLKey) throws -> Bool { ++ try budget.allocate(text.count, stage: "scalar decode") ++ try budget.step(text.count) ++ if text.count == 4, ++ bytes[text.lowerBound] == CodeUnits.lowerT, ++ bytes[text.lowerBound + 1] == CodeUnits.lowerR, ++ bytes[text.lowerBound + 2] == CodeUnits.lowerU, ++ bytes[text.lowerBound + 3] == CodeUnits.lowerE ++ { ++ return true ++ } else if text.count == 5, ++ bytes[text.lowerBound] == CodeUnits.lowerF, ++ bytes[text.lowerBound + 1] == CodeUnits.lowerA, ++ bytes[text.lowerBound + 2] == CodeUnits.lowerL, ++ bytes[text.lowerBound + 3] == CodeUnits.lowerS, ++ bytes[text.lowerBound + 4] == CodeUnits.lowerE ++ { ++ return false ++ } ++ ++ throw TOMLError(.invalidBool(context: context, lineNumber: lineNumber)) ++ } ++ ++ func unpackFloat(bytes: UnsafeBufferPointer, context: TOMLKey) throws -> Double { ++ try budget.allocate(text.count, stage: "scalar decode") ++ try budget.step(text.count) ++ var resultCodeUnits: [UTF8.CodeUnit] = [] ++ var index = text.lowerBound ++ if bytes[index] == CodeUnits.plus || bytes[index] == CodeUnits.minus { ++ try budget.allocate(1, stage: "decoded scalar storage") ++ resultCodeUnits.append(bytes[index]) ++ index += 1 ++ } ++ guard index < text.upperBound else { ++ throw TOMLError( ++ .invalidFloat( ++ context: context, lineNumber: lineNumber, reason: "expected digit, nan or inf after sign") ++ ) ++ } ++ ++ if !bytes[index].isDecimalDigit { ++ let nameEnd = index + 3 ++ guard nameEnd == text.upperBound, ++ (bytes[index] == CodeUnits.lowerN && bytes[index + 1] == CodeUnits.lowerA ++ && bytes[index + 2] == CodeUnits.lowerN) ++ || (bytes[index] == CodeUnits.lowerI && bytes[index + 1] == CodeUnits.lowerN ++ && bytes[index + 2] == CodeUnits.lowerF) ++ else { ++ throw TOMLError( ++ .invalidFloat( ++ context: context, lineNumber: lineNumber, ++ reason: "Expected nan or inf, found \(bytes[index])")) ++ } ++ try budget.allocate(1, stage: "decoded scalar storage") ++ resultCodeUnits.append(bytes[index]) ++ try budget.allocate(1, stage: "decoded scalar storage") ++ resultCodeUnits.append(bytes[index + 1]) ++ try budget.allocate(1, stage: "decoded scalar storage") ++ resultCodeUnits.append(bytes[index + 2]) ++ } else { ++ let nextIndex = index + 1 ++ if bytes[index] == CodeUnits.number0, ++ nextIndex < text.upperBound, ++ case let next = bytes[nextIndex], ++ next != CodeUnits.dot, next != CodeUnits.lowerE, next != CodeUnits.upperE ++ { ++ throw TOMLError( ++ .invalidFloat( ++ context: context, lineNumber: lineNumber, ++ reason: "Float begins with 0 must be followed by a '.', 'e' or 'E'")) ++ } ++ ++ while index < text.upperBound { ++ try budget.step() ++ let ch = bytes[index] ++ index += 1 ++ ++ if ch == CodeUnits.underscore { ++ guard ++ let last = resultCodeUnits.last, ++ last.isDecimalDigit ++ else { ++ throw TOMLError( ++ .invalidFloat( ++ context: context, lineNumber: lineNumber, reason: "'_' must be preceded by a digit") ++ ) ++ } ++ ++ guard ++ index < text.upperBound, ++ case let next = bytes[index], ++ next.isDecimalDigit ++ else { ++ throw TOMLError( ++ .invalidFloat( ++ context: context, lineNumber: lineNumber, reason: "'_' must be follewed by a digit") ++ ) ++ } ++ ++ continue ++ } else if ch == CodeUnits.dot { ++ if resultCodeUnits.isEmpty { ++ throw TOMLError( ++ .invalidFloat( ++ context: context, lineNumber: lineNumber, ++ reason: "First digit of floats cannot be '.'")) ++ } ++ ++ if !resultCodeUnits.last!.isDecimalDigit { ++ throw TOMLError( ++ .invalidFloat( ++ context: context, lineNumber: lineNumber, ++ reason: "'.' must be preceded by a decimal digit")) ++ } ++ ++ guard index < text.upperBound, bytes[index].isDecimalDigit else { ++ throw TOMLError( ++ .invalidFloat( ++ context: context, lineNumber: lineNumber, reason: "A digit must follow '.'")) ++ } ++ ++ } else if ch == CodeUnits.upperE || ch == CodeUnits.lowerE { ++ } else if !ch.isDecimalDigit, ch != CodeUnits.plus, ch != CodeUnits.minus { ++ throw TOMLError( ++ .invalidFloat( ++ context: context, lineNumber: lineNumber, reason: "invalid character for float")) ++ } ++ ++ try budget.allocate(1, stage: "decoded scalar storage") ++ resultCodeUnits.append(ch) ++ } ++ } ++ ++ guard let double = Double(String(decoding: resultCodeUnits, as: UTF8.self)) else { ++ throw TOMLError( ++ .invalidFloat(context: context, lineNumber: lineNumber, reason: "not a float")) ++ } ++ ++ return double ++ } ++ ++ func unpackString(bytes: UnsafeBufferPointer, context: TOMLKey) throws -> String { ++ try budget.allocate(text.count, stage: "scalar decode") ++ try budget.step(text.count) ++ var multiline = false ++ ++ if bytes.count == 0 { ++ throw TOMLError( ++ .invalidString(context: context, lineNumber: lineNumber, reason: "missing closing quote")) ++ } ++ ++ let quoteChar = bytes[text.lowerBound] ++ if quoteChar != CodeUnits.doubleQuote, quoteChar != CodeUnits.singleQuote { ++ throw TOMLError(.typeMismatch(context: context, lineNumber: lineNumber, expected: "string")) ++ } ++ var index = text.lowerBound ++ var endIndex = text.upperBound ++ ++ if endIndex - index >= 3 && bytes[index] == CodeUnits.doubleQuote ++ && bytes[index + 1] == CodeUnits.doubleQuote && bytes[index + 2] == CodeUnits.doubleQuote ++ || endIndex - index >= 3 && bytes[index] == CodeUnits.singleQuote ++ && bytes[index + 1] == CodeUnits.singleQuote && bytes[index + 2] == CodeUnits.singleQuote ++ { ++ multiline = true ++ index += 3 ++ endIndex -= 3 ++ ++ if index < endIndex, bytes[index] == CodeUnits.lf { ++ index += 1 ++ } else if endIndex - index >= 2, bytes[index] == CodeUnits.cr, ++ bytes[index + 1] == CodeUnits.lf ++ { ++ index += 2 ++ } ++ } else { ++ index = index + 1 ++ endIndex = endIndex - 1 ++ guard endIndex >= 0, bytes[endIndex] == quoteChar else { ++ throw TOMLError( ++ .invalidString(context: context, lineNumber: lineNumber, reason: "missing closing quote")) ++ } ++ } ++ ++ if quoteChar == CodeUnits.singleQuote { ++ return try literalString( ++ budget: budget, bytes: bytes, range: index.., context: TOMLKey) throws -> Int64 { ++ try budget.allocate(text.count, stage: "scalar decode") ++ try budget.step(text.count) ++ @_transparent ++ func isValidDigit(_ codeUnit: UTF8.CodeUnit, base: Int) -> Bool { ++ switch base { ++ case 10: ++ codeUnit.isDecimalDigit ++ case 16: ++ codeUnit.isHexDigit ++ case 2: ++ codeUnit == CodeUnits.number0 || codeUnit == CodeUnits.number1 ++ case 8: ++ CodeUnits.number0 <= codeUnit && codeUnit <= CodeUnits.number7 ++ default: ++ false ++ } ++ } ++ ++ var resultCodeUnits: [UTF8.CodeUnit] = [] ++ var index = text.lowerBound ++ var base = 10 ++ var hasSign = false ++ if bytes[index] == CodeUnits.plus || bytes[index] == CodeUnits.minus { ++ hasSign = true ++ try budget.allocate(1, stage: "decoded scalar storage") ++ resultCodeUnits.append(bytes[index]) ++ index = text.index(after: index) ++ } ++ guard index < text.upperBound else { ++ throw TOMLError( ++ .invalidInteger( ++ context: context, lineNumber: lineNumber, reason: "expected digit after sign")) ++ } ++ ++ if bytes[index] == CodeUnits.underscore { ++ throw TOMLError( ++ .invalidInteger(context: context, lineNumber: lineNumber, reason: "cannot start with a '_'") ++ ) ++ } ++ ++ if bytes[index] == CodeUnits.number0 { ++ let nextIndex = index + 1 ++ if nextIndex < text.upperBound { ++ if bytes[nextIndex] == CodeUnits.lowerX { ++ if hasSign { ++ throw TOMLError( ++ .invalidInteger( ++ context: context, lineNumber: lineNumber, ++ reason: "hexadecimal integers cannot have explicit signs")) ++ } ++ base = 16 ++ index += 2 ++ } else if bytes[nextIndex] == CodeUnits.lowerO { ++ if hasSign { ++ throw TOMLError( ++ .invalidInteger( ++ context: context, lineNumber: lineNumber, ++ reason: "octal integers cannot have explicit signs")) ++ } ++ base = 8 ++ index += 2 ++ } else if bytes[nextIndex] == CodeUnits.lowerB { ++ if hasSign { ++ throw TOMLError( ++ .invalidInteger( ++ context: context, lineNumber: lineNumber, ++ reason: "binary integers cannot have explicit signs")) ++ } ++ base = 2 ++ index += 2 ++ } else if bytes[nextIndex].isDecimalDigit || bytes[nextIndex] == CodeUnits.underscore { ++ throw TOMLError( ++ .invalidInteger( ++ context: context, lineNumber: lineNumber, ++ reason: "decimal integers cannot have leading zeros")) ++ } ++ } ++ // Single zero is allowed to continue to the main loop ++ } ++ guard index < text.upperBound else { ++ throw TOMLError( ++ .invalidInteger( ++ context: context, lineNumber: lineNumber, reason: "expected digit after base prefix")) ++ } ++ ++ while index < text.upperBound { ++ try budget.step() ++ let ch = bytes[index] ++ index += 1 ++ ++ if ch == CodeUnits.underscore { ++ guard ++ let last = resultCodeUnits.last, ++ isValidDigit(last, base: base) ++ else { ++ throw TOMLError( ++ .invalidInteger( ++ context: context, lineNumber: lineNumber, ++ reason: "cannot use '_' adjacent to a non-digit")) ++ } ++ ++ if index >= text.endIndex { ++ throw TOMLError( ++ .invalidInteger( ++ context: context, lineNumber: lineNumber, reason: "cannot end with a '_'")) ++ } ++ ++ let next = bytes[index] ++ if next == CodeUnits.underscore { ++ throw TOMLError( ++ .invalidInteger( ++ context: context, lineNumber: lineNumber, reason: "cannot contain consecutive '_'")) ++ } ++ guard isValidDigit(next, base: base) else { ++ throw TOMLError( ++ .invalidInteger( ++ context: context, lineNumber: lineNumber, ++ reason: "cannot use '_' adjacent to a non-digit")) ++ } ++ continue ++ } ++ ++ guard isValidDigit(ch, base: base) else { ++ throw TOMLError( ++ .invalidInteger( ++ context: context, lineNumber: lineNumber, reason: "invalid digit for base \(base)")) ++ } ++ ++ try budget.allocate(1, stage: "decoded scalar storage") ++ resultCodeUnits.append(ch) ++ } ++ ++ let s = String(decoding: resultCodeUnits, as: UTF8.self) ++ guard let i = Int64(s, radix: base) else { ++ throw TOMLError( ++ .invalidInteger( ++ context: context, lineNumber: lineNumber, ++ reason: "\(s) is a invalid integer of base \(base)")) ++ } ++ return i ++ } ++ ++ func unpackDateTime(bytes: UnsafeBufferPointer, context: TOMLKey) throws ++ -> DateTimeComponents ++ { ++ try budget.allocate(text.count, stage: "scalar decode") ++ try budget.step(text.count) ++ var mustParseTime = false ++ var date: (year: Int, month: Int, day: Int)? ++ var time: (hour: Int, minute: Int, second: Int)? ++ ++ var index = text.lowerBound ++ if let (year, month, day, _) = scanDate(bytes: bytes, range: text) { ++ // Validate date components ++ if month < 1 || month > 12 { ++ throw TOMLError( ++ .invalidDateTime3( ++ context: context, lineNumber: lineNumber, reason: "month must be between 01 and 12")) ++ } ++ if day < 1 { ++ throw TOMLError( ++ .invalidDateTime3( ++ context: context, lineNumber: lineNumber, reason: "day must be between 01 and 31")) ++ } ++ ++ // Validate days per month and leap years ++ let isLeapYear = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) ++ let maxDaysInMonth: Int = ++ switch month { ++ case 2: ++ isLeapYear ? 29 : 28 ++ case 4, 6, 9, 11: ++ 30 ++ default: ++ 31 ++ } ++ ++ if day > maxDaysInMonth { ++ if month == 2, !isLeapYear { ++ throw TOMLError( ++ .invalidDateTime3( ++ context: context, lineNumber: lineNumber, ++ reason: "February only has 28 days in non-leap years")) ++ } else if month == 2, isLeapYear { ++ throw TOMLError( ++ .invalidDateTime3( ++ context: context, lineNumber: lineNumber, ++ reason: "February only has 29 days in leap years")) ++ } else { ++ throw TOMLError( ++ .invalidDateTime3( ++ context: context, lineNumber: lineNumber, ++ reason: "day \(day) is invalid for month \(month)")) ++ } ++ } ++ ++ date = (year, month, day) ++ index += 10 ++ } ++ ++ var features: OffsetDateTime.Features = [] ++ var nanoseconds: UInt32? ++ if index < text.upperBound { ++ if date != nil { ++ let isSeparatorLowerT = bytes[index] == CodeUnits.lowerT ++ let isSeparatorUpperT = bytes[index] == CodeUnits.upperT ++ guard isSeparatorLowerT || isSeparatorUpperT || bytes[index] == CodeUnits.space else { ++ throw TOMLError( ++ .invalidDateTime3( ++ context: context, lineNumber: lineNumber, ++ reason: "expected 'T' or 't' or space to separate date and time")) ++ } ++ if isSeparatorLowerT { ++ features.insert(.lowercaseT) ++ } else if isSeparatorUpperT { ++ features.insert(.uppercaseT) ++ } ++ mustParseTime = true ++ index += 1 ++ } else { ++ // For standalone time values, don't advance index ++ mustParseTime = true ++ } ++ if let (hour, minute, second, newIndex) = scanTime( ++ bytes: bytes, range: index.. 23 { ++ throw TOMLError( ++ .invalidDateTime3( ++ context: context, lineNumber: lineNumber, reason: "hour must be between 00 and 23")) ++ } ++ if minute > 59 { ++ throw TOMLError( ++ .invalidDateTime3( ++ context: context, lineNumber: lineNumber, reason: "minute must be between 00 and 59")) ++ } ++ if second > 59 { ++ throw TOMLError( ++ .invalidDateTime3( ++ context: context, lineNumber: lineNumber, reason: "second must be between 00 and 59")) ++ } ++ ++ time = (hour, minute, second) ++ ++ index = newIndex ++ if index < text.upperBound, bytes[index] == CodeUnits.dot { ++ index += 1 ++ let beforeNanoIndex = index ++ nanoseconds = try parseNanoSeconds( ++ budget: budget, bytes: bytes, range: index.. 24 { ++ throw TOMLError( ++ .invalidDateTime3( ++ context: context, lineNumber: lineNumber, ++ reason: "timezone offset hour must be between 00 and 24")) ++ } ++ if offsetMinute > 59 { ++ throw TOMLError( ++ .invalidDateTime3( ++ context: context, lineNumber: lineNumber, ++ reason: "timezone offset minute must be between 00 and 59")) ++ } ++ ++ let offsetInMinutes = offsetHour * 60 + offsetMinute ++ timeOffset = Int16(offsetIsNegative ? -offsetInMinutes : offsetInMinutes) ++ index += consumedLength ++ } catch let parseError { ++ if let tomlError = parseError as? TOMLError { ++ switch tomlError.reason { ++ case .invalidDateTime(_, let reason): ++ throw TOMLError( ++ .invalidDateTime3(context: context, lineNumber: lineNumber, reason: reason)) ++ default: ++ throw tomlError +@@ -645,198 +1774,184 @@ +- +- if token.kind != .string, token.kind != .bareKey { +- throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "expect a string")) +- } +- +- try parseKeyValue(bytes: bytes, tableIndex: tableIndex, isKeyed: true) +- +- try skipNewlines(bytes: bytes, isDotSpecial: false) +- +- if token.kind == .comma { +- try eatToken(bytes: bytes, kind: .comma, isDotSpecial: true) +- continue +- } +- break +- } +- +- try eatToken(bytes: bytes, kind: .rbrace, isDotSpecial: true) +- +- keyTables[tableIndex].table.readOnly = true +- } +- +- mutating func parseInlineTable(bytes: UnsafeBufferPointer, tableIndex: Int) throws(TOMLError) { +- try eatToken(bytes: bytes, kind: .lbrace, isDotSpecial: true) +- +- while true { +- try skipNewlines(bytes: bytes, isDotSpecial: false) +- +- if token.kind == .rbrace { +- break +- } +- +- if token.kind != .string, token.kind != .bareKey { +- throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "expect a string")) +- } +- +- try parseKeyValue(bytes: bytes, tableIndex: tableIndex, isKeyed: false) +- +- try skipNewlines(bytes: bytes, isDotSpecial: false) +- +- if token.kind == .comma { +- try eatToken(bytes: bytes, kind: .comma, isDotSpecial: true) +- continue +- } +- break +- } +- +- try eatToken(bytes: bytes, kind: .rbrace, isDotSpecial: true) +- +- tables[tableIndex].readOnly = true +- } +- +- mutating func parseKeyedArray(bytes: UnsafeBufferPointer, arrayIndex: Int) throws(TOMLError) { +- try eatToken(bytes: bytes, kind: .lbracket, isDotSpecial: false) +- +- while true { +- try skipNewlines(bytes: bytes, isDotSpecial: false) +- +- if token.kind == .rbracket { +- break +- } +- if keyArrays[arrayIndex].array.elements.isEmpty { +- keyArrays[arrayIndex].array.elements.reserveCapacity(8) +- } +- +- switch token.kind { +- case .string, .bareKey: +- if keyArrays[arrayIndex].array.kind == nil { +- keyArrays[arrayIndex].array.kind = .value +- } else if keyArrays[arrayIndex].array.kind != .value { +- keyArrays[arrayIndex].array.kind = .mixed +- } +- +- keyArrays[arrayIndex].array.elements.append(.leaf(token)) +- +- try nextToken(bytes: bytes, isDotSpecial: true) +- +- case .lbracket: // Nested array +- if keyArrays[arrayIndex].array.kind == nil { +- keyArrays[arrayIndex].array.kind = .array +- } else if keyArrays[arrayIndex].array.kind != .array { +- keyArrays[arrayIndex].array.kind = .mixed +- } +- +- let newArrayIndex = arrays.count +- arrays.append(InternalTOMLArray()) +- keyArrays[arrayIndex].array.elements.append(.array(lineNumber: token.lineNumber, newArrayIndex)) +- +- try parseArray(bytes: bytes, arrayIndex: newArrayIndex) +- +- case .lbrace: // Nested table +- if keyArrays[arrayIndex].array.kind == nil { +- keyArrays[arrayIndex].array.kind = .table +- } else if keyArrays[arrayIndex].array.kind != .table { +- keyArrays[arrayIndex].array.kind = .mixed +- } +- +- let newTableIndex = tables.count +- tables.append(InternalTOMLTable()) +- keyArrays[arrayIndex].array.elements.append(.table(lineNumber: token.lineNumber, newTableIndex)) +- +- try parseInlineTable(bytes: bytes, tableIndex: newTableIndex) +- +- default: +- throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "syntax error")) +- } +- +- try skipNewlines(bytes: bytes, isDotSpecial: false) +- +- if token.kind == .comma { +- try eatToken(bytes: bytes, kind: .comma, isDotSpecial: false) +- continue +- } +- break +- } +- +- try eatToken(bytes: bytes, kind: .rbracket, isDotSpecial: true) +- } +- +- mutating func parseArray(bytes: UnsafeBufferPointer, arrayIndex: Int) throws(TOMLError) { +- try eatToken(bytes: bytes, kind: .lbracket, isDotSpecial: false) +- +- while true { +- try skipNewlines(bytes: bytes, isDotSpecial: false) +- +- if token.kind == .rbracket { +- break +- } +- if arrays[arrayIndex].elements.isEmpty { +- arrays[arrayIndex].elements.reserveCapacity(8) +- } +- +- switch token.kind { +- case .string, .bareKey: +- if arrays[arrayIndex].kind == nil { +- arrays[arrayIndex].kind = .value +- } else if arrays[arrayIndex].kind != .value { +- arrays[arrayIndex].kind = .mixed +- } +- +- arrays[arrayIndex].elements.append(.leaf(token)) +- +- try nextToken(bytes: bytes, isDotSpecial: true) +- +- case .lbracket: // Nested array +- if arrays[arrayIndex].kind == nil { +- arrays[arrayIndex].kind = .array +- } else if arrays[arrayIndex].kind != .array { +- arrays[arrayIndex].kind = .mixed +- } +- +- let newArrayIndex = arrays.count +- arrays.append(InternalTOMLArray()) +- arrays[arrayIndex].elements.append(.array(lineNumber: token.lineNumber, newArrayIndex)) +- +- try parseArray(bytes: bytes, arrayIndex: newArrayIndex) +- +- case .lbrace: // Nested table +- if arrays[arrayIndex].kind == nil { +- arrays[arrayIndex].kind = .table +- } else if arrays[arrayIndex].kind != .table { +- arrays[arrayIndex].kind = .mixed +- } +- +- let newTableIndex = tables.count +- tables.append(InternalTOMLTable()) +- arrays[arrayIndex].elements.append(.table(lineNumber: token.lineNumber, newTableIndex)) +- +- try parseInlineTable(bytes: bytes, tableIndex: newTableIndex) +- +- default: +- throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "syntax error")) +- } +- +- try skipNewlines(bytes: bytes, isDotSpecial: false) +- +- if token.kind == .comma { +- try eatToken(bytes: bytes, kind: .comma, isDotSpecial: false) +- continue +- } +- break +- } +- +- try eatToken(bytes: bytes, kind: .rbracket, isDotSpecial: true) +- } +- +- mutating func parseKeyValue(bytes: UnsafeBufferPointer, tableIndex: Int, isKeyed: Bool) throws(TOMLError) { +- if isKeyed ? keyTables[tableIndex].table.readOnly : tables[tableIndex].readOnly { +- throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "cannot insert new entry into existing table")) +- } +- +- let key = token +- try nextToken(bytes: bytes, isDotSpecial: true) +- +- if token.kind == .dot { +- let (subTableKey, subTableHash) = try normalizeKeyAndHash( +- bytes: bytes, +- token: key, +- keyTransform: keyTransform ++ } else { ++ throw TOMLError( ++ .invalidDateTime3( ++ context: context, lineNumber: lineNumber, reason: "timezone parsing error")) ++ } ++ } ++ } ++ } ++ ++ if index < text.upperBound { ++ throw TOMLError( ++ .invalidDateTime3( ++ context: context, lineNumber: lineNumber, reason: "extra character after date time")) ++ } ++ ++ return DateTimeComponents( ++ date: date.map { ++ LocalDate(year: .init($0.year), month: .init($0.month), day: .init($0.day)) ++ }, ++ time: time.map { ++ LocalTime( ++ hour: .init($0.hour), minute: .init($0.minute), second: .init($0.second), ++ nanosecond: nanoseconds ?? 0) ++ }, ++ offset: timeOffset, ++ features: features ++ ) ++ } ++ ++} ++ ++func parseTimezoneOffset(bytes: UnsafeBufferPointer, range: Range, lineNumber: Int) ++ throws -> (hour: Int, minute: Int, consumedLength: Int) ++{ ++ guard range.count >= 2 else { ++ throw TOMLError( ++ .invalidDateTime( ++ lineNumber: lineNumber, reason: "timezone offset must have at least 2 digits for hour")) ++ } ++ ++ var index = range.lowerBound ++ ++ // Parse hour digits (exactly 2 required) ++ guard ++ index < range.upperBound, ++ bytes[index].isDecimalDigit, ++ case let firstHourDigit = bytes[index], ++ case let nextIndex = index + 1, ++ nextIndex < range.upperBound, ++ bytes[nextIndex].isDecimalDigit, ++ case let secondHourDigit = bytes[nextIndex] ++ else { ++ throw TOMLError( ++ .invalidDateTime( ++ lineNumber: lineNumber, reason: "timezone offset hour must be exactly 2 digits")) ++ } ++ ++ let offsetHour = ++ Int(firstHourDigit - CodeUnits.number0) * 10 + Int(secondHourDigit - CodeUnits.number0) ++ index += 2 ++ var consumedLength = 2 ++ ++ // Parse required minute digits (timezone offset must include minutes) ++ guard index < range.upperBound, bytes[index] == CodeUnits.colon else { ++ throw TOMLError( ++ .invalidDateTime( ++ lineNumber: lineNumber, reason: "timezone offset must include minutes (format: ±HH:MM)")) ++ } ++ ++ index += 1 ++ consumedLength += 1 ++ ++ guard ++ index < range.upperBound, ++ bytes[index].isDecimalDigit, ++ case let firstMinuteDigit = bytes[index], ++ case let nextMinuteIndex = index + 1, ++ nextMinuteIndex < range.upperBound, ++ bytes[nextMinuteIndex].isDecimalDigit, ++ case let secondMinuteDigit = bytes[nextMinuteIndex] ++ else { ++ throw TOMLError( ++ .invalidDateTime( ++ lineNumber: lineNumber, reason: "timezone offset minute must be exactly 2 digits")) ++ } ++ ++ let offsetMinute = ++ Int(firstMinuteDigit - CodeUnits.number0) * 10 + Int(secondMinuteDigit - CodeUnits.number0) ++ consumedLength += 2 ++ ++ return (offsetHour, offsetMinute, consumedLength) ++} ++ ++func literalString( ++ budget: SemanticBudget, bytes: UnsafeBufferPointer, range: Range, multiline: Bool ++) throws -> String { ++ var resultCodeUnits: [UTF8.CodeUnit] = [] ++ var consecutiveQuotes = 0 ++ ++ for index in range { ++ try budget.step() ++ let codeUnit = bytes[index] ++ if codeUnit >= CodeUnits.null && codeUnit <= CodeUnits.backspace ++ || codeUnit >= CodeUnits.lf && codeUnit <= CodeUnits.unitSeparator ++ || codeUnit == CodeUnits.delete ++ { ++ if multiline, codeUnit == CodeUnits.lf { ++ // Allow LF in multiline literal strings ++ } else if multiline, codeUnit == CodeUnits.cr { ++ // Only allow CR if followed by LF (CRLF sequence) ++ let nextIndex = index + 1 ++ if nextIndex < range.upperBound, bytes[nextIndex] == CodeUnits.lf { ++ // Allow CRLF sequence - will be processed as separate characters ++ } else { ++ throw TOMLError(.invalidCharacter(codeUnit)) ++ } ++ } else { ++ throw TOMLError(.invalidCharacter(codeUnit)) ++ } ++ } ++ ++ if multiline, codeUnit == CodeUnits.singleQuote { ++ consecutiveQuotes += 1 ++ if consecutiveQuotes > 2 { ++ throw TOMLError( ++ .syntax( ++ lineNumber: 0, ++ message: ++ "literal multiline strings cannot contain more than 2 consecutive single quotes")) ++ } ++ } else { ++ consecutiveQuotes = 0 ++ } ++ ++ try budget.allocate(1, stage: "decoded scalar storage") ++ resultCodeUnits.append(codeUnit) ++ } ++ return String(decoding: resultCodeUnits, as: UTF8.self) ++} ++ ++func basicString( ++ budget: SemanticBudget, bytes: UnsafeBufferPointer, range: Range, multiline: Bool ++) throws -> String { ++ let startIndex = range.lowerBound ++ let endIndex = range.upperBound ++ var resultCodeUnits: [UTF8.CodeUnit] = [] ++ try budget.allocate(range.count, stage: "decoded string capacity") ++ resultCodeUnits.reserveCapacity(range.count) ++ var consecutiveQuotes = 0 ++ var index = startIndex ++ while true { ++ try budget.step() ++ if index >= endIndex { ++ break ++ } ++ ++ var ch = bytes[index] ++ index += 1 ++ if ch != CodeUnits.backslash { ++ if ch >= CodeUnits.null && ch <= CodeUnits.backspace ++ || ch >= CodeUnits.lf && ch <= CodeUnits.unitSeparator || ch == CodeUnits.delete ++ { ++ if multiline, ch == CodeUnits.lf { ++ // Allow LF in multiline basic strings ++ } else if multiline, ch == CodeUnits.cr { ++ // Only allow CR if followed by LF (CRLF sequence) ++ if index < endIndex, bytes[index] == CodeUnits.lf { ++ // Allow CRLF sequence - will be processed as separate characters ++ } else { ++ throw TOMLError(.invalidCharacter(ch)) ++ } ++ } else { ++ throw TOMLError(.invalidCharacter(ch)) ++ } ++ } ++ ++ if multiline, ch == CodeUnits.doubleQuote { ++ consecutiveQuotes += 1 ++ if consecutiveQuotes > 2 { ++ throw TOMLError( ++ .syntax( ++ lineNumber: 0, ++ message: ++ "basic multiline strings cannot contain more than 2 consecutive double quotes" +@@ -844,91 +1959,23 @@ +- let subTableIndex: Int +- +- if let existingTableIndex = lookupTable(in: tableIndex, keyed: isKeyed, key: subTableKey, keyHash: subTableHash) { +- // Check if the existing table is explicitly defined (not implicit) +- if !keyTables[existingTableIndex].table.implicit { +- throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "cannot add to explicitly defined table using dotted keys")) +- } +- subTableIndex = existingTableIndex +- } else { +- subTableIndex = try createKeyTable( +- normalizedKey: subTableKey, +- keyHash: subTableHash, +- lineNumber: key.lineNumber, +- inTable: tableIndex, +- isKeyed: isKeyed, +- implicit: true +- ) +- } +- +- try nextToken(bytes: bytes, isDotSpecial: true) +- try parseKeyValue(bytes: bytes, tableIndex: subTableIndex, isKeyed: true) +- return +- } +- +- if token.kind != .equal { +- throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "missing =")) +- } +- +- try nextToken(bytes: bytes, isDotSpecial: false) +- +- if token.kind == .string || token.kind == .bareKey { +- try createKeyValue(bytes: bytes, token: key, value: token, inTable: tableIndex, isKeyed: isKeyed) +- try nextToken(bytes: bytes, isDotSpecial: false) +- return +- } +- +- if token.kind == .lbracket { +- let index = try createKeyArray(bytes: bytes, token: key, inTable: tableIndex, isKeyed: isKeyed) +- try parseKeyedArray(bytes: bytes, arrayIndex: index) +- return +- } +- +- if token.kind == .lbrace { +- let index = try createKeyTable(bytes: bytes, token: key, inTable: tableIndex, isKeyed: isKeyed) +- try parseKeyedInlineTable(bytes: bytes, tableIndex: index) +- return +- } +- +- throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "syntax error")) +- } +- +- mutating func fillTablePath(bytes: UnsafeBufferPointer, clearPath: Bool = true) throws(TOMLError) -> ( +- key: String, +- keyHash: Int, +- token: Token +- ) { +- let lineNumber = token.lineNumber +- if clearPath { +- tablePath.removeAll(keepingCapacity: true) +- } +- +- while true { +- if token.kind != .string, token.kind != .bareKey { +- throw TOMLError(.syntax(lineNumber: lineNumber, message: "invalid or missing key")) +- } +- +- let currentToken = token +- let (key, keyHash) = try normalizeKeyAndHash(bytes: bytes, token: token, keyTransform: keyTransform) +- try nextToken(bytes: bytes, isDotSpecial: true) +- +- if token.kind == .rbracket { +- return (key: key, keyHash: keyHash, token: currentToken) +- } +- +- tablePath.append((key: key, keyHash: keyHash)) +- +- if token.kind != .dot { +- throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "invalid key")) +- } +- +- try nextToken(bytes: bytes, isDotSpecial: true) +- } +- } +- +- mutating func parseSelect(bytes: UnsafeBufferPointer) throws(TOMLError) { +- assert(token.kind == .lbracket) +- let nextIndex = token.text.lowerBound + 1 +- let llb = nextIndex < bytes.count && bytes[nextIndex] == CodeUnits.lbracket +- if llb { +- cursor = nextIndex + 1 +- try nextToken(bytes: bytes, isDotSpecial: true) ++ ) ++ } ++ } else { ++ consecutiveQuotes = 0 ++ } ++ ++ try budget.allocate(1, stage: "decoded scalar storage") ++ resultCodeUnits.append(ch) ++ continue ++ } ++ ++ if index >= endIndex { ++ throw TOMLError(.invalidCharacter(CodeUnits.backslash)) ++ } ++ ++ func indexAfterSkippingCharacters(start: Int, endIndex: Int, characters: [UTF8.CodeUnit]) ++ throws -> Int ++ { ++ var index = start ++ while index < endIndex { ++ try budget.step() ++ if characters.contains(bytes[index]) { ++ index += 1 +@@ -936,614 +1983,15 @@ +- try eatToken(bytes: bytes, kind: .lbracket, isDotSpecial: true) +- } +- +- if token.kind != .string, token.kind != .bareKey { +- throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "invalid or missing key")) +- } +- +- let firstToken = token +- let firstIsBareNoTransform = keyTransform == nil && firstToken.kind == .bareKey +- let firstKey: String? +- let firstKeyHash: Int +- if firstIsBareNoTransform { +- firstKey = nil +- firstKeyHash = fastKeyHash(bytes: bytes, range: firstToken.text) +- } else { +- let normalized = try normalizeKeyAndHash( +- bytes: bytes, +- token: firstToken, +- keyTransform: keyTransform +- ) +- firstKey = normalized.key +- firstKeyHash = normalized.keyHash +- } +- try nextToken(bytes: bytes, isDotSpecial: true) +- +- if token.kind == .rbracket { +- currentTable = 0 +- currentTableIsKeyed = false +- if !llb { +- let key = firstKey ?? makeString(bytes: bytes, range: firstToken.text) +- currentTable = try createKeyTable( +- normalizedKey: key, +- keyHash: firstKeyHash, +- lineNumber: firstToken.lineNumber, +- inTable: currentTable, +- isKeyed: currentTableIsKeyed +- ) +- currentTableIsKeyed = true +- } else { +- let arrayIndex: Int +- if firstIsBareNoTransform { +- if let existingArrayIndex = lookupArray( +- in: currentTable, +- keyed: currentTableIsKeyed, +- bytes: bytes, +- token: firstToken, +- keyHash: firstKeyHash +- ) { +- arrayIndex = existingArrayIndex +- } else { +- let key = makeString(bytes: bytes, range: firstToken.text) +- arrayIndex = try createKeyArray( +- normalizedKey: key, +- keyHash: firstKeyHash, +- lineNumber: firstToken.lineNumber, +- inTable: currentTable, +- isKeyed: currentTableIsKeyed, +- kind: .table +- ) +- } +- } else { +- let key = firstKey! +- if let existingArrayIndex = lookupArray( +- in: currentTable, +- keyed: currentTableIsKeyed, +- key: key, +- keyHash: firstKeyHash +- ) { +- arrayIndex = existingArrayIndex +- } else { +- arrayIndex = try createKeyArray( +- normalizedKey: key, +- keyHash: firstKeyHash, +- lineNumber: firstToken.lineNumber, +- inTable: currentTable, +- isKeyed: currentTableIsKeyed, +- kind: .table +- ) +- } +- } +- if keyArrays[arrayIndex].array.kind != .table { +- throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "array mismatch")) +- } +- +- let newTableIndex = tables.count +- tables.append(InternalTOMLTable()) +- keyArrays[arrayIndex].array.elements.append(.table(lineNumber: token.lineNumber, newTableIndex)) +- currentTable = newTableIndex +- currentTableIsKeyed = false +- } +- } else { +- if token.kind != .dot { +- throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "invalid key")) +- } +- +- let firstPathKey = firstKey ?? makeString(bytes: bytes, range: firstToken.text) +- var pathTableIndex = 0 +- var pathTableIsKeyed = false +- try advanceTablePathSegment( +- tableIndex: &pathTableIndex, +- isKeyed: &pathTableIsKeyed, +- key: firstPathKey, +- keyHash: firstKeyHash +- ) +- +- try nextToken(bytes: bytes, isDotSpecial: true) +- if token.kind != .string, token.kind != .bareKey { +- throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "invalid or missing key")) +- } +- +- let secondToken = token +- let (secondKey, secondKeyHash) = try normalizeKeyAndHash( +- bytes: bytes, +- token: secondToken, +- keyTransform: keyTransform +- ) +- try nextToken(bytes: bytes, isDotSpecial: true) +- +- let key: String +- let keyHash: Int +- let keyToken: Token +- +- if token.kind == .rbracket { +- currentTable = pathTableIndex +- currentTableIsKeyed = pathTableIsKeyed +- key = secondKey +- keyHash = secondKeyHash +- keyToken = secondToken +- } else { +- tablePath.removeAll(keepingCapacity: true) +- tablePath.append((key: secondKey, keyHash: secondKeyHash)) +- if token.kind != .dot { +- throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "invalid key")) +- } +- try nextToken(bytes: bytes, isDotSpecial: true) +- +- let terminal = try fillTablePath(bytes: bytes, clearPath: false) +- key = terminal.key +- keyHash = terminal.keyHash +- keyToken = terminal.token +- try walkTablePath(startTable: pathTableIndex, startKeyed: pathTableIsKeyed) +- } +- +- if !llb { +- currentTable = try createKeyTable( +- normalizedKey: key, +- keyHash: keyHash, +- lineNumber: keyToken.lineNumber, +- inTable: currentTable, +- isKeyed: currentTableIsKeyed +- ) +- currentTableIsKeyed = true +- } else { +- let arrayIndex: Int = if let existingArrayIndex = lookupArray( +- in: currentTable, +- keyed: currentTableIsKeyed, +- key: key, +- keyHash: keyHash +- ) { +- existingArrayIndex +- } else { +- try createKeyArray( +- normalizedKey: key, +- keyHash: keyHash, +- lineNumber: keyToken.lineNumber, +- inTable: currentTable, +- isKeyed: currentTableIsKeyed, +- kind: .table +- ) +- } +- if keyArrays[arrayIndex].array.kind != .table { +- throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "array mismatch")) +- } +- +- let newTableIndex = tables.count +- tables.append(InternalTOMLTable()) +- keyArrays[arrayIndex].array.elements.append(.table(lineNumber: token.lineNumber, newTableIndex)) +- currentTable = newTableIndex +- currentTableIsKeyed = false +- } +- } +- +- if token.kind != .rbracket { +- throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "expects ]")) +- } +- +- if llb { +- guard cursor < bytes.count, bytes[cursor] == CodeUnits.rbracket else { +- throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "expects ]]")) +- } +- cursor += 1 +- try nextToken(bytes: bytes, isDotSpecial: true) +- } else { +- try eatToken(bytes: bytes, kind: .rbracket, isDotSpecial: true) +- } +- +- if token.kind != .newline, token.kind != .eof { +- throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "extra chars after ] or ]]")) +- } +- } +-} +- +-extension Token { +- func unpackBool(bytes: UnsafeBufferPointer, context: TOMLKey) throws(TOMLError) -> Bool { +- if text.count == 4, +- bytes[text.lowerBound] == CodeUnits.lowerT, +- bytes[text.lowerBound + 1] == CodeUnits.lowerR, +- bytes[text.lowerBound + 2] == CodeUnits.lowerU, +- bytes[text.lowerBound + 3] == CodeUnits.lowerE +- { +- return true +- } else if text.count == 5, +- bytes[text.lowerBound] == CodeUnits.lowerF, +- bytes[text.lowerBound + 1] == CodeUnits.lowerA, +- bytes[text.lowerBound + 2] == CodeUnits.lowerL, +- bytes[text.lowerBound + 3] == CodeUnits.lowerS, +- bytes[text.lowerBound + 4] == CodeUnits.lowerE +- { +- return false +- } +- +- throw TOMLError(.invalidBool(context: context, lineNumber: lineNumber)) +- } +- +- func unpackFloat(bytes: UnsafeBufferPointer, context: TOMLKey) throws(TOMLError) -> Double { +- var resultCodeUnits: [UTF8.CodeUnit] = [] +- var index = text.lowerBound +- if bytes[index] == CodeUnits.plus || bytes[index] == CodeUnits.minus { +- resultCodeUnits.append(bytes[index]) +- index += 1 +- } +- guard index < text.upperBound else { +- throw TOMLError(.invalidFloat(context: context, lineNumber: lineNumber, reason: "expected digit, nan or inf after sign")) +- } +- +- if !bytes[index].isDecimalDigit { +- let nameEnd = index + 3 +- guard nameEnd == text.upperBound, +- ( +- bytes[index] == CodeUnits.lowerN && +- bytes[index + 1] == CodeUnits.lowerA && +- bytes[index + 2] == CodeUnits.lowerN +- ) || +- ( +- bytes[index] == CodeUnits.lowerI && +- bytes[index + 1] == CodeUnits.lowerN && +- bytes[index + 2] == CodeUnits.lowerF +- ) +- else { +- throw TOMLError(.invalidFloat(context: context, lineNumber: lineNumber, reason: "Expected nan or inf, found \(bytes[index])")) +- } +- resultCodeUnits.append(bytes[index]) +- resultCodeUnits.append(bytes[index + 1]) +- resultCodeUnits.append(bytes[index + 2]) +- } else { +- let nextIndex = index + 1 +- if bytes[index] == CodeUnits.number0, +- nextIndex < text.upperBound, +- case let next = bytes[nextIndex], +- next != CodeUnits.dot, next != CodeUnits.lowerE, next != CodeUnits.upperE +- { +- throw TOMLError(.invalidFloat(context: context, lineNumber: lineNumber, reason: "Float begins with 0 must be followed by a '.', 'e' or 'E'")) +- } +- +- while index < text.upperBound { +- let ch = bytes[index] +- index += 1 +- +- if ch == CodeUnits.underscore { +- guard +- let last = resultCodeUnits.last, +- last.isDecimalDigit +- else { +- throw TOMLError(.invalidFloat(context: context, lineNumber: lineNumber, reason: "'_' must be preceded by a digit")) +- } +- +- guard +- index < text.upperBound, +- case let next = bytes[index], +- next.isDecimalDigit +- else { +- throw TOMLError(.invalidFloat(context: context, lineNumber: lineNumber, reason: "'_' must be follewed by a digit")) +- } +- +- continue +- } else if ch == CodeUnits.dot { +- if resultCodeUnits.isEmpty { +- throw TOMLError(.invalidFloat(context: context, lineNumber: lineNumber, reason: "First digit of floats cannot be '.'")) +- } +- +- if !resultCodeUnits.last!.isDecimalDigit { +- throw TOMLError(.invalidFloat(context: context, lineNumber: lineNumber, reason: "'.' must be preceded by a decimal digit")) +- } +- +- guard index < text.upperBound, bytes[index].isDecimalDigit else { +- throw TOMLError(.invalidFloat(context: context, lineNumber: lineNumber, reason: "A digit must follow '.'")) +- } +- +- } else if ch == CodeUnits.upperE || ch == CodeUnits.lowerE { +- } else if !ch.isDecimalDigit, ch != CodeUnits.plus, ch != CodeUnits.minus { +- throw TOMLError(.invalidFloat(context: context, lineNumber: lineNumber, reason: "invalid character for float")) +- } +- +- resultCodeUnits.append(ch) +- } +- } +- +- guard let double = Double(String(decoding: resultCodeUnits, as: UTF8.self)) else { +- throw TOMLError(.invalidFloat(context: context, lineNumber: lineNumber, reason: "not a float")) +- } +- +- return double +- } +- +- func unpackString(bytes: UnsafeBufferPointer, context: TOMLKey) throws(TOMLError) -> String { +- var multiline = false +- +- if bytes.count == 0 { +- throw TOMLError(.invalidString(context: context, lineNumber: lineNumber, reason: "missing closing quote")) +- } +- +- let quoteChar = bytes[text.lowerBound] +- if quoteChar != CodeUnits.doubleQuote, quoteChar != CodeUnits.singleQuote { +- throw TOMLError(.typeMismatch(context: context, lineNumber: lineNumber, expected: "string")) +- } +- var index = text.lowerBound +- var endIndex = text.upperBound +- +- if endIndex - index >= 3 && bytes[index] == CodeUnits.doubleQuote && bytes[index + 1] == CodeUnits.doubleQuote && bytes[index + 2] == CodeUnits.doubleQuote || +- endIndex - index >= 3 && bytes[index] == CodeUnits.singleQuote && bytes[index + 1] == CodeUnits.singleQuote && bytes[index + 2] == CodeUnits.singleQuote +- { +- multiline = true +- index += 3 +- endIndex -= 3 +- +- if index < endIndex, bytes[index] == CodeUnits.lf { +- index += 1 +- } else if endIndex - index >= 2, bytes[index] == CodeUnits.cr, bytes[index + 1] == CodeUnits.lf { +- index += 2 +- } +- } else { +- index = index + 1 +- endIndex = endIndex - 1 +- guard endIndex >= 0, bytes[endIndex] == quoteChar else { +- throw TOMLError(.invalidString(context: context, lineNumber: lineNumber, reason: "missing closing quote")) +- } +- } +- +- if quoteChar == CodeUnits.singleQuote { +- return try literalString(bytes: bytes, range: index ..< endIndex, multiline: multiline) +- } else { +- return try basicString(bytes: bytes, range: index ..< endIndex, multiline: multiline) +- } +- } +- +- func unpackInteger(bytes: UnsafeBufferPointer, context: TOMLKey) throws(TOMLError) -> Int64 { +- @_transparent +- func isValidDigit(_ codeUnit: UTF8.CodeUnit, base: Int) -> Bool { +- switch base { +- case 10: +- codeUnit.isDecimalDigit +- case 16: +- codeUnit.isHexDigit +- case 2: +- codeUnit == CodeUnits.number0 || codeUnit == CodeUnits.number1 +- case 8: +- CodeUnits.number0 <= codeUnit && codeUnit <= CodeUnits.number7 +- default: +- false +- } +- } +- +- var resultCodeUnits: [UTF8.CodeUnit] = [] +- var index = text.lowerBound +- var base = 10 +- var hasSign = false +- if bytes[index] == CodeUnits.plus || bytes[index] == CodeUnits.minus { +- hasSign = true +- resultCodeUnits.append(bytes[index]) +- index = text.index(after: index) +- } +- guard index < text.upperBound else { +- throw TOMLError(.invalidInteger(context: context, lineNumber: lineNumber, reason: "expected digit after sign")) +- } +- +- if bytes[index] == CodeUnits.underscore { +- throw TOMLError(.invalidInteger(context: context, lineNumber: lineNumber, reason: "cannot start with a '_'")) +- } +- +- if bytes[index] == CodeUnits.number0 { +- let nextIndex = index + 1 +- if nextIndex < text.upperBound { +- if bytes[nextIndex] == CodeUnits.lowerX { +- if hasSign { +- throw TOMLError(.invalidInteger(context: context, lineNumber: lineNumber, reason: "hexadecimal integers cannot have explicit signs")) +- } +- base = 16 +- index += 2 +- } else if bytes[nextIndex] == CodeUnits.lowerO { +- if hasSign { +- throw TOMLError(.invalidInteger(context: context, lineNumber: lineNumber, reason: "octal integers cannot have explicit signs")) +- } +- base = 8 +- index += 2 +- } else if bytes[nextIndex] == CodeUnits.lowerB { +- if hasSign { +- throw TOMLError(.invalidInteger(context: context, lineNumber: lineNumber, reason: "binary integers cannot have explicit signs")) +- } +- base = 2 +- index += 2 +- } else if bytes[nextIndex].isDecimalDigit || bytes[nextIndex] == CodeUnits.underscore { +- throw TOMLError(.invalidInteger(context: context, lineNumber: lineNumber, reason: "decimal integers cannot have leading zeros")) +- } +- } +- // Single zero is allowed to continue to the main loop +- } +- guard index < text.upperBound else { +- throw TOMLError(.invalidInteger(context: context, lineNumber: lineNumber, reason: "expected digit after base prefix")) +- } +- +- while index < text.upperBound { +- let ch = bytes[index] +- index += 1 +- +- if ch == CodeUnits.underscore { +- guard +- let last = resultCodeUnits.last, +- isValidDigit(last, base: base) +- else { +- throw TOMLError(.invalidInteger(context: context, lineNumber: lineNumber, reason: "cannot use '_' adjacent to a non-digit")) +- } +- +- if index >= text.endIndex { +- throw TOMLError(.invalidInteger(context: context, lineNumber: lineNumber, reason: "cannot end with a '_'")) +- } +- +- let next = bytes[index] +- if next == CodeUnits.underscore { +- throw TOMLError(.invalidInteger(context: context, lineNumber: lineNumber, reason: "cannot contain consecutive '_'")) +- } +- guard isValidDigit(next, base: base) else { +- throw TOMLError(.invalidInteger(context: context, lineNumber: lineNumber, reason: "cannot use '_' adjacent to a non-digit")) +- } +- continue +- } +- +- guard isValidDigit(ch, base: base) else { +- throw TOMLError(.invalidInteger(context: context, lineNumber: lineNumber, reason: "invalid digit for base \(base)")) +- } +- +- resultCodeUnits.append(ch) +- } +- +- let s = String(decoding: resultCodeUnits, as: UTF8.self) +- guard let i = Int64(s, radix: base) else { +- throw TOMLError(.invalidInteger(context: context, lineNumber: lineNumber, reason: "\(s) is a invalid integer of base \(base)")) +- } +- return i +- } +- +- func unpackDateTime(bytes: UnsafeBufferPointer, context: TOMLKey) throws(TOMLError) -> DateTimeComponents { +- var mustParseTime = false +- var date: (year: Int, month: Int, day: Int)? +- var time: (hour: Int, minute: Int, second: Int)? +- +- var index = text.lowerBound +- if let (year, month, day, _) = scanDate(bytes: bytes, range: text) { +- // Validate date components +- if month < 1 || month > 12 { +- throw TOMLError(.invalidDateTime3(context: context, lineNumber: lineNumber, reason: "month must be between 01 and 12")) +- } +- if day < 1 { +- throw TOMLError(.invalidDateTime3(context: context, lineNumber: lineNumber, reason: "day must be between 01 and 31")) +- } +- +- // Validate days per month and leap years +- let isLeapYear = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) +- let maxDaysInMonth: Int = switch month { +- case 2: +- isLeapYear ? 29 : 28 +- case 4, 6, 9, 11: +- 30 +- default: +- 31 +- } +- +- if day > maxDaysInMonth { +- if month == 2, !isLeapYear { +- throw TOMLError(.invalidDateTime3(context: context, lineNumber: lineNumber, reason: "February only has 28 days in non-leap years")) +- } else if month == 2, isLeapYear { +- throw TOMLError(.invalidDateTime3(context: context, lineNumber: lineNumber, reason: "February only has 29 days in leap years")) +- } else { +- throw TOMLError(.invalidDateTime3(context: context, lineNumber: lineNumber, reason: "day \(day) is invalid for month \(month)")) +- } +- } +- +- date = (year, month, day) +- index += 10 +- } +- +- var features: OffsetDateTime.Features = [] +- var nanoseconds: UInt32? +- if index < text.upperBound { +- if date != nil { +- let isSeparatorLowerT = bytes[index] == CodeUnits.lowerT +- let isSeparatorUpperT = bytes[index] == CodeUnits.upperT +- guard isSeparatorLowerT || isSeparatorUpperT || bytes[index] == CodeUnits.space else { +- throw TOMLError(.invalidDateTime3(context: context, lineNumber: lineNumber, reason: "expected 'T' or 't' or space to separate date and time")) +- } +- if isSeparatorLowerT { +- features.insert(.lowercaseT) +- } else if isSeparatorUpperT { +- features.insert(.uppercaseT) +- } +- mustParseTime = true +- index += 1 +- } else { +- // For standalone time values, don't advance index +- mustParseTime = true +- } +- if let (hour, minute, second, newIndex) = scanTime(bytes: bytes, range: index ..< text.upperBound) { +- // Validate time components +- if hour > 23 { +- throw TOMLError(.invalidDateTime3(context: context, lineNumber: lineNumber, reason: "hour must be between 00 and 23")) +- } +- if minute > 59 { +- throw TOMLError(.invalidDateTime3(context: context, lineNumber: lineNumber, reason: "minute must be between 00 and 59")) +- } +- if second > 59 { +- throw TOMLError(.invalidDateTime3(context: context, lineNumber: lineNumber, reason: "second must be between 00 and 59")) +- } +- +- time = (hour, minute, second) +- +- index = newIndex +- if index < text.upperBound, bytes[index] == CodeUnits.dot { +- index += 1 +- let beforeNanoIndex = index +- nanoseconds = parseNanoSeconds(bytes: bytes, range: index ..< text.upperBound, updatedIndex: &index) +- // Must have at least one digit after decimal point +- if index == beforeNanoIndex { +- throw TOMLError(.invalidDateTime3(context: context, lineNumber: lineNumber, reason: "decimal point must be followed by digits")) +- } +- } +- } +- } +- +- if mustParseTime, time == nil { +- throw TOMLError(.invalidDateTime3(context: context, lineNumber: lineNumber, reason: "expected valid time")) +- } +- +- var timeOffset: Int16? +- if index < text.upperBound { +- if bytes[index] == CodeUnits.lowerZ { +- features.insert(.lowercaseZ) +- index += 1 +- timeOffset = 0 +- } else if bytes[index] == CodeUnits.upperZ { +- features.insert(.uppercaseZ) +- index += 1 +- timeOffset = 0 +- } else if bytes[index] == CodeUnits.plus || bytes[index] == CodeUnits.minus { +- let offsetIsNegative = bytes[index] == CodeUnits.minus +- index += 1 +- +- // Scan ahead to find the end of the timezone offset +- var endIndex = index +- while endIndex < text.upperBound { +- let ch = bytes[endIndex] +- if ch.isDecimalDigit || ch == CodeUnits.colon { +- endIndex += 1 +- } else { +- break +- } +- } +- +- do { +- let (offsetHour, offsetMinute, consumedLength) = try parseTimezoneOffset(bytes: bytes, range: index ..< endIndex, lineNumber: lineNumber) +- +- // Validate timezone offset ranges +- if offsetHour > 24 { +- throw TOMLError(.invalidDateTime3(context: context, lineNumber: lineNumber, reason: "timezone offset hour must be between 00 and 24")) +- } +- if offsetMinute > 59 { +- throw TOMLError(.invalidDateTime3(context: context, lineNumber: lineNumber, reason: "timezone offset minute must be between 00 and 59")) +- } +- +- let offsetInMinutes = offsetHour * 60 + offsetMinute +- timeOffset = Int16(offsetIsNegative ? -offsetInMinutes : offsetInMinutes) +- index += consumedLength +- } catch let parseError { +- if let tomlError = parseError as? TOMLError { +- switch tomlError.reason { +- case let .invalidDateTime(_, reason): +- throw TOMLError(.invalidDateTime3(context: context, lineNumber: lineNumber, reason: reason)) +- default: +- throw tomlError +- } +- } else { +- throw TOMLError(.invalidDateTime3(context: context, lineNumber: lineNumber, reason: "timezone parsing error")) +- } +- } +- } +- } +- +- if index < text.upperBound { +- throw TOMLError(.invalidDateTime3(context: context, lineNumber: lineNumber, reason: "extra character after date time")) +- } +- +- return DateTimeComponents( +- date: date.map { LocalDate(year: .init($0.year), month: .init($0.month), day: .init($0.day)) }, +- time: time.map { LocalTime(hour: .init($0.hour), minute: .init($0.minute), second: .init($0.second), nanosecond: nanoseconds ?? 0) }, +- offset: timeOffset, +- features: features ++ break ++ } ++ } ++ return index ++ } ++ ++ if multiline { ++ let afterWhitespace = try indexAfterSkippingCharacters( ++ start: index, endIndex: endIndex, ++ characters: [CodeUnits.space, CodeUnits.tab, CodeUnits.cr] ++ ) ++ if afterWhitespace < endIndex, bytes[afterWhitespace] == CodeUnits.lf { ++ index = try indexAfterSkippingCharacters( ++ start: index, endIndex: endIndex, ++ characters: [CodeUnits.space, CodeUnits.tab, CodeUnits.cr, CodeUnits.lf] +@@ -1551,69 +1999,5 @@ +- } +- +- func unpackAnyValue(bytes: UnsafeBufferPointer, context: TOMLKey) throws(TOMLError) -> Any { +- let firstChar = text.count > 0 ? bytes[text.lowerBound] : nil +- if firstChar == CodeUnits.singleQuote || firstChar == CodeUnits.doubleQuote { +- return try unpackString(bytes: bytes, context: context) +- } +- +- if let boolValue = try? unpackBool(bytes: bytes, context: context) { +- return boolValue +- } +- +- if let intValue = try? unpackInteger(bytes: bytes, context: context) { +- return intValue +- } +- +- if let floatValue = try? unpackFloat(bytes: bytes, context: context) { +- return floatValue +- } +- +- guard firstChar?.isDecimalDigit == true else { +- throw TOMLError(.invalidValueInTable(context: context, lineNumber: lineNumber)) +- } +- +- let datetime = try unpackDateTime(bytes: bytes, context: context) +- switch (datetime.date, datetime.time, datetime.offset) { +- case let (.some(date), .some(time), .some(offset)): +- return OffsetDateTime(date: date, time: time, offset: offset, features: datetime.features) +- case let (.some(date), .some(time), .none): +- return LocalDateTime(date: date, time: time) +- case let (.some(date), .none, .none): +- return date +- case let (.none, .some(time), .none): +- return time +- default: +- throw TOMLError(.invalidValueInTable(context: context, lineNumber: lineNumber)) +- } +- } +-} +- +-func parseTimezoneOffset(bytes: UnsafeBufferPointer, range: Range, lineNumber: Int) throws(TOMLError) -> (hour: Int, minute: Int, consumedLength: Int) { +- guard range.count >= 2 else { +- throw TOMLError(.invalidDateTime(lineNumber: lineNumber, reason: "timezone offset must have at least 2 digits for hour")) +- } +- +- var index = range.lowerBound +- +- // Parse hour digits (exactly 2 required) +- guard +- index < range.upperBound, +- bytes[index].isDecimalDigit, +- case let firstHourDigit = bytes[index], +- case let nextIndex = index + 1, +- nextIndex < range.upperBound, +- bytes[nextIndex].isDecimalDigit, +- case let secondHourDigit = bytes[nextIndex] +- else { +- throw TOMLError(.invalidDateTime(lineNumber: lineNumber, reason: "timezone offset hour must be exactly 2 digits")) +- } +- +- let offsetHour = Int(firstHourDigit - CodeUnits.number0) * 10 + Int(secondHourDigit - CodeUnits.number0) +- index += 2 +- var consumedLength = 2 +- +- // Parse required minute digits (timezone offset must include minutes) +- guard index < range.upperBound, bytes[index] == CodeUnits.colon else { +- throw TOMLError(.invalidDateTime(lineNumber: lineNumber, reason: "timezone offset must include minutes (format: ±HH:MM)")) +- } +- ++ continue ++ } ++ } ++ ++ ch = bytes[index] +@@ -1621,64 +2005,12 @@ +- consumedLength += 1 +- +- guard +- index < range.upperBound, +- bytes[index].isDecimalDigit, +- case let firstMinuteDigit = bytes[index], +- case let nextMinuteIndex = index + 1, +- nextMinuteIndex < range.upperBound, +- bytes[nextMinuteIndex].isDecimalDigit, +- case let secondMinuteDigit = bytes[nextMinuteIndex] +- else { +- throw TOMLError(.invalidDateTime(lineNumber: lineNumber, reason: "timezone offset minute must be exactly 2 digits")) +- } +- +- let offsetMinute = Int(firstMinuteDigit - CodeUnits.number0) * 10 + Int(secondMinuteDigit - CodeUnits.number0) +- consumedLength += 2 +- +- return (offsetHour, offsetMinute, consumedLength) +-} +- +-func literalString(bytes: UnsafeBufferPointer, range: Range, multiline: Bool) throws(TOMLError) -> String { +- var resultCodeUnits: [UTF8.CodeUnit] = [] +- var consecutiveQuotes = 0 +- +- for index in range { +- let codeUnit = bytes[index] +- if codeUnit >= CodeUnits.null && codeUnit <= CodeUnits.backspace || codeUnit >= CodeUnits.lf && codeUnit <= CodeUnits.unitSeparator || codeUnit == CodeUnits.delete { +- if multiline, codeUnit == CodeUnits.lf { +- // Allow LF in multiline literal strings +- } else if multiline, codeUnit == CodeUnits.cr { +- // Only allow CR if followed by LF (CRLF sequence) +- let nextIndex = index + 1 +- if nextIndex < range.upperBound, bytes[nextIndex] == CodeUnits.lf { +- // Allow CRLF sequence - will be processed as separate characters +- } else { +- throw TOMLError(.invalidCharacter(codeUnit)) +- } +- } else { +- throw TOMLError(.invalidCharacter(codeUnit)) +- } +- } +- +- if multiline, codeUnit == CodeUnits.singleQuote { +- consecutiveQuotes += 1 +- if consecutiveQuotes > 2 { +- throw TOMLError(.syntax(lineNumber: 0, message: "literal multiline strings cannot contain more than 2 consecutive single quotes")) +- } +- } else { +- consecutiveQuotes = 0 +- } +- +- resultCodeUnits.append(codeUnit) +- } +- return String(decoding: resultCodeUnits, as: UTF8.self) +-} +- +-func basicString(bytes: UnsafeBufferPointer, range: Range, multiline: Bool) throws(TOMLError) -> String { +- let startIndex = range.lowerBound +- let endIndex = range.upperBound +- var resultCodeUnits: [UTF8.CodeUnit] = [] +- resultCodeUnits.reserveCapacity(range.count) +- var consecutiveQuotes = 0 +- var index = startIndex +- while true { ++ ++ if ch == CodeUnits.lowerU || ch == CodeUnits.upperU || ch == CodeUnits.lowerX { ++ let hexCount = ++ switch ch { ++ case CodeUnits.lowerU: 4 ++ case CodeUnits.upperU: 8 ++ case CodeUnits.lowerX: 2 ++ default: fatalError("Unsupported CodeUnit: \(ch)") ++ } ++ var ucs: UInt32 = 0 ++ for _ in 0..= CodeUnits.null && ch <= CodeUnits.backspace +- || ch >= CodeUnits.lf && ch <= CodeUnits.unitSeparator || ch == CodeUnits.delete +- { +- if multiline, ch == CodeUnits.lf { +- // Allow LF in multiline basic strings +- } else if multiline, ch == CodeUnits.cr { +- // Only allow CR if followed by LF (CRLF sequence) +- if index < endIndex, bytes[index] == CodeUnits.lf { +- // Allow CRLF sequence - will be processed as separate characters +- } else { +- throw TOMLError(.invalidCharacter(ch)) +- } +- } else { +- throw TOMLError(.invalidCharacter(ch)) +- } +- } +- +- if multiline, ch == CodeUnits.doubleQuote { +- consecutiveQuotes += 1 +- if consecutiveQuotes > 2 { +- throw TOMLError( +- .syntax( +- lineNumber: 0, +- message: +- "basic multiline strings cannot contain more than 2 consecutive double quotes" +- ) +- ) +- } +- } else { +- consecutiveQuotes = 0 +- } +- +- resultCodeUnits.append(ch) +- continue +- } +- +- if index >= endIndex { +- throw TOMLError(.invalidCharacter(CodeUnits.backslash)) +- } +- +- func indexAfterSkippingCharacters(start: Int, endIndex: Int, characters: [UTF8.CodeUnit]) +- -> Int +- { +- var index = start +- while index < endIndex { +- if characters.contains(bytes[index]) { +- index += 1 +- } else { +- break +- } +- } +- return index +- } +- +- if multiline { +- let afterWhitespace = indexAfterSkippingCharacters( +- start: index, endIndex: endIndex, +- characters: [CodeUnits.space, CodeUnits.tab, CodeUnits.cr] +- ) +- if afterWhitespace < endIndex, bytes[afterWhitespace] == CodeUnits.lf { +- index = indexAfterSkippingCharacters( +- start: index, endIndex: endIndex, +- characters: [CodeUnits.space, CodeUnits.tab, CodeUnits.cr, CodeUnits.lf] +- ) +- continue +- } +- } +- ++ throw TOMLError(.expectedHexCharacters(ch, hexCount)) ++ } +@@ -1762,53 +2022,40 @@ +- +- if ch == CodeUnits.lowerU || ch == CodeUnits.upperU || ch == CodeUnits.lowerX { +- let hexCount = switch ch { +- case CodeUnits.lowerU: 4 +- case CodeUnits.upperU: 8 +- case CodeUnits.lowerX: 2 +- default: fatalError("Unsupported CodeUnit: \(ch)") +- } +- var ucs: UInt32 = 0 +- for _ in 0 ..< hexCount { +- if index >= endIndex { +- throw TOMLError(.expectedHexCharacters(ch, hexCount)) +- } +- ch = bytes[index] +- index += 1 +- let v: Int32 = +- ch.isDecimalDigit +- ? Int32(ch - CodeUnits.number0) +- : (ch >= CodeUnits.upperA && ch <= CodeUnits.upperF) +- ? Int32(ch - CodeUnits.upperA + 10) +- : (ch >= CodeUnits.lowerA && ch <= CodeUnits.lowerF) +- ? Int32(ch - CodeUnits.lowerA + 10) +- : -1 +- if v == -1 { +- throw TOMLError(.invalidHexCharacters(ch)) +- } +- ucs = ucs * 16 + UInt32(v) +- } +- guard let scalar = Unicode.Scalar(ucs) else { +- throw TOMLError(.illegalUCSCode(ucs)) +- } +- resultCodeUnits.append(contentsOf: scalar.utf8) +- continue +- } else if ch == CodeUnits.lowerB { +- ch = CodeUnits.backspace +- } else if ch == CodeUnits.lowerT { +- ch = CodeUnits.tab +- } else if ch == CodeUnits.lowerF { +- ch = CodeUnits.formfeed +- } else if ch == CodeUnits.lowerR { +- ch = CodeUnits.cr +- } else if ch == CodeUnits.lowerN { +- ch = CodeUnits.lf +- } else if ch == CodeUnits.lowerE { +- ch = CodeUnits.escape +- } else if ch != CodeUnits.doubleQuote, ch != CodeUnits.backslash { +- throw TOMLError(.illegalEscapeCharacter(ch)) +- } +- +- consecutiveQuotes = 0 // Reset count after escape sequence +- resultCodeUnits.append(ch) +- } +- return String(decoding: resultCodeUnits, as: UTF8.self) ++ let v: Int32 = ++ ch.isDecimalDigit ++ ? Int32(ch - CodeUnits.number0) ++ : (ch >= CodeUnits.upperA && ch <= CodeUnits.upperF) ++ ? Int32(ch - CodeUnits.upperA + 10) ++ : (ch >= CodeUnits.lowerA && ch <= CodeUnits.lowerF) ++ ? Int32(ch - CodeUnits.lowerA + 10) ++ : -1 ++ if v == -1 { ++ throw TOMLError(.invalidHexCharacters(ch)) ++ } ++ ucs = ucs * 16 + UInt32(v) ++ } ++ guard let scalar = Unicode.Scalar(ucs) else { ++ throw TOMLError(.illegalUCSCode(ucs)) ++ } ++ try budget.allocate(1, stage: "decoded scalar storage") ++ resultCodeUnits.append(contentsOf: scalar.utf8) ++ continue ++ } else if ch == CodeUnits.lowerB { ++ ch = CodeUnits.backspace ++ } else if ch == CodeUnits.lowerT { ++ ch = CodeUnits.tab ++ } else if ch == CodeUnits.lowerF { ++ ch = CodeUnits.formfeed ++ } else if ch == CodeUnits.lowerR { ++ ch = CodeUnits.cr ++ } else if ch == CodeUnits.lowerN { ++ ch = CodeUnits.lf ++ } else if ch == CodeUnits.lowerE { ++ ch = CodeUnits.escape ++ } else if ch != CodeUnits.doubleQuote, ch != CodeUnits.backslash { ++ throw TOMLError(.illegalEscapeCharacter(ch)) ++ } ++ ++ consecutiveQuotes = 0 // Reset count after escape sequence ++ try budget.allocate(1, stage: "decoded scalar storage") ++ resultCodeUnits.append(ch) ++ } ++ return String(decoding: resultCodeUnits, as: UTF8.self) +@@ -1818,11 +2065,36 @@ +- guard let year = scanDigits(bytes: bytes, range: range, n: 4) else { +- return nil +- } +- +- var index = range.lowerBound +- index += 4 +- +- guard index < range.upperBound, bytes[index] == CodeUnits.minus else { +- return nil +- } +- ++ guard let year = scanDigits(bytes: bytes, range: range, n: 4) else { ++ return nil ++ } ++ ++ var index = range.lowerBound ++ index += 4 ++ ++ guard index < range.upperBound, bytes[index] == CodeUnits.minus else { ++ return nil ++ } ++ ++ index += 1 ++ guard let month = scanDigits(bytes: bytes, range: index.., range: Range, n: Int) -> Int? { ++ var result = 0 ++ var n = n ++ var index = range.lowerBound ++ while n > 0, index < range.upperBound, bytes[index].isDecimalDigit { ++ result = 10 * result + Int(bytes[index]) - Int(CodeUnits.number0) +@@ -1830,9 +2102,47 @@ +- guard let month = scanDigits(bytes: bytes, range: index ..< range.upperBound, n: 2) else { +- return nil +- } +- +- index += 2 +- guard bytes[index] == CodeUnits.minus else { +- return nil +- } +- ++ n -= 1 ++ } ++ return n != 0 ? nil : result ++} ++ ++func scanTime(bytes: UnsafeBufferPointer, range: Range) -> (Int, Int, Int, Int)? { ++ guard let hour = scanDigits(bytes: bytes, range: range, n: 2) else { ++ return nil ++ } ++ ++ var index = range.lowerBound ++ ++ index += 2 ++ guard index < range.upperBound, bytes[index] == CodeUnits.colon else { ++ return nil ++ } ++ ++ index += 1 ++ guard let minute = scanDigits(bytes: bytes, range: index.., range: Range, ++ updatedIndex: inout Int ++) throws -> UInt32 { ++ var unit: Double = 100_000_000 ++ var result: Double = 0 ++ var index = range.lowerBound ++ while index < range.upperBound, bytes[index].isDecimalDigit { ++ try budget.step() ++ result += Double(bytes[index] - CodeUnits.number0) * unit +@@ -1840,6 +2150,4 @@ +- guard let day = scanDigits(bytes: bytes, range: index ..< range.upperBound, n: 2) else { +- return nil +- } +- +- index += 2 +- return (year, month, day, index) ++ unit /= 10 ++ } ++ updatedIndex = index ++ return UInt32(result) +@@ -1848,56 +2155,0 @@ +-func scanDigits(bytes: UnsafeBufferPointer, range: Range, n: Int) -> Int? { +- var result = 0 +- var n = n +- var index = range.lowerBound +- while n > 0, index < range.upperBound, bytes[index].isDecimalDigit { +- result = 10 * result + Int(bytes[index]) - Int(CodeUnits.number0) +- index += 1 +- n -= 1 +- } +- return n != 0 ? nil : result +-} +- +-func scanTime(bytes: UnsafeBufferPointer, range: Range) -> (Int, Int, Int, Int)? { +- guard let hour = scanDigits(bytes: bytes, range: range, n: 2) else { +- return nil +- } +- +- var index = range.lowerBound +- +- index += 2 +- guard index < range.upperBound, bytes[index] == CodeUnits.colon else { +- return nil +- } +- +- index += 1 +- guard let minute = scanDigits(bytes: bytes, range: index ..< range.upperBound, n: 2) else { +- return nil +- } +- +- index += 2 +- guard index < range.upperBound, bytes[index] == CodeUnits.colon else { +- return (hour, minute, 0, index) // Seconds are optional since 1.1.0. When omitted, :00 seconds is assumed +- } +- +- index += 1 +- guard let second = scanDigits(bytes: bytes, range: index ..< range.upperBound, n: 2) else { +- return nil +- } +- +- index += 2 +- return (hour, minute, second, index) +-} +- +-func parseNanoSeconds(bytes: UnsafeBufferPointer, range: Range, updatedIndex: inout Int) -> UInt32 { +- var unit: Double = 100_000_000 +- var result: Double = 0 +- var index = range.lowerBound +- while index < range.upperBound, bytes[index].isDecimalDigit { +- result += Double(bytes[index] - CodeUnits.number0) * unit +- index += 1 +- unit /= 10 +- } +- updatedIndex = index +- return UInt32(result) +-} +- +@@ -1905,21 +2157,22 @@ +- var index = range.lowerBound +- guard index < range.upperBound, bytes[index] == CodeUnits.plus || bytes[index] == CodeUnits.minus else { +- return nil +- } +- +- index += 1 +- guard let _ = scanDigits(bytes: bytes, range: index ..< range.upperBound, n: 2) else { +- return nil +- } +- +- index += 2 +- guard index < range.upperBound, bytes[index] == CodeUnits.colon else { +- return nil +- } +- +- index += 1 +- guard let _ = scanDigits(bytes: bytes, range: index ..< range.upperBound, n: 2) else { +- return nil +- } +- index += 2 +- return index ++ var index = range.lowerBound ++ guard index < range.upperBound, bytes[index] == CodeUnits.plus || bytes[index] == CodeUnits.minus ++ else { ++ return nil ++ } ++ ++ index += 1 ++ guard scanDigits(bytes: bytes, range: index.. Bool { +- let xor = chunk ^ bytePattern +- return ((xor &- ones) & ~xor & highBits) != 0 +- } +- +- return hasByte(0x2222_2222_2222_2222) +- || hasByte(0x5C5C_5C5C_5C5C_5C5C) +- || hasByte(0x0A0A_0A0A_0A0A_0A0A) ++ let ones: UInt64 = 0x0101_0101_0101_0101 ++ let highBits: UInt64 = 0x8080_8080_8080_8080 ++ ++ @inline(__always) ++ func hasByte(_ bytePattern: UInt64) -> Bool { ++ let xor = chunk ^ bytePattern ++ return ((xor &- ones) & ~xor & highBits) != 0 ++ } ++ ++ return hasByte(0x2222_2222_2222_2222) ++ || hasByte(0x5C5C_5C5C_5C5C_5C5C) ++ || hasByte(0x0A0A_0A0A_0A0A_0A0A) +@@ -1944,52 +2197,48 @@ +-func normalizeKeyAndHash(bytes: UnsafeBufferPointer, token: Token, keyTransform: (@Sendable (String) -> String)?) throws(TOMLError) -> (key: String, keyHash: Int) { +- var start = token.text.lowerBound +- var end = token.text.upperBound +- if token.kind == .bareKey { +- var str = makeString(bytes: bytes, range: start ..< end) +- if let keyTransform { +- str = keyTransform(str) +- return (str, fastKeyHash(str)) +- } +- return (str, fastKeyHash(bytes: bytes, range: start ..< end)) +- } +- +- let ch = bytes[start] +- var result = "" +- if ch == CodeUnits.doubleQuote || ch == CodeUnits.singleQuote { +- if bytes[start + 1] == ch, bytes[start + 2] == ch { +- // Keys cannot be multiline +- throw TOMLError(.badKey(lineNumber: token.lineNumber)) +- } else { +- start = start + 1 +- end = end - 1 +- } +- +- if ch == CodeUnits.singleQuote { +- result = makeString(bytes: bytes, range: start ..< end) +- return (result, fastKeyHash(bytes: bytes, range: start ..< end)) +- } else { +- result = try basicString(bytes: bytes, range: start ..< end, multiline: false) +- return (result, fastKeyHash(result)) +- } +- } +- +- for i in start ..< end { +- let byte = bytes[i] +- if byte >= CodeUnits.number0 && byte <= CodeUnits.number9 || // 0-9 +- byte >= CodeUnits.upperA && byte <= CodeUnits.upperZ || // A-Z +- byte >= CodeUnits.lowerA && byte <= CodeUnits.lowerZ || // a-z +- byte == CodeUnits.underscore || // _ +- byte == CodeUnits.minus // - +- { +- continue +- } +- throw TOMLError(.badKey(lineNumber: token.lineNumber)) +- } +- +- if let keyTransform { +- let key = keyTransform(makeString(bytes: bytes, range: start ..< end)) +- return (key, fastKeyHash(key)) +- } +- +- let key = makeString(bytes: bytes, range: start ..< end) +- return (key, fastKeyHash(bytes: bytes, range: start ..< end)) ++func normalizeKeyAndHash(bytes: UnsafeBufferPointer, token: Token) throws -> ( ++ key: String, keyHash: Int ++) { ++ let budget = token.budget! ++ try budget.allocate(token.text.count, stage: "decoded key") ++ var start = token.text.lowerBound ++ var end = token.text.upperBound ++ if token.kind == .bareKey { ++ let str = try makeString(budget: budget, bytes: bytes, range: start..= CodeUnits.number0 && byte <= CodeUnits.number9 // 0-9 ++ || byte >= CodeUnits.upperA && byte <= CodeUnits.upperZ // A-Z ++ || byte >= CodeUnits.lowerA && byte <= CodeUnits.lowerZ // a-z ++ || byte == CodeUnits.underscore // _ ++ || byte == CodeUnits.minus // - ++ { ++ continue ++ } ++ throw TOMLError(.badKey(lineNumber: token.lineNumber)) ++ } ++ ++ let key = try makeString(budget: budget, bytes: bytes, range: start.. UInt64 in +- if buffer.count <= 8 { +- return packedKeyHash(buffer) +- } +- if let start = buffer.baseAddress { +- return sampledKeyHash(start: start, count: buffer.count) +- } +- return 0 +- }) { +- return Int(truncatingIfNeeded: hash) +- } +- +- let offsetBasis: UInt64 = 14_695_981_039_346_656_037 +- let prime: UInt64 = 1_099_511_628_211 +- var hash = offsetBasis +- var packed: UInt64 = 0 +- var count = 0 +- for byte in key.utf8 { +- if count < 8 { +- packed |= UInt64(byte) << (UInt64(count) * 8) +- } +- hash ^= UInt64(byte) +- hash &*= prime +- count += 1 +- } +- return Int(truncatingIfNeeded: count <= 8 ? packed : hash) ++ if let hash = key.utf8.withContiguousStorageIfAvailable({ buffer -> UInt64 in ++ if buffer.count <= 8 { ++ return packedKeyHash(buffer) ++ } ++ if let start = buffer.baseAddress { ++ return sampledKeyHash(start: start, count: buffer.count) ++ } ++ return 0 ++ }) { ++ return Int(truncatingIfNeeded: hash) ++ } ++ ++ let offsetBasis: UInt64 = 14_695_981_039_346_656_037 ++ let prime: UInt64 = 1_099_511_628_211 ++ var hash = offsetBasis ++ var packed: UInt64 = 0 ++ var count = 0 ++ for byte in key.utf8 { ++ if count < 8 { ++ packed |= UInt64(byte) << (UInt64(count) * 8) ++ } ++ hash ^= UInt64(byte) ++ hash &*= prime ++ count += 1 ++ } ++ return Int(truncatingIfNeeded: count <= 8 ? packed : hash) +@@ -2043,4 +2292,4 @@ +- let prefix = packedKeyHash(UnsafeBufferPointer(start: start, count: 8)) +- let suffix = packedKeyHash(UnsafeBufferPointer(start: start.advanced(by: count - 8), count: 8)) +- let rotatedSuffix = (suffix << 1) | (suffix >> 63) +- return prefix ^ rotatedSuffix ^ (UInt64(truncatingIfNeeded: count) &* 0x9E37_79B1_85EB_CA87) ++ let prefix = packedKeyHash(UnsafeBufferPointer(start: start, count: 8)) ++ let suffix = packedKeyHash(UnsafeBufferPointer(start: start.advanced(by: count - 8), count: 8)) ++ let rotatedSuffix = (suffix << 1) | (suffix >> 63) ++ return prefix ^ rotatedSuffix ^ (UInt64(truncatingIfNeeded: count) &* 0x9E37_79B1_85EB_CA87) +@@ -2051,25 +2300,349 @@ +- var packed: UInt64 = 0 +- switch buffer.count { +- case 8: +- packed |= UInt64(buffer[7]) << 56 +- fallthrough +- case 7: +- packed |= UInt64(buffer[6]) << 48 +- fallthrough +- case 6: +- packed |= UInt64(buffer[5]) << 40 +- fallthrough +- case 5: +- packed |= UInt64(buffer[4]) << 32 +- fallthrough +- case 4: +- packed |= UInt64(buffer[3]) << 24 +- fallthrough +- case 3: +- packed |= UInt64(buffer[2]) << 16 +- fallthrough +- case 2: +- packed |= UInt64(buffer[1]) << 8 +- fallthrough +- case 1: +- packed |= UInt64(buffer[0]) ++ var packed: UInt64 = 0 ++ switch buffer.count { ++ case 8: ++ packed |= UInt64(buffer[7]) << 56 ++ fallthrough ++ case 7: ++ packed |= UInt64(buffer[6]) << 48 ++ fallthrough ++ case 6: ++ packed |= UInt64(buffer[5]) << 40 ++ fallthrough ++ case 5: ++ packed |= UInt64(buffer[4]) << 32 ++ fallthrough ++ case 4: ++ packed |= UInt64(buffer[3]) << 24 ++ fallthrough ++ case 3: ++ packed |= UInt64(buffer[2]) << 16 ++ fallthrough ++ case 2: ++ packed |= UInt64(buffer[1]) << 8 ++ fallthrough ++ case 1: ++ packed |= UInt64(buffer[0]) ++ default: ++ break ++ } ++ return packed ++} ++ ++@inline(__always) ++private func makeString( ++ budget: SemanticBudget, bytes: UnsafeBufferPointer, range: Range ++) throws -> String { ++ try budget.allocate(range.count, stage: "decoded key copy") ++ try budget.step(range.count) ++ let count = range.upperBound - range.lowerBound ++ if count == 0 { ++ return "" ++ } ++ let start = bytes.baseAddress!.advanced(by: range.lowerBound) ++ return String(decoding: UnsafeBufferPointer(start: start, count: count), as: UTF8.self) ++} ++ ++extension Parser { ++ @inline(__always) ++ func matchKeyValue(in indices: borrowing [Int], key: borrowing String, keyHash: Int) throws ++ -> Int? ++ { ++ if indices.isEmpty { ++ return nil ++ } ++ return try keyValues.withUnsafeBufferPointer { keyValueBuffer -> Int? in ++ guard let keyValueBase = keyValueBuffer.baseAddress else { ++ return nil ++ } ++ let indexCount = indices.count ++ var i = 0 ++ while i < indexCount { ++ try budget.step() ++ let keyValueIndex = indices[i] ++ let keyValuePair = keyValueBase.advanced(by: keyValueIndex).pointee ++ if keyValuePair.keyHash == keyHash, try budget.equal(keyValuePair.key, key) { ++ return keyValueIndex ++ } ++ i += 1 ++ } ++ return nil ++ } ++ } ++ ++ @inline(__always) ++ func matchKeyArray(in indices: borrowing [Int], key: borrowing String, keyHash: Int) throws ++ -> Int? ++ { ++ if indices.isEmpty { ++ return nil ++ } ++ return try keyArrays.withUnsafeBufferPointer { keyArrayBuffer -> Int? in ++ guard let keyArrayBase = keyArrayBuffer.baseAddress else { ++ return nil ++ } ++ let indexCount = indices.count ++ var i = 0 ++ while i < indexCount { ++ try budget.step() ++ let keyArrayIndex = indices[i] ++ let keyArrayPair = keyArrayBase.advanced(by: keyArrayIndex).pointee ++ if keyArrayPair.keyHash == keyHash, try budget.equal(keyArrayPair.key, key) { ++ return keyArrayIndex ++ } ++ i += 1 ++ } ++ return nil ++ } ++ } ++ ++ @inline(__always) ++ func keyMatchesToken(bytes: UnsafeBufferPointer, token: Token, key: borrowing String) ++ throws -> Bool ++ { ++ let range = token.text ++ let count = range.upperBound - range.lowerBound ++ ++ if let matches = try key.utf8.withContiguousStorageIfAvailable({ keyBuffer -> Bool in ++ if keyBuffer.count != count { ++ return false ++ } ++ ++ var keyIndex = 0 ++ var byteIndex = range.lowerBound ++ while keyIndex < count { ++ try budget.step() ++ if keyBuffer[keyIndex] != bytes[byteIndex] { ++ return false ++ } ++ keyIndex += 1 ++ byteIndex += 1 ++ } ++ return true ++ }) { ++ return matches ++ } ++ ++ var index = range.lowerBound ++ for byte in key.utf8 { ++ try budget.step() ++ if index >= range.upperBound || bytes[index] != byte { ++ return false ++ } ++ index += 1 ++ } ++ return index == range.upperBound ++ } ++ ++ @inline(__always) ++ func matchKeyArray( ++ in indices: borrowing [Int], ++ bytes: UnsafeBufferPointer, ++ token: Token, ++ keyHash: Int ++ ) throws -> Int? { ++ if indices.isEmpty { ++ return nil ++ } ++ return try keyArrays.withUnsafeBufferPointer { keyArrayBuffer -> Int? in ++ guard let keyArrayBase = keyArrayBuffer.baseAddress else { ++ return nil ++ } ++ let indexCount = indices.count ++ var i = 0 ++ while i < indexCount { ++ try budget.step() ++ let keyArrayIndex = indices[i] ++ let keyArrayPair = keyArrayBase.advanced(by: keyArrayIndex).pointee ++ if keyArrayPair.keyHash == keyHash, ++ try keyMatchesToken(bytes: bytes, token: token, key: keyArrayPair.key) ++ { ++ return keyArrayIndex ++ } ++ i += 1 ++ } ++ return nil ++ } ++ } ++ ++ @inline(__always) ++ func matchKeyTable(in indices: borrowing [Int], key: borrowing String, keyHash: Int) throws ++ -> Int? ++ { ++ if indices.isEmpty { ++ return nil ++ } ++ return try keyTables.withUnsafeBufferPointer { keyTableBuffer -> Int? in ++ guard let keyTableBase = keyTableBuffer.baseAddress else { ++ return nil ++ } ++ let indexCount = indices.count ++ var i = 0 ++ while i < indexCount { ++ try budget.step() ++ let keyTableIndex = indices[i] ++ let keyTablePair = keyTableBase.advanced(by: keyTableIndex).pointee ++ if keyTablePair.keyHash == keyHash, try budget.equal(keyTablePair.key, key) { ++ return keyTableIndex ++ } ++ i += 1 ++ } ++ return nil ++ } ++ } ++ ++ @inline(__always) ++ func tableValue( ++ tableIndex: Int, ++ keyed: Bool, ++ key: borrowing String, ++ keyHash: Int ++ ) throws -> InternalTOMLTable.Value? { ++ if keyed { ++ if !keyTables[tableIndex].table.mightContainKeyHash(keyHash) { ++ return nil ++ } ++ } else if !tables[tableIndex].mightContainKeyHash(keyHash) { ++ return nil ++ } ++ ++ if keyed { ++ if let keyValueIndex = try matchKeyValue( ++ in: keyTables[tableIndex].table.keyValues, key: key, keyHash: keyHash) ++ { ++ return .keyValue(keyValueIndex) ++ } ++ ++ if let keyArrayIndex = try matchKeyArray( ++ in: keyTables[tableIndex].table.arrays, key: key, keyHash: keyHash) ++ { ++ return .array(keyArrayIndex) ++ } ++ ++ if let keyTableIndex = try matchKeyTable( ++ in: keyTables[tableIndex].table.tables, key: key, keyHash: keyHash) ++ { ++ return .table(keyTableIndex) ++ } ++ return nil ++ } ++ ++ if let keyValueIndex = try matchKeyValue( ++ in: tables[tableIndex].keyValues, key: key, keyHash: keyHash) ++ { ++ return .keyValue(keyValueIndex) ++ } ++ ++ if let keyArrayIndex = try matchKeyArray( ++ in: tables[tableIndex].arrays, key: key, keyHash: keyHash) ++ { ++ return .array(keyArrayIndex) ++ } ++ ++ if let keyTableIndex = try matchKeyTable( ++ in: tables[tableIndex].tables, key: key, keyHash: keyHash) ++ { ++ return .table(keyTableIndex) ++ } ++ ++ return nil ++ } ++ ++ @inline(__always) ++ func lookupTable(in tableIndex: Int, keyed: Bool, key: borrowing String, keyHash: Int) throws ++ -> Int? ++ { ++ if keyed { ++ if !keyTables[tableIndex].table.mightContainKeyHash(keyHash) { ++ return nil ++ } ++ return try matchKeyTable(in: keyTables[tableIndex].table.tables, key: key, keyHash: keyHash) ++ } ++ if !tables[tableIndex].mightContainKeyHash(keyHash) { ++ return nil ++ } ++ return try matchKeyTable(in: tables[tableIndex].tables, key: key, keyHash: keyHash) ++ } ++ ++ @inline(__always) ++ func lookupArray(in tableIndex: Int, keyed: Bool, key: borrowing String, keyHash: Int) throws ++ -> Int? ++ { ++ if keyed { ++ if !keyTables[tableIndex].table.mightContainKeyHash(keyHash) { ++ return nil ++ } ++ return try matchKeyArray(in: keyTables[tableIndex].table.arrays, key: key, keyHash: keyHash) ++ } ++ if !tables[tableIndex].mightContainKeyHash(keyHash) { ++ return nil ++ } ++ return try matchKeyArray(in: tables[tableIndex].arrays, key: key, keyHash: keyHash) ++ } ++ ++ @inline(__always) ++ func lookupArray( ++ in tableIndex: Int, ++ keyed: Bool, ++ bytes: UnsafeBufferPointer, ++ token: Token, ++ keyHash: Int ++ ) throws -> Int? { ++ if keyed { ++ if !keyTables[tableIndex].table.mightContainKeyHash(keyHash) { ++ return nil ++ } ++ return try matchKeyArray( ++ in: keyTables[tableIndex].table.arrays, ++ bytes: bytes, ++ token: token, ++ keyHash: keyHash ++ ) ++ } ++ if !tables[tableIndex].mightContainKeyHash(keyHash) { ++ return nil ++ } ++ return try matchKeyArray( ++ in: tables[tableIndex].arrays, ++ bytes: bytes, ++ token: token, ++ keyHash: keyHash ++ ) ++ } ++ ++ mutating func advanceTablePathSegment( ++ tableIndex: inout Int, ++ isKeyed: inout Bool, ++ key: String, ++ keyHash: Int ++ ) throws { ++ if isKeyed ? keyTables[tableIndex].table.readOnly : tables[tableIndex].readOnly { ++ throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "cannot add to inline table")) ++ } ++ switch try tableValue(tableIndex: tableIndex, keyed: isKeyed, key: key, keyHash: keyHash) { ++ case .table(let index): ++ guard !keyTables[index].table.readOnly else { ++ throw TOMLError( ++ .syntax(lineNumber: token.lineNumber, message: "cannot add to inline table")) ++ } ++ tableIndex = index ++ isKeyed = true ++ case .array(let arrayIndex): ++ let array = keyArrays[arrayIndex].array ++ guard case .table = array.kind else { ++ throw TOMLError( ++ .syntax(lineNumber: token.lineNumber, message: "array element is not a table")) ++ } ++ ++ if array.elements.isEmpty { ++ throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "empty array")) ++ } ++ ++ guard case .table(_, let index) = array.elements.last else { ++ throw TOMLError( ++ .syntax(lineNumber: token.lineNumber, message: "array element is not a table")) ++ } ++ ++ tableIndex = index ++ isKeyed = false ++ case .keyValue: ++ throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "key-value already exists")) +@@ -2077,3 +2650,46 @@ +- break +- } +- return packed ++ let newTableAddress = keyTables.count ++ var newTable = InternalTOMLTable() ++ newTable.implicit = true ++ newTable.definedByDottedKey = false ++ try budget.node(depth: depth) ++ keyTables.append( ++ KeyTablePair( ++ key: key, keyHash: keyHash, sourcePosition: token.text.lowerBound, table: newTable)) ++ ++ if isKeyed { ++ if keyTables[tableIndex].table.tables.isEmpty { ++ try budget.allocate(8, stage: "semantic storage") ++ keyTables[tableIndex].table.tables.reserveCapacity(8) ++ } ++ try budget.node(depth: depth) ++ keyTables[tableIndex].table.tables.append(newTableAddress) ++ keyTables[tableIndex].table.recordKeyHash(keyHash) ++ } else { ++ if tables[tableIndex].tables.isEmpty { ++ try budget.allocate(8, stage: "semantic storage") ++ tables[tableIndex].tables.reserveCapacity(8) ++ } ++ try budget.node(depth: depth) ++ tables[tableIndex].tables.append(newTableAddress) ++ tables[tableIndex].recordKeyHash(keyHash) ++ } ++ tableIndex = newTableAddress ++ isKeyed = true ++ } ++ } ++ ++ mutating func walkTablePath(startTable: Int = 0, startKeyed: Bool = false) throws { ++ var tableIndex = startTable ++ var isKeyed = startKeyed ++ for (key, keyHash) in tablePath { ++ try budget.step() ++ try advanceTablePathSegment( ++ tableIndex: &tableIndex, ++ isKeyed: &isKeyed, ++ key: key, ++ keyHash: keyHash ++ ) ++ } ++ currentTable = tableIndex ++ currentTableIsKeyed = isKeyed ++ } +@@ -2081,316 +2696,0 @@ +- +-@inline(__always) +-private func makeString(bytes: UnsafeBufferPointer, range: Range) -> String { +- let count = range.upperBound - range.lowerBound +- if count == 0 { +- return "" +- } +- let start = bytes.baseAddress!.advanced(by: range.lowerBound) +- return String(decoding: UnsafeBufferPointer(start: start, count: count), as: UTF8.self) +-} +- +-extension Parser { +- @inline(__always) +- func matchKeyValue(in indices: borrowing [Int], key: borrowing String, keyHash: Int) -> Int? { +- if indices.isEmpty { +- return nil +- } +- return keyValues.withUnsafeBufferPointer { keyValueBuffer -> Int? in +- guard let keyValueBase = keyValueBuffer.baseAddress else { +- return nil +- } +- let indexCount = indices.count +- var i = 0 +- while i < indexCount { +- let keyValueIndex = indices[i] +- let keyValuePair = keyValueBase.advanced(by: keyValueIndex).pointee +- if keyValuePair.keyHash == keyHash, keyValuePair.key == key { +- return keyValueIndex +- } +- i += 1 +- } +- return nil +- } +- } +- +- @inline(__always) +- func matchKeyArray(in indices: borrowing [Int], key: borrowing String, keyHash: Int) -> Int? { +- if indices.isEmpty { +- return nil +- } +- return keyArrays.withUnsafeBufferPointer { keyArrayBuffer -> Int? in +- guard let keyArrayBase = keyArrayBuffer.baseAddress else { +- return nil +- } +- let indexCount = indices.count +- var i = 0 +- while i < indexCount { +- let keyArrayIndex = indices[i] +- let keyArrayPair = keyArrayBase.advanced(by: keyArrayIndex).pointee +- if keyArrayPair.keyHash == keyHash, keyArrayPair.key == key { +- return keyArrayIndex +- } +- i += 1 +- } +- return nil +- } +- } +- +- @inline(__always) +- func keyMatchesToken(bytes: UnsafeBufferPointer, token: Token, key: borrowing String) -> Bool { +- let range = token.text +- let count = range.upperBound - range.lowerBound +- +- if let matches = key.utf8.withContiguousStorageIfAvailable({ keyBuffer -> Bool in +- if keyBuffer.count != count { +- return false +- } +- +- var keyIndex = 0 +- var byteIndex = range.lowerBound +- while keyIndex < count { +- if keyBuffer[keyIndex] != bytes[byteIndex] { +- return false +- } +- keyIndex += 1 +- byteIndex += 1 +- } +- return true +- }) { +- return matches +- } +- +- var index = range.lowerBound +- for byte in key.utf8 { +- if index >= range.upperBound || bytes[index] != byte { +- return false +- } +- index += 1 +- } +- return index == range.upperBound +- } +- +- @inline(__always) +- func matchKeyArray( +- in indices: borrowing [Int], +- bytes: UnsafeBufferPointer, +- token: Token, +- keyHash: Int +- ) -> Int? { +- if indices.isEmpty { +- return nil +- } +- return keyArrays.withUnsafeBufferPointer { keyArrayBuffer -> Int? in +- guard let keyArrayBase = keyArrayBuffer.baseAddress else { +- return nil +- } +- let indexCount = indices.count +- var i = 0 +- while i < indexCount { +- let keyArrayIndex = indices[i] +- let keyArrayPair = keyArrayBase.advanced(by: keyArrayIndex).pointee +- if keyArrayPair.keyHash == keyHash, +- keyMatchesToken(bytes: bytes, token: token, key: keyArrayPair.key) +- { +- return keyArrayIndex +- } +- i += 1 +- } +- return nil +- } +- } +- +- @inline(__always) +- func matchKeyTable(in indices: borrowing [Int], key: borrowing String, keyHash: Int) -> Int? { +- if indices.isEmpty { +- return nil +- } +- return keyTables.withUnsafeBufferPointer { keyTableBuffer -> Int? in +- guard let keyTableBase = keyTableBuffer.baseAddress else { +- return nil +- } +- let indexCount = indices.count +- var i = 0 +- while i < indexCount { +- let keyTableIndex = indices[i] +- let keyTablePair = keyTableBase.advanced(by: keyTableIndex).pointee +- if keyTablePair.keyHash == keyHash, keyTablePair.key == key { +- return keyTableIndex +- } +- i += 1 +- } +- return nil +- } +- } +- +- @inline(__always) +- func tableValue( +- tableIndex: Int, +- keyed: Bool, +- key: borrowing String, +- keyHash: Int +- ) -> InternalTOMLTable.Value? { +- if keyed { +- if !keyTables[tableIndex].table.mightContainKeyHash(keyHash) { +- return nil +- } +- } else if !tables[tableIndex].mightContainKeyHash(keyHash) { +- return nil +- } +- +- if keyed { +- if let keyValueIndex = matchKeyValue(in: keyTables[tableIndex].table.keyValues, key: key, keyHash: keyHash) { +- return .keyValue(keyValueIndex) +- } +- +- if let keyArrayIndex = matchKeyArray(in: keyTables[tableIndex].table.arrays, key: key, keyHash: keyHash) { +- return .array(keyArrayIndex) +- } +- +- if let keyTableIndex = matchKeyTable(in: keyTables[tableIndex].table.tables, key: key, keyHash: keyHash) { +- return .table(keyTableIndex) +- } +- return nil +- } +- +- if let keyValueIndex = matchKeyValue(in: tables[tableIndex].keyValues, key: key, keyHash: keyHash) { +- return .keyValue(keyValueIndex) +- } +- +- if let keyArrayIndex = matchKeyArray(in: tables[tableIndex].arrays, key: key, keyHash: keyHash) { +- return .array(keyArrayIndex) +- } +- +- if let keyTableIndex = matchKeyTable(in: tables[tableIndex].tables, key: key, keyHash: keyHash) { +- return .table(keyTableIndex) +- } +- +- return nil +- } +- +- @inline(__always) +- func lookupTable(in tableIndex: Int, keyed: Bool, key: borrowing String, keyHash: Int) -> Int? { +- if keyed { +- if !keyTables[tableIndex].table.mightContainKeyHash(keyHash) { +- return nil +- } +- return matchKeyTable(in: keyTables[tableIndex].table.tables, key: key, keyHash: keyHash) +- } +- if !tables[tableIndex].mightContainKeyHash(keyHash) { +- return nil +- } +- return matchKeyTable(in: tables[tableIndex].tables, key: key, keyHash: keyHash) +- } +- +- @inline(__always) +- func lookupArray(in tableIndex: Int, keyed: Bool, key: borrowing String, keyHash: Int) -> Int? { +- if keyed { +- if !keyTables[tableIndex].table.mightContainKeyHash(keyHash) { +- return nil +- } +- return matchKeyArray(in: keyTables[tableIndex].table.arrays, key: key, keyHash: keyHash) +- } +- if !tables[tableIndex].mightContainKeyHash(keyHash) { +- return nil +- } +- return matchKeyArray(in: tables[tableIndex].arrays, key: key, keyHash: keyHash) +- } +- +- @inline(__always) +- func lookupArray( +- in tableIndex: Int, +- keyed: Bool, +- bytes: UnsafeBufferPointer, +- token: Token, +- keyHash: Int +- ) -> Int? { +- if keyed { +- if !keyTables[tableIndex].table.mightContainKeyHash(keyHash) { +- return nil +- } +- return matchKeyArray( +- in: keyTables[tableIndex].table.arrays, +- bytes: bytes, +- token: token, +- keyHash: keyHash +- ) +- } +- if !tables[tableIndex].mightContainKeyHash(keyHash) { +- return nil +- } +- return matchKeyArray( +- in: tables[tableIndex].arrays, +- bytes: bytes, +- token: token, +- keyHash: keyHash +- ) +- } +- +- mutating func advanceTablePathSegment( +- tableIndex: inout Int, +- isKeyed: inout Bool, +- key: String, +- keyHash: Int +- ) throws(TOMLError) { +- switch tableValue(tableIndex: tableIndex, keyed: isKeyed, key: key, keyHash: keyHash) { +- case let .table(index): +- tableIndex = index +- isKeyed = true +- case let .array(arrayIndex): +- let array = keyArrays[arrayIndex].array +- guard case .table = array.kind else { +- throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "array element is not a table")) +- } +- +- if array.elements.isEmpty { +- throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "empty array")) +- } +- +- guard case let .table(_, index) = array.elements.last else { +- throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "array element is not a table")) +- } +- +- tableIndex = index +- isKeyed = false +- case .keyValue: +- throw TOMLError(.syntax(lineNumber: token.lineNumber, message: "key-value already exists")) +- default: +- let newTableAddress = keyTables.count +- var newTable = InternalTOMLTable() +- newTable.implicit = true +- newTable.definedByDottedKey = false +- keyTables.append(KeyTablePair(key: key, keyHash: keyHash, table: newTable)) +- +- if isKeyed { +- if keyTables[tableIndex].table.tables.isEmpty { +- keyTables[tableIndex].table.tables.reserveCapacity(8) +- } +- keyTables[tableIndex].table.tables.append(newTableAddress) +- keyTables[tableIndex].table.recordKeyHash(keyHash) +- } else { +- if tables[tableIndex].tables.isEmpty { +- tables[tableIndex].tables.reserveCapacity(8) +- } +- tables[tableIndex].tables.append(newTableAddress) +- tables[tableIndex].recordKeyHash(keyHash) +- } +- tableIndex = newTableAddress +- isKeyed = true +- } +- } +- +- mutating func walkTablePath(startTable: Int = 0, startKeyed: Bool = false) throws(TOMLError) { +- var tableIndex = startTable +- var isKeyed = startKeyed +- for (key, keyHash) in tablePath { +- try advanceTablePathSegment( +- tableIndex: &tableIndex, +- isKeyed: &isKeyed, +- key: key, +- keyHash: keyHash +- ) +- } +- currentTable = tableIndex +- currentTableIsKeyed = isKeyed +- } +-} +--- Sources/TOMLDecoder/Parsing/Parser+Finish.swift ++++ Sources/TOMLDecoder/Parsing/Parser+Finish.swift +@@ -2,6 +2,6 @@ +- consuming func finish(source: String) -> TOMLDocument { +- var tables: [InternalTOMLTable] = [] +- var arrays: [InternalTOMLArray] = [] +- var keyTables: [KeyTablePair] = [] +- var keyArrays: [KeyArrayPair] = [] +- var keyValues: [KeyValuePair] = [] ++ consuming func finish(source: String) -> TOMLDocument { ++ var tables: [InternalTOMLTable] = [] ++ var arrays: [InternalTOMLArray] = [] ++ var keyTables: [KeyTablePair] = [] ++ var keyArrays: [KeyArrayPair] = [] ++ var keyValues: [KeyValuePair] = [] +@@ -9,5 +9,5 @@ +- swap(&tables, &self.tables) +- swap(&arrays, &self.arrays) +- swap(&keyTables, &self.keyTables) +- swap(&keyArrays, &self.keyArrays) +- swap(&keyValues, &self.keyValues) ++ swap(&tables, &self.tables) ++ swap(&arrays, &self.arrays) ++ swap(&keyTables, &self.keyTables) ++ swap(&keyArrays, &self.keyArrays) ++ swap(&keyValues, &self.keyValues) +@@ -15,9 +15,9 @@ +- return TOMLDocument( +- source: source, +- tables: tables, +- arrays: arrays, +- keyTables: keyTables, +- keyArrays: keyArrays, +- keyValues: keyValues +- ) +- } ++ return TOMLDocument( ++ source: source, ++ tables: tables, ++ arrays: arrays, ++ keyTables: keyTables, ++ keyArrays: keyArrays, ++ keyValues: keyValues ++ ) ++ } +--- Sources/TOMLDecoder/Parsing/Token.swift ++++ Sources/TOMLDecoder/Parsing/Token.swift +@@ -2,13 +2,13 @@ +- enum Kind: UInt8 { +- case dot +- case comma +- case equal +- case lbrace +- case rbrace +- case newline +- case lbracket +- case rbracket +- case string +- case bareKey +- case eof +- } ++ enum Kind: UInt8 { ++ case dot ++ case comma ++ case equal ++ case lbrace ++ case rbrace ++ case newline ++ case lbracket ++ case rbracket ++ case string ++ case bareKey ++ case eof ++ } +@@ -16,3 +16 @@ +- let kind: Kind +- let lineNumber: Int +- let text: Range ++ var budget: SemanticBudget! = nil +@@ -20 +18,9 @@ +- static let empty = Token(kind: .newline, lineNumber: 1, text: 0 ..< 0) ++ let kind: Kind ++ let lineNumber: Int ++ let text: Range ++ ++ static func == (lhs: Token, rhs: Token) -> Bool { ++ lhs.kind == rhs.kind && lhs.lineNumber == rhs.lineNumber && lhs.text == rhs.text ++ } ++ ++ static var empty: Token { Token(kind: .newline, lineNumber: 1, text: 0..<0) } +@@ -22,89 +27,0 @@ +- +-extension Token { +- func unpackBool(source: String, context: TOMLKey) throws(TOMLError) -> Bool { +- do { +- return try (source.utf8.withContiguousStorageIfAvailable { try unpackBool(bytes: $0, context: context) })! +- } catch { +- throw error as! TOMLError +- } +- } +- +- func unpackFloat(source: String, context: TOMLKey) throws(TOMLError) -> Double { +- do { +- return try (source.utf8.withContiguousStorageIfAvailable { try unpackFloat(bytes: $0, context: context) })! +- } catch { +- throw error as! TOMLError +- } +- } +- +- func unpackString(source: String, context: TOMLKey) throws(TOMLError) -> String { +- do { +- return try (source.utf8.withContiguousStorageIfAvailable { try unpackString(bytes: $0, context: context) })! +- } catch { +- throw error as! TOMLError +- } +- } +- +- func unpackInteger(source: String, context: TOMLKey) throws(TOMLError) -> Int64 { +- do { +- return try (source.utf8.withContiguousStorageIfAvailable { try unpackInteger(bytes: $0, context: context) })! +- } catch { +- throw error as! TOMLError +- } +- } +- +- func unpackDateTime(source: String, context: TOMLKey) throws(TOMLError) -> DateTimeComponents { +- do { +- return try (source.utf8.withContiguousStorageIfAvailable { try unpackDateTime(bytes: $0, context: context) })! +- } catch { +- throw error as! TOMLError +- } +- } +- +- func unpackOffsetDateTime(source: String, context: TOMLKey) throws(TOMLError) -> OffsetDateTime { +- let datetime: DateTimeComponents +- do { +- datetime = try (source.utf8.withContiguousStorageIfAvailable { try unpackDateTime(bytes: $0, context: context) })! +- } catch { +- throw error as! TOMLError +- } +- switch (datetime.date, datetime.time, datetime.offset) { +- case let (.some(date), .some(time), .some(offset)): +- return OffsetDateTime(date: date, time: time, offset: offset, features: datetime.features) +- default: +- throw TOMLError(.typeMismatch(context: context, lineNumber: lineNumber, expected: "offset date-time")) +- } +- } +- +- func unpackLocalDateTime(source: String, context: TOMLKey, exactMatch: Bool = true) throws(TOMLError) -> LocalDateTime { +- let components = try unpackDateTime(source: source, context: context) +- guard let localDateTime = components.localDateTime(exactMatch: exactMatch) else { +- throw TOMLError(.typeMismatch(context: context, lineNumber: lineNumber, expected: "local date-time")) +- } +- return localDateTime +- } +- +- func unpackLocalDate(source: String, context: TOMLKey, exactMatch: Bool = true) throws(TOMLError) -> LocalDate { +- let components = try unpackDateTime(source: source, context: context) +- guard let localDate = components.localDate(exactMatch: exactMatch) else { +- throw TOMLError(.typeMismatch(context: context, lineNumber: lineNumber, expected: "local date")) +- } +- return localDate +- } +- +- func unpackLocalTime(source: String, context: TOMLKey, exactMatch: Bool = true) throws(TOMLError) -> LocalTime { +- let components = try unpackDateTime(source: source, context: context) +- guard let localTime = components.localTime(exactMatch: exactMatch) else { +- throw TOMLError(.typeMismatch(context: context, lineNumber: lineNumber, expected: "local time")) +- } +- return localTime +- } +- +- func unpackAnyValue(source: String, context: TOMLKey) throws(TOMLError) -> Any { +- do { +- return try (source.utf8.withContiguousStorageIfAvailable { try unpackAnyValue(bytes: $0, context: context) })! +- } catch { +- throw error as! TOMLError +- } +- } +-} +--- Sources/TOMLDecoder/Parsing/TOMLDocument.swift ++++ Sources/TOMLDecoder/Parsing/TOMLDocument.swift +@@ -3,6 +3,6 @@ +-struct TOMLDocument: Equatable, @unchecked Sendable { +- let tables: [InternalTOMLTable] +- let arrays: [InternalTOMLArray] +- let keyTables: [KeyTablePair] +- let keyArrays: [KeyArrayPair] +- let keyValues: [KeyValuePair] ++struct TOMLDocument { ++ let tables: [InternalTOMLTable] ++ let arrays: [InternalTOMLArray] ++ let keyTables: [KeyTablePair] ++ let keyArrays: [KeyArrayPair] ++ let keyValues: [KeyValuePair] +@@ -10 +10 @@ +- let source: String ++ let source: String +@@ -12,14 +12,41 @@ +- init( +- source: String, +- tables: [InternalTOMLTable], +- arrays: [InternalTOMLArray], +- keyTables: [KeyTablePair], +- keyArrays: [KeyArrayPair], +- keyValues: [KeyValuePair] +- ) { +- self.source = source +- self.tables = tables +- self.arrays = arrays +- self.keyTables = keyTables +- self.keyArrays = keyArrays +- self.keyValues = keyValues ++ init( ++ source: String, ++ tables: [InternalTOMLTable], ++ arrays: [InternalTOMLArray], ++ keyTables: [KeyTablePair], ++ keyArrays: [KeyArrayPair], ++ keyValues: [KeyValuePair] ++ ) { ++ self.source = source ++ self.tables = tables ++ self.arrays = arrays ++ self.keyTables = keyTables ++ self.keyArrays = keyArrays ++ self.keyValues = keyValues ++ } ++ ++} ++ ++struct InternalTOMLArray: Equatable { ++ var kind: Kind? ++ var elements: [Element] ++ ++ init(kind: Kind? = nil, elements: [Element] = []) { ++ self.kind = kind ++ self.elements = elements ++ } ++ ++ enum Element: Equatable { ++ case leaf(Token) ++ case array(lineNumber: Int, Int) ++ case table(lineNumber: Int, Int) ++ ++ var lineNumber: Int { ++ switch self { ++ case .leaf(let token): ++ token.lineNumber ++ case .array(let lineNumber, _): ++ lineNumber ++ case .table(let lineNumber, _): ++ lineNumber ++ } +@@ -28,3 +55,13 @@ +- init(source: String, keyTransform: (@Sendable (String) -> String)?) throws(TOMLError) { +- var hasContinousStorage = false +- var parser = Parser(keyTransform: keyTransform) ++ static func == (lhs: Element, rhs: Element) -> Bool { ++ switch (lhs, rhs) { ++ case (.leaf(let lhsToken), .leaf(let rhsToken)): ++ lhsToken == rhsToken ++ case (.array(let lhsLineNumber, let lhsIndex), .array(let rhsLineNumber, let rhsIndex)): ++ lhsLineNumber == rhsLineNumber && lhsIndex == rhsIndex ++ case (.table(let lhsLineNumber, let lhsIndex), .table(let rhsLineNumber, let rhsIndex)): ++ lhsLineNumber == rhsLineNumber && lhsIndex == rhsIndex ++ default: ++ false ++ } ++ } ++ } +@@ -32,20 +69,7 @@ +- do { +- try source.utf8.withContiguousStorageIfAvailable { +- hasContinousStorage = true +- try parser.parse(bytes: $0) +- } +- } catch { +- throw error as! TOMLError +- } +- +- if !hasContinousStorage { +- var source = source +- do { +- try source.withUTF8 { try parser.parse(bytes: $0) } +- } catch { +- throw error as! TOMLError +- } +- } +- +- self = parser.finish(source: source) +- } ++ enum Kind: UInt8 { ++ case value ++ case array ++ case table ++ case inlineTable ++ case mixed ++ } +@@ -54,45 +78,5 @@ +-struct InternalTOMLArray: Equatable, Sendable { +- var kind: Kind? +- var elements: [Element] +- +- init(kind: Kind? = nil, elements: [Element] = []) { +- self.kind = kind +- self.elements = elements +- } +- +- enum Element: Equatable { +- case leaf(Token) +- case array(lineNumber: Int, Int) +- case table(lineNumber: Int, Int) +- +- var lineNumber: Int { +- switch self { +- case let .leaf(token): +- token.lineNumber +- case let .array(lineNumber, _): +- lineNumber +- case let .table(lineNumber, _): +- lineNumber +- } +- } +- +- static func == (lhs: Element, rhs: Element) -> Bool { +- switch (lhs, rhs) { +- case let (.leaf(lhsToken), .leaf(rhsToken)): +- lhsToken == rhsToken +- case let (.array(lhsLineNumber, lhsIndex), .array(rhsLineNumber, rhsIndex)): +- lhsLineNumber == rhsLineNumber && lhsIndex == rhsIndex +- case let (.table(lhsLineNumber, lhsIndex), .table(rhsLineNumber, rhsIndex)): +- lhsLineNumber == rhsLineNumber && lhsIndex == rhsIndex +- default: +- false +- } +- } +- } +- +- enum Kind: UInt8 { +- case value +- case array +- case table +- case mixed +- } ++struct KeyTablePair { ++ let key: String ++ let keyHash: Int ++ let sourcePosition: Int ++ var table: InternalTOMLTable +@@ -101,4 +85,5 @@ +-struct KeyTablePair: Equatable { +- let key: String +- let keyHash: Int +- var table: InternalTOMLTable ++struct KeyArrayPair { ++ let key: String ++ let keyHash: Int ++ let sourcePosition: Int ++ var array: InternalTOMLArray +@@ -107,4 +92,5 @@ +-struct KeyArrayPair: Equatable { +- let key: String +- let keyHash: Int +- var array: InternalTOMLArray ++struct KeyValuePair { ++ let key: String ++ let keyHash: Int ++ let sourcePosition: Int ++ var value: Token +@@ -113,5 +99,8 @@ +-struct KeyValuePair: Equatable { +- let key: String +- let keyHash: Int +- var value: Token +-} ++struct InternalTOMLTable: Equatable { ++ var implicit: Bool = false ++ var readOnly: Bool = false ++ var definedByDottedKey: Bool = false ++ var keyHashBloom: UInt64 = 0 ++ var keyValues: [Int] = [] ++ var arrays: [Int] = [] ++ var tables: [Int] = [] +@@ -119,8 +108,4 @@ +-struct InternalTOMLTable: Equatable, Sendable { +- var implicit: Bool = false +- var readOnly: Bool = false +- var definedByDottedKey: Bool = false +- var keyHashBloom: UInt64 = 0 +- var keyValues: [Int] = [] +- var arrays: [Int] = [] +- var tables: [Int] = [] ++ @inline(__always) ++ mutating func recordKeyHash(_ keyHash: Int) { ++ keyHashBloom |= keyHashBloomMask(keyHash) ++ } +@@ -128,4 +113,5 @@ +- @inline(__always) +- mutating func recordKeyHash(_ keyHash: Int) { +- keyHashBloom |= keyHashBloomMask(keyHash) +- } ++ @inline(__always) ++ func mightContainKeyHash(_ keyHash: Int) -> Bool { ++ let mask = keyHashBloomMask(keyHash) ++ return (keyHashBloom & mask) == mask ++ } +@@ -133,48 +119,5 @@ +- @inline(__always) +- func mightContainKeyHash(_ keyHash: Int) -> Bool { +- let mask = keyHashBloomMask(keyHash) +- return (keyHashBloom & mask) == mask +- } +- +- func allKeys(_ document: TOMLDocument) -> [String] { +- var keys = [String]() +- for kv in keyValues { +- keys.append(document.keyValues[kv].key) +- } +- for arr in arrays { +- keys.append(document.keyArrays[arr].key) +- } +- for table in tables { +- keys.append(document.keyTables[table].key) +- } +- return keys +- } +- +- func contains(source: TOMLDocument, key: String) -> Bool { +- let keyHash = fastKeyHash(key) +- for kv in keyValues { +- let pair = source.keyValues[kv] +- if pair.keyHash == keyHash, pair.key == key { +- return true +- } +- } +- for arr in arrays { +- let arrayPair = source.keyArrays[arr] +- if arrayPair.keyHash == keyHash, arrayPair.key == key { +- return true +- } +- } +- for table in tables { +- let tablePair = source.keyTables[table] +- if tablePair.keyHash == keyHash, tablePair.key == key { +- return true +- } +- } +- return false +- } +- +- enum Value { +- case keyValue(Int) +- case array(Int) +- case table(Int) +- } ++ enum Value { ++ case keyValue(Int) ++ case array(Int) ++ case table(Int) ++ } +@@ -185,4 +128,4 @@ +- let raw = UInt(bitPattern: keyHash) +- let bit0 = UInt64(1) << UInt64(raw & 63) +- let bit1 = UInt64(1) << UInt64((raw >> 6) & 63) +- return bit0 | bit1 ++ let raw = UInt(bitPattern: keyHash) ++ let bit0 = UInt64(1) << UInt64(raw & 63) ++ let bit1 = UInt64(1) << UInt64((raw >> 6) & 63) ++ return bit0 | bit1 +@@ -192,4 +135,4 @@ +- let date: LocalDate? +- let time: LocalTime? +- let offset: Int16? +- let features: OffsetDateTime.Features ++ let date: LocalDate? ++ let time: LocalTime? ++ let offset: Int16? ++ let features: OffsetDateTime.Features +@@ -197,10 +140,9 @@ +- @inline(__always) +- func localDate(exactMatch: Bool = true) -> LocalDate? { +- switch (date, time, offset) { +- case let (.some(date), .none, .none): +- date +- case let (.some(date), _, _) where !exactMatch: +- date +- default: +- nil +- } ++ @inline(__always) ++ func localDate(exactMatch: Bool = true) -> LocalDate? { ++ switch (date, time, offset) { ++ case (.some(let date), .none, .none): ++ date ++ case (.some(let date), _, _) where !exactMatch: ++ date ++ default: ++ nil +@@ -207,0 +150 @@ ++ } +@@ -209,10 +152,9 @@ +- @inline(__always) +- func localTime(exactMatch: Bool = true) -> LocalTime? { +- switch (date, time, offset) { +- case let (.none, .some(time), .none): +- time +- case let (_, .some(time), _) where !exactMatch: +- time +- default: +- nil +- } ++ @inline(__always) ++ func localTime(exactMatch: Bool = true) -> LocalTime? { ++ switch (date, time, offset) { ++ case (.none, .some(let time), .none): ++ time ++ case (_, .some(let time), _) where !exactMatch: ++ time ++ default: ++ nil +@@ -219,0 +162 @@ ++ } +@@ -221,10 +164,9 @@ +- @inline(__always) +- func localDateTime(exactMatch: Bool = true) -> LocalDateTime? { +- switch (date, time, offset) { +- case let (.some(date), .some(time), .none): +- LocalDateTime(date: date, time: time) +- case let (.some(date), .some(time), .some) where !exactMatch: +- LocalDateTime(date: date, time: time) +- default: +- nil +- } ++ @inline(__always) ++ func localDateTime(exactMatch: Bool = true) -> LocalDateTime? { ++ switch (date, time, offset) { ++ case (.some(let date), .some(let time), .none): ++ LocalDateTime(date: date, time: time) ++ case (.some(let date), .some(let time), .some) where !exactMatch: ++ LocalDateTime(date: date, time: time) ++ default: ++ nil +@@ -232,41 +174 @@ +-} +- +-extension InternalTOMLTable { +- func dictionary(source: TOMLDocument) throws(TOMLError) -> [String: Any] { +- var result = [String: Any]() +- for tableIndex in tables { +- let tablePair = source.keyTables[tableIndex] +- result[tablePair.key] = try tablePair.table.dictionary(source: source) +- } +- +- for arrayIndex in arrays { +- let arrayPair = source.keyArrays[arrayIndex] +- result[arrayPair.key] = try arrayPair.array.array(source: source) +- } +- +- for kvIndex in keyValues { +- let pair = source.keyValues[kvIndex] +- result[pair.key] = try pair.value.unpackAnyValue(source: source.source, context: .string(pair.key)) +- } +- +- return result +- } +-} +- +-extension InternalTOMLArray { +- func array(source: TOMLDocument) throws(TOMLError) -> [Any] { +- var result = [Any]() +- +- for (index, element) in zip(0..., elements) { +- switch element { +- case let .array(_, arrayIndex): +- try result.append(source.arrays[arrayIndex].array(source: source)) +- case let .table(_, tableIndex): +- try result.append(source.tables[tableIndex].dictionary(source: source)) +- case let .leaf(token): +- try result.append(token.unpackAnyValue(source: source.source, context: .int(index))) +- } +- } +- +- return result +- } ++ } +@@ -276,4 +178,4 @@ +- @inline(__always) +- func table(at index: Int, keyed: Bool) -> InternalTOMLTable { +- keyed ? keyTables[index].table : tables[index] +- } ++ @inline(__always) ++ func table(at index: Int, keyed: Bool) -> InternalTOMLTable { ++ keyed ? keyTables[index].table : tables[index] ++ } +@@ -281,4 +183,4 @@ +- @inline(__always) +- func array(at index: Int, keyed: Bool) -> InternalTOMLArray { +- keyed ? keyArrays[index].array : arrays[index] +- } ++ @inline(__always) ++ func array(at index: Int, keyed: Bool) -> InternalTOMLArray { ++ keyed ? keyArrays[index].array : arrays[index] ++ } +--- Sources/TOMLDecoder/Parsing/Constants.swift ++++ Sources/TOMLDecoder/Parsing/Constants.swift +@@ -2,22 +2,22 @@ +- static let escape: UTF8.CodeUnit = 27 +- static let equal: UTF8.CodeUnit = 61 +- static let comma: UTF8.CodeUnit = 44 +- static let lbrace: UTF8.CodeUnit = 123 +- static let rbrace: UTF8.CodeUnit = 125 +- static let lbracket: UTF8.CodeUnit = 91 +- static let rbracket: UTF8.CodeUnit = 93 +- static let pound: UTF8.CodeUnit = 35 +- static let backslash: UTF8.CodeUnit = 92 +- static let backspace: UTF8.CodeUnit = 8 +- static let cr: UTF8.CodeUnit = 13 +- static let colon: UTF8.CodeUnit = 58 +- static let dot: UTF8.CodeUnit = 46 +- static let doubleQuote: UTF8.CodeUnit = 34 +- static let formfeed: UTF8.CodeUnit = 12 +- static let lf: UTF8.CodeUnit = 10 +- static let minus: UTF8.CodeUnit = 45 +- static let plus: UTF8.CodeUnit = 43 +- static let singleQuote: UTF8.CodeUnit = 39 +- static let space: UTF8.CodeUnit = 32 +- static let tab: UTF8.CodeUnit = 9 +- static let underscore: UTF8.CodeUnit = 95 ++ static let escape: UTF8.CodeUnit = 27 ++ static let equal: UTF8.CodeUnit = 61 ++ static let comma: UTF8.CodeUnit = 44 ++ static let lbrace: UTF8.CodeUnit = 123 ++ static let rbrace: UTF8.CodeUnit = 125 ++ static let lbracket: UTF8.CodeUnit = 91 ++ static let rbracket: UTF8.CodeUnit = 93 ++ static let pound: UTF8.CodeUnit = 35 ++ static let backslash: UTF8.CodeUnit = 92 ++ static let backspace: UTF8.CodeUnit = 8 ++ static let cr: UTF8.CodeUnit = 13 ++ static let colon: UTF8.CodeUnit = 58 ++ static let dot: UTF8.CodeUnit = 46 ++ static let doubleQuote: UTF8.CodeUnit = 34 ++ static let formfeed: UTF8.CodeUnit = 12 ++ static let lf: UTF8.CodeUnit = 10 ++ static let minus: UTF8.CodeUnit = 45 ++ static let plus: UTF8.CodeUnit = 43 ++ static let singleQuote: UTF8.CodeUnit = 39 ++ static let space: UTF8.CodeUnit = 32 ++ static let tab: UTF8.CodeUnit = 9 ++ static let underscore: UTF8.CodeUnit = 95 +@@ -25,4 +25,4 @@ +- static let number0: UTF8.CodeUnit = 48 +- static let number1: UTF8.CodeUnit = 49 +- static let number7: UTF8.CodeUnit = 55 +- static let number9: UTF8.CodeUnit = 57 ++ static let number0: UTF8.CodeUnit = 48 ++ static let number1: UTF8.CodeUnit = 49 ++ static let number7: UTF8.CodeUnit = 55 ++ static let number9: UTF8.CodeUnit = 57 +@@ -30,20 +30,20 @@ +- static let lowerA: UTF8.CodeUnit = 97 +- static let lowerB: UTF8.CodeUnit = 98 +- static let lowerI: UTF8.CodeUnit = 105 +- static let lowerE: UTF8.CodeUnit = 101 +- static let lowerF: UTF8.CodeUnit = 102 +- static let lowerL: UTF8.CodeUnit = 108 +- static let lowerS: UTF8.CodeUnit = 115 +- static let lowerN: UTF8.CodeUnit = 110 +- static let lowerO: UTF8.CodeUnit = 111 +- static let lowerR: UTF8.CodeUnit = 114 +- static let lowerT: UTF8.CodeUnit = 116 +- static let lowerU: UTF8.CodeUnit = 117 +- static let lowerX: UTF8.CodeUnit = 120 +- static let lowerZ: UTF8.CodeUnit = 122 +- static let upperA: UTF8.CodeUnit = 65 +- static let upperE: UTF8.CodeUnit = 69 +- static let upperF: UTF8.CodeUnit = 70 +- static let upperT: UTF8.CodeUnit = 84 +- static let upperU: UTF8.CodeUnit = 85 +- static let upperZ: UTF8.CodeUnit = 90 ++ static let lowerA: UTF8.CodeUnit = 97 ++ static let lowerB: UTF8.CodeUnit = 98 ++ static let lowerI: UTF8.CodeUnit = 105 ++ static let lowerE: UTF8.CodeUnit = 101 ++ static let lowerF: UTF8.CodeUnit = 102 ++ static let lowerL: UTF8.CodeUnit = 108 ++ static let lowerS: UTF8.CodeUnit = 115 ++ static let lowerN: UTF8.CodeUnit = 110 ++ static let lowerO: UTF8.CodeUnit = 111 ++ static let lowerR: UTF8.CodeUnit = 114 ++ static let lowerT: UTF8.CodeUnit = 116 ++ static let lowerU: UTF8.CodeUnit = 117 ++ static let lowerX: UTF8.CodeUnit = 120 ++ static let lowerZ: UTF8.CodeUnit = 122 ++ static let upperA: UTF8.CodeUnit = 65 ++ static let upperE: UTF8.CodeUnit = 69 ++ static let upperF: UTF8.CodeUnit = 70 ++ static let upperT: UTF8.CodeUnit = 84 ++ static let upperU: UTF8.CodeUnit = 85 ++ static let upperZ: UTF8.CodeUnit = 90 +@@ -51,16 +51,15 @@ +- nonisolated(unsafe) static let isBareKeyChar: UnsafePointer = { +- let ptr = UnsafeMutablePointer.allocate(capacity: 256) +- ptr.initialize(repeating: false, count: 256) +- for i in 0 ..< 256 { +- let ch = UTF8.CodeUnit(i) +- if (ch >= CodeUnits.lowerA && ch <= CodeUnits.lowerZ) || +- (ch >= CodeUnits.upperA && ch <= CodeUnits.upperZ) || +- (ch >= CodeUnits.number0 && ch <= CodeUnits.number9) || +- ch == CodeUnits.underscore || +- ch == CodeUnits.minus +- { +- ptr[i] = true +- } +- } +- return UnsafePointer(ptr) +- }() ++ nonisolated(unsafe) static let isBareKeyChar: UnsafePointer = { ++ let ptr = UnsafeMutablePointer.allocate(capacity: 256) ++ ptr.initialize(repeating: false, count: 256) ++ for i in 0..<256 { ++ let ch = UTF8.CodeUnit(i) ++ if (ch >= CodeUnits.lowerA && ch <= CodeUnits.lowerZ) ++ || (ch >= CodeUnits.upperA && ch <= CodeUnits.upperZ) ++ || (ch >= CodeUnits.number0 && ch <= CodeUnits.number9) || ch == CodeUnits.underscore ++ || ch == CodeUnits.minus ++ { ++ ptr[i] = true ++ } ++ } ++ return UnsafePointer(ptr) ++ }() +@@ -68,18 +67,15 @@ +- nonisolated(unsafe) static let isValueChar: UnsafePointer = { +- let ptr = UnsafeMutablePointer.allocate(capacity: 256) +- ptr.initialize(repeating: false, count: 256) +- for i in 0 ..< 256 { +- let ch = UTF8.CodeUnit(i) +- if (ch >= CodeUnits.lowerA && ch <= CodeUnits.lowerZ) || +- (ch >= CodeUnits.upperA && ch <= CodeUnits.upperZ) || +- (ch >= CodeUnits.number0 && ch <= CodeUnits.number9) || +- ch == CodeUnits.underscore || +- ch == CodeUnits.minus || +- ch == CodeUnits.plus || +- ch == CodeUnits.dot +- { +- ptr[i] = true +- } +- } +- return UnsafePointer(ptr) +- }() ++ nonisolated(unsafe) static let isValueChar: UnsafePointer = { ++ let ptr = UnsafeMutablePointer.allocate(capacity: 256) ++ ptr.initialize(repeating: false, count: 256) ++ for i in 0..<256 { ++ let ch = UTF8.CodeUnit(i) ++ if (ch >= CodeUnits.lowerA && ch <= CodeUnits.lowerZ) ++ || (ch >= CodeUnits.upperA && ch <= CodeUnits.upperZ) ++ || (ch >= CodeUnits.number0 && ch <= CodeUnits.number9) || ch == CodeUnits.underscore ++ || ch == CodeUnits.minus || ch == CodeUnits.plus || ch == CodeUnits.dot ++ { ++ ptr[i] = true ++ } ++ } ++ return UnsafePointer(ptr) ++ }() +@@ -87,8 +83,8 @@ +- nonisolated(unsafe) static let isBasicStringBodyChar: UnsafePointer = { +- let ptr = UnsafeMutablePointer.allocate(capacity: 256) +- ptr.initialize(repeating: true, count: 256) +- ptr[Int(CodeUnits.backslash)] = false +- ptr[Int(CodeUnits.doubleQuote)] = false +- ptr[Int(CodeUnits.lf)] = false +- return UnsafePointer(ptr) +- }() ++ nonisolated(unsafe) static let isBasicStringBodyChar: UnsafePointer = { ++ let ptr = UnsafeMutablePointer.allocate(capacity: 256) ++ ptr.initialize(repeating: true, count: 256) ++ ptr[Int(CodeUnits.backslash)] = false ++ ptr[Int(CodeUnits.doubleQuote)] = false ++ ptr[Int(CodeUnits.lf)] = false ++ return UnsafePointer(ptr) ++ }() +@@ -96,3 +92,3 @@ +- static let null: UTF8.CodeUnit = 0x00 +- static let unitSeparator: UTF8.CodeUnit = 0x1F +- static let delete: UTF8.CodeUnit = 0x7F ++ static let null: UTF8.CodeUnit = 0x00 ++ static let unitSeparator: UTF8.CodeUnit = 0x1F ++ static let delete: UTF8.CodeUnit = 0x7F +@@ -102,4 +98,4 @@ +- @_transparent +- var isDecimalDigit: Bool { +- CodeUnits.number0 <= self && self <= CodeUnits.number9 +- } ++ @_transparent ++ var isDecimalDigit: Bool { ++ CodeUnits.number0 <= self && self <= CodeUnits.number9 ++ } +@@ -107,6 +103,6 @@ +- @_transparent +- var isHexDigit: Bool { +- isDecimalDigit +- || CodeUnits.lowerA <= self && self <= CodeUnits.lowerF +- || CodeUnits.upperA <= self && self <= CodeUnits.upperF +- } ++ @_transparent ++ var isHexDigit: Bool { ++ isDecimalDigit ++ || CodeUnits.lowerA <= self && self <= CodeUnits.lowerF ++ || CodeUnits.upperA <= self && self <= CodeUnits.upperF ++ } +--- Sources/TOMLDecoder/DateTime.swift ++++ Sources/TOMLDecoder/DateTime.swift +@@ -23,188 +23,183 @@ +- /// The date component of the offset date-time. +- public var date: LocalDate +- /// The time component of the offset date-time. +- public var time: LocalTime +- /// The offset from UTC in minutes, valid range is [-1440, 1440]. +- public var offset: Int16 +- /// Details about the formatting of the date-time string. +- /// For example, whether the 'T' connecting the date and time is lowercase or uppercase. +- /// Or whether 00:00 offset is represented as 'Z' or '+00:00'. +- public var features: Features +- +- /// Create a new offset date-time from it's members. +- /// +- /// This initializer does not validate the components. +- /// Use ``isValid`` to check if the offset date-time is valid. +- /// +- /// - Parameters: +- /// - date: The date component of the offset date-time. +- /// - time: The time component of the offset date-time. +- /// - offset: The offset from UTC in minutes, valid range is [-1440, 1440]. +- /// - features: Details about the formatting of the date-time string. +- public init(date: LocalDate, time: LocalTime, offset: Int16, features: Features) { +- self.date = date +- self.time = time +- self.offset = offset +- self.features = features +- } +- +- public init(from decoder: any Decoder) throws { +- if let decoder = decoder as? _TOMLDecoder { +- self = try decoder.decode(OffsetDateTime.self) +- } else { +- try self.init(from: decoder) +- } +- } +- +- /// Create a new offset date-time from it's members. +- /// +- /// This initializer validates the components. +- /// A invalid component causes a error to be thrown. +- /// +- /// - Parameters: +- /// - date: The date component of the offset date-time. +- /// - time: The time component of the offset date-time. +- /// - offset: The offset from UTC in minutes, valid range is [-1440, 1440]. +- /// - features: Details about the formatting of the date-time string. +- public init(validatingDate date: LocalDate, time: LocalTime, offset: Int16, features: Features) throws(TOMLError) { +- self.init(date: date, time: time, offset: offset, features: features) +- guard date.isValid else { +- throw TOMLError(.invalidDateTimeComponents("Invalid local date: \(date)")) +- } +- guard time.isValid else { +- throw TOMLError(.invalidDateTimeComponents("Invalid local time: \(time)")) +- } +- guard offsetIsValid else { +- throw TOMLError(.invalidDateTimeComponents("Invalid offset: \(offset)")) +- } +- guard featuresAreValid else { +- throw TOMLError(.invalidDateTimeComponents("Invalid features: \(features)")) +- } +- } +- +- /// Check if the offset date-time is valid. +- public var isValid: Bool { +- guard date.isValid, time.isValid, offsetIsValid else { +- return false +- } +- +- return featuresAreValid +- } +- +- private var offsetIsValid: Bool { +- offset >= -1440 && offset <= 1440 +- } +- +- private var featuresAreValid: Bool { +- if features.contains(.lowercaseZ) || features.contains(.uppercaseZ) { +- return offset == 0 +- } +- +- return true +- } +- +- /// Number of seconds since 2001-01-01T00:00:00Z according to the proleptic Gregorian calendar. +- /// +- /// > Important: This is similar to `Foundation.Date.timeIntervalSinceReferenceDate`. +- /// But for ancient dates, this result may disagree with `Foundation.Date` on how much time has passed. +- /// this is because Foundation's Gregorian calendar follows the Julian calendar up to 1582-10-04, +- /// then the Gregorian calendar after that. According to the TOML specification, +- /// an offset date-time should follow the proleptic Gregorian calendar, +- /// which extends the Gregorian calendar backwards to year 1. +- public var timeIntervalSince2001: Double { +- timeIntervalSince1970 - 978_307_200 +- } +- +- /// Number of seconds since 1970-01-01T00:00:00Z according to the proleptic Gregorian calendar. +- /// +- /// > Important: This is similar to `Foundation.Date.timeIntervalSinceReferenceDate`. +- /// But for ancient dates, this result may disagree with `Foundation.Date` on how much time has passed. +- /// this is because Foundation's Gregorian calendar follows the Julian calendar up to 1582-10-04, +- /// then the Gregorian calendar after that. According to the TOML specification, +- /// an offset date-time should follow the proleptic Gregorian calendar, +- /// which extends the Gregorian calendar backwards to year 1. +- public var timeIntervalSince1970: Double { +- let year = Int64(date.year) +- let month = Int64(date.month) +- let day = Int64(date.day) +- let hour = Int64(time.hour) +- let minute = Int64(time.minute) +- let second = Int64(time.second) +- let nanosecond = Int64(time.nanosecond) +- let offsetInSeconds = Int64(offset) * 60 +- +- var y = year +- if month <= 2 { y -= 1 } +- +- let era = (y >= 0 ? y : y - 399) / 400 +- let yoe = y - era * 400 +- let doy = (153 * (month + (month > 2 ? -3 : 9)) + 2) / 5 + day - 1 +- let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy +- let epochOffset = Int64(719_468) +- let dayCounts = era * 146_097 + doe - epochOffset +- let secondOfDay = hour * 3600 + minute * 60 + second +- let totalSeconds = dayCounts * 86400 + secondOfDay - offsetInSeconds +- +- return Double(totalSeconds) + Double(nanosecond) / 1_000_000_000 +- } +- +- /// The string representation of the offset date-time. +- /// +- /// If a value has precision up to 1 nanosecond, +- /// and it does not require superfluous trailing zeros in its fraction seconds, +- /// this value can be recreated exactly. +- public var description: String { +- let dateString = date.description +- let timeString = time.description +- let separator = if features.contains(.lowercaseT) { +- "t" +- } else if features.contains(.uppercaseT) { +- "T" +- } else { +- " " +- } +- +- if features.contains(.lowercaseZ) { +- return "\(dateString)\(separator)\(timeString)z" +- } else if features.contains(.uppercaseZ) { +- return "\(dateString)\(separator)\(timeString)Z" +- } else { +- let sign = offset >= 0 ? "+" : "-" +- let absOffset = abs(offset) +- let hours = absOffset / 60 +- let minutes = absOffset % 60 +- let hoursStr = hours < 10 ? "0\(hours)" : "\(hours)" +- let minutesStr = minutes < 10 ? "0\(minutes)" : "\(minutes)" +- return "\(dateString)\(separator)\(timeString)\(sign)\(hoursStr):\(minutesStr)" +- } +- } +- +- /// Presentation details for string representation of the offset date-time. +- /// +- /// A parser can preserve features of a offset date-time string with this type. +- /// If neither lowercase nor uppercase 'T' is present, the date-time seprator is a space, which is allowed by TOML. +- public struct Features: OptionSet, Hashable, Sendable, Codable { +- /// The raw value of the features. +- public let rawValue: UInt8 +- +- /// Create a new features from it's raw value. +- public init(rawValue: UInt8) { +- self.rawValue = rawValue +- } +- +- /// Indicates the date-time seprator is a lowercase 't'. +- public static let lowercaseT = Features(rawValue: 1 << 1) +- +- /// Indicates the date-time seprator is a uppercase 'T'. +- public static let uppercaseT = Features(rawValue: 1 << 2) +- +- /// Indicates the offset is represented as a lowercase 'z'. +- /// This should not be present if the offset is non-zero, +- /// or if it's +00:00. +- public static let lowercaseZ = Features(rawValue: 1 << 3) +- +- /// Indicates the offset is represented as a uppercase 'Z'. +- /// This should not be present if the offset is non-zero, +- /// or if it's +00:00. +- public static let uppercaseZ = Features(rawValue: 1 << 4) +- } ++ /// The date component of the offset date-time. ++ public var date: LocalDate ++ /// The time component of the offset date-time. ++ public var time: LocalTime ++ /// The offset from UTC in minutes, valid range is [-1440, 1440]. ++ public var offset: Int16 ++ /// Details about the formatting of the date-time string. ++ /// For example, whether the 'T' connecting the date and time is lowercase or uppercase. ++ /// Or whether 00:00 offset is represented as 'Z' or '+00:00'. ++ public var features: Features ++ ++ /// Create a new offset date-time from it's members. ++ /// ++ /// This initializer does not validate the components. ++ /// Use ``isValid`` to check if the offset date-time is valid. ++ /// ++ /// - Parameters: ++ /// - date: The date component of the offset date-time. ++ /// - time: The time component of the offset date-time. ++ /// - offset: The offset from UTC in minutes, valid range is [-1440, 1440]. ++ /// - features: Details about the formatting of the date-time string. ++ public init(date: LocalDate, time: LocalTime, offset: Int16, features: Features) { ++ self.date = date ++ self.time = time ++ self.offset = offset ++ self.features = features ++ } ++ ++ /// Create a new offset date-time from it's members. ++ /// ++ /// This initializer validates the components. ++ /// A invalid component causes a error to be thrown. ++ /// ++ /// - Parameters: ++ /// - date: The date component of the offset date-time. ++ /// - time: The time component of the offset date-time. ++ /// - offset: The offset from UTC in minutes, valid range is [-1440, 1440]. ++ /// - features: Details about the formatting of the date-time string. ++ public init(validatingDate date: LocalDate, time: LocalTime, offset: Int16, features: Features) ++ throws ++ { ++ self.init(date: date, time: time, offset: offset, features: features) ++ guard date.isValid else { ++ throw TOMLError(.invalidDateTimeComponents("Invalid local date: \(date)")) ++ } ++ guard time.isValid else { ++ throw TOMLError(.invalidDateTimeComponents("Invalid local time: \(time)")) ++ } ++ guard offsetIsValid else { ++ throw TOMLError(.invalidDateTimeComponents("Invalid offset: \(offset)")) ++ } ++ guard featuresAreValid else { ++ throw TOMLError(.invalidDateTimeComponents("Invalid features: \(features)")) ++ } ++ } ++ ++ /// Check if the offset date-time is valid. ++ public var isValid: Bool { ++ guard date.isValid, time.isValid, offsetIsValid else { ++ return false ++ } ++ ++ return featuresAreValid ++ } ++ ++ private var offsetIsValid: Bool { ++ offset >= -1440 && offset <= 1440 ++ } ++ ++ private var featuresAreValid: Bool { ++ if features.contains(.lowercaseZ) || features.contains(.uppercaseZ) { ++ return offset == 0 ++ } ++ ++ return true ++ } ++ ++ /// Number of seconds since 2001-01-01T00:00:00Z according to the proleptic Gregorian calendar. ++ /// ++ /// > Important: This is similar to `Foundation.Date.timeIntervalSinceReferenceDate`. ++ /// But for ancient dates, this result may disagree with `Foundation.Date` on how much time has passed. ++ /// this is because Foundation's Gregorian calendar follows the Julian calendar up to 1582-10-04, ++ /// then the Gregorian calendar after that. According to the TOML specification, ++ /// an offset date-time should follow the proleptic Gregorian calendar, ++ /// which extends the Gregorian calendar backwards to year 1. ++ public var timeIntervalSince2001: Double { ++ timeIntervalSince1970 - 978_307_200 ++ } ++ ++ /// Number of seconds since 1970-01-01T00:00:00Z according to the proleptic Gregorian calendar. ++ /// ++ /// > Important: This is similar to `Foundation.Date.timeIntervalSinceReferenceDate`. ++ /// But for ancient dates, this result may disagree with `Foundation.Date` on how much time has passed. ++ /// this is because Foundation's Gregorian calendar follows the Julian calendar up to 1582-10-04, ++ /// then the Gregorian calendar after that. According to the TOML specification, ++ /// an offset date-time should follow the proleptic Gregorian calendar, ++ /// which extends the Gregorian calendar backwards to year 1. ++ public var timeIntervalSince1970: Double { ++ let year = Int64(date.year) ++ let month = Int64(date.month) ++ let day = Int64(date.day) ++ let hour = Int64(time.hour) ++ let minute = Int64(time.minute) ++ let second = Int64(time.second) ++ let nanosecond = Int64(time.nanosecond) ++ let offsetInSeconds = Int64(offset) * 60 ++ ++ var y = year ++ if month <= 2 { y -= 1 } ++ ++ let era = (y >= 0 ? y : y - 399) / 400 ++ let yoe = y - era * 400 ++ let doy = (153 * (month + (month > 2 ? -3 : 9)) + 2) / 5 + day - 1 ++ let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy ++ let epochOffset = Int64(719_468) ++ let dayCounts = era * 146_097 + doe - epochOffset ++ let secondOfDay = hour * 3600 + minute * 60 + second ++ let totalSeconds = dayCounts * 86400 + secondOfDay - offsetInSeconds ++ ++ return Double(totalSeconds) + Double(nanosecond) / 1_000_000_000 ++ } ++ ++ /// The string representation of the offset date-time. ++ /// ++ /// If a value has precision up to 1 nanosecond, ++ /// and it does not require superfluous trailing zeros in its fraction seconds, ++ /// this value can be recreated exactly. ++ public var description: String { ++ let dateString = date.description ++ let timeString = time.description ++ let separator = ++ if features.contains(.lowercaseT) { ++ "t" ++ } else if features.contains(.uppercaseT) { ++ "T" ++ } else { ++ " " ++ } ++ ++ if features.contains(.lowercaseZ) { ++ return "\(dateString)\(separator)\(timeString)z" ++ } else if features.contains(.uppercaseZ) { ++ return "\(dateString)\(separator)\(timeString)Z" ++ } else { ++ let sign = offset >= 0 ? "+" : "-" ++ let absOffset = abs(offset) ++ let hours = absOffset / 60 ++ let minutes = absOffset % 60 ++ let hoursStr = hours < 10 ? "0\(hours)" : "\(hours)" ++ let minutesStr = minutes < 10 ? "0\(minutes)" : "\(minutes)" ++ return "\(dateString)\(separator)\(timeString)\(sign)\(hoursStr):\(minutesStr)" ++ } ++ } ++ ++ /// Presentation details for string representation of the offset date-time. ++ /// ++ /// A parser can preserve features of a offset date-time string with this type. ++ /// If neither lowercase nor uppercase 'T' is present, the date-time seprator is a space, which is allowed by TOML. ++ public struct Features: OptionSet, Hashable, Sendable, Codable { ++ /// The raw value of the features. ++ public let rawValue: UInt8 ++ ++ /// Create a new features from it's raw value. ++ public init(rawValue: UInt8) { ++ self.rawValue = rawValue ++ } ++ ++ /// Indicates the date-time seprator is a lowercase 't'. ++ public static let lowercaseT = Features(rawValue: 1 << 1) ++ ++ /// Indicates the date-time seprator is a uppercase 'T'. ++ public static let uppercaseT = Features(rawValue: 1 << 2) ++ ++ /// Indicates the offset is represented as a lowercase 'z'. ++ /// This should not be present if the offset is non-zero, ++ /// or if it's +00:00. ++ public static let lowercaseZ = Features(rawValue: 1 << 3) ++ ++ /// Indicates the offset is represented as a uppercase 'Z'. ++ /// This should not be present if the offset is non-zero, ++ /// or if it's +00:00. ++ public static let uppercaseZ = Features(rawValue: 1 << 4) ++ } +@@ -217,52 +212,44 @@ +- /// The date component of the local date-time. +- public var date: LocalDate +- /// The time component of the local date-time. +- public var time: LocalTime +- +- /// Create a new local date-time from it's members. +- /// +- /// This initializer does not validate the components. +- /// Use ``isValid`` to check if the local date-time is valid. +- /// - Parameters: +- /// - date: The date component of the local date-time. +- /// - time: The time component of the local date-time. +- public init(date: LocalDate, time: LocalTime) { +- self.date = date +- self.time = time +- } +- +- public init(from decoder: any Decoder) throws { +- if let decoder = decoder as? _TOMLDecoder { +- self = try decoder.decode(LocalDateTime.self) +- } else { +- try self.init(from: decoder) +- } +- } +- +- /// Create a new local date-time from it's members. +- /// +- /// This initializer validates the components. +- /// A invalid component causes a error to be thrown. +- /// +- /// - Parameters: +- /// - date: The date component of the local date-time. +- /// - time: The time component of the local date-time. +- public init(validatingDate date: LocalDate, time: LocalTime) throws(TOMLError) { +- self.init(date: date, time: time) +- guard date.isValid else { +- throw TOMLError(.invalidDateTimeComponents("Invalid local date: \(date)")) +- } +- guard time.isValid else { +- throw TOMLError(.invalidDateTimeComponents("Invalid local time: \(time)")) +- } +- } +- +- /// Check if the local date-time is valid. +- public var isValid: Bool { +- date.isValid && time.isValid +- } +- +- /// The string representation of the local date-time. +- public var description: String { +- "\(date.description)T\(time.description)" +- } ++ /// The date component of the local date-time. ++ public var date: LocalDate ++ /// The time component of the local date-time. ++ public var time: LocalTime ++ ++ /// Create a new local date-time from it's members. ++ /// ++ /// This initializer does not validate the components. ++ /// Use ``isValid`` to check if the local date-time is valid. ++ /// - Parameters: ++ /// - date: The date component of the local date-time. ++ /// - time: The time component of the local date-time. ++ public init(date: LocalDate, time: LocalTime) { ++ self.date = date ++ self.time = time ++ } ++ ++ /// Create a new local date-time from it's members. ++ /// ++ /// This initializer validates the components. ++ /// A invalid component causes a error to be thrown. ++ /// ++ /// - Parameters: ++ /// - date: The date component of the local date-time. ++ /// - time: The time component of the local date-time. ++ public init(validatingDate date: LocalDate, time: LocalTime) throws { ++ self.init(date: date, time: time) ++ guard date.isValid else { ++ throw TOMLError(.invalidDateTimeComponents("Invalid local date: \(date)")) ++ } ++ guard time.isValid else { ++ throw TOMLError(.invalidDateTimeComponents("Invalid local time: \(time)")) ++ } ++ } ++ ++ /// Check if the local date-time is valid. ++ public var isValid: Bool { ++ date.isValid && time.isValid ++ } ++ ++ /// The string representation of the local date-time. ++ public var description: String { ++ "\(date.description)T\(time.description)" ++ } +@@ -275,63 +262,67 @@ +- /// The hour component of the local time. +- public var hour: UInt8 +- /// The minute component of the local time. +- public var minute: UInt8 +- /// The second component of the local time. +- public var second: UInt8 +- /// The fractional second component of the local time in nanoseconds. +- public var nanosecond: UInt32 +- +- /// Create a new local time from it's members. +- /// +- /// This initializer validates the components. +- /// A invalid component causes a error to be thrown. +- /// +- /// - Parameters: +- /// - hour: The hour component of the local time. +- /// - minute: The minute component of the local time. +- /// - second: The second component of the local time. +- /// - nanosecond: The fractional second component of the local time in nanoseconds. +- public init(validatingHour hour: UInt8, minute: UInt8, second: UInt8, nanosecond: UInt32 = 0) throws(TOMLError) { +- self.init(hour: hour, minute: minute, second: second, nanosecond: nanosecond) +- guard isValid else { +- throw TOMLError(.invalidDateTimeComponents("Invalid local time components: \(hour):\(minute):\(second).\(nanosecond)")) +- } +- } +- +- /// Create a new local time from it's members. +- /// +- /// This initializer does not validate the components. +- /// Use ``isValid`` to check if the local time is valid. +- /// +- /// - Parameters: +- /// - hour: The hour component of the local time. +- /// - minute: The minute component of the local time. +- /// - second: The second component of the local time. +- /// - nanosecond: The fractional second component of the local time in nanoseconds. +- public init(hour: UInt8, minute: UInt8, second: UInt8, nanosecond: UInt32 = 0) { +- self.hour = hour +- self.minute = minute +- self.second = second +- self.nanosecond = nanosecond +- } +- +- /// Check if the local time is valid. +- public var isValid: Bool { +- hour < 24 && minute < 60 && second < 60 && nanosecond < 1_000_000_000 +- } +- +- /// The string representation of the local time. +- public var description: String { +- let hourStr = hour < 10 ? "0\(hour)" : "\(hour)" +- let minuteStr = minute < 10 ? "0\(minute)" : "\(minute)" +- let secondStr = second < 10 ? "0\(second)" : "\(second)" +- +- if nanosecond == 0 { +- return "\(hourStr):\(minuteStr):\(secondStr)" +- } else { +- let nanosecondStr = String(nanosecond).padded(to: 9, with: "0") +- let trimmedFractional = nanosecondStr.trimmingSuffix("0") +- let finalFractional = trimmedFractional.isEmpty ? "0" : trimmedFractional +- return "\(hourStr):\(minuteStr):\(secondStr).\(finalFractional)" +- } +- } ++ /// The hour component of the local time. ++ public var hour: UInt8 ++ /// The minute component of the local time. ++ public var minute: UInt8 ++ /// The second component of the local time. ++ public var second: UInt8 ++ /// The fractional second component of the local time in nanoseconds. ++ public var nanosecond: UInt32 ++ ++ /// Create a new local time from it's members. ++ /// ++ /// This initializer validates the components. ++ /// A invalid component causes a error to be thrown. ++ /// ++ /// - Parameters: ++ /// - hour: The hour component of the local time. ++ /// - minute: The minute component of the local time. ++ /// - second: The second component of the local time. ++ /// - nanosecond: The fractional second component of the local time in nanoseconds. ++ public init(validatingHour hour: UInt8, minute: UInt8, second: UInt8, nanosecond: UInt32 = 0) ++ throws ++ { ++ self.init(hour: hour, minute: minute, second: second, nanosecond: nanosecond) ++ guard isValid else { ++ throw TOMLError( ++ .invalidDateTimeComponents( ++ "Invalid local time components: \(hour):\(minute):\(second).\(nanosecond)")) ++ } ++ } ++ ++ /// Create a new local time from it's members. ++ /// ++ /// This initializer does not validate the components. ++ /// Use ``isValid`` to check if the local time is valid. ++ /// ++ /// - Parameters: ++ /// - hour: The hour component of the local time. ++ /// - minute: The minute component of the local time. ++ /// - second: The second component of the local time. ++ /// - nanosecond: The fractional second component of the local time in nanoseconds. ++ public init(hour: UInt8, minute: UInt8, second: UInt8, nanosecond: UInt32 = 0) { ++ self.hour = hour ++ self.minute = minute ++ self.second = second ++ self.nanosecond = nanosecond ++ } ++ ++ /// Check if the local time is valid. ++ public var isValid: Bool { ++ hour < 24 && minute < 60 && second < 60 && nanosecond < 1_000_000_000 ++ } ++ ++ /// The string representation of the local time. ++ public var description: String { ++ let hourStr = hour < 10 ? "0\(hour)" : "\(hour)" ++ let minuteStr = minute < 10 ? "0\(minute)" : "\(minute)" ++ let secondStr = second < 10 ? "0\(second)" : "\(second)" ++ ++ if nanosecond == 0 { ++ return "\(hourStr):\(minuteStr):\(secondStr)" ++ } else { ++ let nanosecondStr = String(nanosecond).padded(to: 9, with: "0") ++ let trimmedFractional = nanosecondStr.trimmingSuffix("0") ++ let finalFractional = trimmedFractional.isEmpty ? "0" : trimmedFractional ++ return "\(hourStr):\(minuteStr):\(secondStr).\(finalFractional)" ++ } ++ } +@@ -344,71 +335,72 @@ +- /// The year component of the local date. +- /// Valid range is [1, 9999]. +- public var year: UInt16 +- +- /// The month component of the local date. +- /// Valid range is [1, 12]. +- public var month: UInt8 +- +- /// The day component of the local date. +- /// Valid range is depends on the month and year. +- public var day: UInt8 +- +- /// Create a new local date from it's members. +- /// +- /// This initializer validates the components. +- /// A invalid component causes a error to be thrown. +- /// +- /// - Parameters: +- /// - year: The year component of the local date. +- /// - month: The month component of the local date. +- /// - day: The day component of the local date. +- public init(validatingYear year: UInt16, month: UInt8, day: UInt8) throws(TOMLError) { +- self.init(year: year, month: month, day: day) +- guard isValid else { +- throw TOMLError(.invalidDateTimeComponents("Invalid local date components: \(year)-\(month)-\(day)")) +- } +- } +- +- /// Create a new local date from it's members. +- /// +- /// This initializer does not validate the components. +- /// Use ``isValid`` to check if the local date is valid. +- /// +- /// - Parameters: +- /// - year: The year component of the local date. +- /// - month: The month component of the local date. +- /// - day: The day component of the local date. +- public init(year: UInt16, month: UInt8, day: UInt8) { +- self.year = year +- self.month = month +- self.day = day +- } +- +- /// Check if the local date is valid. +- public var isValid: Bool { +- guard month >= 1, month <= 12 else { return false } +- guard day >= 1 else { return false } +- +- let daysInMonth: UInt8 +- switch month { +- case 1, 3, 5, 7, 8, 10, 12: +- daysInMonth = 31 +- case 4, 6, 9, 11: +- daysInMonth = 30 +- case 2: +- let isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) +- daysInMonth = isLeapYear ? 29 : 28 +- default: +- return false +- } +- +- return day <= daysInMonth +- } +- +- /// The string representation of the local date. +- public var description: String { +- let yearStr = String(year).padded(to: 4, with: "0") +- let monthStr = month < 10 ? "0\(month)" : "\(month)" +- let dayStr = day < 10 ? "0\(day)" : "\(day)" +- return "\(yearStr)-\(monthStr)-\(dayStr)" +- } ++ /// The year component of the local date. ++ /// Valid range is [1, 9999]. ++ public var year: UInt16 ++ ++ /// The month component of the local date. ++ /// Valid range is [1, 12]. ++ public var month: UInt8 ++ ++ /// The day component of the local date. ++ /// Valid range is depends on the month and year. ++ public var day: UInt8 ++ ++ /// Create a new local date from it's members. ++ /// ++ /// This initializer validates the components. ++ /// A invalid component causes a error to be thrown. ++ /// ++ /// - Parameters: ++ /// - year: The year component of the local date. ++ /// - month: The month component of the local date. ++ /// - day: The day component of the local date. ++ public init(validatingYear year: UInt16, month: UInt8, day: UInt8) throws { ++ self.init(year: year, month: month, day: day) ++ guard isValid else { ++ throw TOMLError( ++ .invalidDateTimeComponents("Invalid local date components: \(year)-\(month)-\(day)")) ++ } ++ } ++ ++ /// Create a new local date from it's members. ++ /// ++ /// This initializer does not validate the components. ++ /// Use ``isValid`` to check if the local date is valid. ++ /// ++ /// - Parameters: ++ /// - year: The year component of the local date. ++ /// - month: The month component of the local date. ++ /// - day: The day component of the local date. ++ public init(year: UInt16, month: UInt8, day: UInt8) { ++ self.year = year ++ self.month = month ++ self.day = day ++ } ++ ++ /// Check if the local date is valid. ++ public var isValid: Bool { ++ guard month >= 1, month <= 12 else { return false } ++ guard day >= 1 else { return false } ++ ++ let daysInMonth: UInt8 ++ switch month { ++ case 1, 3, 5, 7, 8, 10, 12: ++ daysInMonth = 31 ++ case 4, 6, 9, 11: ++ daysInMonth = 30 ++ case 2: ++ let isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) ++ daysInMonth = isLeapYear ? 29 : 28 ++ default: ++ return false ++ } ++ ++ return day <= daysInMonth ++ } ++ ++ /// The string representation of the local date. ++ public var description: String { ++ let yearStr = String(year).padded(to: 4, with: "0") ++ let monthStr = month < 10 ? "0\(month)" : "\(month)" ++ let dayStr = day < 10 ? "0\(day)" : "\(day)" ++ return "\(yearStr)-\(monthStr)-\(dayStr)" ++ } +@@ -418,14 +410,14 @@ +- fileprivate func padded(to length: Int, with character: Character) -> String { +- if count >= length { +- return self +- } +- return String(repeating: character, count: length - count) + self +- } +- +- fileprivate func trimmingSuffix(_ suffix: Character) -> String { +- var result = self +- while result.last == suffix { +- result.removeLast() +- } +- return result +- } ++ fileprivate func padded(to length: Int, with character: Character) -> String { ++ if count >= length { ++ return self ++ } ++ return String(repeating: character, count: length - count) + self ++ } ++ ++ fileprivate func trimmingSuffix(_ suffix: Character) -> String { ++ var result = self ++ while result.last == suffix { ++ result.removeLast() ++ } ++ return result ++ } +@@ -433,49 +424,0 @@ +- +-#if canImport(Foundation) +-public import Foundation +- +-extension DateComponents { +- /// Create a new `Foundation.DateComponents` from an offset date-time. +- /// Only the literal components of a offset date-time will be in the components. +- /// the calendar component, for example, is not set. +- /// +- /// - Parameter offsetDateTime: The offset date-time to convert. +- public init(offsetDateTime: OffsetDateTime) { +- self.init( +- timeZone: TimeZone(secondsFromGMT: Int(offsetDateTime.offset) * 60), +- year: Int(offsetDateTime.date.year), +- month: Int(offsetDateTime.date.month), +- day: Int(offsetDateTime.date.day), +- hour: Int(offsetDateTime.time.hour), +- minute: Int(offsetDateTime.time.minute), +- second: Int(offsetDateTime.time.second), +- nanosecond: Int(offsetDateTime.time.nanosecond) +- ) +- } +-} +- +-extension Date { +- /// Create a new `Foundation.Date` from an offset date-time. +- /// +- /// - Parameter offsetDateTime: The offset date-time to convert. +- /// - Parameter calendar: The calendar based on which the date is constructed. +- /// Defaults to the Gregorian calendar. +- /// Note that Foundation's Gregorian calendar is NOT proleptic. +- /// It follows the Julian calendar up to 1582-10-04, +- /// then the Gregorian calendar after that. +- /// According to the TOML specification, +- /// an offset date-time should follow the proleptic Gregorian calendar, +- /// which extends the Gregorian calendar backwards to year 1. +- /// Therefore, +- /// for ancient dates, +- /// the resulting `Date`'s `.timeIntervalSince1970` or `.timeIntervalSinceReferenceDate` may have a different value as defined in the TOML specification, +- /// which follows RFC 3339. +- /// To get the proleptic Gregorian time interval, +- /// use ``OffsetDateTime/timeIntervalSince2001`` or ``OffsetDateTime/timeIntervalSince1970``. +- public init(offsetDateTime: OffsetDateTime, calendar: Calendar = Calendar(identifier: .gregorian)) { +- var components = DateComponents(offsetDateTime: offsetDateTime) +- components.calendar = calendar +- self = components.date! +- } +-} +-#endif +--- Sources/TOMLDecoder/TOMLKey.swift ++++ Sources/TOMLDecoder/TOMLKey.swift +@@ -2,3 +2,3 @@ +- case string(String) +- case int(Int) +- case `super` ++ case string(String) ++ case int(Int) ++ case `super` +@@ -6,2 +6,16 @@ +- init(stringValue: String) { +- self = .string(stringValue) ++ init(stringValue: String) { ++ self = .string(stringValue) ++ } ++ ++ init(intValue: Int) { ++ self = .int(intValue) ++ } ++ ++ var stringValue: String { ++ switch self { ++ case .string(let string): ++ string ++ case .int(let int): ++ "Index \(int)" ++ case .super: ++ "super" +@@ -8,0 +23 @@ ++ } +@@ -10,2 +25,6 @@ +- init(intValue: Int) { +- self = .int(intValue) ++ var intValue: Int? { ++ switch self { ++ case .int(let int): ++ int ++ default: ++ nil +@@ -13,20 +32 @@ +- +- var stringValue: String { +- switch self { +- case let .string(string): +- string +- case let .int(int): +- "Index \(int)" +- case .super: +- "super" +- } +- } +- +- var intValue: Int? { +- switch self { +- case let .int(int): +- int +- default: +- nil +- } +- } ++ } +--- Sources/TOMLDecoder/TOMLError.swift ++++ Sources/TOMLDecoder/TOMLError.swift +@@ -8 +8 @@ +- let reason: Reason ++ let reason: Reason +@@ -10,3 +10,3 @@ +- init(_ reason: Reason) { +- self.reason = reason +- } ++ init(_ reason: Reason) { ++ self.reason = reason ++ } +@@ -14,27 +14,27 @@ +- enum Reason { +- case arrayOutOfBound(index: Int, bound: Int) +- case badKey(lineNumber: Int) +- case expectedHexCharacters(UTF8.CodeUnit, Int) +- case illegalEscapeCharacter(UTF8.CodeUnit) +- case illegalUCSCode(UInt32) +- case internalError(lineNumber: Int) +- case invalidBool(context: TOMLKey, lineNumber: Int) +- case invalidCharacter(UTF8.CodeUnit) +- case invalidDateTime(lineNumber: Int?, reason: String) +- case invalidDateTime3(context: TOMLKey, lineNumber: Int, reason: String) +- case invalidDateTimeComponents(String) +- case invalidFloat(context: TOMLKey, lineNumber: Int, reason: String) +- case invalidHexCharacters(UTF8.CodeUnit) +- case invalidInteger(context: TOMLKey, lineNumber: Int, reason: String) +- case invalidNumber(reason: String) +- case invalidString(context: TOMLKey, lineNumber: Int, reason: String) +- case invalidUTF8 +- case invalidValueInTable(context: TOMLKey, lineNumber: Int) +- case keyExists(lineNumber: Int) +- case keyNotFoundInTable(key: String, expected: String) +- case notReallyCodable +- case syntax(lineNumber: Int, message: String) +- case typeMismatch(context: TOMLKey, lineNumber: Int, expected: String) +- case typeMismatchInArray(lineNumber: Int, index: Int, expected: String) +- case typeMismatchInTable(key: String, expected: String) +- } ++ enum Reason { ++ case arrayOutOfBound(index: Int, bound: Int) ++ case badKey(lineNumber: Int) ++ case expectedHexCharacters(UTF8.CodeUnit, Int) ++ case illegalEscapeCharacter(UTF8.CodeUnit) ++ case illegalUCSCode(UInt32) ++ case internalError(lineNumber: Int) ++ case invalidBool(context: TOMLKey, lineNumber: Int) ++ case invalidCharacter(UTF8.CodeUnit) ++ case invalidDateTime(lineNumber: Int?, reason: String) ++ case invalidDateTime3(context: TOMLKey, lineNumber: Int, reason: String) ++ case invalidDateTimeComponents(String) ++ case invalidFloat(context: TOMLKey, lineNumber: Int, reason: String) ++ case invalidHexCharacters(UTF8.CodeUnit) ++ case invalidInteger(context: TOMLKey, lineNumber: Int, reason: String) ++ case invalidNumber(reason: String) ++ case invalidString(context: TOMLKey, lineNumber: Int, reason: String) ++ case invalidUTF8 ++ case invalidValueInTable(context: TOMLKey, lineNumber: Int) ++ case keyExists(lineNumber: Int) ++ case keyNotFoundInTable(key: String, expected: String) ++ case notReallyCodable ++ case syntax(lineNumber: Int, message: String) ++ case typeMismatch(context: TOMLKey, lineNumber: Int, expected: String) ++ case typeMismatchInArray(lineNumber: Int, index: Int, expected: String) ++ case typeMismatchInTable(key: String, expected: String) ++ } +@@ -44,102 +44,101 @@ +- public var description: String { +- switch reason { +- case let .arrayOutOfBound(index, bound): +- "Array index \(index) is out of bounds (0..<\(bound))." +- case let .badKey(lineNumber): +- "(Line \(lineNumber)) Ill-formed key." +- case let .expectedHexCharacters(codeUnit, hexCount): +- "Expected \(hexCount) hexadecimal characters after '\(String(UnicodeScalar(codeUnit))).'." +- case let .illegalEscapeCharacter(codeUnit): +- "Illegal escape character '\(String(UnicodeScalar(codeUnit)))'." +- case let .illegalUCSCode(ucs): +- "Illegal UCS code '\(ucs)'." +- case let .internalError(lineNumber): +- "(Line \(lineNumber)) Internal error." +- case let .invalidBool(context, lineNumber): +- switch context { +- case let .string(key): +- "(Line \(lineNumber)) Invalid boolean value for key '\(key)'." +- case let .int(index): +- "(Line \(lineNumber)) Invalid boolean value for index \(index)." +- case .super: +- "(Line \(lineNumber)) Invalid boolean value for 'super'." +- } +- case let .invalidCharacter(codeUnit): +- "Invalid character '\(String(UnicodeScalar(codeUnit)))'." +- case let .invalidDateTime(lineNumber, reason): +- "\(lineNumber.map { "(Line \($0)) " } ?? "")Invalid date-time: \(reason)." +- case let .invalidDateTime3(context, lineNumber, reason): +- switch context { +- case let .string(key): +- "(Line \(lineNumber)) Invalid date-time value for key '\(key)': \(reason)." +- case let .int(index): +- "(Line \(lineNumber)) Invalid date-time value for index \(index)': \(reason)." +- case .super: +- "(Line \(lineNumber)) Invalid date-time value for 'super': \(reason)." +- } +- case let .invalidDateTimeComponents(components): +- "Invalid date-time components: \(components)." +- case let .invalidFloat(context, lineNumber, reason): +- switch context { +- case let .string(key): +- "(Line \(lineNumber)) Invalid float value for key '\(key)': \(reason)." +- case let .int(index): +- "(Line \(lineNumber)) Invalid float value for index \(index)': \(reason)." +- case .super: +- "(Line \(lineNumber)) Invalid float value for 'super': \(reason)." +- } +- case let .invalidHexCharacters(codeUnit): +- "Invalid hexadecimal characters '\(String(UnicodeScalar(codeUnit)))'." +- case let .invalidInteger(context, lineNumber, reason): +- switch context { +- case let .string(key): +- "(Line \(lineNumber)) Invalid integer value for key '\(key)': \(reason)." +- case let .int(index): +- "(Line \(lineNumber)) Invalid integer value for index \(index)': \(reason)." +- case .super: +- "(Line \(lineNumber)) Invalid integer value for 'super': \(reason)." +- } +- case let .invalidNumber(reason): +- "Invalid number: \(reason)." +- case let .invalidString(context, lineNumber, reason): +- switch context { +- case let .string(key): +- "(Line \(lineNumber)) Invalid string value for key '\(key)': \(reason)." +- case let .int(index): +- "(Line \(lineNumber)) Invalid string value for index \(index)': \(reason)." +- case .super: +- "(Line \(lineNumber)) Invalid string value for 'super': \(reason)." +- } +- case .invalidUTF8: +- "The given data was not valid UTF8." +- case let .invalidValueInTable(context, lineNumber): +- switch context { +- case let .string(key): +- "(Line \(lineNumber)) Invalid value in table for key '\(key)'." +- case let .int(index): +- "(Line \(lineNumber)) Invalid value in table for index \(index)." +- case .super: +- "(Line \(lineNumber)) Invalid value in table for 'super'." +- } +- case let .keyExists(lineNumber): +- "(Line \(lineNumber)) Key already exists." +- case let .keyNotFoundInTable(key, expected): +- "Key '\(key)' not found in table while looking for \(expected)." +- case .notReallyCodable: +- "This type is not generally codable. Use TOMLDecoder to decode it as part of a larger Codable." +- case let .syntax(lineNumber, message): +- "(Line \(lineNumber)) Syntax error: \(message)." +- case let .typeMismatch(context, lineNumber, expected): +- switch context { +- case let .string(key): +- "(Line \(lineNumber)) Type mismatch at table key '\(key)': expected \(expected)." +- case let .int(index): +- "(Line \(lineNumber)) Type mismatch at array index \(index): expected \(expected)." +- case .super: +- "(Line \(lineNumber)) Type mismatch at 'super': expected \(expected)." +- } +- case let .typeMismatchInArray(lineNumber, index, expected): +- "(Line \(lineNumber)) Type mismatch at array index \(index): expected \(expected)." +- case let .typeMismatchInTable(key, expected): +- "Type mismatch at table key '\(key)': expected \(expected)." +- } ++ public var description: String { ++ switch reason { ++ case .arrayOutOfBound(let index, let bound): ++ "Array index \(index) is out of bounds (0..<\(bound))." ++ case .badKey(let lineNumber): ++ "(Line \(lineNumber)) Ill-formed key." ++ case .expectedHexCharacters(let codeUnit, let hexCount): ++ "Expected \(hexCount) hexadecimal characters after '\(String(UnicodeScalar(codeUnit))).'." ++ case .illegalEscapeCharacter(let codeUnit): ++ "Illegal escape character '\(String(UnicodeScalar(codeUnit)))'." ++ case .illegalUCSCode(let ucs): ++ "Illegal UCS code '\(ucs)'." ++ case .internalError(let lineNumber): ++ "(Line \(lineNumber)) Internal error." ++ case .invalidBool(let context, let lineNumber): ++ switch context { ++ case .string(let key): ++ "(Line \(lineNumber)) Invalid boolean value for key '\(key)'." ++ case .int(let index): ++ "(Line \(lineNumber)) Invalid boolean value for index \(index)." ++ case .super: ++ "(Line \(lineNumber)) Invalid boolean value for 'super'." ++ } ++ case .invalidCharacter(let codeUnit): ++ "Invalid character '\(String(UnicodeScalar(codeUnit)))'." ++ case .invalidDateTime(let lineNumber, let reason): ++ "\(lineNumber.map { "(Line \($0)) " } ?? "")Invalid date-time: \(reason)." ++ case .invalidDateTime3(let context, let lineNumber, let reason): ++ switch context { ++ case .string(let key): ++ "(Line \(lineNumber)) Invalid date-time value for key '\(key)': \(reason)." ++ case .int(let index): ++ "(Line \(lineNumber)) Invalid date-time value for index \(index)': \(reason)." ++ case .super: ++ "(Line \(lineNumber)) Invalid date-time value for 'super': \(reason)." ++ } ++ case .invalidDateTimeComponents(let components): ++ "Invalid date-time components: \(components)." ++ case .invalidFloat(let context, let lineNumber, let reason): ++ switch context { ++ case .string(let key): ++ "(Line \(lineNumber)) Invalid float value for key '\(key)': \(reason)." ++ case .int(let index): ++ "(Line \(lineNumber)) Invalid float value for index \(index)': \(reason)." ++ case .super: ++ "(Line \(lineNumber)) Invalid float value for 'super': \(reason)." ++ } ++ case .invalidHexCharacters(let codeUnit): ++ "Invalid hexadecimal characters '\(String(UnicodeScalar(codeUnit)))'." ++ case .invalidInteger(let context, let lineNumber, let reason): ++ switch context { ++ case .string(let key): ++ "(Line \(lineNumber)) Invalid integer value for key '\(key)': \(reason)." ++ case .int(let index): ++ "(Line \(lineNumber)) Invalid integer value for index \(index)': \(reason)." ++ case .super: ++ "(Line \(lineNumber)) Invalid integer value for 'super': \(reason)." ++ } ++ case .invalidNumber(let reason): ++ "Invalid number: \(reason)." ++ case .invalidString(let context, let lineNumber, let reason): ++ switch context { ++ case .string(let key): ++ "(Line \(lineNumber)) Invalid string value for key '\(key)': \(reason)." ++ case .int(let index): ++ "(Line \(lineNumber)) Invalid string value for index \(index)': \(reason)." ++ case .super: ++ "(Line \(lineNumber)) Invalid string value for 'super': \(reason)." ++ } ++ case .invalidUTF8: ++ "The given data was not valid UTF8." ++ case .invalidValueInTable(let context, let lineNumber): ++ switch context { ++ case .string(let key): ++ "(Line \(lineNumber)) Invalid value in table for key '\(key)'." ++ case .int(let index): ++ "(Line \(lineNumber)) Invalid value in table for index \(index)." ++ case .super: ++ "(Line \(lineNumber)) Invalid value in table for 'super'." ++ } ++ case .keyExists(let lineNumber): ++ "(Line \(lineNumber)) Key already exists." ++ case .keyNotFoundInTable(let key, let expected): ++ "Key '\(key)' not found in table while looking for \(expected)." ++ case .notReallyCodable: ++ "This type is not generally codable. Use TOMLDecoder to decode it as part of a larger Codable." ++ case .syntax(let lineNumber, let message): ++ "(Line \(lineNumber)) Syntax error: \(message)." ++ case .typeMismatch(let context, let lineNumber, let expected): ++ switch context { ++ case .string(let key): ++ "(Line \(lineNumber)) Type mismatch at table key '\(key)': expected \(expected)." ++ case .int(let index): ++ "(Line \(lineNumber)) Type mismatch at array index \(index): expected \(expected)." ++ case .super: ++ "(Line \(lineNumber)) Type mismatch at 'super': expected \(expected)." ++ } ++ case .typeMismatchInArray(let lineNumber, let index, let expected): ++ "(Line \(lineNumber)) Type mismatch at array index \(index): expected \(expected)." ++ case .typeMismatchInTable(let key, let expected): ++ "Type mismatch at table key '\(key)': expected \(expected)." +@@ -146,0 +146 @@ ++ } diff --git a/Sources/TreeSitterTOML/LICENSE b/Sources/TreeSitterTOML/LICENSE new file mode 100644 index 0000000..7bf071b --- /dev/null +++ b/Sources/TreeSitterTOML/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Ika (https://github.com/ikatyang) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Sources/TreeSitterTOML/include/toml.h b/Sources/TreeSitterTOML/include/toml.h new file mode 100644 index 0000000..85a2e7c --- /dev/null +++ b/Sources/TreeSitterTOML/include/toml.h @@ -0,0 +1,16 @@ +#ifndef TREE_SITTER_TOML_H_ +#define TREE_SITTER_TOML_H_ + +typedef struct TSLanguage TSLanguage; + +#ifdef __cplusplus +extern "C" { +#endif + +const TSLanguage *tree_sitter_toml(void); + +#ifdef __cplusplus +} +#endif + +#endif // TREE_SITTER_TOML_H_ diff --git a/Sources/TreeSitterTOML/parser.c b/Sources/TreeSitterTOML/parser.c new file mode 100644 index 0000000..1cfc62b --- /dev/null +++ b/Sources/TreeSitterTOML/parser.c @@ -0,0 +1,4739 @@ +#include "tree_sitter/parser.h" + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic ignored "-Wmissing-field-initializers" +#endif + +#define LANGUAGE_VERSION 14 +#define STATE_COUNT 152 +#define LARGE_STATE_COUNT 2 +#define SYMBOL_COUNT 66 +#define ALIAS_COUNT 0 +#define TOKEN_COUNT 40 +#define EXTERNAL_TOKEN_COUNT 5 +#define FIELD_COUNT 0 +#define MAX_ALIAS_SEQUENCE_LENGTH 8 +#define PRODUCTION_ID_COUNT 2 + +enum ts_symbol_identifiers { + aux_sym_document_token1 = 1, + sym_comment = 2, + anon_sym_LBRACK = 3, + anon_sym_RBRACK = 4, + anon_sym_LBRACK_LBRACK = 5, + anon_sym_RBRACK_RBRACK = 6, + anon_sym_EQ = 7, + anon_sym_DOT = 8, + sym_bare_key = 9, + anon_sym_DQUOTE = 10, + aux_sym__basic_string_token1 = 11, + anon_sym_DQUOTE2 = 12, + anon_sym_DQUOTE_DQUOTE_DQUOTE = 13, + aux_sym__multiline_basic_string_token1 = 14, + sym_escape_sequence = 15, + sym__escape_line_ending = 16, + anon_sym_SQUOTE = 17, + aux_sym__literal_string_token1 = 18, + anon_sym_SQUOTE2 = 19, + anon_sym_SQUOTE_SQUOTE_SQUOTE = 20, + aux_sym_integer_token1 = 21, + aux_sym_integer_token2 = 22, + aux_sym_integer_token3 = 23, + aux_sym_integer_token4 = 24, + aux_sym_float_token1 = 25, + aux_sym_float_token2 = 26, + sym_boolean = 27, + sym_offset_date_time = 28, + sym_local_date_time = 29, + sym_local_date = 30, + sym_local_time = 31, + anon_sym_COMMA = 32, + anon_sym_LBRACE = 33, + anon_sym_RBRACE = 34, + sym__line_ending_or_eof = 35, + sym__multiline_basic_string_content = 36, + sym__multiline_basic_string_end = 37, + sym__multiline_literal_string_content = 38, + sym__multiline_literal_string_end = 39, + sym_document = 40, + sym_table = 41, + sym_table_array_element = 42, + sym_pair = 43, + sym__inline_pair = 44, + sym__key = 45, + sym_dotted_key = 46, + sym_quoted_key = 47, + sym__inline_value = 48, + sym_string = 49, + sym__basic_string = 50, + sym__multiline_basic_string = 51, + sym__literal_string = 52, + sym__multiline_literal_string = 53, + sym_integer = 54, + sym_float = 55, + sym_array = 56, + sym_inline_table = 57, + aux_sym_document_repeat1 = 58, + aux_sym_document_repeat2 = 59, + aux_sym__basic_string_repeat1 = 60, + aux_sym__multiline_basic_string_repeat1 = 61, + aux_sym__multiline_literal_string_repeat1 = 62, + aux_sym_array_repeat1 = 63, + aux_sym_array_repeat2 = 64, + aux_sym_inline_table_repeat1 = 65, +}; + +static const char * const ts_symbol_names[] = { + [ts_builtin_sym_end] = "end", + [aux_sym_document_token1] = "document_token1", + [sym_comment] = "comment", + [anon_sym_LBRACK] = "[", + [anon_sym_RBRACK] = "]", + [anon_sym_LBRACK_LBRACK] = "[[", + [anon_sym_RBRACK_RBRACK] = "]]", + [anon_sym_EQ] = "=", + [anon_sym_DOT] = ".", + [sym_bare_key] = "bare_key", + [anon_sym_DQUOTE] = "\"", + [aux_sym__basic_string_token1] = "_basic_string_token1", + [anon_sym_DQUOTE2] = "\"", + [anon_sym_DQUOTE_DQUOTE_DQUOTE] = "\"\"\"", + [aux_sym__multiline_basic_string_token1] = "_multiline_basic_string_token1", + [sym_escape_sequence] = "escape_sequence", + [sym__escape_line_ending] = "escape_sequence", + [anon_sym_SQUOTE] = "'", + [aux_sym__literal_string_token1] = "_literal_string_token1", + [anon_sym_SQUOTE2] = "'", + [anon_sym_SQUOTE_SQUOTE_SQUOTE] = "'''", + [aux_sym_integer_token1] = "integer_token1", + [aux_sym_integer_token2] = "integer_token2", + [aux_sym_integer_token3] = "integer_token3", + [aux_sym_integer_token4] = "integer_token4", + [aux_sym_float_token1] = "float_token1", + [aux_sym_float_token2] = "float_token2", + [sym_boolean] = "boolean", + [sym_offset_date_time] = "offset_date_time", + [sym_local_date_time] = "local_date_time", + [sym_local_date] = "local_date", + [sym_local_time] = "local_time", + [anon_sym_COMMA] = ",", + [anon_sym_LBRACE] = "{", + [anon_sym_RBRACE] = "}", + [sym__line_ending_or_eof] = "_line_ending_or_eof", + [sym__multiline_basic_string_content] = "_multiline_basic_string_content", + [sym__multiline_basic_string_end] = "_multiline_basic_string_end", + [sym__multiline_literal_string_content] = "_multiline_literal_string_content", + [sym__multiline_literal_string_end] = "_multiline_literal_string_end", + [sym_document] = "document", + [sym_table] = "table", + [sym_table_array_element] = "table_array_element", + [sym_pair] = "pair", + [sym__inline_pair] = "_inline_pair", + [sym__key] = "_key", + [sym_dotted_key] = "dotted_key", + [sym_quoted_key] = "quoted_key", + [sym__inline_value] = "_inline_value", + [sym_string] = "string", + [sym__basic_string] = "_basic_string", + [sym__multiline_basic_string] = "_multiline_basic_string", + [sym__literal_string] = "_literal_string", + [sym__multiline_literal_string] = "_multiline_literal_string", + [sym_integer] = "integer", + [sym_float] = "float", + [sym_array] = "array", + [sym_inline_table] = "inline_table", + [aux_sym_document_repeat1] = "document_repeat1", + [aux_sym_document_repeat2] = "document_repeat2", + [aux_sym__basic_string_repeat1] = "_basic_string_repeat1", + [aux_sym__multiline_basic_string_repeat1] = "_multiline_basic_string_repeat1", + [aux_sym__multiline_literal_string_repeat1] = "_multiline_literal_string_repeat1", + [aux_sym_array_repeat1] = "array_repeat1", + [aux_sym_array_repeat2] = "array_repeat2", + [aux_sym_inline_table_repeat1] = "inline_table_repeat1", +}; + +static const TSSymbol ts_symbol_map[] = { + [ts_builtin_sym_end] = ts_builtin_sym_end, + [aux_sym_document_token1] = aux_sym_document_token1, + [sym_comment] = sym_comment, + [anon_sym_LBRACK] = anon_sym_LBRACK, + [anon_sym_RBRACK] = anon_sym_RBRACK, + [anon_sym_LBRACK_LBRACK] = anon_sym_LBRACK_LBRACK, + [anon_sym_RBRACK_RBRACK] = anon_sym_RBRACK_RBRACK, + [anon_sym_EQ] = anon_sym_EQ, + [anon_sym_DOT] = anon_sym_DOT, + [sym_bare_key] = sym_bare_key, + [anon_sym_DQUOTE] = anon_sym_DQUOTE, + [aux_sym__basic_string_token1] = aux_sym__basic_string_token1, + [anon_sym_DQUOTE2] = anon_sym_DQUOTE, + [anon_sym_DQUOTE_DQUOTE_DQUOTE] = anon_sym_DQUOTE_DQUOTE_DQUOTE, + [aux_sym__multiline_basic_string_token1] = aux_sym__multiline_basic_string_token1, + [sym_escape_sequence] = sym_escape_sequence, + [sym__escape_line_ending] = sym_escape_sequence, + [anon_sym_SQUOTE] = anon_sym_SQUOTE, + [aux_sym__literal_string_token1] = aux_sym__literal_string_token1, + [anon_sym_SQUOTE2] = anon_sym_SQUOTE, + [anon_sym_SQUOTE_SQUOTE_SQUOTE] = anon_sym_SQUOTE_SQUOTE_SQUOTE, + [aux_sym_integer_token1] = aux_sym_integer_token1, + [aux_sym_integer_token2] = aux_sym_integer_token2, + [aux_sym_integer_token3] = aux_sym_integer_token3, + [aux_sym_integer_token4] = aux_sym_integer_token4, + [aux_sym_float_token1] = aux_sym_float_token1, + [aux_sym_float_token2] = aux_sym_float_token2, + [sym_boolean] = sym_boolean, + [sym_offset_date_time] = sym_offset_date_time, + [sym_local_date_time] = sym_local_date_time, + [sym_local_date] = sym_local_date, + [sym_local_time] = sym_local_time, + [anon_sym_COMMA] = anon_sym_COMMA, + [anon_sym_LBRACE] = anon_sym_LBRACE, + [anon_sym_RBRACE] = anon_sym_RBRACE, + [sym__line_ending_or_eof] = sym__line_ending_or_eof, + [sym__multiline_basic_string_content] = sym__multiline_basic_string_content, + [sym__multiline_basic_string_end] = sym__multiline_basic_string_end, + [sym__multiline_literal_string_content] = sym__multiline_literal_string_content, + [sym__multiline_literal_string_end] = sym__multiline_literal_string_end, + [sym_document] = sym_document, + [sym_table] = sym_table, + [sym_table_array_element] = sym_table_array_element, + [sym_pair] = sym_pair, + [sym__inline_pair] = sym__inline_pair, + [sym__key] = sym__key, + [sym_dotted_key] = sym_dotted_key, + [sym_quoted_key] = sym_quoted_key, + [sym__inline_value] = sym__inline_value, + [sym_string] = sym_string, + [sym__basic_string] = sym__basic_string, + [sym__multiline_basic_string] = sym__multiline_basic_string, + [sym__literal_string] = sym__literal_string, + [sym__multiline_literal_string] = sym__multiline_literal_string, + [sym_integer] = sym_integer, + [sym_float] = sym_float, + [sym_array] = sym_array, + [sym_inline_table] = sym_inline_table, + [aux_sym_document_repeat1] = aux_sym_document_repeat1, + [aux_sym_document_repeat2] = aux_sym_document_repeat2, + [aux_sym__basic_string_repeat1] = aux_sym__basic_string_repeat1, + [aux_sym__multiline_basic_string_repeat1] = aux_sym__multiline_basic_string_repeat1, + [aux_sym__multiline_literal_string_repeat1] = aux_sym__multiline_literal_string_repeat1, + [aux_sym_array_repeat1] = aux_sym_array_repeat1, + [aux_sym_array_repeat2] = aux_sym_array_repeat2, + [aux_sym_inline_table_repeat1] = aux_sym_inline_table_repeat1, +}; + +static const TSSymbolMetadata ts_symbol_metadata[] = { + [ts_builtin_sym_end] = { + .visible = false, + .named = true, + }, + [aux_sym_document_token1] = { + .visible = false, + .named = false, + }, + [sym_comment] = { + .visible = true, + .named = true, + }, + [anon_sym_LBRACK] = { + .visible = true, + .named = false, + }, + [anon_sym_RBRACK] = { + .visible = true, + .named = false, + }, + [anon_sym_LBRACK_LBRACK] = { + .visible = true, + .named = false, + }, + [anon_sym_RBRACK_RBRACK] = { + .visible = true, + .named = false, + }, + [anon_sym_EQ] = { + .visible = true, + .named = false, + }, + [anon_sym_DOT] = { + .visible = true, + .named = false, + }, + [sym_bare_key] = { + .visible = true, + .named = true, + }, + [anon_sym_DQUOTE] = { + .visible = true, + .named = false, + }, + [aux_sym__basic_string_token1] = { + .visible = false, + .named = false, + }, + [anon_sym_DQUOTE2] = { + .visible = true, + .named = false, + }, + [anon_sym_DQUOTE_DQUOTE_DQUOTE] = { + .visible = true, + .named = false, + }, + [aux_sym__multiline_basic_string_token1] = { + .visible = false, + .named = false, + }, + [sym_escape_sequence] = { + .visible = true, + .named = true, + }, + [sym__escape_line_ending] = { + .visible = true, + .named = true, + }, + [anon_sym_SQUOTE] = { + .visible = true, + .named = false, + }, + [aux_sym__literal_string_token1] = { + .visible = false, + .named = false, + }, + [anon_sym_SQUOTE2] = { + .visible = true, + .named = false, + }, + [anon_sym_SQUOTE_SQUOTE_SQUOTE] = { + .visible = true, + .named = false, + }, + [aux_sym_integer_token1] = { + .visible = false, + .named = false, + }, + [aux_sym_integer_token2] = { + .visible = false, + .named = false, + }, + [aux_sym_integer_token3] = { + .visible = false, + .named = false, + }, + [aux_sym_integer_token4] = { + .visible = false, + .named = false, + }, + [aux_sym_float_token1] = { + .visible = false, + .named = false, + }, + [aux_sym_float_token2] = { + .visible = false, + .named = false, + }, + [sym_boolean] = { + .visible = true, + .named = true, + }, + [sym_offset_date_time] = { + .visible = true, + .named = true, + }, + [sym_local_date_time] = { + .visible = true, + .named = true, + }, + [sym_local_date] = { + .visible = true, + .named = true, + }, + [sym_local_time] = { + .visible = true, + .named = true, + }, + [anon_sym_COMMA] = { + .visible = true, + .named = false, + }, + [anon_sym_LBRACE] = { + .visible = true, + .named = false, + }, + [anon_sym_RBRACE] = { + .visible = true, + .named = false, + }, + [sym__line_ending_or_eof] = { + .visible = false, + .named = true, + }, + [sym__multiline_basic_string_content] = { + .visible = false, + .named = true, + }, + [sym__multiline_basic_string_end] = { + .visible = false, + .named = true, + }, + [sym__multiline_literal_string_content] = { + .visible = false, + .named = true, + }, + [sym__multiline_literal_string_end] = { + .visible = false, + .named = true, + }, + [sym_document] = { + .visible = true, + .named = true, + }, + [sym_table] = { + .visible = true, + .named = true, + }, + [sym_table_array_element] = { + .visible = true, + .named = true, + }, + [sym_pair] = { + .visible = true, + .named = true, + }, + [sym__inline_pair] = { + .visible = false, + .named = true, + }, + [sym__key] = { + .visible = false, + .named = true, + }, + [sym_dotted_key] = { + .visible = true, + .named = true, + }, + [sym_quoted_key] = { + .visible = true, + .named = true, + }, + [sym__inline_value] = { + .visible = false, + .named = true, + }, + [sym_string] = { + .visible = true, + .named = true, + }, + [sym__basic_string] = { + .visible = false, + .named = true, + }, + [sym__multiline_basic_string] = { + .visible = false, + .named = true, + }, + [sym__literal_string] = { + .visible = false, + .named = true, + }, + [sym__multiline_literal_string] = { + .visible = false, + .named = true, + }, + [sym_integer] = { + .visible = true, + .named = true, + }, + [sym_float] = { + .visible = true, + .named = true, + }, + [sym_array] = { + .visible = true, + .named = true, + }, + [sym_inline_table] = { + .visible = true, + .named = true, + }, + [aux_sym_document_repeat1] = { + .visible = false, + .named = false, + }, + [aux_sym_document_repeat2] = { + .visible = false, + .named = false, + }, + [aux_sym__basic_string_repeat1] = { + .visible = false, + .named = false, + }, + [aux_sym__multiline_basic_string_repeat1] = { + .visible = false, + .named = false, + }, + [aux_sym__multiline_literal_string_repeat1] = { + .visible = false, + .named = false, + }, + [aux_sym_array_repeat1] = { + .visible = false, + .named = false, + }, + [aux_sym_array_repeat2] = { + .visible = false, + .named = false, + }, + [aux_sym_inline_table_repeat1] = { + .visible = false, + .named = false, + }, +}; + +static const TSSymbol ts_alias_sequences[PRODUCTION_ID_COUNT][MAX_ALIAS_SEQUENCE_LENGTH] = { + [0] = {0}, + [1] = { + [1] = sym_pair, + }, +}; + +static const uint16_t ts_non_terminal_alias_map[] = { + sym__inline_pair, 2, + sym__inline_pair, + sym_pair, + 0, +}; + +static const TSStateId ts_primary_state_ids[STATE_COUNT] = { + [0] = 0, + [1] = 1, + [2] = 2, + [3] = 3, + [4] = 4, + [5] = 5, + [6] = 6, + [7] = 2, + [8] = 8, + [9] = 9, + [10] = 10, + [11] = 9, + [12] = 12, + [13] = 13, + [14] = 5, + [15] = 3, + [16] = 8, + [17] = 6, + [18] = 4, + [19] = 10, + [20] = 12, + [21] = 13, + [22] = 22, + [23] = 23, + [24] = 24, + [25] = 24, + [26] = 26, + [27] = 27, + [28] = 28, + [29] = 29, + [30] = 30, + [31] = 31, + [32] = 32, + [33] = 33, + [34] = 33, + [35] = 35, + [36] = 36, + [37] = 37, + [38] = 38, + [39] = 39, + [40] = 40, + [41] = 41, + [42] = 40, + [43] = 43, + [44] = 41, + [45] = 43, + [46] = 46, + [47] = 47, + [48] = 48, + [49] = 49, + [50] = 50, + [51] = 51, + [52] = 52, + [53] = 53, + [54] = 54, + [55] = 55, + [56] = 56, + [57] = 57, + [58] = 58, + [59] = 57, + [60] = 58, + [61] = 61, + [62] = 61, + [63] = 54, + [64] = 56, + [65] = 53, + [66] = 66, + [67] = 67, + [68] = 68, + [69] = 69, + [70] = 70, + [71] = 71, + [72] = 72, + [73] = 73, + [74] = 74, + [75] = 75, + [76] = 76, + [77] = 77, + [78] = 78, + [79] = 79, + [80] = 80, + [81] = 81, + [82] = 82, + [83] = 83, + [84] = 84, + [85] = 85, + [86] = 86, + [87] = 87, + [88] = 88, + [89] = 67, + [90] = 88, + [91] = 67, + [92] = 92, + [93] = 88, + [94] = 94, + [95] = 95, + [96] = 96, + [97] = 97, + [98] = 94, + [99] = 99, + [100] = 97, + [101] = 99, + [102] = 102, + [103] = 102, + [104] = 104, + [105] = 104, + [106] = 106, + [107] = 107, + [108] = 108, + [109] = 109, + [110] = 47, + [111] = 48, + [112] = 51, + [113] = 52, + [114] = 114, + [115] = 115, + [116] = 114, + [117] = 117, + [118] = 107, + [119] = 109, + [120] = 120, + [121] = 114, + [122] = 96, + [123] = 78, + [124] = 48, + [125] = 125, + [126] = 79, + [127] = 127, + [128] = 75, + [129] = 71, + [130] = 81, + [131] = 51, + [132] = 76, + [133] = 84, + [134] = 85, + [135] = 82, + [136] = 72, + [137] = 77, + [138] = 115, + [139] = 73, + [140] = 86, + [141] = 141, + [142] = 142, + [143] = 83, + [144] = 47, + [145] = 145, + [146] = 141, + [147] = 87, + [148] = 52, + [149] = 74, + [150] = 141, + [151] = 80, +}; + +static bool ts_lex(TSLexer *lexer, TSStateId state) { + START_LEXER(); + eof = lexer->eof(lexer); + switch (state) { + case 0: + if (eof) ADVANCE(77); + ADVANCE_MAP( + '\n', 129, + '\r', 1, + '"', 127, + '#', 79, + '\'', 137, + '+', 15, + ',', 161, + '-', 95, + '.', 86, + '0', 92, + '1', 90, + '2', 89, + '=', 85, + '[', 81, + '\\', 5, + ']', 82, + 'f', 102, + 'i', 108, + 'n', 103, + 't', 109, + '{', 162, + '}', 163, + ); + if (lookahead == '\t' || + lookahead == ' ') SKIP(75); + if (('3' <= lookahead && lookahead <= '9')) ADVANCE(91); + if (('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 1: + if (lookahead == '\n') ADVANCE(129); + END_STATE(); + case 2: + if (lookahead == '\n') ADVANCE(129); + if (lookahead == '\r') ADVANCE(1); + if (lookahead == '"') ADVANCE(126); + if (lookahead == '#') ADVANCE(125); + if (lookahead == '\\') ADVANCE(5); + if (lookahead == '\t' || + lookahead == ' ') ADVANCE(124); + if (lookahead > ' ' && + lookahead != 0x7f) ADVANCE(125); + END_STATE(); + case 3: + if (lookahead == '\n') ADVANCE(129); + if (lookahead == '\r') ADVANCE(1); + if (lookahead == '#') ADVANCE(135); + if (lookahead == '\'') ADVANCE(136); + if (lookahead == '\t' || + lookahead == ' ') ADVANCE(134); + if (lookahead > ' ' && + lookahead != 0x7f) ADVANCE(135); + END_STATE(); + case 4: + if (lookahead == '\n') ADVANCE(131); + END_STATE(); + case 5: + ADVANCE_MAP( + '\n', 131, + '\r', 4, + 'U', 74, + 'u', 70, + '"', 130, + '\\', 130, + 'b', 130, + 'f', 130, + 'n', 130, + 'r', 130, + 't', 130, + ); + END_STATE(); + case 6: + if (lookahead == '\n') ADVANCE(78); + END_STATE(); + case 7: + ADVANCE_MAP( + '\n', 78, + '\r', 6, + '"', 123, + '#', 79, + '\'', 133, + ',', 161, + '0', 144, + '1', 142, + '2', 141, + '[', 80, + ']', 82, + 'f', 30, + 'i', 35, + 'n', 31, + 't', 37, + '{', 162, + ); + if (lookahead == '\t' || + lookahead == ' ') SKIP(7); + if (('+' <= lookahead && lookahead <= '-')) ADVANCE(17); + if (('3' <= lookahead && lookahead <= '9')) ADVANCE(143); + END_STATE(); + case 8: + if (lookahead == '"') ADVANCE(128); + END_STATE(); + case 9: + if (lookahead == '#') ADVANCE(79); + if (lookahead == '\'') ADVANCE(136); + if (lookahead == '.') ADVANCE(86); + if (lookahead == ']') ADVANCE(29); + if (lookahead == '\t' || + lookahead == ' ') SKIP(10); + END_STATE(); + case 10: + if (lookahead == '#') ADVANCE(79); + if (lookahead == '.') ADVANCE(86); + if (lookahead == ']') ADVANCE(29); + if (lookahead == '\t' || + lookahead == ' ') SKIP(10); + END_STATE(); + case 11: + if (lookahead == '\'') ADVANCE(138); + END_STATE(); + case 12: + if (lookahead == '-') ADVANCE(18); + if (lookahead == ':') ADVANCE(46); + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(13); + END_STATE(); + case 13: + if (lookahead == '-') ADVANCE(18); + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(13); + END_STATE(); + case 14: + if (lookahead == '-') ADVANCE(20); + END_STATE(); + case 15: + if (lookahead == '0') ADVANCE(139); + if (lookahead == 'i') ADVANCE(35); + if (lookahead == 'n') ADVANCE(31); + if (('1' <= lookahead && lookahead <= '9')) ADVANCE(147); + END_STATE(); + case 16: + if (lookahead == '0') ADVANCE(159); + END_STATE(); + case 17: + if (lookahead == '0') ADVANCE(146); + if (lookahead == 'i') ADVANCE(35); + if (lookahead == 'n') ADVANCE(31); + if (('1' <= lookahead && lookahead <= '9')) ADVANCE(145); + END_STATE(); + case 18: + if (lookahead == '0') ADVANCE(50); + if (lookahead == '1') ADVANCE(43); + END_STATE(); + case 19: + if (lookahead == '0') ADVANCE(156); + END_STATE(); + case 20: + if (lookahead == '0') ADVANCE(51); + if (lookahead == '3') ADVANCE(42); + if (lookahead == '1' || + lookahead == '2') ADVANCE(59); + END_STATE(); + case 21: + if (lookahead == '2') ADVANCE(44); + if (lookahead == '0' || + lookahead == '1') ADVANCE(63); + END_STATE(); + case 22: + if (lookahead == '2') ADVANCE(45); + if (lookahead == '0' || + lookahead == '1') ADVANCE(64); + END_STATE(); + case 23: + if (lookahead == '6') ADVANCE(16); + if (('0' <= lookahead && lookahead <= '5')) ADVANCE(54); + END_STATE(); + case 24: + if (lookahead == '6') ADVANCE(19); + if (('0' <= lookahead && lookahead <= '5')) ADVANCE(60); + END_STATE(); + case 25: + if (lookahead == ':') ADVANCE(23); + END_STATE(); + case 26: + if (lookahead == ':') ADVANCE(47); + END_STATE(); + case 27: + if (lookahead == ':') ADVANCE(24); + END_STATE(); + case 28: + if (lookahead == ':') ADVANCE(48); + END_STATE(); + case 29: + if (lookahead == ']') ADVANCE(84); + END_STATE(); + case 30: + if (lookahead == 'a') ADVANCE(34); + END_STATE(); + case 31: + if (lookahead == 'a') ADVANCE(36); + END_STATE(); + case 32: + if (lookahead == 'e') ADVANCE(154); + END_STATE(); + case 33: + if (lookahead == 'f') ADVANCE(153); + END_STATE(); + case 34: + if (lookahead == 'l') ADVANCE(38); + END_STATE(); + case 35: + if (lookahead == 'n') ADVANCE(33); + END_STATE(); + case 36: + if (lookahead == 'n') ADVANCE(153); + END_STATE(); + case 37: + if (lookahead == 'r') ADVANCE(39); + END_STATE(); + case 38: + if (lookahead == 's') ADVANCE(32); + END_STATE(); + case 39: + if (lookahead == 'u') ADVANCE(32); + END_STATE(); + case 40: + if (lookahead == '+' || + lookahead == '-') ADVANCE(58); + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(152); + END_STATE(); + case 41: + if (lookahead == '0' || + lookahead == '1') ADVANCE(150); + END_STATE(); + case 42: + if (lookahead == '0' || + lookahead == '1') ADVANCE(158); + END_STATE(); + case 43: + if (('0' <= lookahead && lookahead <= '2')) ADVANCE(14); + END_STATE(); + case 44: + if (('0' <= lookahead && lookahead <= '3')) ADVANCE(28); + END_STATE(); + case 45: + if (('0' <= lookahead && lookahead <= '3')) ADVANCE(26); + END_STATE(); + case 46: + if (('0' <= lookahead && lookahead <= '5')) ADVANCE(53); + END_STATE(); + case 47: + if (('0' <= lookahead && lookahead <= '5')) ADVANCE(61); + END_STATE(); + case 48: + if (('0' <= lookahead && lookahead <= '5')) ADVANCE(65); + END_STATE(); + case 49: + if (('0' <= lookahead && lookahead <= '7')) ADVANCE(149); + END_STATE(); + case 50: + if (('1' <= lookahead && lookahead <= '9')) ADVANCE(14); + END_STATE(); + case 51: + if (('1' <= lookahead && lookahead <= '9')) ADVANCE(158); + END_STATE(); + case 52: + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(147); + END_STATE(); + case 53: + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(25); + END_STATE(); + case 54: + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(159); + END_STATE(); + case 55: + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(160); + END_STATE(); + case 56: + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(145); + END_STATE(); + case 57: + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(151); + END_STATE(); + case 58: + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(152); + END_STATE(); + case 59: + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(158); + END_STATE(); + case 60: + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(156); + END_STATE(); + case 61: + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(155); + END_STATE(); + case 62: + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(157); + END_STATE(); + case 63: + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(28); + END_STATE(); + case 64: + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(26); + END_STATE(); + case 65: + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(27); + END_STATE(); + case 66: + if (('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'F') || + ('a' <= lookahead && lookahead <= 'f')) ADVANCE(130); + END_STATE(); + case 67: + if (('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'F') || + ('a' <= lookahead && lookahead <= 'f')) ADVANCE(148); + END_STATE(); + case 68: + if (('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'F') || + ('a' <= lookahead && lookahead <= 'f')) ADVANCE(66); + END_STATE(); + case 69: + if (('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'F') || + ('a' <= lookahead && lookahead <= 'f')) ADVANCE(68); + END_STATE(); + case 70: + if (('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'F') || + ('a' <= lookahead && lookahead <= 'f')) ADVANCE(69); + END_STATE(); + case 71: + if (('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'F') || + ('a' <= lookahead && lookahead <= 'f')) ADVANCE(70); + END_STATE(); + case 72: + if (('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'F') || + ('a' <= lookahead && lookahead <= 'f')) ADVANCE(71); + END_STATE(); + case 73: + if (('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'F') || + ('a' <= lookahead && lookahead <= 'f')) ADVANCE(72); + END_STATE(); + case 74: + if (('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'F') || + ('a' <= lookahead && lookahead <= 'f')) ADVANCE(73); + END_STATE(); + case 75: + if (eof) ADVANCE(77); + ADVANCE_MAP( + '\n', 78, + '\r', 6, + '"', 123, + '#', 79, + '\'', 133, + '+', 15, + ',', 161, + '-', 95, + '.', 86, + '0', 92, + '1', 90, + '2', 89, + '=', 85, + '[', 81, + ']', 82, + 'f', 102, + 'i', 108, + 'n', 103, + 't', 109, + '{', 162, + '}', 163, + ); + if (lookahead == '\t' || + lookahead == ' ') SKIP(75); + if (('3' <= lookahead && lookahead <= '9')) ADVANCE(91); + if (('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 76: + if (eof) ADVANCE(77); + ADVANCE_MAP( + '\n', 78, + '\r', 6, + '"', 122, + '#', 79, + '\'', 132, + ',', 161, + '.', 86, + '=', 85, + '[', 81, + ']', 82, + '}', 163, + ); + if (lookahead == '\t' || + lookahead == ' ') SKIP(76); + if (lookahead == '-' || + ('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 77: + ACCEPT_TOKEN(ts_builtin_sym_end); + END_STATE(); + case 78: + ACCEPT_TOKEN(aux_sym_document_token1); + END_STATE(); + case 79: + ACCEPT_TOKEN(sym_comment); + if (lookahead > 0x08 && + (lookahead < '\n' || 0x1f < lookahead) && + lookahead != 0x7f) ADVANCE(79); + END_STATE(); + case 80: + ACCEPT_TOKEN(anon_sym_LBRACK); + END_STATE(); + case 81: + ACCEPT_TOKEN(anon_sym_LBRACK); + if (lookahead == '[') ADVANCE(83); + END_STATE(); + case 82: + ACCEPT_TOKEN(anon_sym_RBRACK); + END_STATE(); + case 83: + ACCEPT_TOKEN(anon_sym_LBRACK_LBRACK); + END_STATE(); + case 84: + ACCEPT_TOKEN(anon_sym_RBRACK_RBRACK); + END_STATE(); + case 85: + ACCEPT_TOKEN(anon_sym_EQ); + END_STATE(); + case 86: + ACCEPT_TOKEN(anon_sym_DOT); + END_STATE(); + case 87: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == '-') ADVANCE(96); + if (lookahead == ':') ADVANCE(46); + if (lookahead == '_') ADVANCE(119); + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(91); + if (('A' <= lookahead && lookahead <= 'Z') || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 88: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == '-') ADVANCE(96); + if (lookahead == ':') ADVANCE(46); + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(93); + if (('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 89: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == '-') ADVANCE(96); + if (lookahead == '_') ADVANCE(119); + if (('0' <= lookahead && lookahead <= '3')) ADVANCE(87); + if (('4' <= lookahead && lookahead <= '9')) ADVANCE(91); + if (('A' <= lookahead && lookahead <= 'Z') || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 90: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == '-') ADVANCE(96); + if (lookahead == '_') ADVANCE(119); + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(87); + if (('A' <= lookahead && lookahead <= 'Z') || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 91: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == '-') ADVANCE(96); + if (lookahead == '_') ADVANCE(119); + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(91); + if (('A' <= lookahead && lookahead <= 'Z') || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 92: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == '-') ADVANCE(96); + if (lookahead == 'b') ADVANCE(113); + if (lookahead == 'o') ADVANCE(115); + if (lookahead == 'x') ADVANCE(120); + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(88); + if (('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 93: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == '-') ADVANCE(96); + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(93); + if (('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 94: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == '-') ADVANCE(97); + if (('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 95: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == '0') ADVANCE(121); + if (lookahead == 'i') ADVANCE(108); + if (lookahead == 'n') ADVANCE(103); + if (('1' <= lookahead && lookahead <= '9')) ADVANCE(101); + if (lookahead == '-' || + ('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 96: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == '0') ADVANCE(117); + if (lookahead == '1') ADVANCE(114); + if (lookahead == '-' || + ('2' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 97: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == '0') ADVANCE(116); + if (lookahead == '3') ADVANCE(112); + if (lookahead == '1' || + lookahead == '2') ADVANCE(118); + if (lookahead == '-' || + ('4' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 98: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == '_') ADVANCE(113); + if (lookahead == '0' || + lookahead == '1') ADVANCE(98); + if (lookahead == '-' || + ('2' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'Z') || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 99: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == '_') ADVANCE(115); + if (('0' <= lookahead && lookahead <= '7')) ADVANCE(99); + if (lookahead == '-' || + lookahead == '8' || + lookahead == '9' || + ('A' <= lookahead && lookahead <= 'Z') || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 100: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == '_') ADVANCE(120); + if (('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'F') || + ('a' <= lookahead && lookahead <= 'f')) ADVANCE(100); + if (lookahead == '-' || + ('G' <= lookahead && lookahead <= 'Z') || + ('g' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 101: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == '_') ADVANCE(119); + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(101); + if (lookahead == '-' || + ('A' <= lookahead && lookahead <= 'Z') || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 102: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == 'a') ADVANCE(106); + if (lookahead == '-' || + ('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('b' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 103: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == 'a') ADVANCE(107); + if (lookahead == '-' || + ('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('b' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 104: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == 'e') ADVANCE(121); + if (lookahead == '-' || + ('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 105: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == 'f') ADVANCE(121); + if (lookahead == '-' || + ('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 106: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == 'l') ADVANCE(110); + if (lookahead == '-' || + ('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 107: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == 'n') ADVANCE(121); + if (lookahead == '-' || + ('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 108: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == 'n') ADVANCE(105); + if (lookahead == '-' || + ('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 109: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == 'r') ADVANCE(111); + if (lookahead == '-' || + ('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 110: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == 's') ADVANCE(104); + if (lookahead == '-' || + ('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 111: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == 'u') ADVANCE(104); + if (lookahead == '-' || + ('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 112: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == '0' || + lookahead == '1') ADVANCE(121); + if (lookahead == '-' || + ('2' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 113: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == '0' || + lookahead == '1') ADVANCE(98); + if (lookahead == '-' || + ('2' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 114: + ACCEPT_TOKEN(sym_bare_key); + if (('0' <= lookahead && lookahead <= '2')) ADVANCE(94); + if (lookahead == '-' || + ('3' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 115: + ACCEPT_TOKEN(sym_bare_key); + if (('0' <= lookahead && lookahead <= '7')) ADVANCE(99); + if (lookahead == '-' || + lookahead == '8' || + lookahead == '9' || + ('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 116: + ACCEPT_TOKEN(sym_bare_key); + if (('1' <= lookahead && lookahead <= '9')) ADVANCE(121); + if (lookahead == '-' || + lookahead == '0' || + ('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 117: + ACCEPT_TOKEN(sym_bare_key); + if (('1' <= lookahead && lookahead <= '9')) ADVANCE(94); + if (lookahead == '-' || + lookahead == '0' || + ('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 118: + ACCEPT_TOKEN(sym_bare_key); + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(121); + if (lookahead == '-' || + ('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 119: + ACCEPT_TOKEN(sym_bare_key); + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(101); + if (lookahead == '-' || + ('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 120: + ACCEPT_TOKEN(sym_bare_key); + if (('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'F') || + ('a' <= lookahead && lookahead <= 'f')) ADVANCE(100); + if (lookahead == '-' || + ('G' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('g' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 121: + ACCEPT_TOKEN(sym_bare_key); + if (lookahead == '-' || + ('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(121); + END_STATE(); + case 122: + ACCEPT_TOKEN(anon_sym_DQUOTE); + END_STATE(); + case 123: + ACCEPT_TOKEN(anon_sym_DQUOTE); + if (lookahead == '"') ADVANCE(8); + END_STATE(); + case 124: + ACCEPT_TOKEN(aux_sym__basic_string_token1); + if (lookahead == '#') ADVANCE(125); + if (lookahead == '\t' || + lookahead == ' ') ADVANCE(124); + if (lookahead > ' ' && + lookahead != '"' && + lookahead != '#' && + lookahead != '\\' && + lookahead != 0x7f) ADVANCE(125); + END_STATE(); + case 125: + ACCEPT_TOKEN(aux_sym__basic_string_token1); + if (lookahead > 0x08 && + (lookahead < '\n' || 0x1f < lookahead) && + lookahead != '"' && + lookahead != '\\' && + lookahead != 0x7f) ADVANCE(125); + END_STATE(); + case 126: + ACCEPT_TOKEN(anon_sym_DQUOTE2); + END_STATE(); + case 127: + ACCEPT_TOKEN(anon_sym_DQUOTE2); + if (lookahead == '"') ADVANCE(8); + END_STATE(); + case 128: + ACCEPT_TOKEN(anon_sym_DQUOTE_DQUOTE_DQUOTE); + END_STATE(); + case 129: + ACCEPT_TOKEN(aux_sym__multiline_basic_string_token1); + END_STATE(); + case 130: + ACCEPT_TOKEN(sym_escape_sequence); + END_STATE(); + case 131: + ACCEPT_TOKEN(sym__escape_line_ending); + END_STATE(); + case 132: + ACCEPT_TOKEN(anon_sym_SQUOTE); + END_STATE(); + case 133: + ACCEPT_TOKEN(anon_sym_SQUOTE); + if (lookahead == '\'') ADVANCE(11); + END_STATE(); + case 134: + ACCEPT_TOKEN(aux_sym__literal_string_token1); + if (lookahead == '#') ADVANCE(135); + if (lookahead == '\t' || + lookahead == ' ') ADVANCE(134); + if (lookahead > ' ' && + lookahead != '\'' && + lookahead != 0x7f) ADVANCE(135); + END_STATE(); + case 135: + ACCEPT_TOKEN(aux_sym__literal_string_token1); + if (lookahead > 0x08 && + (lookahead < '\n' || 0x1f < lookahead) && + lookahead != '\'' && + lookahead != 0x7f) ADVANCE(135); + END_STATE(); + case 136: + ACCEPT_TOKEN(anon_sym_SQUOTE2); + END_STATE(); + case 137: + ACCEPT_TOKEN(anon_sym_SQUOTE2); + if (lookahead == '\'') ADVANCE(11); + END_STATE(); + case 138: + ACCEPT_TOKEN(anon_sym_SQUOTE_SQUOTE_SQUOTE); + END_STATE(); + case 139: + ACCEPT_TOKEN(aux_sym_integer_token1); + END_STATE(); + case 140: + ACCEPT_TOKEN(aux_sym_integer_token1); + if (lookahead == '-') ADVANCE(18); + if (lookahead == '.') ADVANCE(57); + if (lookahead == ':') ADVANCE(46); + if (lookahead == '_') ADVANCE(56); + if (lookahead == 'E' || + lookahead == 'e') ADVANCE(40); + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(143); + END_STATE(); + case 141: + ACCEPT_TOKEN(aux_sym_integer_token1); + if (lookahead == '-') ADVANCE(18); + if (lookahead == '.') ADVANCE(57); + if (lookahead == '_') ADVANCE(56); + if (lookahead == 'E' || + lookahead == 'e') ADVANCE(40); + if (('0' <= lookahead && lookahead <= '3')) ADVANCE(140); + if (('4' <= lookahead && lookahead <= '9')) ADVANCE(143); + END_STATE(); + case 142: + ACCEPT_TOKEN(aux_sym_integer_token1); + if (lookahead == '-') ADVANCE(18); + if (lookahead == '.') ADVANCE(57); + if (lookahead == '_') ADVANCE(56); + if (lookahead == 'E' || + lookahead == 'e') ADVANCE(40); + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(140); + END_STATE(); + case 143: + ACCEPT_TOKEN(aux_sym_integer_token1); + if (lookahead == '-') ADVANCE(18); + if (lookahead == '.') ADVANCE(57); + if (lookahead == '_') ADVANCE(56); + if (lookahead == 'E' || + lookahead == 'e') ADVANCE(40); + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(143); + END_STATE(); + case 144: + ACCEPT_TOKEN(aux_sym_integer_token1); + if (lookahead == '-') ADVANCE(18); + if (lookahead == '.') ADVANCE(57); + if (lookahead == 'b') ADVANCE(41); + if (lookahead == 'o') ADVANCE(49); + if (lookahead == 'x') ADVANCE(67); + if (lookahead == 'E' || + lookahead == 'e') ADVANCE(40); + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(12); + END_STATE(); + case 145: + ACCEPT_TOKEN(aux_sym_integer_token1); + if (lookahead == '.') ADVANCE(57); + if (lookahead == '_') ADVANCE(56); + if (lookahead == 'E' || + lookahead == 'e') ADVANCE(40); + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(145); + END_STATE(); + case 146: + ACCEPT_TOKEN(aux_sym_integer_token1); + if (lookahead == '.') ADVANCE(57); + if (lookahead == 'E' || + lookahead == 'e') ADVANCE(40); + END_STATE(); + case 147: + ACCEPT_TOKEN(aux_sym_integer_token1); + if (lookahead == '_') ADVANCE(52); + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(147); + END_STATE(); + case 148: + ACCEPT_TOKEN(aux_sym_integer_token2); + if (lookahead == '_') ADVANCE(67); + if (('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'F') || + ('a' <= lookahead && lookahead <= 'f')) ADVANCE(148); + END_STATE(); + case 149: + ACCEPT_TOKEN(aux_sym_integer_token3); + if (lookahead == '_') ADVANCE(49); + if (('0' <= lookahead && lookahead <= '7')) ADVANCE(149); + END_STATE(); + case 150: + ACCEPT_TOKEN(aux_sym_integer_token4); + if (lookahead == '_') ADVANCE(41); + if (lookahead == '0' || + lookahead == '1') ADVANCE(150); + END_STATE(); + case 151: + ACCEPT_TOKEN(aux_sym_float_token1); + if (lookahead == '_') ADVANCE(57); + if (lookahead == 'E' || + lookahead == 'e') ADVANCE(40); + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(151); + END_STATE(); + case 152: + ACCEPT_TOKEN(aux_sym_float_token1); + if (lookahead == '_') ADVANCE(58); + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(152); + END_STATE(); + case 153: + ACCEPT_TOKEN(aux_sym_float_token2); + END_STATE(); + case 154: + ACCEPT_TOKEN(sym_boolean); + END_STATE(); + case 155: + ACCEPT_TOKEN(sym_offset_date_time); + END_STATE(); + case 156: + ACCEPT_TOKEN(sym_local_date_time); + if (lookahead == '.') ADVANCE(62); + if (lookahead == '+' || + lookahead == '-') ADVANCE(22); + if (lookahead == 'Z' || + lookahead == 'z') ADVANCE(155); + END_STATE(); + case 157: + ACCEPT_TOKEN(sym_local_date_time); + if (lookahead == '+' || + lookahead == '-') ADVANCE(22); + if (lookahead == 'Z' || + lookahead == 'z') ADVANCE(155); + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(157); + END_STATE(); + case 158: + ACCEPT_TOKEN(sym_local_date); + if (lookahead == ' ' || + lookahead == 'T' || + lookahead == 't') ADVANCE(21); + END_STATE(); + case 159: + ACCEPT_TOKEN(sym_local_time); + if (lookahead == '.') ADVANCE(55); + END_STATE(); + case 160: + ACCEPT_TOKEN(sym_local_time); + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(160); + END_STATE(); + case 161: + ACCEPT_TOKEN(anon_sym_COMMA); + END_STATE(); + case 162: + ACCEPT_TOKEN(anon_sym_LBRACE); + END_STATE(); + case 163: + ACCEPT_TOKEN(anon_sym_RBRACE); + END_STATE(); + default: + return false; + } +} + +static const TSLexMode ts_lex_modes[STATE_COUNT] = { + [0] = {.lex_state = 0, .external_lex_state = 1}, + [1] = {.lex_state = 76}, + [2] = {.lex_state = 7}, + [3] = {.lex_state = 7}, + [4] = {.lex_state = 7}, + [5] = {.lex_state = 7}, + [6] = {.lex_state = 7}, + [7] = {.lex_state = 7}, + [8] = {.lex_state = 7}, + [9] = {.lex_state = 7}, + [10] = {.lex_state = 7}, + [11] = {.lex_state = 7}, + [12] = {.lex_state = 7}, + [13] = {.lex_state = 7}, + [14] = {.lex_state = 7}, + [15] = {.lex_state = 7}, + [16] = {.lex_state = 7}, + [17] = {.lex_state = 7}, + [18] = {.lex_state = 7}, + [19] = {.lex_state = 7}, + [20] = {.lex_state = 7}, + [21] = {.lex_state = 7}, + [22] = {.lex_state = 7}, + [23] = {.lex_state = 7}, + [24] = {.lex_state = 7}, + [25] = {.lex_state = 7}, + [26] = {.lex_state = 7}, + [27] = {.lex_state = 76}, + [28] = {.lex_state = 76}, + [29] = {.lex_state = 76}, + [30] = {.lex_state = 76}, + [31] = {.lex_state = 76}, + [32] = {.lex_state = 76}, + [33] = {.lex_state = 76}, + [34] = {.lex_state = 76}, + [35] = {.lex_state = 76}, + [36] = {.lex_state = 76}, + [37] = {.lex_state = 76}, + [38] = {.lex_state = 76}, + [39] = {.lex_state = 2, .external_lex_state = 2}, + [40] = {.lex_state = 76}, + [41] = {.lex_state = 2, .external_lex_state = 2}, + [42] = {.lex_state = 76}, + [43] = {.lex_state = 2, .external_lex_state = 2}, + [44] = {.lex_state = 2, .external_lex_state = 2}, + [45] = {.lex_state = 2, .external_lex_state = 2}, + [46] = {.lex_state = 0}, + [47] = {.lex_state = 76}, + [48] = {.lex_state = 76}, + [49] = {.lex_state = 0}, + [50] = {.lex_state = 0}, + [51] = {.lex_state = 76}, + [52] = {.lex_state = 76}, + [53] = {.lex_state = 76}, + [54] = {.lex_state = 76}, + [55] = {.lex_state = 3, .external_lex_state = 3}, + [56] = {.lex_state = 76}, + [57] = {.lex_state = 3, .external_lex_state = 3}, + [58] = {.lex_state = 76}, + [59] = {.lex_state = 3, .external_lex_state = 3}, + [60] = {.lex_state = 76}, + [61] = {.lex_state = 3, .external_lex_state = 3}, + [62] = {.lex_state = 3, .external_lex_state = 3}, + [63] = {.lex_state = 76}, + [64] = {.lex_state = 76}, + [65] = {.lex_state = 76}, + [66] = {.lex_state = 2}, + [67] = {.lex_state = 2}, + [68] = {.lex_state = 76}, + [69] = {.lex_state = 76}, + [70] = {.lex_state = 76}, + [71] = {.lex_state = 76}, + [72] = {.lex_state = 76}, + [73] = {.lex_state = 76}, + [74] = {.lex_state = 76}, + [75] = {.lex_state = 76}, + [76] = {.lex_state = 76}, + [77] = {.lex_state = 76}, + [78] = {.lex_state = 76}, + [79] = {.lex_state = 76}, + [80] = {.lex_state = 76}, + [81] = {.lex_state = 76}, + [82] = {.lex_state = 76}, + [83] = {.lex_state = 76}, + [84] = {.lex_state = 76}, + [85] = {.lex_state = 76}, + [86] = {.lex_state = 76}, + [87] = {.lex_state = 76}, + [88] = {.lex_state = 2}, + [89] = {.lex_state = 2}, + [90] = {.lex_state = 2}, + [91] = {.lex_state = 2}, + [92] = {.lex_state = 76}, + [93] = {.lex_state = 2}, + [94] = {.lex_state = 0}, + [95] = {.lex_state = 0}, + [96] = {.lex_state = 0}, + [97] = {.lex_state = 0}, + [98] = {.lex_state = 0}, + [99] = {.lex_state = 0}, + [100] = {.lex_state = 0}, + [101] = {.lex_state = 0}, + [102] = {.lex_state = 0}, + [103] = {.lex_state = 0}, + [104] = {.lex_state = 0}, + [105] = {.lex_state = 0}, + [106] = {.lex_state = 0}, + [107] = {.lex_state = 0}, + [108] = {.lex_state = 0}, + [109] = {.lex_state = 0}, + [110] = {.lex_state = 9}, + [111] = {.lex_state = 9}, + [112] = {.lex_state = 9}, + [113] = {.lex_state = 9}, + [114] = {.lex_state = 3}, + [115] = {.lex_state = 0}, + [116] = {.lex_state = 3}, + [117] = {.lex_state = 0}, + [118] = {.lex_state = 9}, + [119] = {.lex_state = 0}, + [120] = {.lex_state = 9}, + [121] = {.lex_state = 3}, + [122] = {.lex_state = 9}, + [123] = {.lex_state = 0, .external_lex_state = 4}, + [124] = {.lex_state = 0, .external_lex_state = 4}, + [125] = {.lex_state = 0}, + [126] = {.lex_state = 0, .external_lex_state = 4}, + [127] = {.lex_state = 0, .external_lex_state = 4}, + [128] = {.lex_state = 0, .external_lex_state = 4}, + [129] = {.lex_state = 0, .external_lex_state = 4}, + [130] = {.lex_state = 0, .external_lex_state = 4}, + [131] = {.lex_state = 0, .external_lex_state = 4}, + [132] = {.lex_state = 0, .external_lex_state = 4}, + [133] = {.lex_state = 0, .external_lex_state = 4}, + [134] = {.lex_state = 0, .external_lex_state = 4}, + [135] = {.lex_state = 0, .external_lex_state = 4}, + [136] = {.lex_state = 0, .external_lex_state = 4}, + [137] = {.lex_state = 0, .external_lex_state = 4}, + [138] = {.lex_state = 0, .external_lex_state = 4}, + [139] = {.lex_state = 0, .external_lex_state = 4}, + [140] = {.lex_state = 0, .external_lex_state = 4}, + [141] = {.lex_state = 9}, + [142] = {.lex_state = 0, .external_lex_state = 4}, + [143] = {.lex_state = 0, .external_lex_state = 4}, + [144] = {.lex_state = 0, .external_lex_state = 4}, + [145] = {.lex_state = 0, .external_lex_state = 4}, + [146] = {.lex_state = 9}, + [147] = {.lex_state = 0, .external_lex_state = 4}, + [148] = {.lex_state = 0, .external_lex_state = 4}, + [149] = {.lex_state = 0, .external_lex_state = 4}, + [150] = {.lex_state = 9}, + [151] = {.lex_state = 0, .external_lex_state = 4}, +}; + +static const uint16_t ts_parse_table[LARGE_STATE_COUNT][SYMBOL_COUNT] = { + [0] = { + [ts_builtin_sym_end] = ACTIONS(1), + [aux_sym_document_token1] = ACTIONS(1), + [sym_comment] = ACTIONS(3), + [anon_sym_LBRACK] = ACTIONS(1), + [anon_sym_RBRACK] = ACTIONS(1), + [anon_sym_LBRACK_LBRACK] = ACTIONS(1), + [anon_sym_EQ] = ACTIONS(1), + [anon_sym_DOT] = ACTIONS(1), + [sym_bare_key] = ACTIONS(1), + [anon_sym_DQUOTE] = ACTIONS(1), + [anon_sym_DQUOTE2] = ACTIONS(1), + [anon_sym_DQUOTE_DQUOTE_DQUOTE] = ACTIONS(1), + [aux_sym__multiline_basic_string_token1] = ACTIONS(1), + [sym_escape_sequence] = ACTIONS(1), + [sym__escape_line_ending] = ACTIONS(1), + [anon_sym_SQUOTE] = ACTIONS(1), + [anon_sym_SQUOTE2] = ACTIONS(1), + [anon_sym_SQUOTE_SQUOTE_SQUOTE] = ACTIONS(1), + [aux_sym_integer_token1] = ACTIONS(1), + [aux_sym_integer_token2] = ACTIONS(1), + [aux_sym_integer_token3] = ACTIONS(1), + [aux_sym_integer_token4] = ACTIONS(1), + [aux_sym_float_token2] = ACTIONS(1), + [sym_boolean] = ACTIONS(1), + [sym_local_date] = ACTIONS(1), + [sym_local_time] = ACTIONS(1), + [anon_sym_COMMA] = ACTIONS(1), + [anon_sym_LBRACE] = ACTIONS(1), + [anon_sym_RBRACE] = ACTIONS(1), + [sym__line_ending_or_eof] = ACTIONS(1), + [sym__multiline_basic_string_content] = ACTIONS(1), + [sym__multiline_basic_string_end] = ACTIONS(1), + [sym__multiline_literal_string_content] = ACTIONS(1), + [sym__multiline_literal_string_end] = ACTIONS(1), + }, + [1] = { + [sym_document] = STATE(125), + [sym_table] = STATE(46), + [sym_table_array_element] = STATE(46), + [sym_pair] = STATE(27), + [sym__inline_pair] = STATE(127), + [sym__key] = STATE(119), + [sym_dotted_key] = STATE(119), + [sym_quoted_key] = STATE(119), + [sym__basic_string] = STATE(96), + [sym__literal_string] = STATE(96), + [aux_sym_document_repeat1] = STATE(27), + [aux_sym_document_repeat2] = STATE(46), + [ts_builtin_sym_end] = ACTIONS(5), + [aux_sym_document_token1] = ACTIONS(7), + [sym_comment] = ACTIONS(3), + [anon_sym_LBRACK] = ACTIONS(9), + [anon_sym_LBRACK_LBRACK] = ACTIONS(11), + [sym_bare_key] = ACTIONS(13), + [anon_sym_DQUOTE] = ACTIONS(15), + [anon_sym_SQUOTE] = ACTIONS(17), + }, +}; + +static const uint16_t ts_small_parse_table[] = { + [0] = 17, + ACTIONS(3), 1, + sym_comment, + ACTIONS(19), 1, + aux_sym_document_token1, + ACTIONS(21), 1, + anon_sym_LBRACK, + ACTIONS(23), 1, + anon_sym_RBRACK, + ACTIONS(25), 1, + anon_sym_DQUOTE, + ACTIONS(27), 1, + anon_sym_DQUOTE_DQUOTE_DQUOTE, + ACTIONS(29), 1, + anon_sym_SQUOTE, + ACTIONS(31), 1, + anon_sym_SQUOTE_SQUOTE_SQUOTE, + ACTIONS(33), 1, + aux_sym_integer_token1, + ACTIONS(43), 1, + anon_sym_LBRACE, + STATE(26), 1, + aux_sym_array_repeat1, + ACTIONS(37), 2, + aux_sym_float_token1, + aux_sym_float_token2, + ACTIONS(41), 2, + sym_local_date_time, + sym_local_date, + ACTIONS(35), 3, + aux_sym_integer_token2, + aux_sym_integer_token3, + aux_sym_integer_token4, + ACTIONS(39), 3, + sym_boolean, + sym_offset_date_time, + sym_local_time, + STATE(73), 4, + sym__basic_string, + sym__multiline_basic_string, + sym__literal_string, + sym__multiline_literal_string, + STATE(63), 6, + sym__inline_value, + sym_string, + sym_integer, + sym_float, + sym_array, + sym_inline_table, + [66] = 17, + ACTIONS(3), 1, + sym_comment, + ACTIONS(19), 1, + aux_sym_document_token1, + ACTIONS(21), 1, + anon_sym_LBRACK, + ACTIONS(25), 1, + anon_sym_DQUOTE, + ACTIONS(27), 1, + anon_sym_DQUOTE_DQUOTE_DQUOTE, + ACTIONS(29), 1, + anon_sym_SQUOTE, + ACTIONS(31), 1, + anon_sym_SQUOTE_SQUOTE_SQUOTE, + ACTIONS(33), 1, + aux_sym_integer_token1, + ACTIONS(43), 1, + anon_sym_LBRACE, + ACTIONS(45), 1, + anon_sym_RBRACK, + STATE(26), 1, + aux_sym_array_repeat1, + ACTIONS(37), 2, + aux_sym_float_token1, + aux_sym_float_token2, + ACTIONS(49), 2, + sym_local_date_time, + sym_local_date, + ACTIONS(35), 3, + aux_sym_integer_token2, + aux_sym_integer_token3, + aux_sym_integer_token4, + ACTIONS(47), 3, + sym_boolean, + sym_offset_date_time, + sym_local_time, + STATE(73), 4, + sym__basic_string, + sym__multiline_basic_string, + sym__literal_string, + sym__multiline_literal_string, + STATE(69), 6, + sym__inline_value, + sym_string, + sym_integer, + sym_float, + sym_array, + sym_inline_table, + [132] = 17, + ACTIONS(3), 1, + sym_comment, + ACTIONS(21), 1, + anon_sym_LBRACK, + ACTIONS(25), 1, + anon_sym_DQUOTE, + ACTIONS(27), 1, + anon_sym_DQUOTE_DQUOTE_DQUOTE, + ACTIONS(29), 1, + anon_sym_SQUOTE, + ACTIONS(31), 1, + anon_sym_SQUOTE_SQUOTE_SQUOTE, + ACTIONS(33), 1, + aux_sym_integer_token1, + ACTIONS(43), 1, + anon_sym_LBRACE, + ACTIONS(51), 1, + aux_sym_document_token1, + ACTIONS(53), 1, + anon_sym_RBRACK, + STATE(6), 1, + aux_sym_array_repeat1, + ACTIONS(37), 2, + aux_sym_float_token1, + aux_sym_float_token2, + ACTIONS(57), 2, + sym_local_date_time, + sym_local_date, + ACTIONS(35), 3, + aux_sym_integer_token2, + aux_sym_integer_token3, + aux_sym_integer_token4, + ACTIONS(55), 3, + sym_boolean, + sym_offset_date_time, + sym_local_time, + STATE(73), 4, + sym__basic_string, + sym__multiline_basic_string, + sym__literal_string, + sym__multiline_literal_string, + STATE(92), 6, + sym__inline_value, + sym_string, + sym_integer, + sym_float, + sym_array, + sym_inline_table, + [198] = 17, + ACTIONS(3), 1, + sym_comment, + ACTIONS(21), 1, + anon_sym_LBRACK, + ACTIONS(25), 1, + anon_sym_DQUOTE, + ACTIONS(27), 1, + anon_sym_DQUOTE_DQUOTE_DQUOTE, + ACTIONS(29), 1, + anon_sym_SQUOTE, + ACTIONS(31), 1, + anon_sym_SQUOTE_SQUOTE_SQUOTE, + ACTIONS(33), 1, + aux_sym_integer_token1, + ACTIONS(43), 1, + anon_sym_LBRACE, + ACTIONS(59), 1, + aux_sym_document_token1, + ACTIONS(61), 1, + anon_sym_RBRACK, + STATE(7), 1, + aux_sym_array_repeat1, + ACTIONS(37), 2, + aux_sym_float_token1, + aux_sym_float_token2, + ACTIONS(65), 2, + sym_local_date_time, + sym_local_date, + ACTIONS(35), 3, + aux_sym_integer_token2, + aux_sym_integer_token3, + aux_sym_integer_token4, + ACTIONS(63), 3, + sym_boolean, + sym_offset_date_time, + sym_local_time, + STATE(73), 4, + sym__basic_string, + sym__multiline_basic_string, + sym__literal_string, + sym__multiline_literal_string, + STATE(58), 6, + sym__inline_value, + sym_string, + sym_integer, + sym_float, + sym_array, + sym_inline_table, + [264] = 17, + ACTIONS(3), 1, + sym_comment, + ACTIONS(19), 1, + aux_sym_document_token1, + ACTIONS(21), 1, + anon_sym_LBRACK, + ACTIONS(25), 1, + anon_sym_DQUOTE, + ACTIONS(27), 1, + anon_sym_DQUOTE_DQUOTE_DQUOTE, + ACTIONS(29), 1, + anon_sym_SQUOTE, + ACTIONS(31), 1, + anon_sym_SQUOTE_SQUOTE_SQUOTE, + ACTIONS(33), 1, + aux_sym_integer_token1, + ACTIONS(43), 1, + anon_sym_LBRACE, + ACTIONS(67), 1, + anon_sym_RBRACK, + STATE(26), 1, + aux_sym_array_repeat1, + ACTIONS(37), 2, + aux_sym_float_token1, + aux_sym_float_token2, + ACTIONS(49), 2, + sym_local_date_time, + sym_local_date, + ACTIONS(35), 3, + aux_sym_integer_token2, + aux_sym_integer_token3, + aux_sym_integer_token4, + ACTIONS(47), 3, + sym_boolean, + sym_offset_date_time, + sym_local_time, + STATE(73), 4, + sym__basic_string, + sym__multiline_basic_string, + sym__literal_string, + sym__multiline_literal_string, + STATE(69), 6, + sym__inline_value, + sym_string, + sym_integer, + sym_float, + sym_array, + sym_inline_table, + [330] = 17, + ACTIONS(3), 1, + sym_comment, + ACTIONS(19), 1, + aux_sym_document_token1, + ACTIONS(21), 1, + anon_sym_LBRACK, + ACTIONS(25), 1, + anon_sym_DQUOTE, + ACTIONS(27), 1, + anon_sym_DQUOTE_DQUOTE_DQUOTE, + ACTIONS(29), 1, + anon_sym_SQUOTE, + ACTIONS(31), 1, + anon_sym_SQUOTE_SQUOTE_SQUOTE, + ACTIONS(33), 1, + aux_sym_integer_token1, + ACTIONS(43), 1, + anon_sym_LBRACE, + ACTIONS(69), 1, + anon_sym_RBRACK, + STATE(26), 1, + aux_sym_array_repeat1, + ACTIONS(37), 2, + aux_sym_float_token1, + aux_sym_float_token2, + ACTIONS(73), 2, + sym_local_date_time, + sym_local_date, + ACTIONS(35), 3, + aux_sym_integer_token2, + aux_sym_integer_token3, + aux_sym_integer_token4, + ACTIONS(71), 3, + sym_boolean, + sym_offset_date_time, + sym_local_time, + STATE(73), 4, + sym__basic_string, + sym__multiline_basic_string, + sym__literal_string, + sym__multiline_literal_string, + STATE(54), 6, + sym__inline_value, + sym_string, + sym_integer, + sym_float, + sym_array, + sym_inline_table, + [396] = 17, + ACTIONS(3), 1, + sym_comment, + ACTIONS(21), 1, + anon_sym_LBRACK, + ACTIONS(25), 1, + anon_sym_DQUOTE, + ACTIONS(27), 1, + anon_sym_DQUOTE_DQUOTE_DQUOTE, + ACTIONS(29), 1, + anon_sym_SQUOTE, + ACTIONS(31), 1, + anon_sym_SQUOTE_SQUOTE_SQUOTE, + ACTIONS(33), 1, + aux_sym_integer_token1, + ACTIONS(43), 1, + anon_sym_LBRACE, + ACTIONS(67), 1, + anon_sym_RBRACK, + ACTIONS(75), 1, + aux_sym_document_token1, + STATE(9), 1, + aux_sym_array_repeat1, + ACTIONS(37), 2, + aux_sym_float_token1, + aux_sym_float_token2, + ACTIONS(57), 2, + sym_local_date_time, + sym_local_date, + ACTIONS(35), 3, + aux_sym_integer_token2, + aux_sym_integer_token3, + aux_sym_integer_token4, + ACTIONS(55), 3, + sym_boolean, + sym_offset_date_time, + sym_local_time, + STATE(73), 4, + sym__basic_string, + sym__multiline_basic_string, + sym__literal_string, + sym__multiline_literal_string, + STATE(92), 6, + sym__inline_value, + sym_string, + sym_integer, + sym_float, + sym_array, + sym_inline_table, + [462] = 17, + ACTIONS(3), 1, + sym_comment, + ACTIONS(19), 1, + aux_sym_document_token1, + ACTIONS(21), 1, + anon_sym_LBRACK, + ACTIONS(25), 1, + anon_sym_DQUOTE, + ACTIONS(27), 1, + anon_sym_DQUOTE_DQUOTE_DQUOTE, + ACTIONS(29), 1, + anon_sym_SQUOTE, + ACTIONS(31), 1, + anon_sym_SQUOTE_SQUOTE_SQUOTE, + ACTIONS(33), 1, + aux_sym_integer_token1, + ACTIONS(43), 1, + anon_sym_LBRACE, + ACTIONS(77), 1, + anon_sym_RBRACK, + STATE(26), 1, + aux_sym_array_repeat1, + ACTIONS(37), 2, + aux_sym_float_token1, + aux_sym_float_token2, + ACTIONS(49), 2, + sym_local_date_time, + sym_local_date, + ACTIONS(35), 3, + aux_sym_integer_token2, + aux_sym_integer_token3, + aux_sym_integer_token4, + ACTIONS(47), 3, + sym_boolean, + sym_offset_date_time, + sym_local_time, + STATE(73), 4, + sym__basic_string, + sym__multiline_basic_string, + sym__literal_string, + sym__multiline_literal_string, + STATE(69), 6, + sym__inline_value, + sym_string, + sym_integer, + sym_float, + sym_array, + sym_inline_table, + [528] = 17, + ACTIONS(3), 1, + sym_comment, + ACTIONS(21), 1, + anon_sym_LBRACK, + ACTIONS(25), 1, + anon_sym_DQUOTE, + ACTIONS(27), 1, + anon_sym_DQUOTE_DQUOTE_DQUOTE, + ACTIONS(29), 1, + anon_sym_SQUOTE, + ACTIONS(31), 1, + anon_sym_SQUOTE_SQUOTE_SQUOTE, + ACTIONS(33), 1, + aux_sym_integer_token1, + ACTIONS(43), 1, + anon_sym_LBRACE, + ACTIONS(77), 1, + anon_sym_RBRACK, + ACTIONS(79), 1, + aux_sym_document_token1, + STATE(12), 1, + aux_sym_array_repeat1, + ACTIONS(37), 2, + aux_sym_float_token1, + aux_sym_float_token2, + ACTIONS(57), 2, + sym_local_date_time, + sym_local_date, + ACTIONS(35), 3, + aux_sym_integer_token2, + aux_sym_integer_token3, + aux_sym_integer_token4, + ACTIONS(55), 3, + sym_boolean, + sym_offset_date_time, + sym_local_time, + STATE(73), 4, + sym__basic_string, + sym__multiline_basic_string, + sym__literal_string, + sym__multiline_literal_string, + STATE(92), 6, + sym__inline_value, + sym_string, + sym_integer, + sym_float, + sym_array, + sym_inline_table, + [594] = 17, + ACTIONS(3), 1, + sym_comment, + ACTIONS(19), 1, + aux_sym_document_token1, + ACTIONS(21), 1, + anon_sym_LBRACK, + ACTIONS(25), 1, + anon_sym_DQUOTE, + ACTIONS(27), 1, + anon_sym_DQUOTE_DQUOTE_DQUOTE, + ACTIONS(29), 1, + anon_sym_SQUOTE, + ACTIONS(31), 1, + anon_sym_SQUOTE_SQUOTE_SQUOTE, + ACTIONS(33), 1, + aux_sym_integer_token1, + ACTIONS(43), 1, + anon_sym_LBRACE, + ACTIONS(81), 1, + anon_sym_RBRACK, + STATE(26), 1, + aux_sym_array_repeat1, + ACTIONS(37), 2, + aux_sym_float_token1, + aux_sym_float_token2, + ACTIONS(49), 2, + sym_local_date_time, + sym_local_date, + ACTIONS(35), 3, + aux_sym_integer_token2, + aux_sym_integer_token3, + aux_sym_integer_token4, + ACTIONS(47), 3, + sym_boolean, + sym_offset_date_time, + sym_local_time, + STATE(73), 4, + sym__basic_string, + sym__multiline_basic_string, + sym__literal_string, + sym__multiline_literal_string, + STATE(69), 6, + sym__inline_value, + sym_string, + sym_integer, + sym_float, + sym_array, + sym_inline_table, + [660] = 17, + ACTIONS(3), 1, + sym_comment, + ACTIONS(19), 1, + aux_sym_document_token1, + ACTIONS(21), 1, + anon_sym_LBRACK, + ACTIONS(25), 1, + anon_sym_DQUOTE, + ACTIONS(27), 1, + anon_sym_DQUOTE_DQUOTE_DQUOTE, + ACTIONS(29), 1, + anon_sym_SQUOTE, + ACTIONS(31), 1, + anon_sym_SQUOTE_SQUOTE_SQUOTE, + ACTIONS(33), 1, + aux_sym_integer_token1, + ACTIONS(43), 1, + anon_sym_LBRACE, + ACTIONS(83), 1, + anon_sym_RBRACK, + STATE(26), 1, + aux_sym_array_repeat1, + ACTIONS(37), 2, + aux_sym_float_token1, + aux_sym_float_token2, + ACTIONS(49), 2, + sym_local_date_time, + sym_local_date, + ACTIONS(35), 3, + aux_sym_integer_token2, + aux_sym_integer_token3, + aux_sym_integer_token4, + ACTIONS(47), 3, + sym_boolean, + sym_offset_date_time, + sym_local_time, + STATE(73), 4, + sym__basic_string, + sym__multiline_basic_string, + sym__literal_string, + sym__multiline_literal_string, + STATE(69), 6, + sym__inline_value, + sym_string, + sym_integer, + sym_float, + sym_array, + sym_inline_table, + [726] = 17, + ACTIONS(3), 1, + sym_comment, + ACTIONS(21), 1, + anon_sym_LBRACK, + ACTIONS(25), 1, + anon_sym_DQUOTE, + ACTIONS(27), 1, + anon_sym_DQUOTE_DQUOTE_DQUOTE, + ACTIONS(29), 1, + anon_sym_SQUOTE, + ACTIONS(31), 1, + anon_sym_SQUOTE_SQUOTE_SQUOTE, + ACTIONS(33), 1, + aux_sym_integer_token1, + ACTIONS(43), 1, + anon_sym_LBRACE, + ACTIONS(83), 1, + anon_sym_RBRACK, + ACTIONS(85), 1, + aux_sym_document_token1, + STATE(15), 1, + aux_sym_array_repeat1, + ACTIONS(37), 2, + aux_sym_float_token1, + aux_sym_float_token2, + ACTIONS(57), 2, + sym_local_date_time, + sym_local_date, + ACTIONS(35), 3, + aux_sym_integer_token2, + aux_sym_integer_token3, + aux_sym_integer_token4, + ACTIONS(55), 3, + sym_boolean, + sym_offset_date_time, + sym_local_time, + STATE(73), 4, + sym__basic_string, + sym__multiline_basic_string, + sym__literal_string, + sym__multiline_literal_string, + STATE(92), 6, + sym__inline_value, + sym_string, + sym_integer, + sym_float, + sym_array, + sym_inline_table, + [792] = 17, + ACTIONS(3), 1, + sym_comment, + ACTIONS(21), 1, + anon_sym_LBRACK, + ACTIONS(25), 1, + anon_sym_DQUOTE, + ACTIONS(27), 1, + anon_sym_DQUOTE_DQUOTE_DQUOTE, + ACTIONS(29), 1, + anon_sym_SQUOTE, + ACTIONS(31), 1, + anon_sym_SQUOTE_SQUOTE_SQUOTE, + ACTIONS(33), 1, + aux_sym_integer_token1, + ACTIONS(43), 1, + anon_sym_LBRACE, + ACTIONS(87), 1, + aux_sym_document_token1, + ACTIONS(89), 1, + anon_sym_RBRACK, + STATE(2), 1, + aux_sym_array_repeat1, + ACTIONS(37), 2, + aux_sym_float_token1, + aux_sym_float_token2, + ACTIONS(93), 2, + sym_local_date_time, + sym_local_date, + ACTIONS(35), 3, + aux_sym_integer_token2, + aux_sym_integer_token3, + aux_sym_integer_token4, + ACTIONS(91), 3, + sym_boolean, + sym_offset_date_time, + sym_local_time, + STATE(73), 4, + sym__basic_string, + sym__multiline_basic_string, + sym__literal_string, + sym__multiline_literal_string, + STATE(60), 6, + sym__inline_value, + sym_string, + sym_integer, + sym_float, + sym_array, + sym_inline_table, + [858] = 17, + ACTIONS(3), 1, + sym_comment, + ACTIONS(19), 1, + aux_sym_document_token1, + ACTIONS(21), 1, + anon_sym_LBRACK, + ACTIONS(25), 1, + anon_sym_DQUOTE, + ACTIONS(27), 1, + anon_sym_DQUOTE_DQUOTE_DQUOTE, + ACTIONS(29), 1, + anon_sym_SQUOTE, + ACTIONS(31), 1, + anon_sym_SQUOTE_SQUOTE_SQUOTE, + ACTIONS(33), 1, + aux_sym_integer_token1, + ACTIONS(43), 1, + anon_sym_LBRACE, + ACTIONS(95), 1, + anon_sym_RBRACK, + STATE(26), 1, + aux_sym_array_repeat1, + ACTIONS(37), 2, + aux_sym_float_token1, + aux_sym_float_token2, + ACTIONS(49), 2, + sym_local_date_time, + sym_local_date, + ACTIONS(35), 3, + aux_sym_integer_token2, + aux_sym_integer_token3, + aux_sym_integer_token4, + ACTIONS(47), 3, + sym_boolean, + sym_offset_date_time, + sym_local_time, + STATE(73), 4, + sym__basic_string, + sym__multiline_basic_string, + sym__literal_string, + sym__multiline_literal_string, + STATE(69), 6, + sym__inline_value, + sym_string, + sym_integer, + sym_float, + sym_array, + sym_inline_table, + [924] = 17, + ACTIONS(3), 1, + sym_comment, + ACTIONS(21), 1, + anon_sym_LBRACK, + ACTIONS(25), 1, + anon_sym_DQUOTE, + ACTIONS(27), 1, + anon_sym_DQUOTE_DQUOTE_DQUOTE, + ACTIONS(29), 1, + anon_sym_SQUOTE, + ACTIONS(31), 1, + anon_sym_SQUOTE_SQUOTE_SQUOTE, + ACTIONS(33), 1, + aux_sym_integer_token1, + ACTIONS(43), 1, + anon_sym_LBRACE, + ACTIONS(97), 1, + aux_sym_document_token1, + ACTIONS(99), 1, + anon_sym_RBRACK, + STATE(11), 1, + aux_sym_array_repeat1, + ACTIONS(37), 2, + aux_sym_float_token1, + aux_sym_float_token2, + ACTIONS(57), 2, + sym_local_date_time, + sym_local_date, + ACTIONS(35), 3, + aux_sym_integer_token2, + aux_sym_integer_token3, + aux_sym_integer_token4, + ACTIONS(55), 3, + sym_boolean, + sym_offset_date_time, + sym_local_time, + STATE(73), 4, + sym__basic_string, + sym__multiline_basic_string, + sym__literal_string, + sym__multiline_literal_string, + STATE(92), 6, + sym__inline_value, + sym_string, + sym_integer, + sym_float, + sym_array, + sym_inline_table, + [990] = 17, + ACTIONS(3), 1, + sym_comment, + ACTIONS(19), 1, + aux_sym_document_token1, + ACTIONS(21), 1, + anon_sym_LBRACK, + ACTIONS(25), 1, + anon_sym_DQUOTE, + ACTIONS(27), 1, + anon_sym_DQUOTE_DQUOTE_DQUOTE, + ACTIONS(29), 1, + anon_sym_SQUOTE, + ACTIONS(31), 1, + anon_sym_SQUOTE_SQUOTE_SQUOTE, + ACTIONS(33), 1, + aux_sym_integer_token1, + ACTIONS(43), 1, + anon_sym_LBRACE, + ACTIONS(99), 1, + anon_sym_RBRACK, + STATE(26), 1, + aux_sym_array_repeat1, + ACTIONS(37), 2, + aux_sym_float_token1, + aux_sym_float_token2, + ACTIONS(49), 2, + sym_local_date_time, + sym_local_date, + ACTIONS(35), 3, + aux_sym_integer_token2, + aux_sym_integer_token3, + aux_sym_integer_token4, + ACTIONS(47), 3, + sym_boolean, + sym_offset_date_time, + sym_local_time, + STATE(73), 4, + sym__basic_string, + sym__multiline_basic_string, + sym__literal_string, + sym__multiline_literal_string, + STATE(69), 6, + sym__inline_value, + sym_string, + sym_integer, + sym_float, + sym_array, + sym_inline_table, + [1056] = 17, + ACTIONS(3), 1, + sym_comment, + ACTIONS(21), 1, + anon_sym_LBRACK, + ACTIONS(25), 1, + anon_sym_DQUOTE, + ACTIONS(27), 1, + anon_sym_DQUOTE_DQUOTE_DQUOTE, + ACTIONS(29), 1, + anon_sym_SQUOTE, + ACTIONS(31), 1, + anon_sym_SQUOTE_SQUOTE_SQUOTE, + ACTIONS(33), 1, + aux_sym_integer_token1, + ACTIONS(43), 1, + anon_sym_LBRACE, + ACTIONS(101), 1, + aux_sym_document_token1, + ACTIONS(103), 1, + anon_sym_RBRACK, + STATE(17), 1, + aux_sym_array_repeat1, + ACTIONS(37), 2, + aux_sym_float_token1, + aux_sym_float_token2, + ACTIONS(57), 2, + sym_local_date_time, + sym_local_date, + ACTIONS(35), 3, + aux_sym_integer_token2, + aux_sym_integer_token3, + aux_sym_integer_token4, + ACTIONS(55), 3, + sym_boolean, + sym_offset_date_time, + sym_local_time, + STATE(73), 4, + sym__basic_string, + sym__multiline_basic_string, + sym__literal_string, + sym__multiline_literal_string, + STATE(92), 6, + sym__inline_value, + sym_string, + sym_integer, + sym_float, + sym_array, + sym_inline_table, + [1122] = 17, + ACTIONS(3), 1, + sym_comment, + ACTIONS(21), 1, + anon_sym_LBRACK, + ACTIONS(25), 1, + anon_sym_DQUOTE, + ACTIONS(27), 1, + anon_sym_DQUOTE_DQUOTE_DQUOTE, + ACTIONS(29), 1, + anon_sym_SQUOTE, + ACTIONS(31), 1, + anon_sym_SQUOTE_SQUOTE_SQUOTE, + ACTIONS(33), 1, + aux_sym_integer_token1, + ACTIONS(43), 1, + anon_sym_LBRACE, + ACTIONS(81), 1, + anon_sym_RBRACK, + ACTIONS(105), 1, + aux_sym_document_token1, + STATE(20), 1, + aux_sym_array_repeat1, + ACTIONS(37), 2, + aux_sym_float_token1, + aux_sym_float_token2, + ACTIONS(57), 2, + sym_local_date_time, + sym_local_date, + ACTIONS(35), 3, + aux_sym_integer_token2, + aux_sym_integer_token3, + aux_sym_integer_token4, + ACTIONS(55), 3, + sym_boolean, + sym_offset_date_time, + sym_local_time, + STATE(73), 4, + sym__basic_string, + sym__multiline_basic_string, + sym__literal_string, + sym__multiline_literal_string, + STATE(92), 6, + sym__inline_value, + sym_string, + sym_integer, + sym_float, + sym_array, + sym_inline_table, + [1188] = 17, + ACTIONS(3), 1, + sym_comment, + ACTIONS(19), 1, + aux_sym_document_token1, + ACTIONS(21), 1, + anon_sym_LBRACK, + ACTIONS(25), 1, + anon_sym_DQUOTE, + ACTIONS(27), 1, + anon_sym_DQUOTE_DQUOTE_DQUOTE, + ACTIONS(29), 1, + anon_sym_SQUOTE, + ACTIONS(31), 1, + anon_sym_SQUOTE_SQUOTE_SQUOTE, + ACTIONS(33), 1, + aux_sym_integer_token1, + ACTIONS(43), 1, + anon_sym_LBRACE, + ACTIONS(107), 1, + anon_sym_RBRACK, + STATE(26), 1, + aux_sym_array_repeat1, + ACTIONS(37), 2, + aux_sym_float_token1, + aux_sym_float_token2, + ACTIONS(49), 2, + sym_local_date_time, + sym_local_date, + ACTIONS(35), 3, + aux_sym_integer_token2, + aux_sym_integer_token3, + aux_sym_integer_token4, + ACTIONS(47), 3, + sym_boolean, + sym_offset_date_time, + sym_local_time, + STATE(73), 4, + sym__basic_string, + sym__multiline_basic_string, + sym__literal_string, + sym__multiline_literal_string, + STATE(69), 6, + sym__inline_value, + sym_string, + sym_integer, + sym_float, + sym_array, + sym_inline_table, + [1254] = 17, + ACTIONS(3), 1, + sym_comment, + ACTIONS(21), 1, + anon_sym_LBRACK, + ACTIONS(25), 1, + anon_sym_DQUOTE, + ACTIONS(27), 1, + anon_sym_DQUOTE_DQUOTE_DQUOTE, + ACTIONS(29), 1, + anon_sym_SQUOTE, + ACTIONS(31), 1, + anon_sym_SQUOTE_SQUOTE_SQUOTE, + ACTIONS(33), 1, + aux_sym_integer_token1, + ACTIONS(43), 1, + anon_sym_LBRACE, + ACTIONS(107), 1, + anon_sym_RBRACK, + ACTIONS(109), 1, + aux_sym_document_token1, + STATE(3), 1, + aux_sym_array_repeat1, + ACTIONS(37), 2, + aux_sym_float_token1, + aux_sym_float_token2, + ACTIONS(57), 2, + sym_local_date_time, + sym_local_date, + ACTIONS(35), 3, + aux_sym_integer_token2, + aux_sym_integer_token3, + aux_sym_integer_token4, + ACTIONS(55), 3, + sym_boolean, + sym_offset_date_time, + sym_local_time, + STATE(73), 4, + sym__basic_string, + sym__multiline_basic_string, + sym__literal_string, + sym__multiline_literal_string, + STATE(92), 6, + sym__inline_value, + sym_string, + sym_integer, + sym_float, + sym_array, + sym_inline_table, + [1320] = 16, + ACTIONS(3), 1, + sym_comment, + ACTIONS(21), 1, + anon_sym_LBRACK, + ACTIONS(25), 1, + anon_sym_DQUOTE, + ACTIONS(27), 1, + anon_sym_DQUOTE_DQUOTE_DQUOTE, + ACTIONS(29), 1, + anon_sym_SQUOTE, + ACTIONS(31), 1, + anon_sym_SQUOTE_SQUOTE_SQUOTE, + ACTIONS(33), 1, + aux_sym_integer_token1, + ACTIONS(43), 1, + anon_sym_LBRACE, + ACTIONS(111), 1, + aux_sym_document_token1, + STATE(23), 1, + aux_sym_array_repeat1, + ACTIONS(37), 2, + aux_sym_float_token1, + aux_sym_float_token2, + ACTIONS(57), 2, + sym_local_date_time, + sym_local_date, + ACTIONS(35), 3, + aux_sym_integer_token2, + aux_sym_integer_token3, + aux_sym_integer_token4, + ACTIONS(55), 3, + sym_boolean, + sym_offset_date_time, + sym_local_time, + STATE(73), 4, + sym__basic_string, + sym__multiline_basic_string, + sym__literal_string, + sym__multiline_literal_string, + STATE(92), 6, + sym__inline_value, + sym_string, + sym_integer, + sym_float, + sym_array, + sym_inline_table, + [1383] = 16, + ACTIONS(3), 1, + sym_comment, + ACTIONS(19), 1, + aux_sym_document_token1, + ACTIONS(21), 1, + anon_sym_LBRACK, + ACTIONS(25), 1, + anon_sym_DQUOTE, + ACTIONS(27), 1, + anon_sym_DQUOTE_DQUOTE_DQUOTE, + ACTIONS(29), 1, + anon_sym_SQUOTE, + ACTIONS(31), 1, + anon_sym_SQUOTE_SQUOTE_SQUOTE, + ACTIONS(33), 1, + aux_sym_integer_token1, + ACTIONS(43), 1, + anon_sym_LBRACE, + STATE(26), 1, + aux_sym_array_repeat1, + ACTIONS(37), 2, + aux_sym_float_token1, + aux_sym_float_token2, + ACTIONS(49), 2, + sym_local_date_time, + sym_local_date, + ACTIONS(35), 3, + aux_sym_integer_token2, + aux_sym_integer_token3, + aux_sym_integer_token4, + ACTIONS(47), 3, + sym_boolean, + sym_offset_date_time, + sym_local_time, + STATE(73), 4, + sym__basic_string, + sym__multiline_basic_string, + sym__literal_string, + sym__multiline_literal_string, + STATE(69), 6, + sym__inline_value, + sym_string, + sym_integer, + sym_float, + sym_array, + sym_inline_table, + [1446] = 14, + ACTIONS(3), 1, + sym_comment, + ACTIONS(113), 1, + anon_sym_LBRACK, + ACTIONS(115), 1, + anon_sym_DQUOTE, + ACTIONS(117), 1, + anon_sym_DQUOTE_DQUOTE_DQUOTE, + ACTIONS(119), 1, + anon_sym_SQUOTE, + ACTIONS(121), 1, + anon_sym_SQUOTE_SQUOTE_SQUOTE, + ACTIONS(123), 1, + aux_sym_integer_token1, + ACTIONS(133), 1, + anon_sym_LBRACE, + ACTIONS(127), 2, + aux_sym_float_token1, + aux_sym_float_token2, + ACTIONS(131), 2, + sym_local_date_time, + sym_local_date, + ACTIONS(125), 3, + aux_sym_integer_token2, + aux_sym_integer_token3, + aux_sym_integer_token4, + ACTIONS(129), 3, + sym_boolean, + sym_offset_date_time, + sym_local_time, + STATE(139), 4, + sym__basic_string, + sym__multiline_basic_string, + sym__literal_string, + sym__multiline_literal_string, + STATE(138), 6, + sym__inline_value, + sym_string, + sym_integer, + sym_float, + sym_array, + sym_inline_table, + [1503] = 14, + ACTIONS(3), 1, + sym_comment, + ACTIONS(21), 1, + anon_sym_LBRACK, + ACTIONS(25), 1, + anon_sym_DQUOTE, + ACTIONS(27), 1, + anon_sym_DQUOTE_DQUOTE_DQUOTE, + ACTIONS(29), 1, + anon_sym_SQUOTE, + ACTIONS(31), 1, + anon_sym_SQUOTE_SQUOTE_SQUOTE, + ACTIONS(33), 1, + aux_sym_integer_token1, + ACTIONS(43), 1, + anon_sym_LBRACE, + ACTIONS(37), 2, + aux_sym_float_token1, + aux_sym_float_token2, + ACTIONS(137), 2, + sym_local_date_time, + sym_local_date, + ACTIONS(35), 3, + aux_sym_integer_token2, + aux_sym_integer_token3, + aux_sym_integer_token4, + ACTIONS(135), 3, + sym_boolean, + sym_offset_date_time, + sym_local_time, + STATE(73), 4, + sym__basic_string, + sym__multiline_basic_string, + sym__literal_string, + sym__multiline_literal_string, + STATE(115), 6, + sym__inline_value, + sym_string, + sym_integer, + sym_float, + sym_array, + sym_inline_table, + [1560] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(139), 1, + aux_sym_document_token1, + STATE(26), 1, + aux_sym_array_repeat1, + ACTIONS(144), 5, + anon_sym_DQUOTE, + anon_sym_SQUOTE, + aux_sym_integer_token1, + sym_local_date_time, + sym_local_date, + ACTIONS(142), 14, + anon_sym_LBRACK, + anon_sym_RBRACK, + anon_sym_DQUOTE_DQUOTE_DQUOTE, + anon_sym_SQUOTE_SQUOTE_SQUOTE, + aux_sym_integer_token2, + aux_sym_integer_token3, + aux_sym_integer_token4, + aux_sym_float_token1, + aux_sym_float_token2, + sym_boolean, + sym_offset_date_time, + sym_local_time, + anon_sym_COMMA, + anon_sym_LBRACE, + [1593] = 13, + ACTIONS(3), 1, + sym_comment, + ACTIONS(9), 1, + anon_sym_LBRACK, + ACTIONS(11), 1, + anon_sym_LBRACK_LBRACK, + ACTIONS(13), 1, + sym_bare_key, + ACTIONS(15), 1, + anon_sym_DQUOTE, + ACTIONS(17), 1, + anon_sym_SQUOTE, + ACTIONS(146), 1, + ts_builtin_sym_end, + ACTIONS(148), 1, + aux_sym_document_token1, + STATE(127), 1, + sym__inline_pair, + STATE(29), 2, + sym_pair, + aux_sym_document_repeat1, + STATE(96), 2, + sym__basic_string, + sym__literal_string, + STATE(49), 3, + sym_table, + sym_table_array_element, + aux_sym_document_repeat2, + STATE(119), 3, + sym__key, + sym_dotted_key, + sym_quoted_key, + [1639] = 11, + ACTIONS(3), 1, + sym_comment, + ACTIONS(13), 1, + sym_bare_key, + ACTIONS(15), 1, + anon_sym_DQUOTE, + ACTIONS(17), 1, + anon_sym_SQUOTE, + ACTIONS(152), 1, + aux_sym_document_token1, + ACTIONS(154), 1, + anon_sym_LBRACK, + STATE(127), 1, + sym__inline_pair, + ACTIONS(150), 2, + ts_builtin_sym_end, + anon_sym_LBRACK_LBRACK, + STATE(31), 2, + sym_pair, + aux_sym_document_repeat1, + STATE(96), 2, + sym__basic_string, + sym__literal_string, + STATE(119), 3, + sym__key, + sym_dotted_key, + sym_quoted_key, + [1678] = 11, + ACTIONS(3), 1, + sym_comment, + ACTIONS(158), 1, + aux_sym_document_token1, + ACTIONS(161), 1, + anon_sym_LBRACK, + ACTIONS(163), 1, + sym_bare_key, + ACTIONS(166), 1, + anon_sym_DQUOTE, + ACTIONS(169), 1, + anon_sym_SQUOTE, + STATE(127), 1, + sym__inline_pair, + ACTIONS(156), 2, + ts_builtin_sym_end, + anon_sym_LBRACK_LBRACK, + STATE(29), 2, + sym_pair, + aux_sym_document_repeat1, + STATE(96), 2, + sym__basic_string, + sym__literal_string, + STATE(119), 3, + sym__key, + sym_dotted_key, + sym_quoted_key, + [1717] = 11, + ACTIONS(3), 1, + sym_comment, + ACTIONS(13), 1, + sym_bare_key, + ACTIONS(15), 1, + anon_sym_DQUOTE, + ACTIONS(17), 1, + anon_sym_SQUOTE, + ACTIONS(148), 1, + aux_sym_document_token1, + ACTIONS(174), 1, + anon_sym_LBRACK, + STATE(127), 1, + sym__inline_pair, + ACTIONS(172), 2, + ts_builtin_sym_end, + anon_sym_LBRACK_LBRACK, + STATE(29), 2, + sym_pair, + aux_sym_document_repeat1, + STATE(96), 2, + sym__basic_string, + sym__literal_string, + STATE(119), 3, + sym__key, + sym_dotted_key, + sym_quoted_key, + [1756] = 11, + ACTIONS(3), 1, + sym_comment, + ACTIONS(13), 1, + sym_bare_key, + ACTIONS(15), 1, + anon_sym_DQUOTE, + ACTIONS(17), 1, + anon_sym_SQUOTE, + ACTIONS(148), 1, + aux_sym_document_token1, + ACTIONS(178), 1, + anon_sym_LBRACK, + STATE(127), 1, + sym__inline_pair, + ACTIONS(176), 2, + ts_builtin_sym_end, + anon_sym_LBRACK_LBRACK, + STATE(29), 2, + sym_pair, + aux_sym_document_repeat1, + STATE(96), 2, + sym__basic_string, + sym__literal_string, + STATE(119), 3, + sym__key, + sym_dotted_key, + sym_quoted_key, + [1795] = 11, + ACTIONS(3), 1, + sym_comment, + ACTIONS(13), 1, + sym_bare_key, + ACTIONS(15), 1, + anon_sym_DQUOTE, + ACTIONS(17), 1, + anon_sym_SQUOTE, + ACTIONS(182), 1, + aux_sym_document_token1, + ACTIONS(184), 1, + anon_sym_LBRACK, + STATE(127), 1, + sym__inline_pair, + ACTIONS(180), 2, + ts_builtin_sym_end, + anon_sym_LBRACK_LBRACK, + STATE(30), 2, + sym_pair, + aux_sym_document_repeat1, + STATE(96), 2, + sym__basic_string, + sym__literal_string, + STATE(119), 3, + sym__key, + sym_dotted_key, + sym_quoted_key, + [1834] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(15), 1, + anon_sym_DQUOTE, + ACTIONS(17), 1, + anon_sym_SQUOTE, + ACTIONS(186), 1, + sym_bare_key, + ACTIONS(188), 1, + anon_sym_RBRACE, + STATE(94), 1, + sym__inline_pair, + STATE(96), 2, + sym__basic_string, + sym__literal_string, + STATE(109), 3, + sym__key, + sym_dotted_key, + sym_quoted_key, + [1862] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(15), 1, + anon_sym_DQUOTE, + ACTIONS(17), 1, + anon_sym_SQUOTE, + ACTIONS(186), 1, + sym_bare_key, + ACTIONS(190), 1, + anon_sym_RBRACE, + STATE(98), 1, + sym__inline_pair, + STATE(96), 2, + sym__basic_string, + sym__literal_string, + STATE(109), 3, + sym__key, + sym_dotted_key, + sym_quoted_key, + [1890] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(15), 1, + anon_sym_DQUOTE, + ACTIONS(17), 1, + anon_sym_SQUOTE, + ACTIONS(186), 1, + sym_bare_key, + STATE(108), 1, + sym__inline_pair, + STATE(96), 2, + sym__basic_string, + sym__literal_string, + STATE(109), 3, + sym__key, + sym_dotted_key, + sym_quoted_key, + [1915] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(15), 1, + anon_sym_DQUOTE, + ACTIONS(17), 1, + anon_sym_SQUOTE, + ACTIONS(192), 1, + sym_bare_key, + STATE(96), 2, + sym__basic_string, + sym__literal_string, + STATE(117), 3, + sym__key, + sym_dotted_key, + sym_quoted_key, + [1937] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(194), 1, + sym_bare_key, + ACTIONS(196), 1, + anon_sym_DQUOTE, + ACTIONS(198), 1, + anon_sym_SQUOTE, + STATE(122), 2, + sym__basic_string, + sym__literal_string, + STATE(120), 3, + sym__key, + sym_dotted_key, + sym_quoted_key, + [1959] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(202), 1, + anon_sym_LBRACK, + ACTIONS(200), 6, + ts_builtin_sym_end, + aux_sym_document_token1, + anon_sym_LBRACK_LBRACK, + sym_bare_key, + anon_sym_DQUOTE, + anon_sym_SQUOTE, + [1974] = 4, + ACTIONS(204), 1, + sym_comment, + ACTIONS(209), 1, + sym__multiline_basic_string_end, + STATE(39), 1, + aux_sym__multiline_basic_string_repeat1, + ACTIONS(206), 5, + sym__multiline_basic_string_content, + aux_sym__basic_string_token1, + aux_sym__multiline_basic_string_token1, + sym_escape_sequence, + sym__escape_line_ending, + [1991] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(196), 1, + anon_sym_DQUOTE, + ACTIONS(198), 1, + anon_sym_SQUOTE, + ACTIONS(211), 1, + sym_bare_key, + STATE(118), 2, + sym__key, + sym_quoted_key, + STATE(122), 2, + sym__basic_string, + sym__literal_string, + [2012] = 4, + ACTIONS(204), 1, + sym_comment, + ACTIONS(215), 1, + sym__multiline_basic_string_end, + STATE(43), 1, + aux_sym__multiline_basic_string_repeat1, + ACTIONS(213), 5, + sym__multiline_basic_string_content, + aux_sym__basic_string_token1, + aux_sym__multiline_basic_string_token1, + sym_escape_sequence, + sym__escape_line_ending, + [2029] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(15), 1, + anon_sym_DQUOTE, + ACTIONS(17), 1, + anon_sym_SQUOTE, + ACTIONS(217), 1, + sym_bare_key, + STATE(96), 2, + sym__basic_string, + sym__literal_string, + STATE(107), 2, + sym__key, + sym_quoted_key, + [2050] = 4, + ACTIONS(204), 1, + sym_comment, + ACTIONS(221), 1, + sym__multiline_basic_string_end, + STATE(39), 1, + aux_sym__multiline_basic_string_repeat1, + ACTIONS(219), 5, + sym__multiline_basic_string_content, + aux_sym__basic_string_token1, + aux_sym__multiline_basic_string_token1, + sym_escape_sequence, + sym__escape_line_ending, + [2067] = 4, + ACTIONS(204), 1, + sym_comment, + ACTIONS(225), 1, + sym__multiline_basic_string_end, + STATE(45), 1, + aux_sym__multiline_basic_string_repeat1, + ACTIONS(223), 5, + sym__multiline_basic_string_content, + aux_sym__basic_string_token1, + aux_sym__multiline_basic_string_token1, + sym_escape_sequence, + sym__escape_line_ending, + [2084] = 4, + ACTIONS(204), 1, + sym_comment, + ACTIONS(227), 1, + sym__multiline_basic_string_end, + STATE(39), 1, + aux_sym__multiline_basic_string_repeat1, + ACTIONS(219), 5, + sym__multiline_basic_string_content, + aux_sym__basic_string_token1, + aux_sym__multiline_basic_string_token1, + sym_escape_sequence, + sym__escape_line_ending, + [2101] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(9), 1, + anon_sym_LBRACK, + ACTIONS(11), 1, + anon_sym_LBRACK_LBRACK, + ACTIONS(146), 1, + ts_builtin_sym_end, + STATE(50), 3, + sym_table, + sym_table_array_element, + aux_sym_document_repeat2, + [2119] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(229), 6, + aux_sym_document_token1, + anon_sym_RBRACK, + anon_sym_EQ, + anon_sym_DOT, + anon_sym_COMMA, + anon_sym_RBRACE, + [2131] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(231), 6, + aux_sym_document_token1, + anon_sym_RBRACK, + anon_sym_EQ, + anon_sym_DOT, + anon_sym_COMMA, + anon_sym_RBRACE, + [2143] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(9), 1, + anon_sym_LBRACK, + ACTIONS(11), 1, + anon_sym_LBRACK_LBRACK, + ACTIONS(233), 1, + ts_builtin_sym_end, + STATE(50), 3, + sym_table, + sym_table_array_element, + aux_sym_document_repeat2, + [2161] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(235), 1, + ts_builtin_sym_end, + ACTIONS(237), 1, + anon_sym_LBRACK, + ACTIONS(240), 1, + anon_sym_LBRACK_LBRACK, + STATE(50), 3, + sym_table, + sym_table_array_element, + aux_sym_document_repeat2, + [2179] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(243), 6, + aux_sym_document_token1, + anon_sym_RBRACK, + anon_sym_EQ, + anon_sym_DOT, + anon_sym_COMMA, + anon_sym_RBRACE, + [2191] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(245), 6, + aux_sym_document_token1, + anon_sym_RBRACK, + anon_sym_EQ, + anon_sym_DOT, + anon_sym_COMMA, + anon_sym_RBRACE, + [2203] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(19), 1, + aux_sym_document_token1, + ACTIONS(103), 1, + anon_sym_RBRACK, + ACTIONS(247), 1, + anon_sym_COMMA, + STATE(26), 1, + aux_sym_array_repeat1, + STATE(103), 1, + aux_sym_array_repeat2, + [2222] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(53), 1, + anon_sym_RBRACK, + ACTIONS(249), 1, + aux_sym_document_token1, + ACTIONS(251), 1, + anon_sym_COMMA, + STATE(56), 1, + aux_sym_array_repeat1, + STATE(102), 1, + aux_sym_array_repeat2, + [2241] = 4, + ACTIONS(204), 1, + sym_comment, + ACTIONS(256), 1, + sym__multiline_literal_string_end, + STATE(55), 1, + aux_sym__multiline_literal_string_repeat1, + ACTIONS(253), 3, + sym__multiline_literal_string_content, + aux_sym__multiline_basic_string_token1, + aux_sym__literal_string_token1, + [2256] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(19), 1, + aux_sym_document_token1, + ACTIONS(67), 1, + anon_sym_RBRACK, + ACTIONS(258), 1, + anon_sym_COMMA, + STATE(26), 1, + aux_sym_array_repeat1, + STATE(104), 1, + aux_sym_array_repeat2, + [2275] = 4, + ACTIONS(204), 1, + sym_comment, + ACTIONS(262), 1, + sym__multiline_literal_string_end, + STATE(62), 1, + aux_sym__multiline_literal_string_repeat1, + ACTIONS(260), 3, + sym__multiline_literal_string_content, + aux_sym__multiline_basic_string_token1, + aux_sym__literal_string_token1, + [2290] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(69), 1, + anon_sym_RBRACK, + ACTIONS(264), 1, + aux_sym_document_token1, + ACTIONS(266), 1, + anon_sym_COMMA, + STATE(65), 1, + aux_sym_array_repeat1, + STATE(97), 1, + aux_sym_array_repeat2, + [2309] = 4, + ACTIONS(204), 1, + sym_comment, + ACTIONS(270), 1, + sym__multiline_literal_string_end, + STATE(61), 1, + aux_sym__multiline_literal_string_repeat1, + ACTIONS(268), 3, + sym__multiline_literal_string_content, + aux_sym__multiline_basic_string_token1, + aux_sym__literal_string_token1, + [2324] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(23), 1, + anon_sym_RBRACK, + ACTIONS(272), 1, + aux_sym_document_token1, + ACTIONS(274), 1, + anon_sym_COMMA, + STATE(53), 1, + aux_sym_array_repeat1, + STATE(100), 1, + aux_sym_array_repeat2, + [2343] = 4, + ACTIONS(204), 1, + sym_comment, + ACTIONS(278), 1, + sym__multiline_literal_string_end, + STATE(55), 1, + aux_sym__multiline_literal_string_repeat1, + ACTIONS(276), 3, + sym__multiline_literal_string_content, + aux_sym__multiline_basic_string_token1, + aux_sym__literal_string_token1, + [2358] = 4, + ACTIONS(204), 1, + sym_comment, + ACTIONS(280), 1, + sym__multiline_literal_string_end, + STATE(55), 1, + aux_sym__multiline_literal_string_repeat1, + ACTIONS(276), 3, + sym__multiline_literal_string_content, + aux_sym__multiline_basic_string_token1, + aux_sym__literal_string_token1, + [2373] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(103), 1, + anon_sym_RBRACK, + ACTIONS(247), 1, + anon_sym_COMMA, + ACTIONS(282), 1, + aux_sym_document_token1, + STATE(64), 1, + aux_sym_array_repeat1, + STATE(103), 1, + aux_sym_array_repeat2, + [2392] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(19), 1, + aux_sym_document_token1, + ACTIONS(99), 1, + anon_sym_RBRACK, + ACTIONS(284), 1, + anon_sym_COMMA, + STATE(26), 1, + aux_sym_array_repeat1, + STATE(105), 1, + aux_sym_array_repeat2, + [2411] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(19), 1, + aux_sym_document_token1, + ACTIONS(53), 1, + anon_sym_RBRACK, + ACTIONS(251), 1, + anon_sym_COMMA, + STATE(26), 1, + aux_sym_array_repeat1, + STATE(102), 1, + aux_sym_array_repeat2, + [2430] = 4, + ACTIONS(204), 1, + sym_comment, + ACTIONS(289), 1, + anon_sym_DQUOTE2, + STATE(66), 1, + aux_sym__basic_string_repeat1, + ACTIONS(286), 2, + aux_sym__basic_string_token1, + sym_escape_sequence, + [2444] = 4, + ACTIONS(204), 1, + sym_comment, + ACTIONS(293), 1, + anon_sym_DQUOTE2, + STATE(66), 1, + aux_sym__basic_string_repeat1, + ACTIONS(291), 2, + aux_sym__basic_string_token1, + sym_escape_sequence, + [2458] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(19), 1, + aux_sym_document_token1, + STATE(26), 1, + aux_sym_array_repeat1, + ACTIONS(295), 2, + anon_sym_RBRACK, + anon_sym_COMMA, + [2472] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(297), 1, + aux_sym_document_token1, + STATE(70), 1, + aux_sym_array_repeat1, + ACTIONS(295), 2, + anon_sym_RBRACK, + anon_sym_COMMA, + [2486] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(19), 1, + aux_sym_document_token1, + STATE(26), 1, + aux_sym_array_repeat1, + ACTIONS(299), 2, + anon_sym_RBRACK, + anon_sym_COMMA, + [2500] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(301), 4, + aux_sym_document_token1, + anon_sym_RBRACK, + anon_sym_COMMA, + anon_sym_RBRACE, + [2510] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(303), 4, + aux_sym_document_token1, + anon_sym_RBRACK, + anon_sym_COMMA, + anon_sym_RBRACE, + [2520] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(305), 4, + aux_sym_document_token1, + anon_sym_RBRACK, + anon_sym_COMMA, + anon_sym_RBRACE, + [2530] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(307), 4, + aux_sym_document_token1, + anon_sym_RBRACK, + anon_sym_COMMA, + anon_sym_RBRACE, + [2540] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(309), 4, + aux_sym_document_token1, + anon_sym_RBRACK, + anon_sym_COMMA, + anon_sym_RBRACE, + [2550] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(311), 4, + aux_sym_document_token1, + anon_sym_RBRACK, + anon_sym_COMMA, + anon_sym_RBRACE, + [2560] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(313), 4, + aux_sym_document_token1, + anon_sym_RBRACK, + anon_sym_COMMA, + anon_sym_RBRACE, + [2570] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(315), 4, + aux_sym_document_token1, + anon_sym_RBRACK, + anon_sym_COMMA, + anon_sym_RBRACE, + [2580] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(317), 4, + aux_sym_document_token1, + anon_sym_RBRACK, + anon_sym_COMMA, + anon_sym_RBRACE, + [2590] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(319), 4, + aux_sym_document_token1, + anon_sym_RBRACK, + anon_sym_COMMA, + anon_sym_RBRACE, + [2600] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(321), 4, + aux_sym_document_token1, + anon_sym_RBRACK, + anon_sym_COMMA, + anon_sym_RBRACE, + [2610] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(323), 4, + aux_sym_document_token1, + anon_sym_RBRACK, + anon_sym_COMMA, + anon_sym_RBRACE, + [2620] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(325), 4, + aux_sym_document_token1, + anon_sym_RBRACK, + anon_sym_COMMA, + anon_sym_RBRACE, + [2630] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(327), 4, + aux_sym_document_token1, + anon_sym_RBRACK, + anon_sym_COMMA, + anon_sym_RBRACE, + [2640] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(329), 4, + aux_sym_document_token1, + anon_sym_RBRACK, + anon_sym_COMMA, + anon_sym_RBRACE, + [2650] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(331), 4, + aux_sym_document_token1, + anon_sym_RBRACK, + anon_sym_COMMA, + anon_sym_RBRACE, + [2660] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(333), 4, + aux_sym_document_token1, + anon_sym_RBRACK, + anon_sym_COMMA, + anon_sym_RBRACE, + [2670] = 4, + ACTIONS(204), 1, + sym_comment, + ACTIONS(337), 1, + anon_sym_DQUOTE2, + STATE(89), 1, + aux_sym__basic_string_repeat1, + ACTIONS(335), 2, + aux_sym__basic_string_token1, + sym_escape_sequence, + [2684] = 4, + ACTIONS(204), 1, + sym_comment, + ACTIONS(339), 1, + anon_sym_DQUOTE2, + STATE(66), 1, + aux_sym__basic_string_repeat1, + ACTIONS(291), 2, + aux_sym__basic_string_token1, + sym_escape_sequence, + [2698] = 4, + ACTIONS(204), 1, + sym_comment, + ACTIONS(343), 1, + anon_sym_DQUOTE2, + STATE(91), 1, + aux_sym__basic_string_repeat1, + ACTIONS(341), 2, + aux_sym__basic_string_token1, + sym_escape_sequence, + [2712] = 4, + ACTIONS(204), 1, + sym_comment, + ACTIONS(345), 1, + anon_sym_DQUOTE2, + STATE(66), 1, + aux_sym__basic_string_repeat1, + ACTIONS(291), 2, + aux_sym__basic_string_token1, + sym_escape_sequence, + [2726] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(347), 1, + aux_sym_document_token1, + STATE(68), 1, + aux_sym_array_repeat1, + ACTIONS(349), 2, + anon_sym_RBRACK, + anon_sym_COMMA, + [2740] = 4, + ACTIONS(204), 1, + sym_comment, + ACTIONS(353), 1, + anon_sym_DQUOTE2, + STATE(67), 1, + aux_sym__basic_string_repeat1, + ACTIONS(351), 2, + aux_sym__basic_string_token1, + sym_escape_sequence, + [2754] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(355), 1, + anon_sym_COMMA, + ACTIONS(357), 1, + anon_sym_RBRACE, + STATE(99), 1, + aux_sym_inline_table_repeat1, + [2767] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(349), 1, + anon_sym_RBRACK, + ACTIONS(359), 1, + anon_sym_COMMA, + STATE(95), 1, + aux_sym_array_repeat2, + [2780] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(362), 3, + anon_sym_RBRACK, + anon_sym_EQ, + anon_sym_DOT, + [2789] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(53), 1, + anon_sym_RBRACK, + ACTIONS(251), 1, + anon_sym_COMMA, + STATE(95), 1, + aux_sym_array_repeat2, + [2802] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(355), 1, + anon_sym_COMMA, + ACTIONS(364), 1, + anon_sym_RBRACE, + STATE(101), 1, + aux_sym_inline_table_repeat1, + [2815] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(355), 1, + anon_sym_COMMA, + ACTIONS(366), 1, + anon_sym_RBRACE, + STATE(106), 1, + aux_sym_inline_table_repeat1, + [2828] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(103), 1, + anon_sym_RBRACK, + ACTIONS(247), 1, + anon_sym_COMMA, + STATE(95), 1, + aux_sym_array_repeat2, + [2841] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(355), 1, + anon_sym_COMMA, + ACTIONS(368), 1, + anon_sym_RBRACE, + STATE(106), 1, + aux_sym_inline_table_repeat1, + [2854] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(67), 1, + anon_sym_RBRACK, + ACTIONS(258), 1, + anon_sym_COMMA, + STATE(95), 1, + aux_sym_array_repeat2, + [2867] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(99), 1, + anon_sym_RBRACK, + ACTIONS(284), 1, + anon_sym_COMMA, + STATE(95), 1, + aux_sym_array_repeat2, + [2880] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(77), 1, + anon_sym_RBRACK, + ACTIONS(370), 1, + anon_sym_COMMA, + STATE(95), 1, + aux_sym_array_repeat2, + [2893] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(81), 1, + anon_sym_RBRACK, + ACTIONS(372), 1, + anon_sym_COMMA, + STATE(95), 1, + aux_sym_array_repeat2, + [2906] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(374), 1, + anon_sym_COMMA, + ACTIONS(377), 1, + anon_sym_RBRACE, + STATE(106), 1, + aux_sym_inline_table_repeat1, + [2919] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(379), 3, + anon_sym_RBRACK, + anon_sym_EQ, + anon_sym_DOT, + [2928] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(381), 2, + anon_sym_COMMA, + anon_sym_RBRACE, + [2936] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(383), 1, + anon_sym_EQ, + ACTIONS(385), 1, + anon_sym_DOT, + [2946] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(229), 2, + anon_sym_RBRACK_RBRACK, + anon_sym_DOT, + [2954] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(231), 2, + anon_sym_RBRACK_RBRACK, + anon_sym_DOT, + [2962] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(243), 2, + anon_sym_RBRACK_RBRACK, + anon_sym_DOT, + [2970] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(245), 2, + anon_sym_RBRACK_RBRACK, + anon_sym_DOT, + [2978] = 3, + ACTIONS(204), 1, + sym_comment, + ACTIONS(387), 1, + aux_sym__literal_string_token1, + ACTIONS(389), 1, + anon_sym_SQUOTE2, + [2988] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(391), 2, + anon_sym_COMMA, + anon_sym_RBRACE, + [2996] = 3, + ACTIONS(204), 1, + sym_comment, + ACTIONS(393), 1, + aux_sym__literal_string_token1, + ACTIONS(395), 1, + anon_sym_SQUOTE2, + [3006] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(385), 1, + anon_sym_DOT, + ACTIONS(397), 1, + anon_sym_RBRACK, + [3016] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(379), 2, + anon_sym_RBRACK_RBRACK, + anon_sym_DOT, + [3024] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(385), 1, + anon_sym_DOT, + ACTIONS(399), 1, + anon_sym_EQ, + [3034] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(401), 1, + anon_sym_RBRACK_RBRACK, + ACTIONS(403), 1, + anon_sym_DOT, + [3044] = 3, + ACTIONS(204), 1, + sym_comment, + ACTIONS(405), 1, + aux_sym__literal_string_token1, + ACTIONS(407), 1, + anon_sym_SQUOTE2, + [3054] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(362), 2, + anon_sym_RBRACK_RBRACK, + anon_sym_DOT, + [3062] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(315), 1, + sym__line_ending_or_eof, + [3069] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(231), 1, + sym__line_ending_or_eof, + [3076] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(409), 1, + ts_builtin_sym_end, + [3083] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(317), 1, + sym__line_ending_or_eof, + [3090] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(411), 1, + sym__line_ending_or_eof, + [3097] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(309), 1, + sym__line_ending_or_eof, + [3104] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(301), 1, + sym__line_ending_or_eof, + [3111] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(321), 1, + sym__line_ending_or_eof, + [3118] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(243), 1, + sym__line_ending_or_eof, + [3125] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(311), 1, + sym__line_ending_or_eof, + [3132] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(327), 1, + sym__line_ending_or_eof, + [3139] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(329), 1, + sym__line_ending_or_eof, + [3146] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(323), 1, + sym__line_ending_or_eof, + [3153] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(303), 1, + sym__line_ending_or_eof, + [3160] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(313), 1, + sym__line_ending_or_eof, + [3167] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(391), 1, + sym__line_ending_or_eof, + [3174] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(305), 1, + sym__line_ending_or_eof, + [3181] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(331), 1, + sym__line_ending_or_eof, + [3188] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(413), 1, + anon_sym_SQUOTE2, + [3195] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(415), 1, + sym__line_ending_or_eof, + [3202] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(325), 1, + sym__line_ending_or_eof, + [3209] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(229), 1, + sym__line_ending_or_eof, + [3216] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(417), 1, + sym__line_ending_or_eof, + [3223] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(419), 1, + anon_sym_SQUOTE2, + [3230] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(333), 1, + sym__line_ending_or_eof, + [3237] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(245), 1, + sym__line_ending_or_eof, + [3244] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(307), 1, + sym__line_ending_or_eof, + [3251] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(421), 1, + anon_sym_SQUOTE2, + [3258] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(319), 1, + sym__line_ending_or_eof, +}; + +static const uint32_t ts_small_parse_table_map[] = { + [SMALL_STATE(2)] = 0, + [SMALL_STATE(3)] = 66, + [SMALL_STATE(4)] = 132, + [SMALL_STATE(5)] = 198, + [SMALL_STATE(6)] = 264, + [SMALL_STATE(7)] = 330, + [SMALL_STATE(8)] = 396, + [SMALL_STATE(9)] = 462, + [SMALL_STATE(10)] = 528, + [SMALL_STATE(11)] = 594, + [SMALL_STATE(12)] = 660, + [SMALL_STATE(13)] = 726, + [SMALL_STATE(14)] = 792, + [SMALL_STATE(15)] = 858, + [SMALL_STATE(16)] = 924, + [SMALL_STATE(17)] = 990, + [SMALL_STATE(18)] = 1056, + [SMALL_STATE(19)] = 1122, + [SMALL_STATE(20)] = 1188, + [SMALL_STATE(21)] = 1254, + [SMALL_STATE(22)] = 1320, + [SMALL_STATE(23)] = 1383, + [SMALL_STATE(24)] = 1446, + [SMALL_STATE(25)] = 1503, + [SMALL_STATE(26)] = 1560, + [SMALL_STATE(27)] = 1593, + [SMALL_STATE(28)] = 1639, + [SMALL_STATE(29)] = 1678, + [SMALL_STATE(30)] = 1717, + [SMALL_STATE(31)] = 1756, + [SMALL_STATE(32)] = 1795, + [SMALL_STATE(33)] = 1834, + [SMALL_STATE(34)] = 1862, + [SMALL_STATE(35)] = 1890, + [SMALL_STATE(36)] = 1915, + [SMALL_STATE(37)] = 1937, + [SMALL_STATE(38)] = 1959, + [SMALL_STATE(39)] = 1974, + [SMALL_STATE(40)] = 1991, + [SMALL_STATE(41)] = 2012, + [SMALL_STATE(42)] = 2029, + [SMALL_STATE(43)] = 2050, + [SMALL_STATE(44)] = 2067, + [SMALL_STATE(45)] = 2084, + [SMALL_STATE(46)] = 2101, + [SMALL_STATE(47)] = 2119, + [SMALL_STATE(48)] = 2131, + [SMALL_STATE(49)] = 2143, + [SMALL_STATE(50)] = 2161, + [SMALL_STATE(51)] = 2179, + [SMALL_STATE(52)] = 2191, + [SMALL_STATE(53)] = 2203, + [SMALL_STATE(54)] = 2222, + [SMALL_STATE(55)] = 2241, + [SMALL_STATE(56)] = 2256, + [SMALL_STATE(57)] = 2275, + [SMALL_STATE(58)] = 2290, + [SMALL_STATE(59)] = 2309, + [SMALL_STATE(60)] = 2324, + [SMALL_STATE(61)] = 2343, + [SMALL_STATE(62)] = 2358, + [SMALL_STATE(63)] = 2373, + [SMALL_STATE(64)] = 2392, + [SMALL_STATE(65)] = 2411, + [SMALL_STATE(66)] = 2430, + [SMALL_STATE(67)] = 2444, + [SMALL_STATE(68)] = 2458, + [SMALL_STATE(69)] = 2472, + [SMALL_STATE(70)] = 2486, + [SMALL_STATE(71)] = 2500, + [SMALL_STATE(72)] = 2510, + [SMALL_STATE(73)] = 2520, + [SMALL_STATE(74)] = 2530, + [SMALL_STATE(75)] = 2540, + [SMALL_STATE(76)] = 2550, + [SMALL_STATE(77)] = 2560, + [SMALL_STATE(78)] = 2570, + [SMALL_STATE(79)] = 2580, + [SMALL_STATE(80)] = 2590, + [SMALL_STATE(81)] = 2600, + [SMALL_STATE(82)] = 2610, + [SMALL_STATE(83)] = 2620, + [SMALL_STATE(84)] = 2630, + [SMALL_STATE(85)] = 2640, + [SMALL_STATE(86)] = 2650, + [SMALL_STATE(87)] = 2660, + [SMALL_STATE(88)] = 2670, + [SMALL_STATE(89)] = 2684, + [SMALL_STATE(90)] = 2698, + [SMALL_STATE(91)] = 2712, + [SMALL_STATE(92)] = 2726, + [SMALL_STATE(93)] = 2740, + [SMALL_STATE(94)] = 2754, + [SMALL_STATE(95)] = 2767, + [SMALL_STATE(96)] = 2780, + [SMALL_STATE(97)] = 2789, + [SMALL_STATE(98)] = 2802, + [SMALL_STATE(99)] = 2815, + [SMALL_STATE(100)] = 2828, + [SMALL_STATE(101)] = 2841, + [SMALL_STATE(102)] = 2854, + [SMALL_STATE(103)] = 2867, + [SMALL_STATE(104)] = 2880, + [SMALL_STATE(105)] = 2893, + [SMALL_STATE(106)] = 2906, + [SMALL_STATE(107)] = 2919, + [SMALL_STATE(108)] = 2928, + [SMALL_STATE(109)] = 2936, + [SMALL_STATE(110)] = 2946, + [SMALL_STATE(111)] = 2954, + [SMALL_STATE(112)] = 2962, + [SMALL_STATE(113)] = 2970, + [SMALL_STATE(114)] = 2978, + [SMALL_STATE(115)] = 2988, + [SMALL_STATE(116)] = 2996, + [SMALL_STATE(117)] = 3006, + [SMALL_STATE(118)] = 3016, + [SMALL_STATE(119)] = 3024, + [SMALL_STATE(120)] = 3034, + [SMALL_STATE(121)] = 3044, + [SMALL_STATE(122)] = 3054, + [SMALL_STATE(123)] = 3062, + [SMALL_STATE(124)] = 3069, + [SMALL_STATE(125)] = 3076, + [SMALL_STATE(126)] = 3083, + [SMALL_STATE(127)] = 3090, + [SMALL_STATE(128)] = 3097, + [SMALL_STATE(129)] = 3104, + [SMALL_STATE(130)] = 3111, + [SMALL_STATE(131)] = 3118, + [SMALL_STATE(132)] = 3125, + [SMALL_STATE(133)] = 3132, + [SMALL_STATE(134)] = 3139, + [SMALL_STATE(135)] = 3146, + [SMALL_STATE(136)] = 3153, + [SMALL_STATE(137)] = 3160, + [SMALL_STATE(138)] = 3167, + [SMALL_STATE(139)] = 3174, + [SMALL_STATE(140)] = 3181, + [SMALL_STATE(141)] = 3188, + [SMALL_STATE(142)] = 3195, + [SMALL_STATE(143)] = 3202, + [SMALL_STATE(144)] = 3209, + [SMALL_STATE(145)] = 3216, + [SMALL_STATE(146)] = 3223, + [SMALL_STATE(147)] = 3230, + [SMALL_STATE(148)] = 3237, + [SMALL_STATE(149)] = 3244, + [SMALL_STATE(150)] = 3251, + [SMALL_STATE(151)] = 3258, +}; + +static const TSParseActionEntry ts_parse_actions[] = { + [0] = {.entry = {.count = 0, .reusable = false}}, + [1] = {.entry = {.count = 1, .reusable = false}}, RECOVER(), + [3] = {.entry = {.count = 1, .reusable = true}}, SHIFT_EXTRA(), + [5] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_document, 0, 0, 0), + [7] = {.entry = {.count = 1, .reusable = true}}, SHIFT(27), + [9] = {.entry = {.count = 1, .reusable = false}}, SHIFT(36), + [11] = {.entry = {.count = 1, .reusable = true}}, SHIFT(37), + [13] = {.entry = {.count = 1, .reusable = true}}, SHIFT(119), + [15] = {.entry = {.count = 1, .reusable = true}}, SHIFT(90), + [17] = {.entry = {.count = 1, .reusable = true}}, SHIFT(116), + [19] = {.entry = {.count = 1, .reusable = true}}, SHIFT(26), + [21] = {.entry = {.count = 1, .reusable = true}}, SHIFT(14), + [23] = {.entry = {.count = 1, .reusable = true}}, SHIFT(78), + [25] = {.entry = {.count = 1, .reusable = false}}, SHIFT(90), + [27] = {.entry = {.count = 1, .reusable = true}}, SHIFT(41), + [29] = {.entry = {.count = 1, .reusable = false}}, SHIFT(116), + [31] = {.entry = {.count = 1, .reusable = true}}, SHIFT(59), + [33] = {.entry = {.count = 1, .reusable = false}}, SHIFT(71), + [35] = {.entry = {.count = 1, .reusable = true}}, SHIFT(71), + [37] = {.entry = {.count = 1, .reusable = true}}, SHIFT(72), + [39] = {.entry = {.count = 1, .reusable = true}}, SHIFT(63), + [41] = {.entry = {.count = 1, .reusable = false}}, SHIFT(63), + [43] = {.entry = {.count = 1, .reusable = true}}, SHIFT(34), + [45] = {.entry = {.count = 1, .reusable = true}}, SHIFT(87), + [47] = {.entry = {.count = 1, .reusable = true}}, SHIFT(69), + [49] = {.entry = {.count = 1, .reusable = false}}, SHIFT(69), + [51] = {.entry = {.count = 1, .reusable = true}}, SHIFT(6), + [53] = {.entry = {.count = 1, .reusable = true}}, SHIFT(135), + [55] = {.entry = {.count = 1, .reusable = true}}, SHIFT(92), + [57] = {.entry = {.count = 1, .reusable = false}}, SHIFT(92), + [59] = {.entry = {.count = 1, .reusable = true}}, SHIFT(7), + [61] = {.entry = {.count = 1, .reusable = true}}, SHIFT(149), + [63] = {.entry = {.count = 1, .reusable = true}}, SHIFT(58), + [65] = {.entry = {.count = 1, .reusable = false}}, SHIFT(58), + [67] = {.entry = {.count = 1, .reusable = true}}, SHIFT(133), + [69] = {.entry = {.count = 1, .reusable = true}}, SHIFT(123), + [71] = {.entry = {.count = 1, .reusable = true}}, SHIFT(54), + [73] = {.entry = {.count = 1, .reusable = false}}, SHIFT(54), + [75] = {.entry = {.count = 1, .reusable = true}}, SHIFT(9), + [77] = {.entry = {.count = 1, .reusable = true}}, SHIFT(134), + [79] = {.entry = {.count = 1, .reusable = true}}, SHIFT(12), + [81] = {.entry = {.count = 1, .reusable = true}}, SHIFT(85), + [83] = {.entry = {.count = 1, .reusable = true}}, SHIFT(140), + [85] = {.entry = {.count = 1, .reusable = true}}, SHIFT(15), + [87] = {.entry = {.count = 1, .reusable = true}}, SHIFT(2), + [89] = {.entry = {.count = 1, .reusable = true}}, SHIFT(74), + [91] = {.entry = {.count = 1, .reusable = true}}, SHIFT(60), + [93] = {.entry = {.count = 1, .reusable = false}}, SHIFT(60), + [95] = {.entry = {.count = 1, .reusable = true}}, SHIFT(147), + [97] = {.entry = {.count = 1, .reusable = true}}, SHIFT(11), + [99] = {.entry = {.count = 1, .reusable = true}}, SHIFT(84), + [101] = {.entry = {.count = 1, .reusable = true}}, SHIFT(17), + [103] = {.entry = {.count = 1, .reusable = true}}, SHIFT(82), + [105] = {.entry = {.count = 1, .reusable = true}}, SHIFT(20), + [107] = {.entry = {.count = 1, .reusable = true}}, SHIFT(86), + [109] = {.entry = {.count = 1, .reusable = true}}, SHIFT(3), + [111] = {.entry = {.count = 1, .reusable = true}}, SHIFT(23), + [113] = {.entry = {.count = 1, .reusable = true}}, SHIFT(5), + [115] = {.entry = {.count = 1, .reusable = false}}, SHIFT(93), + [117] = {.entry = {.count = 1, .reusable = true}}, SHIFT(44), + [119] = {.entry = {.count = 1, .reusable = false}}, SHIFT(121), + [121] = {.entry = {.count = 1, .reusable = true}}, SHIFT(57), + [123] = {.entry = {.count = 1, .reusable = false}}, SHIFT(129), + [125] = {.entry = {.count = 1, .reusable = true}}, SHIFT(129), + [127] = {.entry = {.count = 1, .reusable = true}}, SHIFT(136), + [129] = {.entry = {.count = 1, .reusable = true}}, SHIFT(138), + [131] = {.entry = {.count = 1, .reusable = false}}, SHIFT(138), + [133] = {.entry = {.count = 1, .reusable = true}}, SHIFT(33), + [135] = {.entry = {.count = 1, .reusable = true}}, SHIFT(115), + [137] = {.entry = {.count = 1, .reusable = false}}, SHIFT(115), + [139] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym_array_repeat1, 2, 0, 0), SHIFT_REPEAT(26), + [142] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym_array_repeat1, 2, 0, 0), + [144] = {.entry = {.count = 1, .reusable = false}}, REDUCE(aux_sym_array_repeat1, 2, 0, 0), + [146] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_document, 1, 0, 0), + [148] = {.entry = {.count = 1, .reusable = true}}, SHIFT(29), + [150] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_table, 4, 0, 0), + [152] = {.entry = {.count = 1, .reusable = true}}, SHIFT(31), + [154] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_table, 4, 0, 0), + [156] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym_document_repeat1, 2, 0, 0), + [158] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym_document_repeat1, 2, 0, 0), SHIFT_REPEAT(29), + [161] = {.entry = {.count = 1, .reusable = false}}, REDUCE(aux_sym_document_repeat1, 2, 0, 0), + [163] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym_document_repeat1, 2, 0, 0), SHIFT_REPEAT(119), + [166] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym_document_repeat1, 2, 0, 0), SHIFT_REPEAT(90), + [169] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym_document_repeat1, 2, 0, 0), SHIFT_REPEAT(116), + [172] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_table_array_element, 5, 0, 0), + [174] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_table_array_element, 5, 0, 0), + [176] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_table, 5, 0, 0), + [178] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_table, 5, 0, 0), + [180] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_table_array_element, 4, 0, 0), + [182] = {.entry = {.count = 1, .reusable = true}}, SHIFT(30), + [184] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_table_array_element, 4, 0, 0), + [186] = {.entry = {.count = 1, .reusable = true}}, SHIFT(109), + [188] = {.entry = {.count = 1, .reusable = true}}, SHIFT(137), + [190] = {.entry = {.count = 1, .reusable = true}}, SHIFT(77), + [192] = {.entry = {.count = 1, .reusable = true}}, SHIFT(117), + [194] = {.entry = {.count = 1, .reusable = true}}, SHIFT(120), + [196] = {.entry = {.count = 1, .reusable = true}}, SHIFT(88), + [198] = {.entry = {.count = 1, .reusable = true}}, SHIFT(114), + [200] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_pair, 2, 0, 0), + [202] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_pair, 2, 0, 0), + [204] = {.entry = {.count = 1, .reusable = false}}, SHIFT_EXTRA(), + [206] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__multiline_basic_string_repeat1, 2, 0, 0), SHIFT_REPEAT(39), + [209] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym__multiline_basic_string_repeat1, 2, 0, 0), + [211] = {.entry = {.count = 1, .reusable = true}}, SHIFT(118), + [213] = {.entry = {.count = 1, .reusable = true}}, SHIFT(43), + [215] = {.entry = {.count = 1, .reusable = true}}, SHIFT(75), + [217] = {.entry = {.count = 1, .reusable = true}}, SHIFT(107), + [219] = {.entry = {.count = 1, .reusable = true}}, SHIFT(39), + [221] = {.entry = {.count = 1, .reusable = true}}, SHIFT(79), + [223] = {.entry = {.count = 1, .reusable = true}}, SHIFT(45), + [225] = {.entry = {.count = 1, .reusable = true}}, SHIFT(128), + [227] = {.entry = {.count = 1, .reusable = true}}, SHIFT(126), + [229] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__basic_string, 2, 0, 0), + [231] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__literal_string, 2, 0, 0), + [233] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_document, 2, 0, 0), + [235] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym_document_repeat2, 2, 0, 0), + [237] = {.entry = {.count = 2, .reusable = false}}, REDUCE(aux_sym_document_repeat2, 2, 0, 0), SHIFT_REPEAT(36), + [240] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym_document_repeat2, 2, 0, 0), SHIFT_REPEAT(37), + [243] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__basic_string, 3, 0, 0), + [245] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__literal_string, 3, 0, 0), + [247] = {.entry = {.count = 1, .reusable = true}}, SHIFT(16), + [249] = {.entry = {.count = 1, .reusable = true}}, SHIFT(56), + [251] = {.entry = {.count = 1, .reusable = true}}, SHIFT(8), + [253] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__multiline_literal_string_repeat1, 2, 0, 0), SHIFT_REPEAT(55), + [256] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym__multiline_literal_string_repeat1, 2, 0, 0), + [258] = {.entry = {.count = 1, .reusable = true}}, SHIFT(10), + [260] = {.entry = {.count = 1, .reusable = true}}, SHIFT(62), + [262] = {.entry = {.count = 1, .reusable = true}}, SHIFT(132), + [264] = {.entry = {.count = 1, .reusable = true}}, SHIFT(65), + [266] = {.entry = {.count = 1, .reusable = true}}, SHIFT(4), + [268] = {.entry = {.count = 1, .reusable = true}}, SHIFT(61), + [270] = {.entry = {.count = 1, .reusable = true}}, SHIFT(76), + [272] = {.entry = {.count = 1, .reusable = true}}, SHIFT(53), + [274] = {.entry = {.count = 1, .reusable = true}}, SHIFT(18), + [276] = {.entry = {.count = 1, .reusable = true}}, SHIFT(55), + [278] = {.entry = {.count = 1, .reusable = true}}, SHIFT(80), + [280] = {.entry = {.count = 1, .reusable = true}}, SHIFT(151), + [282] = {.entry = {.count = 1, .reusable = true}}, SHIFT(64), + [284] = {.entry = {.count = 1, .reusable = true}}, SHIFT(19), + [286] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__basic_string_repeat1, 2, 0, 0), SHIFT_REPEAT(66), + [289] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym__basic_string_repeat1, 2, 0, 0), + [291] = {.entry = {.count = 1, .reusable = true}}, SHIFT(66), + [293] = {.entry = {.count = 1, .reusable = true}}, SHIFT(131), + [295] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym_array_repeat2, 3, 0, 0), + [297] = {.entry = {.count = 1, .reusable = true}}, SHIFT(70), + [299] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym_array_repeat2, 4, 0, 0), + [301] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_integer, 1, 0, 0), + [303] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_float, 1, 0, 0), + [305] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_string, 1, 0, 0), + [307] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_array, 2, 0, 0), + [309] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__multiline_basic_string, 2, 0, 0), + [311] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__multiline_literal_string, 2, 0, 0), + [313] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_inline_table, 2, 0, 0), + [315] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_array, 3, 0, 0), + [317] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__multiline_basic_string, 3, 0, 0), + [319] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__multiline_literal_string, 3, 0, 0), + [321] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_inline_table, 3, 0, 1), + [323] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_array, 4, 0, 0), + [325] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_inline_table, 4, 0, 1), + [327] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_array, 5, 0, 0), + [329] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_array, 6, 0, 0), + [331] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_array, 7, 0, 0), + [333] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_array, 8, 0, 0), + [335] = {.entry = {.count = 1, .reusable = true}}, SHIFT(89), + [337] = {.entry = {.count = 1, .reusable = true}}, SHIFT(110), + [339] = {.entry = {.count = 1, .reusable = true}}, SHIFT(112), + [341] = {.entry = {.count = 1, .reusable = true}}, SHIFT(91), + [343] = {.entry = {.count = 1, .reusable = true}}, SHIFT(47), + [345] = {.entry = {.count = 1, .reusable = true}}, SHIFT(51), + [347] = {.entry = {.count = 1, .reusable = true}}, SHIFT(68), + [349] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym_array_repeat2, 2, 0, 0), + [351] = {.entry = {.count = 1, .reusable = true}}, SHIFT(67), + [353] = {.entry = {.count = 1, .reusable = true}}, SHIFT(144), + [355] = {.entry = {.count = 1, .reusable = true}}, SHIFT(35), + [357] = {.entry = {.count = 1, .reusable = true}}, SHIFT(130), + [359] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym_array_repeat2, 2, 0, 0), SHIFT_REPEAT(22), + [362] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_quoted_key, 1, 0, 0), + [364] = {.entry = {.count = 1, .reusable = true}}, SHIFT(81), + [366] = {.entry = {.count = 1, .reusable = true}}, SHIFT(143), + [368] = {.entry = {.count = 1, .reusable = true}}, SHIFT(83), + [370] = {.entry = {.count = 1, .reusable = true}}, SHIFT(13), + [372] = {.entry = {.count = 1, .reusable = true}}, SHIFT(21), + [374] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym_inline_table_repeat1, 2, 0, 0), SHIFT_REPEAT(35), + [377] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym_inline_table_repeat1, 2, 0, 0), + [379] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_dotted_key, 3, 0, 0), + [381] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym_inline_table_repeat1, 2, 0, 1), + [383] = {.entry = {.count = 1, .reusable = true}}, SHIFT(25), + [385] = {.entry = {.count = 1, .reusable = true}}, SHIFT(42), + [387] = {.entry = {.count = 1, .reusable = true}}, SHIFT(141), + [389] = {.entry = {.count = 1, .reusable = true}}, SHIFT(111), + [391] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__inline_pair, 3, 0, 0), + [393] = {.entry = {.count = 1, .reusable = true}}, SHIFT(146), + [395] = {.entry = {.count = 1, .reusable = true}}, SHIFT(48), + [397] = {.entry = {.count = 1, .reusable = true}}, SHIFT(142), + [399] = {.entry = {.count = 1, .reusable = true}}, SHIFT(24), + [401] = {.entry = {.count = 1, .reusable = true}}, SHIFT(145), + [403] = {.entry = {.count = 1, .reusable = true}}, SHIFT(40), + [405] = {.entry = {.count = 1, .reusable = true}}, SHIFT(150), + [407] = {.entry = {.count = 1, .reusable = true}}, SHIFT(124), + [409] = {.entry = {.count = 1, .reusable = true}}, ACCEPT_INPUT(), + [411] = {.entry = {.count = 1, .reusable = true}}, SHIFT(38), + [413] = {.entry = {.count = 1, .reusable = true}}, SHIFT(113), + [415] = {.entry = {.count = 1, .reusable = true}}, SHIFT(28), + [417] = {.entry = {.count = 1, .reusable = true}}, SHIFT(32), + [419] = {.entry = {.count = 1, .reusable = true}}, SHIFT(52), + [421] = {.entry = {.count = 1, .reusable = true}}, SHIFT(148), +}; + +enum ts_external_scanner_symbol_identifiers { + ts_external_token__line_ending_or_eof = 0, + ts_external_token__multiline_basic_string_content = 1, + ts_external_token__multiline_basic_string_end = 2, + ts_external_token__multiline_literal_string_content = 3, + ts_external_token__multiline_literal_string_end = 4, +}; + +static const TSSymbol ts_external_scanner_symbol_map[EXTERNAL_TOKEN_COUNT] = { + [ts_external_token__line_ending_or_eof] = sym__line_ending_or_eof, + [ts_external_token__multiline_basic_string_content] = sym__multiline_basic_string_content, + [ts_external_token__multiline_basic_string_end] = sym__multiline_basic_string_end, + [ts_external_token__multiline_literal_string_content] = sym__multiline_literal_string_content, + [ts_external_token__multiline_literal_string_end] = sym__multiline_literal_string_end, +}; + +static const bool ts_external_scanner_states[5][EXTERNAL_TOKEN_COUNT] = { + [1] = { + [ts_external_token__line_ending_or_eof] = true, + [ts_external_token__multiline_basic_string_content] = true, + [ts_external_token__multiline_basic_string_end] = true, + [ts_external_token__multiline_literal_string_content] = true, + [ts_external_token__multiline_literal_string_end] = true, + }, + [2] = { + [ts_external_token__multiline_basic_string_content] = true, + [ts_external_token__multiline_basic_string_end] = true, + }, + [3] = { + [ts_external_token__multiline_literal_string_content] = true, + [ts_external_token__multiline_literal_string_end] = true, + }, + [4] = { + [ts_external_token__line_ending_or_eof] = true, + }, +}; + +#ifdef __cplusplus +extern "C" { +#endif +void *tree_sitter_toml_external_scanner_create(void); +void tree_sitter_toml_external_scanner_destroy(void *); +bool tree_sitter_toml_external_scanner_scan(void *, TSLexer *, const bool *); +unsigned tree_sitter_toml_external_scanner_serialize(void *, char *); +void tree_sitter_toml_external_scanner_deserialize(void *, const char *, unsigned); + +#ifdef TREE_SITTER_HIDE_SYMBOLS +#define TS_PUBLIC +#elif defined(_WIN32) +#define TS_PUBLIC __declspec(dllexport) +#else +#define TS_PUBLIC __attribute__((visibility("default"))) +#endif + +TS_PUBLIC const TSLanguage *tree_sitter_toml(void) { + static const TSLanguage language = { + .version = LANGUAGE_VERSION, + .symbol_count = SYMBOL_COUNT, + .alias_count = ALIAS_COUNT, + .token_count = TOKEN_COUNT, + .external_token_count = EXTERNAL_TOKEN_COUNT, + .state_count = STATE_COUNT, + .large_state_count = LARGE_STATE_COUNT, + .production_id_count = PRODUCTION_ID_COUNT, + .field_count = FIELD_COUNT, + .max_alias_sequence_length = MAX_ALIAS_SEQUENCE_LENGTH, + .parse_table = &ts_parse_table[0][0], + .small_parse_table = ts_small_parse_table, + .small_parse_table_map = ts_small_parse_table_map, + .parse_actions = ts_parse_actions, + .symbol_names = ts_symbol_names, + .symbol_metadata = ts_symbol_metadata, + .public_symbol_map = ts_symbol_map, + .alias_map = ts_non_terminal_alias_map, + .alias_sequences = &ts_alias_sequences[0][0], + .lex_modes = ts_lex_modes, + .lex_fn = ts_lex, + .external_scanner = { + &ts_external_scanner_states[0][0], + ts_external_scanner_symbol_map, + tree_sitter_toml_external_scanner_create, + tree_sitter_toml_external_scanner_destroy, + tree_sitter_toml_external_scanner_scan, + tree_sitter_toml_external_scanner_serialize, + tree_sitter_toml_external_scanner_deserialize, + }, + .primary_state_ids = ts_primary_state_ids, + }; + return &language; +} +#ifdef __cplusplus +} +#endif diff --git a/Sources/TreeSitterTOML/provenance.json b/Sources/TreeSitterTOML/provenance.json new file mode 100644 index 0000000..128ca3e --- /dev/null +++ b/Sources/TreeSitterTOML/provenance.json @@ -0,0 +1,26 @@ +{ + "upstream": "https://github.com/tree-sitter-grammars/tree-sitter-toml.git", + "revision": "64b56832c2cffe41758f28e05c756a3a98d16f41", + "files": { + "parser.c": { + "source": "src/parser.c", + "sha256": "1991a2608e6f0214e563fe5f762e8df72954dc69a3dd9a1e22ea8a870e4052c3" + }, + "scanner.c": { + "source": "src/scanner.c", + "sha256": "b25ff3b5034f40046e9a041d1e9110aa46d081706bbd1b748b480701aa6f5bde" + }, + "tree_sitter/parser.h": { + "source": "src/tree_sitter/parser.h", + "sha256": "a1f6ef161fbaf48a0e10fca90ef5290a062462b307b3898aa562993853b9f80a" + }, + "include/toml.h": { + "source": "bindings/swift/TreeSitterTOML/toml.h", + "sha256": "5ad880da451bae8855bd376f9ac267ff10cc44c5fbbdf6ea67cd08ffcc087757" + }, + "LICENSE": { + "source": "LICENSE", + "sha256": "b727eee929bee836e8102cecf749a795b199f291b58c885bcd81cae727ac5a46" + } + } +} diff --git a/Sources/TreeSitterTOML/scanner.c b/Sources/TreeSitterTOML/scanner.c new file mode 100644 index 0000000..7fa3c23 --- /dev/null +++ b/Sources/TreeSitterTOML/scanner.c @@ -0,0 +1,82 @@ +#include "tree_sitter/parser.h" + +typedef enum { + LINE_ENDING_OR_EOF, + MULTILINE_BASIC_STRING_CONTENT, + MULTILINE_BASIC_STRING_END, + MULTILINE_LITERAL_STRING_CONTENT, + MULTILINE_LITERAL_STRING_END, +} TokenType; + +void *tree_sitter_toml_external_scanner_create() { return NULL; } + +void tree_sitter_toml_external_scanner_destroy(void *payload) {} + +unsigned tree_sitter_toml_external_scanner_serialize(void *payload, char *buffer) { return 0; } + +void tree_sitter_toml_external_scanner_deserialize(void *payload, const char *buffer, unsigned length) {} + +bool tree_sitter_toml_external_scanner_scan_multiline_string_end(TSLexer *lexer, const bool *valid_symbols, + int32_t delimiter, TokenType content_symbol, + TokenType end_symbol) { + if (!valid_symbols[end_symbol] || lexer->lookahead != delimiter) { + return false; + } + + lexer->advance(lexer, false); + lexer->mark_end(lexer); + + if (lexer->lookahead != delimiter) { + lexer->result_symbol = content_symbol; + return true; + } + + lexer->advance(lexer, false); + + if (lexer->lookahead != delimiter) { + lexer->mark_end(lexer); + lexer->result_symbol = content_symbol; + return true; + } + + lexer->advance(lexer, false); + + if (lexer->lookahead != delimiter) { + lexer->mark_end(lexer); + lexer->result_symbol = end_symbol; + return true; + } + + lexer->result_symbol = content_symbol; + return true; +} + +bool tree_sitter_toml_external_scanner_scan(void *payload, TSLexer *lexer, const bool *valid_symbols) { + if (tree_sitter_toml_external_scanner_scan_multiline_string_end( + lexer, valid_symbols, '"', MULTILINE_BASIC_STRING_CONTENT, MULTILINE_BASIC_STRING_END) || + tree_sitter_toml_external_scanner_scan_multiline_string_end( + lexer, valid_symbols, '\'', MULTILINE_LITERAL_STRING_CONTENT, MULTILINE_LITERAL_STRING_END)) { + return true; + } + + if (valid_symbols[LINE_ENDING_OR_EOF]) { + lexer->result_symbol = LINE_ENDING_OR_EOF; + + while (lexer->lookahead == ' ' || lexer->lookahead == '\t') { + lexer->advance(lexer, true); + } + + if (lexer->lookahead == 0 || lexer->lookahead == '\n') { + return true; + } + + if (lexer->lookahead == '\r') { + lexer->advance(lexer, true); + if (lexer->lookahead == '\n') { + return true; + } + } + } + + return false; +} diff --git a/Sources/TreeSitterTOML/tree_sitter/parser.h b/Sources/TreeSitterTOML/tree_sitter/parser.h new file mode 100644 index 0000000..799f599 --- /dev/null +++ b/Sources/TreeSitterTOML/tree_sitter/parser.h @@ -0,0 +1,266 @@ +#ifndef TREE_SITTER_PARSER_H_ +#define TREE_SITTER_PARSER_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include + +#define ts_builtin_sym_error ((TSSymbol)-1) +#define ts_builtin_sym_end 0 +#define TREE_SITTER_SERIALIZATION_BUFFER_SIZE 1024 + +#ifndef TREE_SITTER_API_H_ +typedef uint16_t TSStateId; +typedef uint16_t TSSymbol; +typedef uint16_t TSFieldId; +typedef struct TSLanguage TSLanguage; +#endif + +typedef struct { + TSFieldId field_id; + uint8_t child_index; + bool inherited; +} TSFieldMapEntry; + +typedef struct { + uint16_t index; + uint16_t length; +} TSFieldMapSlice; + +typedef struct { + bool visible; + bool named; + bool supertype; +} TSSymbolMetadata; + +typedef struct TSLexer TSLexer; + +struct TSLexer { + int32_t lookahead; + TSSymbol result_symbol; + void (*advance)(TSLexer *, bool); + void (*mark_end)(TSLexer *); + uint32_t (*get_column)(TSLexer *); + bool (*is_at_included_range_start)(const TSLexer *); + bool (*eof)(const TSLexer *); + void (*log)(const TSLexer *, const char *, ...); +}; + +typedef enum { + TSParseActionTypeShift, + TSParseActionTypeReduce, + TSParseActionTypeAccept, + TSParseActionTypeRecover, +} TSParseActionType; + +typedef union { + struct { + uint8_t type; + TSStateId state; + bool extra; + bool repetition; + } shift; + struct { + uint8_t type; + uint8_t child_count; + TSSymbol symbol; + int16_t dynamic_precedence; + uint16_t production_id; + } reduce; + uint8_t type; +} TSParseAction; + +typedef struct { + uint16_t lex_state; + uint16_t external_lex_state; +} TSLexMode; + +typedef union { + TSParseAction action; + struct { + uint8_t count; + bool reusable; + } entry; +} TSParseActionEntry; + +typedef struct { + int32_t start; + int32_t end; +} TSCharacterRange; + +struct TSLanguage { + uint32_t version; + uint32_t symbol_count; + uint32_t alias_count; + uint32_t token_count; + uint32_t external_token_count; + uint32_t state_count; + uint32_t large_state_count; + uint32_t production_id_count; + uint32_t field_count; + uint16_t max_alias_sequence_length; + const uint16_t *parse_table; + const uint16_t *small_parse_table; + const uint32_t *small_parse_table_map; + const TSParseActionEntry *parse_actions; + const char * const *symbol_names; + const char * const *field_names; + const TSFieldMapSlice *field_map_slices; + const TSFieldMapEntry *field_map_entries; + const TSSymbolMetadata *symbol_metadata; + const TSSymbol *public_symbol_map; + const uint16_t *alias_map; + const TSSymbol *alias_sequences; + const TSLexMode *lex_modes; + bool (*lex_fn)(TSLexer *, TSStateId); + bool (*keyword_lex_fn)(TSLexer *, TSStateId); + TSSymbol keyword_capture_token; + struct { + const bool *states; + const TSSymbol *symbol_map; + void *(*create)(void); + void (*destroy)(void *); + bool (*scan)(void *, TSLexer *, const bool *symbol_whitelist); + unsigned (*serialize)(void *, char *); + void (*deserialize)(void *, const char *, unsigned); + } external_scanner; + const TSStateId *primary_state_ids; +}; + +static inline bool set_contains(TSCharacterRange *ranges, uint32_t len, int32_t lookahead) { + uint32_t index = 0; + uint32_t size = len - index; + while (size > 1) { + uint32_t half_size = size / 2; + uint32_t mid_index = index + half_size; + TSCharacterRange *range = &ranges[mid_index]; + if (lookahead >= range->start && lookahead <= range->end) { + return true; + } else if (lookahead > range->end) { + index = mid_index; + } + size -= half_size; + } + TSCharacterRange *range = &ranges[index]; + return (lookahead >= range->start && lookahead <= range->end); +} + +/* + * Lexer Macros + */ + +#ifdef _MSC_VER +#define UNUSED __pragma(warning(suppress : 4101)) +#else +#define UNUSED __attribute__((unused)) +#endif + +#define START_LEXER() \ + bool result = false; \ + bool skip = false; \ + UNUSED \ + bool eof = false; \ + int32_t lookahead; \ + goto start; \ + next_state: \ + lexer->advance(lexer, skip); \ + start: \ + skip = false; \ + lookahead = lexer->lookahead; + +#define ADVANCE(state_value) \ + { \ + state = state_value; \ + goto next_state; \ + } + +#define ADVANCE_MAP(...) \ + { \ + static const uint16_t map[] = { __VA_ARGS__ }; \ + for (uint32_t i = 0; i < sizeof(map) / sizeof(map[0]); i += 2) { \ + if (map[i] == lookahead) { \ + state = map[i + 1]; \ + goto next_state; \ + } \ + } \ + } + +#define SKIP(state_value) \ + { \ + skip = true; \ + state = state_value; \ + goto next_state; \ + } + +#define ACCEPT_TOKEN(symbol_value) \ + result = true; \ + lexer->result_symbol = symbol_value; \ + lexer->mark_end(lexer); + +#define END_STATE() return result; + +/* + * Parse Table Macros + */ + +#define SMALL_STATE(id) ((id) - LARGE_STATE_COUNT) + +#define STATE(id) id + +#define ACTIONS(id) id + +#define SHIFT(state_value) \ + {{ \ + .shift = { \ + .type = TSParseActionTypeShift, \ + .state = (state_value) \ + } \ + }} + +#define SHIFT_REPEAT(state_value) \ + {{ \ + .shift = { \ + .type = TSParseActionTypeShift, \ + .state = (state_value), \ + .repetition = true \ + } \ + }} + +#define SHIFT_EXTRA() \ + {{ \ + .shift = { \ + .type = TSParseActionTypeShift, \ + .extra = true \ + } \ + }} + +#define REDUCE(symbol_name, children, precedence, prod_id) \ + {{ \ + .reduce = { \ + .type = TSParseActionTypeReduce, \ + .symbol = symbol_name, \ + .child_count = children, \ + .dynamic_precedence = precedence, \ + .production_id = prod_id \ + }, \ + }} + +#define RECOVER() \ + {{ \ + .type = TSParseActionTypeRecover \ + }} + +#define ACCEPT_INPUT() \ + {{ \ + .type = TSParseActionTypeAccept \ + }} + +#ifdef __cplusplus +} +#endif + +#endif // TREE_SITTER_PARSER_H_ diff --git a/Sources/TreeSitterYAML/LICENSE b/Sources/TreeSitterYAML/LICENSE new file mode 100644 index 0000000..262eb46 --- /dev/null +++ b/Sources/TreeSitterYAML/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2024 tree-sitter-grammars contributors +Copyright (c) 2019-2021 Ika + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Sources/TreeSitterYAML/include/yaml.h b/Sources/TreeSitterYAML/include/yaml.h new file mode 100644 index 0000000..ce248bb --- /dev/null +++ b/Sources/TreeSitterYAML/include/yaml.h @@ -0,0 +1,16 @@ +#ifndef TREE_SITTER_YAML_H_ +#define TREE_SITTER_YAML_H_ + +typedef struct TSLanguage TSLanguage; + +#ifdef __cplusplus +extern "C" { +#endif + +const TSLanguage *tree_sitter_yaml(void); + +#ifdef __cplusplus +} +#endif + +#endif // TREE_SITTER_YAML_H_ diff --git a/Sources/TreeSitterYAML/parser.c b/Sources/TreeSitterYAML/parser.c new file mode 100644 index 0000000..34fe31b --- /dev/null +++ b/Sources/TreeSitterYAML/parser.c @@ -0,0 +1,41384 @@ +/* Automatically @generated by tree-sitter v0.25.10 */ + +#include "tree_sitter/parser.h" + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic ignored "-Wmissing-field-initializers" +#endif + +#define LANGUAGE_VERSION 14 +#define STATE_COUNT 1579 +#define LARGE_STATE_COUNT 96 +#define SYMBOL_COUNT 301 +#define ALIAS_COUNT 0 +#define TOKEN_COUNT 114 +#define EXTERNAL_TOKEN_COUNT 113 +#define FIELD_COUNT 2 +#define MAX_ALIAS_SEQUENCE_LENGTH 5 +#define MAX_RESERVED_WORD_SET_SIZE 0 +#define PRODUCTION_ID_COUNT 12 +#define SUPERTYPE_COUNT 0 + +enum ts_symbol_identifiers { + sym__eof = 1, + sym__s_dir_yml_bgn = 2, + sym__r_dir_yml_ver = 3, + sym__s_dir_tag_bgn = 4, + sym__r_dir_tag_hdl = 5, + sym__r_dir_tag_pfx = 6, + sym__s_dir_rsv_bgn = 7, + sym__r_dir_rsv_prm = 8, + sym__s_drs_end = 9, + sym__s_doc_end = 10, + sym__r_blk_seq_bgn = 11, + sym__br_blk_seq_bgn = 12, + sym__b_blk_seq_bgn = 13, + sym__r_blk_key_bgn = 14, + sym__br_blk_key_bgn = 15, + sym__b_blk_key_bgn = 16, + sym__r_blk_val_bgn = 17, + sym__br_blk_val_bgn = 18, + sym__b_blk_val_bgn = 19, + sym__r_blk_imp_bgn = 20, + sym__r_blk_lit_bgn = 21, + sym__br_blk_lit_bgn = 22, + sym__r_blk_fld_bgn = 23, + sym__br_blk_fld_bgn = 24, + sym__br_blk_str_ctn = 25, + sym__r_flw_seq_bgn = 26, + sym__br_flw_seq_bgn = 27, + sym__b_flw_seq_bgn = 28, + sym__r_flw_seq_end = 29, + sym__br_flw_seq_end = 30, + sym__b_flw_seq_end = 31, + sym__r_flw_map_bgn = 32, + sym__br_flw_map_bgn = 33, + sym__b_flw_map_bgn = 34, + sym__r_flw_map_end = 35, + sym__br_flw_map_end = 36, + sym__b_flw_map_end = 37, + sym__r_flw_sep_bgn = 38, + sym__br_flw_sep_bgn = 39, + sym__r_flw_key_bgn = 40, + sym__br_flw_key_bgn = 41, + sym__r_flw_jsv_bgn = 42, + sym__br_flw_jsv_bgn = 43, + sym__r_flw_njv_bgn = 44, + sym__br_flw_njv_bgn = 45, + sym__r_dqt_str_bgn = 46, + sym__br_dqt_str_bgn = 47, + sym__b_dqt_str_bgn = 48, + sym__r_dqt_str_ctn = 49, + sym__br_dqt_str_ctn = 50, + sym__r_dqt_esc_nwl = 51, + sym__br_dqt_esc_nwl = 52, + sym__r_dqt_esc_seq = 53, + sym__br_dqt_esc_seq = 54, + sym__r_dqt_str_end = 55, + sym__br_dqt_str_end = 56, + sym__r_sqt_str_bgn = 57, + sym__br_sqt_str_bgn = 58, + sym__b_sqt_str_bgn = 59, + sym__r_sqt_str_ctn = 60, + sym__br_sqt_str_ctn = 61, + sym__r_sqt_esc_sqt = 62, + sym__br_sqt_esc_sqt = 63, + sym__r_sqt_str_end = 64, + sym__br_sqt_str_end = 65, + sym__r_sgl_pln_nul_blk = 66, + sym__br_sgl_pln_nul_blk = 67, + sym__b_sgl_pln_nul_blk = 68, + sym__r_sgl_pln_nul_flw = 69, + sym__br_sgl_pln_nul_flw = 70, + sym__r_sgl_pln_bol_blk = 71, + sym__br_sgl_pln_bol_blk = 72, + sym__b_sgl_pln_bol_blk = 73, + sym__r_sgl_pln_bol_flw = 74, + sym__br_sgl_pln_bol_flw = 75, + sym__r_sgl_pln_int_blk = 76, + sym__br_sgl_pln_int_blk = 77, + sym__b_sgl_pln_int_blk = 78, + sym__r_sgl_pln_int_flw = 79, + sym__br_sgl_pln_int_flw = 80, + sym__r_sgl_pln_flt_blk = 81, + sym__br_sgl_pln_flt_blk = 82, + sym__b_sgl_pln_flt_blk = 83, + sym__r_sgl_pln_flt_flw = 84, + sym__br_sgl_pln_flt_flw = 85, + sym__r_sgl_pln_tms_blk = 86, + sym__br_sgl_pln_tms_blk = 87, + sym__b_sgl_pln_tms_blk = 88, + sym__r_sgl_pln_tms_flw = 89, + sym__br_sgl_pln_tms_flw = 90, + sym__r_sgl_pln_str_blk = 91, + sym__br_sgl_pln_str_blk = 92, + sym__b_sgl_pln_str_blk = 93, + sym__r_sgl_pln_str_flw = 94, + sym__br_sgl_pln_str_flw = 95, + sym__r_mtl_pln_str_blk = 96, + sym__br_mtl_pln_str_blk = 97, + sym__r_mtl_pln_str_flw = 98, + sym__br_mtl_pln_str_flw = 99, + sym__r_tag = 100, + sym__br_tag = 101, + sym__b_tag = 102, + sym__r_acr_bgn = 103, + sym__br_acr_bgn = 104, + sym__b_acr_bgn = 105, + sym__r_acr_ctn = 106, + sym__r_als_bgn = 107, + sym__br_als_bgn = 108, + sym__b_als_bgn = 109, + sym__r_als_ctn = 110, + sym__bl = 111, + sym_comment = 112, + sym__err_rec = 113, + sym_stream = 114, + sym__doc_w_bgn_w_end_seq = 115, + sym__doc_w_bgn_wo_end_seq = 116, + sym__doc_wo_bgn_w_end_seq = 117, + sym__doc_wo_bgn_wo_end_seq = 118, + sym__doc_w_bgn_w_end = 119, + sym__doc_w_bgn_wo_end = 120, + sym__doc_wo_bgn_w_end = 121, + sym__doc_wo_bgn_wo_end = 122, + sym__bgn_imp_doc = 123, + sym__drs_doc = 124, + sym__exp_doc = 125, + sym__imp_doc = 126, + sym__drs_doc_end = 127, + sym__exp_doc_end = 128, + sym__imp_doc_end = 129, + sym__bgn_imp_doc_end = 130, + sym__doc_end = 131, + sym__exp_doc_tal = 132, + sym__s_dir = 133, + sym__s_dir_yml = 134, + sym__s_dir_tag = 135, + sym__s_dir_rsv = 136, + sym__r_prp_val = 137, + sym__br_prp_val = 138, + sym__r_sgl_prp_val = 139, + sym__br_sgl_prp_val = 140, + sym__b_sgl_prp_val = 141, + sym__r_prp = 142, + sym__br_prp = 143, + sym__r_sgl_prp = 144, + sym__br_sgl_prp = 145, + sym__b_sgl_prp = 146, + sym__r_blk_seq_r_val = 147, + sym__r_blk_seq_br_val = 148, + sym__br_blk_seq_val = 149, + sym__r_blk_seq_spc_val = 150, + sym__br_blk_seq_spc_val = 151, + sym__b_blk_seq_spc_val = 152, + sym__r_blk_seq = 153, + sym__br_blk_seq = 154, + sym__b_blk_seq_spc = 155, + sym__r_blk_seq_itm = 156, + sym__br_blk_seq_itm = 157, + sym__b_blk_seq_itm = 158, + sym__blk_seq_itm_tal = 159, + sym__r_blk_map_r_val = 160, + sym__r_blk_map_br_val = 161, + sym__br_blk_map_val = 162, + sym__r_blk_map = 163, + sym__br_blk_map = 164, + sym__r_blk_map_itm = 165, + sym__br_blk_map_itm = 166, + sym__b_blk_map_itm = 167, + sym__r_blk_exp_itm = 168, + sym__br_blk_exp_itm = 169, + sym__b_blk_exp_itm = 170, + sym__r_blk_key_itm = 171, + sym__br_blk_key_itm = 172, + sym__b_blk_key_itm = 173, + sym__r_blk_val_itm = 174, + sym__br_blk_val_itm = 175, + sym__b_blk_val_itm = 176, + sym__r_blk_imp_itm = 177, + sym__br_blk_imp_itm = 178, + sym__b_blk_imp_itm = 179, + sym__blk_exp_itm_tal = 180, + sym__blk_imp_itm_tal = 181, + sym__r_blk_str_val = 182, + sym__br_blk_str_val = 183, + sym__r_blk_str = 184, + sym__br_blk_str = 185, + sym__r_flw_seq_val = 186, + sym__br_flw_seq_val = 187, + sym__r_sgl_flw_seq_val = 188, + sym__br_sgl_flw_seq_val = 189, + sym__b_sgl_flw_seq_val = 190, + sym__r_flw_seq = 191, + sym__br_flw_seq = 192, + sym__r_sgl_flw_seq = 193, + sym__br_sgl_flw_seq = 194, + sym__b_sgl_flw_seq = 195, + sym__flw_seq_tal = 196, + sym__sgl_flw_seq_tal = 197, + sym__r_flw_map_val = 198, + sym__br_flw_map_val = 199, + sym__r_sgl_flw_map_val = 200, + sym__br_sgl_flw_map_val = 201, + sym__b_sgl_flw_map_val = 202, + sym__r_flw_map = 203, + sym__br_flw_map = 204, + sym__r_sgl_flw_map = 205, + sym__br_sgl_flw_map = 206, + sym__b_sgl_flw_map = 207, + sym__flw_map_tal = 208, + sym__sgl_flw_map_tal = 209, + sym__r_flw_seq_dat = 210, + sym__br_flw_seq_dat = 211, + sym__r_flw_map_dat = 212, + sym__br_flw_map_dat = 213, + sym__r_sgl_flw_col_dat = 214, + sym__flw_seq_dat_rpt = 215, + sym__flw_map_dat_rpt = 216, + sym__sgl_flw_col_dat_rpt = 217, + sym__r_flw_seq_itm = 218, + sym__br_flw_seq_itm = 219, + sym__r_flw_map_itm = 220, + sym__br_flw_map_itm = 221, + sym__r_sgl_flw_col_itm = 222, + sym__r_flw_exp_par = 223, + sym__br_flw_exp_par = 224, + sym__r_sgl_flw_exp_par = 225, + sym__r_flw_imp_r_par = 226, + sym__r_flw_imp_br_par = 227, + sym__br_flw_imp_r_par = 228, + sym__br_flw_imp_br_par = 229, + sym__r_sgl_flw_imp_par = 230, + sym__r_flw_jsl_ann_par = 231, + sym__br_flw_jsl_ann_par = 232, + sym__r_sgl_flw_jsl_ann_par = 233, + sym__r_flw_njl_ann_par = 234, + sym__br_flw_njl_ann_par = 235, + sym__r_sgl_flw_njl_ann_par = 236, + sym__flw_ann_par_tal = 237, + sym__sgl_flw_ann_par_tal = 238, + sym__r_dqt_str_val = 239, + sym__br_dqt_str_val = 240, + sym__r_sgl_dqt_str_val = 241, + sym__br_sgl_dqt_str_val = 242, + sym__b_sgl_dqt_str_val = 243, + sym__r_dqt_str = 244, + sym__br_dqt_str = 245, + sym__r_sgl_dqt_str = 246, + sym__br_sgl_dqt_str = 247, + sym__b_sgl_dqt_str = 248, + aux_sym__r_sgl_dqt_ctn = 249, + sym__br_mtl_dqt_ctn = 250, + sym__r_sqt_str_val = 251, + sym__br_sqt_str_val = 252, + sym__r_sgl_sqt_str_val = 253, + sym__br_sgl_sqt_str_val = 254, + sym__b_sgl_sqt_str_val = 255, + sym__r_sqt_str = 256, + sym__br_sqt_str = 257, + sym__r_sgl_sqt_str = 258, + sym__br_sgl_sqt_str = 259, + sym__b_sgl_sqt_str = 260, + aux_sym__r_sgl_sqt_ctn = 261, + sym__br_mtl_sqt_ctn = 262, + sym__r_pln_blk_val = 263, + sym__br_pln_blk_val = 264, + sym__r_sgl_pln_blk_val = 265, + sym__br_sgl_pln_blk_val = 266, + sym__b_sgl_pln_blk_val = 267, + sym__r_pln_flw_val = 268, + sym__br_pln_flw_val = 269, + sym__r_sgl_pln_flw_val = 270, + sym__r_sgl_pln_blk = 271, + sym__br_sgl_pln_blk = 272, + sym__b_sgl_pln_blk = 273, + sym__r_sgl_pln_flw = 274, + sym__br_sgl_pln_flw = 275, + sym__r_mtl_pln_blk = 276, + sym__br_mtl_pln_blk = 277, + sym__r_mtl_pln_flw = 278, + sym__br_mtl_pln_flw = 279, + sym__r_als_val = 280, + sym__br_als_val = 281, + sym__b_als_val = 282, + sym__r_als = 283, + sym__br_als = 284, + sym__b_als = 285, + sym__r_acr = 286, + sym__br_acr = 287, + sym__b_acr = 288, + aux_sym__drs_doc_repeat1 = 289, + aux_sym__s_dir_rsv_repeat1 = 290, + aux_sym__r_blk_seq_repeat1 = 291, + aux_sym__r_blk_map_repeat1 = 292, + aux_sym__r_blk_str_repeat1 = 293, + aux_sym__r_flw_seq_dat_repeat1 = 294, + aux_sym__r_flw_map_dat_repeat1 = 295, + aux_sym__r_sgl_flw_col_dat_repeat1 = 296, + aux_sym__r_dqt_str_repeat1 = 297, + aux_sym__br_mtl_dqt_ctn_repeat1 = 298, + aux_sym__r_sqt_str_repeat1 = 299, + aux_sym__br_mtl_sqt_ctn_repeat1 = 300, +}; + +static const char * const ts_symbol_names[] = { + [ts_builtin_sym_end] = "end", + [sym__eof] = "_eof", + [sym__s_dir_yml_bgn] = "_s_dir_yml_bgn", + [sym__r_dir_yml_ver] = "yaml_version", + [sym__s_dir_tag_bgn] = "_s_dir_tag_bgn", + [sym__r_dir_tag_hdl] = "tag_handle", + [sym__r_dir_tag_pfx] = "tag_prefix", + [sym__s_dir_rsv_bgn] = "directive_name", + [sym__r_dir_rsv_prm] = "directive_parameter", + [sym__s_drs_end] = "---", + [sym__s_doc_end] = "...", + [sym__r_blk_seq_bgn] = "-", + [sym__br_blk_seq_bgn] = "-", + [sym__b_blk_seq_bgn] = "-", + [sym__r_blk_key_bgn] = "\?", + [sym__br_blk_key_bgn] = "\?", + [sym__b_blk_key_bgn] = "\?", + [sym__r_blk_val_bgn] = ":", + [sym__br_blk_val_bgn] = ":", + [sym__b_blk_val_bgn] = ":", + [sym__r_blk_imp_bgn] = ":", + [sym__r_blk_lit_bgn] = "|", + [sym__br_blk_lit_bgn] = "|", + [sym__r_blk_fld_bgn] = ">", + [sym__br_blk_fld_bgn] = ">", + [sym__br_blk_str_ctn] = "_br_blk_str_ctn", + [sym__r_flw_seq_bgn] = "[", + [sym__br_flw_seq_bgn] = "[", + [sym__b_flw_seq_bgn] = "[", + [sym__r_flw_seq_end] = "]", + [sym__br_flw_seq_end] = "]", + [sym__b_flw_seq_end] = "]", + [sym__r_flw_map_bgn] = "{", + [sym__br_flw_map_bgn] = "{", + [sym__b_flw_map_bgn] = "{", + [sym__r_flw_map_end] = "}", + [sym__br_flw_map_end] = "}", + [sym__b_flw_map_end] = "}", + [sym__r_flw_sep_bgn] = ",", + [sym__br_flw_sep_bgn] = ",", + [sym__r_flw_key_bgn] = "\?", + [sym__br_flw_key_bgn] = "\?", + [sym__r_flw_jsv_bgn] = ":", + [sym__br_flw_jsv_bgn] = ":", + [sym__r_flw_njv_bgn] = ":", + [sym__br_flw_njv_bgn] = ":", + [sym__r_dqt_str_bgn] = "\"", + [sym__br_dqt_str_bgn] = "\"", + [sym__b_dqt_str_bgn] = "\"", + [sym__r_dqt_str_ctn] = "_r_dqt_str_ctn", + [sym__br_dqt_str_ctn] = "_br_dqt_str_ctn", + [sym__r_dqt_esc_nwl] = "escape_sequence", + [sym__br_dqt_esc_nwl] = "escape_sequence", + [sym__r_dqt_esc_seq] = "escape_sequence", + [sym__br_dqt_esc_seq] = "escape_sequence", + [sym__r_dqt_str_end] = "\"", + [sym__br_dqt_str_end] = "\"", + [sym__r_sqt_str_bgn] = "'", + [sym__br_sqt_str_bgn] = "'", + [sym__b_sqt_str_bgn] = "'", + [sym__r_sqt_str_ctn] = "_r_sqt_str_ctn", + [sym__br_sqt_str_ctn] = "_br_sqt_str_ctn", + [sym__r_sqt_esc_sqt] = "escape_sequence", + [sym__br_sqt_esc_sqt] = "escape_sequence", + [sym__r_sqt_str_end] = "'", + [sym__br_sqt_str_end] = "'", + [sym__r_sgl_pln_nul_blk] = "null_scalar", + [sym__br_sgl_pln_nul_blk] = "null_scalar", + [sym__b_sgl_pln_nul_blk] = "null_scalar", + [sym__r_sgl_pln_nul_flw] = "null_scalar", + [sym__br_sgl_pln_nul_flw] = "null_scalar", + [sym__r_sgl_pln_bol_blk] = "boolean_scalar", + [sym__br_sgl_pln_bol_blk] = "boolean_scalar", + [sym__b_sgl_pln_bol_blk] = "boolean_scalar", + [sym__r_sgl_pln_bol_flw] = "boolean_scalar", + [sym__br_sgl_pln_bol_flw] = "boolean_scalar", + [sym__r_sgl_pln_int_blk] = "integer_scalar", + [sym__br_sgl_pln_int_blk] = "integer_scalar", + [sym__b_sgl_pln_int_blk] = "integer_scalar", + [sym__r_sgl_pln_int_flw] = "integer_scalar", + [sym__br_sgl_pln_int_flw] = "integer_scalar", + [sym__r_sgl_pln_flt_blk] = "float_scalar", + [sym__br_sgl_pln_flt_blk] = "float_scalar", + [sym__b_sgl_pln_flt_blk] = "float_scalar", + [sym__r_sgl_pln_flt_flw] = "float_scalar", + [sym__br_sgl_pln_flt_flw] = "float_scalar", + [sym__r_sgl_pln_tms_blk] = "timestamp_scalar", + [sym__br_sgl_pln_tms_blk] = "timestamp_scalar", + [sym__b_sgl_pln_tms_blk] = "timestamp_scalar", + [sym__r_sgl_pln_tms_flw] = "timestamp_scalar", + [sym__br_sgl_pln_tms_flw] = "timestamp_scalar", + [sym__r_sgl_pln_str_blk] = "string_scalar", + [sym__br_sgl_pln_str_blk] = "string_scalar", + [sym__b_sgl_pln_str_blk] = "string_scalar", + [sym__r_sgl_pln_str_flw] = "string_scalar", + [sym__br_sgl_pln_str_flw] = "string_scalar", + [sym__r_mtl_pln_str_blk] = "string_scalar", + [sym__br_mtl_pln_str_blk] = "string_scalar", + [sym__r_mtl_pln_str_flw] = "string_scalar", + [sym__br_mtl_pln_str_flw] = "string_scalar", + [sym__r_tag] = "tag", + [sym__br_tag] = "tag", + [sym__b_tag] = "tag", + [sym__r_acr_bgn] = "&", + [sym__br_acr_bgn] = "&", + [sym__b_acr_bgn] = "&", + [sym__r_acr_ctn] = "anchor_name", + [sym__r_als_bgn] = "*", + [sym__br_als_bgn] = "*", + [sym__b_als_bgn] = "*", + [sym__r_als_ctn] = "alias_name", + [sym__bl] = "_bl", + [sym_comment] = "comment", + [sym__err_rec] = "_err_rec", + [sym_stream] = "stream", + [sym__doc_w_bgn_w_end_seq] = "_doc_w_bgn_w_end_seq", + [sym__doc_w_bgn_wo_end_seq] = "_doc_w_bgn_wo_end_seq", + [sym__doc_wo_bgn_w_end_seq] = "_doc_wo_bgn_w_end_seq", + [sym__doc_wo_bgn_wo_end_seq] = "_doc_wo_bgn_wo_end_seq", + [sym__doc_w_bgn_w_end] = "_doc_w_bgn_w_end", + [sym__doc_w_bgn_wo_end] = "_doc_w_bgn_wo_end", + [sym__doc_wo_bgn_w_end] = "_doc_wo_bgn_w_end", + [sym__doc_wo_bgn_wo_end] = "_doc_wo_bgn_wo_end", + [sym__bgn_imp_doc] = "_bgn_imp_doc", + [sym__drs_doc] = "_drs_doc", + [sym__exp_doc] = "_exp_doc", + [sym__imp_doc] = "_imp_doc", + [sym__drs_doc_end] = "document", + [sym__exp_doc_end] = "document", + [sym__imp_doc_end] = "document", + [sym__bgn_imp_doc_end] = "document", + [sym__doc_end] = "document", + [sym__exp_doc_tal] = "_exp_doc_tal", + [sym__s_dir] = "_s_dir", + [sym__s_dir_yml] = "yaml_directive", + [sym__s_dir_tag] = "tag_directive", + [sym__s_dir_rsv] = "reserved_directive", + [sym__r_prp_val] = "flow_node", + [sym__br_prp_val] = "flow_node", + [sym__r_sgl_prp_val] = "flow_node", + [sym__br_sgl_prp_val] = "flow_node", + [sym__b_sgl_prp_val] = "flow_node", + [sym__r_prp] = "_r_prp", + [sym__br_prp] = "_br_prp", + [sym__r_sgl_prp] = "_r_sgl_prp", + [sym__br_sgl_prp] = "_br_sgl_prp", + [sym__b_sgl_prp] = "_b_sgl_prp", + [sym__r_blk_seq_r_val] = "block_node", + [sym__r_blk_seq_br_val] = "block_node", + [sym__br_blk_seq_val] = "block_node", + [sym__r_blk_seq_spc_val] = "block_node", + [sym__br_blk_seq_spc_val] = "block_node", + [sym__b_blk_seq_spc_val] = "block_node", + [sym__r_blk_seq] = "block_sequence", + [sym__br_blk_seq] = "block_sequence", + [sym__b_blk_seq_spc] = "block_sequence", + [sym__r_blk_seq_itm] = "block_sequence_item", + [sym__br_blk_seq_itm] = "block_sequence_item", + [sym__b_blk_seq_itm] = "block_sequence_item", + [sym__blk_seq_itm_tal] = "_blk_seq_itm_tal", + [sym__r_blk_map_r_val] = "block_node", + [sym__r_blk_map_br_val] = "block_node", + [sym__br_blk_map_val] = "block_node", + [sym__r_blk_map] = "block_mapping", + [sym__br_blk_map] = "block_mapping", + [sym__r_blk_map_itm] = "_r_blk_map_itm", + [sym__br_blk_map_itm] = "_br_blk_map_itm", + [sym__b_blk_map_itm] = "_b_blk_map_itm", + [sym__r_blk_exp_itm] = "block_mapping_pair", + [sym__br_blk_exp_itm] = "block_mapping_pair", + [sym__b_blk_exp_itm] = "block_mapping_pair", + [sym__r_blk_key_itm] = "_r_blk_key_itm", + [sym__br_blk_key_itm] = "_br_blk_key_itm", + [sym__b_blk_key_itm] = "_b_blk_key_itm", + [sym__r_blk_val_itm] = "_r_blk_val_itm", + [sym__br_blk_val_itm] = "_br_blk_val_itm", + [sym__b_blk_val_itm] = "_b_blk_val_itm", + [sym__r_blk_imp_itm] = "block_mapping_pair", + [sym__br_blk_imp_itm] = "block_mapping_pair", + [sym__b_blk_imp_itm] = "block_mapping_pair", + [sym__blk_exp_itm_tal] = "_blk_exp_itm_tal", + [sym__blk_imp_itm_tal] = "_blk_imp_itm_tal", + [sym__r_blk_str_val] = "block_node", + [sym__br_blk_str_val] = "block_node", + [sym__r_blk_str] = "block_scalar", + [sym__br_blk_str] = "block_scalar", + [sym__r_flw_seq_val] = "flow_node", + [sym__br_flw_seq_val] = "flow_node", + [sym__r_sgl_flw_seq_val] = "flow_node", + [sym__br_sgl_flw_seq_val] = "flow_node", + [sym__b_sgl_flw_seq_val] = "flow_node", + [sym__r_flw_seq] = "flow_sequence", + [sym__br_flw_seq] = "flow_sequence", + [sym__r_sgl_flw_seq] = "flow_sequence", + [sym__br_sgl_flw_seq] = "flow_sequence", + [sym__b_sgl_flw_seq] = "flow_sequence", + [sym__flw_seq_tal] = "_flw_seq_tal", + [sym__sgl_flw_seq_tal] = "_sgl_flw_seq_tal", + [sym__r_flw_map_val] = "flow_node", + [sym__br_flw_map_val] = "flow_node", + [sym__r_sgl_flw_map_val] = "flow_node", + [sym__br_sgl_flw_map_val] = "flow_node", + [sym__b_sgl_flw_map_val] = "flow_node", + [sym__r_flw_map] = "flow_mapping", + [sym__br_flw_map] = "flow_mapping", + [sym__r_sgl_flw_map] = "flow_mapping", + [sym__br_sgl_flw_map] = "flow_mapping", + [sym__b_sgl_flw_map] = "flow_mapping", + [sym__flw_map_tal] = "_flw_map_tal", + [sym__sgl_flw_map_tal] = "_sgl_flw_map_tal", + [sym__r_flw_seq_dat] = "_r_flw_seq_dat", + [sym__br_flw_seq_dat] = "_br_flw_seq_dat", + [sym__r_flw_map_dat] = "_r_flw_map_dat", + [sym__br_flw_map_dat] = "_br_flw_map_dat", + [sym__r_sgl_flw_col_dat] = "_r_sgl_flw_col_dat", + [sym__flw_seq_dat_rpt] = "_flw_seq_dat_rpt", + [sym__flw_map_dat_rpt] = "_flw_map_dat_rpt", + [sym__sgl_flw_col_dat_rpt] = "_sgl_flw_col_dat_rpt", + [sym__r_flw_seq_itm] = "_r_flw_seq_itm", + [sym__br_flw_seq_itm] = "_br_flw_seq_itm", + [sym__r_flw_map_itm] = "_r_flw_map_itm", + [sym__br_flw_map_itm] = "_br_flw_map_itm", + [sym__r_sgl_flw_col_itm] = "_r_sgl_flw_col_itm", + [sym__r_flw_exp_par] = "flow_pair", + [sym__br_flw_exp_par] = "flow_pair", + [sym__r_sgl_flw_exp_par] = "flow_pair", + [sym__r_flw_imp_r_par] = "_r_flw_imp_r_par", + [sym__r_flw_imp_br_par] = "_r_flw_imp_br_par", + [sym__br_flw_imp_r_par] = "_br_flw_imp_r_par", + [sym__br_flw_imp_br_par] = "_br_flw_imp_br_par", + [sym__r_sgl_flw_imp_par] = "_r_sgl_flw_imp_par", + [sym__r_flw_jsl_ann_par] = "_r_flw_jsl_ann_par", + [sym__br_flw_jsl_ann_par] = "_br_flw_jsl_ann_par", + [sym__r_sgl_flw_jsl_ann_par] = "_r_sgl_flw_jsl_ann_par", + [sym__r_flw_njl_ann_par] = "_r_flw_njl_ann_par", + [sym__br_flw_njl_ann_par] = "_br_flw_njl_ann_par", + [sym__r_sgl_flw_njl_ann_par] = "_r_sgl_flw_njl_ann_par", + [sym__flw_ann_par_tal] = "_flw_ann_par_tal", + [sym__sgl_flw_ann_par_tal] = "_sgl_flw_ann_par_tal", + [sym__r_dqt_str_val] = "flow_node", + [sym__br_dqt_str_val] = "flow_node", + [sym__r_sgl_dqt_str_val] = "flow_node", + [sym__br_sgl_dqt_str_val] = "flow_node", + [sym__b_sgl_dqt_str_val] = "flow_node", + [sym__r_dqt_str] = "double_quote_scalar", + [sym__br_dqt_str] = "double_quote_scalar", + [sym__r_sgl_dqt_str] = "double_quote_scalar", + [sym__br_sgl_dqt_str] = "double_quote_scalar", + [sym__b_sgl_dqt_str] = "double_quote_scalar", + [aux_sym__r_sgl_dqt_ctn] = "_r_sgl_dqt_ctn", + [sym__br_mtl_dqt_ctn] = "_br_mtl_dqt_ctn", + [sym__r_sqt_str_val] = "flow_node", + [sym__br_sqt_str_val] = "flow_node", + [sym__r_sgl_sqt_str_val] = "flow_node", + [sym__br_sgl_sqt_str_val] = "flow_node", + [sym__b_sgl_sqt_str_val] = "flow_node", + [sym__r_sqt_str] = "single_quote_scalar", + [sym__br_sqt_str] = "single_quote_scalar", + [sym__r_sgl_sqt_str] = "single_quote_scalar", + [sym__br_sgl_sqt_str] = "single_quote_scalar", + [sym__b_sgl_sqt_str] = "single_quote_scalar", + [aux_sym__r_sgl_sqt_ctn] = "_r_sgl_sqt_ctn", + [sym__br_mtl_sqt_ctn] = "_br_mtl_sqt_ctn", + [sym__r_pln_blk_val] = "flow_node", + [sym__br_pln_blk_val] = "flow_node", + [sym__r_sgl_pln_blk_val] = "flow_node", + [sym__br_sgl_pln_blk_val] = "flow_node", + [sym__b_sgl_pln_blk_val] = "flow_node", + [sym__r_pln_flw_val] = "flow_node", + [sym__br_pln_flw_val] = "flow_node", + [sym__r_sgl_pln_flw_val] = "flow_node", + [sym__r_sgl_pln_blk] = "plain_scalar", + [sym__br_sgl_pln_blk] = "plain_scalar", + [sym__b_sgl_pln_blk] = "plain_scalar", + [sym__r_sgl_pln_flw] = "plain_scalar", + [sym__br_sgl_pln_flw] = "plain_scalar", + [sym__r_mtl_pln_blk] = "plain_scalar", + [sym__br_mtl_pln_blk] = "plain_scalar", + [sym__r_mtl_pln_flw] = "plain_scalar", + [sym__br_mtl_pln_flw] = "plain_scalar", + [sym__r_als_val] = "flow_node", + [sym__br_als_val] = "flow_node", + [sym__b_als_val] = "flow_node", + [sym__r_als] = "alias", + [sym__br_als] = "alias", + [sym__b_als] = "alias", + [sym__r_acr] = "anchor", + [sym__br_acr] = "anchor", + [sym__b_acr] = "anchor", + [aux_sym__drs_doc_repeat1] = "_drs_doc_repeat1", + [aux_sym__s_dir_rsv_repeat1] = "_s_dir_rsv_repeat1", + [aux_sym__r_blk_seq_repeat1] = "_r_blk_seq_repeat1", + [aux_sym__r_blk_map_repeat1] = "_r_blk_map_repeat1", + [aux_sym__r_blk_str_repeat1] = "_r_blk_str_repeat1", + [aux_sym__r_flw_seq_dat_repeat1] = "_r_flw_seq_dat_repeat1", + [aux_sym__r_flw_map_dat_repeat1] = "_r_flw_map_dat_repeat1", + [aux_sym__r_sgl_flw_col_dat_repeat1] = "_r_sgl_flw_col_dat_repeat1", + [aux_sym__r_dqt_str_repeat1] = "_r_dqt_str_repeat1", + [aux_sym__br_mtl_dqt_ctn_repeat1] = "_br_mtl_dqt_ctn_repeat1", + [aux_sym__r_sqt_str_repeat1] = "_r_sqt_str_repeat1", + [aux_sym__br_mtl_sqt_ctn_repeat1] = "_br_mtl_sqt_ctn_repeat1", +}; + +static const TSSymbol ts_symbol_map[] = { + [ts_builtin_sym_end] = ts_builtin_sym_end, + [sym__eof] = sym__eof, + [sym__s_dir_yml_bgn] = sym__s_dir_yml_bgn, + [sym__r_dir_yml_ver] = sym__r_dir_yml_ver, + [sym__s_dir_tag_bgn] = sym__s_dir_tag_bgn, + [sym__r_dir_tag_hdl] = sym__r_dir_tag_hdl, + [sym__r_dir_tag_pfx] = sym__r_dir_tag_pfx, + [sym__s_dir_rsv_bgn] = sym__s_dir_rsv_bgn, + [sym__r_dir_rsv_prm] = sym__r_dir_rsv_prm, + [sym__s_drs_end] = sym__s_drs_end, + [sym__s_doc_end] = sym__s_doc_end, + [sym__r_blk_seq_bgn] = sym__r_blk_seq_bgn, + [sym__br_blk_seq_bgn] = sym__r_blk_seq_bgn, + [sym__b_blk_seq_bgn] = sym__r_blk_seq_bgn, + [sym__r_blk_key_bgn] = sym__r_blk_key_bgn, + [sym__br_blk_key_bgn] = sym__r_blk_key_bgn, + [sym__b_blk_key_bgn] = sym__r_blk_key_bgn, + [sym__r_blk_val_bgn] = sym__r_blk_val_bgn, + [sym__br_blk_val_bgn] = sym__r_blk_val_bgn, + [sym__b_blk_val_bgn] = sym__r_blk_val_bgn, + [sym__r_blk_imp_bgn] = sym__r_blk_val_bgn, + [sym__r_blk_lit_bgn] = sym__r_blk_lit_bgn, + [sym__br_blk_lit_bgn] = sym__r_blk_lit_bgn, + [sym__r_blk_fld_bgn] = sym__r_blk_fld_bgn, + [sym__br_blk_fld_bgn] = sym__r_blk_fld_bgn, + [sym__br_blk_str_ctn] = sym__br_blk_str_ctn, + [sym__r_flw_seq_bgn] = sym__r_flw_seq_bgn, + [sym__br_flw_seq_bgn] = sym__r_flw_seq_bgn, + [sym__b_flw_seq_bgn] = sym__r_flw_seq_bgn, + [sym__r_flw_seq_end] = sym__r_flw_seq_end, + [sym__br_flw_seq_end] = sym__r_flw_seq_end, + [sym__b_flw_seq_end] = sym__r_flw_seq_end, + [sym__r_flw_map_bgn] = sym__r_flw_map_bgn, + [sym__br_flw_map_bgn] = sym__r_flw_map_bgn, + [sym__b_flw_map_bgn] = sym__r_flw_map_bgn, + [sym__r_flw_map_end] = sym__r_flw_map_end, + [sym__br_flw_map_end] = sym__r_flw_map_end, + [sym__b_flw_map_end] = sym__r_flw_map_end, + [sym__r_flw_sep_bgn] = sym__r_flw_sep_bgn, + [sym__br_flw_sep_bgn] = sym__r_flw_sep_bgn, + [sym__r_flw_key_bgn] = sym__r_blk_key_bgn, + [sym__br_flw_key_bgn] = sym__r_blk_key_bgn, + [sym__r_flw_jsv_bgn] = sym__r_blk_val_bgn, + [sym__br_flw_jsv_bgn] = sym__r_blk_val_bgn, + [sym__r_flw_njv_bgn] = sym__r_blk_val_bgn, + [sym__br_flw_njv_bgn] = sym__r_blk_val_bgn, + [sym__r_dqt_str_bgn] = sym__r_dqt_str_bgn, + [sym__br_dqt_str_bgn] = sym__r_dqt_str_bgn, + [sym__b_dqt_str_bgn] = sym__r_dqt_str_bgn, + [sym__r_dqt_str_ctn] = sym__r_dqt_str_ctn, + [sym__br_dqt_str_ctn] = sym__br_dqt_str_ctn, + [sym__r_dqt_esc_nwl] = sym__r_dqt_esc_nwl, + [sym__br_dqt_esc_nwl] = sym__r_dqt_esc_nwl, + [sym__r_dqt_esc_seq] = sym__r_dqt_esc_nwl, + [sym__br_dqt_esc_seq] = sym__r_dqt_esc_nwl, + [sym__r_dqt_str_end] = sym__r_dqt_str_bgn, + [sym__br_dqt_str_end] = sym__r_dqt_str_bgn, + [sym__r_sqt_str_bgn] = sym__r_sqt_str_bgn, + [sym__br_sqt_str_bgn] = sym__r_sqt_str_bgn, + [sym__b_sqt_str_bgn] = sym__r_sqt_str_bgn, + [sym__r_sqt_str_ctn] = sym__r_sqt_str_ctn, + [sym__br_sqt_str_ctn] = sym__br_sqt_str_ctn, + [sym__r_sqt_esc_sqt] = sym__r_dqt_esc_nwl, + [sym__br_sqt_esc_sqt] = sym__r_dqt_esc_nwl, + [sym__r_sqt_str_end] = sym__r_sqt_str_bgn, + [sym__br_sqt_str_end] = sym__r_sqt_str_bgn, + [sym__r_sgl_pln_nul_blk] = sym__r_sgl_pln_nul_blk, + [sym__br_sgl_pln_nul_blk] = sym__r_sgl_pln_nul_blk, + [sym__b_sgl_pln_nul_blk] = sym__r_sgl_pln_nul_blk, + [sym__r_sgl_pln_nul_flw] = sym__r_sgl_pln_nul_blk, + [sym__br_sgl_pln_nul_flw] = sym__r_sgl_pln_nul_blk, + [sym__r_sgl_pln_bol_blk] = sym__r_sgl_pln_bol_blk, + [sym__br_sgl_pln_bol_blk] = sym__r_sgl_pln_bol_blk, + [sym__b_sgl_pln_bol_blk] = sym__r_sgl_pln_bol_blk, + [sym__r_sgl_pln_bol_flw] = sym__r_sgl_pln_bol_blk, + [sym__br_sgl_pln_bol_flw] = sym__r_sgl_pln_bol_blk, + [sym__r_sgl_pln_int_blk] = sym__r_sgl_pln_int_blk, + [sym__br_sgl_pln_int_blk] = sym__r_sgl_pln_int_blk, + [sym__b_sgl_pln_int_blk] = sym__r_sgl_pln_int_blk, + [sym__r_sgl_pln_int_flw] = sym__r_sgl_pln_int_blk, + [sym__br_sgl_pln_int_flw] = sym__r_sgl_pln_int_blk, + [sym__r_sgl_pln_flt_blk] = sym__r_sgl_pln_flt_blk, + [sym__br_sgl_pln_flt_blk] = sym__r_sgl_pln_flt_blk, + [sym__b_sgl_pln_flt_blk] = sym__r_sgl_pln_flt_blk, + [sym__r_sgl_pln_flt_flw] = sym__r_sgl_pln_flt_blk, + [sym__br_sgl_pln_flt_flw] = sym__r_sgl_pln_flt_blk, + [sym__r_sgl_pln_tms_blk] = sym__r_sgl_pln_tms_blk, + [sym__br_sgl_pln_tms_blk] = sym__r_sgl_pln_tms_blk, + [sym__b_sgl_pln_tms_blk] = sym__r_sgl_pln_tms_blk, + [sym__r_sgl_pln_tms_flw] = sym__r_sgl_pln_tms_blk, + [sym__br_sgl_pln_tms_flw] = sym__r_sgl_pln_tms_blk, + [sym__r_sgl_pln_str_blk] = sym__r_sgl_pln_str_blk, + [sym__br_sgl_pln_str_blk] = sym__r_sgl_pln_str_blk, + [sym__b_sgl_pln_str_blk] = sym__r_sgl_pln_str_blk, + [sym__r_sgl_pln_str_flw] = sym__r_sgl_pln_str_blk, + [sym__br_sgl_pln_str_flw] = sym__r_sgl_pln_str_blk, + [sym__r_mtl_pln_str_blk] = sym__r_sgl_pln_str_blk, + [sym__br_mtl_pln_str_blk] = sym__r_sgl_pln_str_blk, + [sym__r_mtl_pln_str_flw] = sym__r_sgl_pln_str_blk, + [sym__br_mtl_pln_str_flw] = sym__r_sgl_pln_str_blk, + [sym__r_tag] = sym__r_tag, + [sym__br_tag] = sym__r_tag, + [sym__b_tag] = sym__r_tag, + [sym__r_acr_bgn] = sym__r_acr_bgn, + [sym__br_acr_bgn] = sym__r_acr_bgn, + [sym__b_acr_bgn] = sym__r_acr_bgn, + [sym__r_acr_ctn] = sym__r_acr_ctn, + [sym__r_als_bgn] = sym__r_als_bgn, + [sym__br_als_bgn] = sym__r_als_bgn, + [sym__b_als_bgn] = sym__r_als_bgn, + [sym__r_als_ctn] = sym__r_als_ctn, + [sym__bl] = sym__bl, + [sym_comment] = sym_comment, + [sym__err_rec] = sym__err_rec, + [sym_stream] = sym_stream, + [sym__doc_w_bgn_w_end_seq] = sym__doc_w_bgn_w_end_seq, + [sym__doc_w_bgn_wo_end_seq] = sym__doc_w_bgn_wo_end_seq, + [sym__doc_wo_bgn_w_end_seq] = sym__doc_wo_bgn_w_end_seq, + [sym__doc_wo_bgn_wo_end_seq] = sym__doc_wo_bgn_wo_end_seq, + [sym__doc_w_bgn_w_end] = sym__doc_w_bgn_w_end, + [sym__doc_w_bgn_wo_end] = sym__doc_w_bgn_wo_end, + [sym__doc_wo_bgn_w_end] = sym__doc_wo_bgn_w_end, + [sym__doc_wo_bgn_wo_end] = sym__doc_wo_bgn_wo_end, + [sym__bgn_imp_doc] = sym__bgn_imp_doc, + [sym__drs_doc] = sym__drs_doc, + [sym__exp_doc] = sym__exp_doc, + [sym__imp_doc] = sym__imp_doc, + [sym__drs_doc_end] = sym__drs_doc_end, + [sym__exp_doc_end] = sym__drs_doc_end, + [sym__imp_doc_end] = sym__drs_doc_end, + [sym__bgn_imp_doc_end] = sym__drs_doc_end, + [sym__doc_end] = sym__drs_doc_end, + [sym__exp_doc_tal] = sym__exp_doc_tal, + [sym__s_dir] = sym__s_dir, + [sym__s_dir_yml] = sym__s_dir_yml, + [sym__s_dir_tag] = sym__s_dir_tag, + [sym__s_dir_rsv] = sym__s_dir_rsv, + [sym__r_prp_val] = sym__r_prp_val, + [sym__br_prp_val] = sym__r_prp_val, + [sym__r_sgl_prp_val] = sym__r_prp_val, + [sym__br_sgl_prp_val] = sym__r_prp_val, + [sym__b_sgl_prp_val] = sym__r_prp_val, + [sym__r_prp] = sym__r_prp, + [sym__br_prp] = sym__br_prp, + [sym__r_sgl_prp] = sym__r_sgl_prp, + [sym__br_sgl_prp] = sym__br_sgl_prp, + [sym__b_sgl_prp] = sym__b_sgl_prp, + [sym__r_blk_seq_r_val] = sym__r_blk_seq_r_val, + [sym__r_blk_seq_br_val] = sym__r_blk_seq_r_val, + [sym__br_blk_seq_val] = sym__r_blk_seq_r_val, + [sym__r_blk_seq_spc_val] = sym__r_blk_seq_r_val, + [sym__br_blk_seq_spc_val] = sym__r_blk_seq_r_val, + [sym__b_blk_seq_spc_val] = sym__r_blk_seq_r_val, + [sym__r_blk_seq] = sym__r_blk_seq, + [sym__br_blk_seq] = sym__r_blk_seq, + [sym__b_blk_seq_spc] = sym__r_blk_seq, + [sym__r_blk_seq_itm] = sym__r_blk_seq_itm, + [sym__br_blk_seq_itm] = sym__r_blk_seq_itm, + [sym__b_blk_seq_itm] = sym__r_blk_seq_itm, + [sym__blk_seq_itm_tal] = sym__blk_seq_itm_tal, + [sym__r_blk_map_r_val] = sym__r_blk_seq_r_val, + [sym__r_blk_map_br_val] = sym__r_blk_seq_r_val, + [sym__br_blk_map_val] = sym__r_blk_seq_r_val, + [sym__r_blk_map] = sym__r_blk_map, + [sym__br_blk_map] = sym__r_blk_map, + [sym__r_blk_map_itm] = sym__r_blk_map_itm, + [sym__br_blk_map_itm] = sym__br_blk_map_itm, + [sym__b_blk_map_itm] = sym__b_blk_map_itm, + [sym__r_blk_exp_itm] = sym__r_blk_exp_itm, + [sym__br_blk_exp_itm] = sym__r_blk_exp_itm, + [sym__b_blk_exp_itm] = sym__r_blk_exp_itm, + [sym__r_blk_key_itm] = sym__r_blk_key_itm, + [sym__br_blk_key_itm] = sym__br_blk_key_itm, + [sym__b_blk_key_itm] = sym__b_blk_key_itm, + [sym__r_blk_val_itm] = sym__r_blk_val_itm, + [sym__br_blk_val_itm] = sym__br_blk_val_itm, + [sym__b_blk_val_itm] = sym__b_blk_val_itm, + [sym__r_blk_imp_itm] = sym__r_blk_exp_itm, + [sym__br_blk_imp_itm] = sym__r_blk_exp_itm, + [sym__b_blk_imp_itm] = sym__r_blk_exp_itm, + [sym__blk_exp_itm_tal] = sym__blk_exp_itm_tal, + [sym__blk_imp_itm_tal] = sym__blk_imp_itm_tal, + [sym__r_blk_str_val] = sym__r_blk_seq_r_val, + [sym__br_blk_str_val] = sym__r_blk_seq_r_val, + [sym__r_blk_str] = sym__r_blk_str, + [sym__br_blk_str] = sym__r_blk_str, + [sym__r_flw_seq_val] = sym__r_prp_val, + [sym__br_flw_seq_val] = sym__r_prp_val, + [sym__r_sgl_flw_seq_val] = sym__r_prp_val, + [sym__br_sgl_flw_seq_val] = sym__r_prp_val, + [sym__b_sgl_flw_seq_val] = sym__r_prp_val, + [sym__r_flw_seq] = sym__r_flw_seq, + [sym__br_flw_seq] = sym__r_flw_seq, + [sym__r_sgl_flw_seq] = sym__r_flw_seq, + [sym__br_sgl_flw_seq] = sym__r_flw_seq, + [sym__b_sgl_flw_seq] = sym__r_flw_seq, + [sym__flw_seq_tal] = sym__flw_seq_tal, + [sym__sgl_flw_seq_tal] = sym__sgl_flw_seq_tal, + [sym__r_flw_map_val] = sym__r_prp_val, + [sym__br_flw_map_val] = sym__r_prp_val, + [sym__r_sgl_flw_map_val] = sym__r_prp_val, + [sym__br_sgl_flw_map_val] = sym__r_prp_val, + [sym__b_sgl_flw_map_val] = sym__r_prp_val, + [sym__r_flw_map] = sym__r_flw_map, + [sym__br_flw_map] = sym__r_flw_map, + [sym__r_sgl_flw_map] = sym__r_flw_map, + [sym__br_sgl_flw_map] = sym__r_flw_map, + [sym__b_sgl_flw_map] = sym__r_flw_map, + [sym__flw_map_tal] = sym__flw_map_tal, + [sym__sgl_flw_map_tal] = sym__sgl_flw_map_tal, + [sym__r_flw_seq_dat] = sym__r_flw_seq_dat, + [sym__br_flw_seq_dat] = sym__br_flw_seq_dat, + [sym__r_flw_map_dat] = sym__r_flw_map_dat, + [sym__br_flw_map_dat] = sym__br_flw_map_dat, + [sym__r_sgl_flw_col_dat] = sym__r_sgl_flw_col_dat, + [sym__flw_seq_dat_rpt] = sym__flw_seq_dat_rpt, + [sym__flw_map_dat_rpt] = sym__flw_map_dat_rpt, + [sym__sgl_flw_col_dat_rpt] = sym__sgl_flw_col_dat_rpt, + [sym__r_flw_seq_itm] = sym__r_flw_seq_itm, + [sym__br_flw_seq_itm] = sym__br_flw_seq_itm, + [sym__r_flw_map_itm] = sym__r_flw_map_itm, + [sym__br_flw_map_itm] = sym__br_flw_map_itm, + [sym__r_sgl_flw_col_itm] = sym__r_sgl_flw_col_itm, + [sym__r_flw_exp_par] = sym__r_flw_exp_par, + [sym__br_flw_exp_par] = sym__r_flw_exp_par, + [sym__r_sgl_flw_exp_par] = sym__r_flw_exp_par, + [sym__r_flw_imp_r_par] = sym__r_flw_imp_r_par, + [sym__r_flw_imp_br_par] = sym__r_flw_imp_br_par, + [sym__br_flw_imp_r_par] = sym__br_flw_imp_r_par, + [sym__br_flw_imp_br_par] = sym__br_flw_imp_br_par, + [sym__r_sgl_flw_imp_par] = sym__r_sgl_flw_imp_par, + [sym__r_flw_jsl_ann_par] = sym__r_flw_jsl_ann_par, + [sym__br_flw_jsl_ann_par] = sym__br_flw_jsl_ann_par, + [sym__r_sgl_flw_jsl_ann_par] = sym__r_sgl_flw_jsl_ann_par, + [sym__r_flw_njl_ann_par] = sym__r_flw_njl_ann_par, + [sym__br_flw_njl_ann_par] = sym__br_flw_njl_ann_par, + [sym__r_sgl_flw_njl_ann_par] = sym__r_sgl_flw_njl_ann_par, + [sym__flw_ann_par_tal] = sym__flw_ann_par_tal, + [sym__sgl_flw_ann_par_tal] = sym__sgl_flw_ann_par_tal, + [sym__r_dqt_str_val] = sym__r_prp_val, + [sym__br_dqt_str_val] = sym__r_prp_val, + [sym__r_sgl_dqt_str_val] = sym__r_prp_val, + [sym__br_sgl_dqt_str_val] = sym__r_prp_val, + [sym__b_sgl_dqt_str_val] = sym__r_prp_val, + [sym__r_dqt_str] = sym__r_dqt_str, + [sym__br_dqt_str] = sym__r_dqt_str, + [sym__r_sgl_dqt_str] = sym__r_dqt_str, + [sym__br_sgl_dqt_str] = sym__r_dqt_str, + [sym__b_sgl_dqt_str] = sym__r_dqt_str, + [aux_sym__r_sgl_dqt_ctn] = aux_sym__r_sgl_dqt_ctn, + [sym__br_mtl_dqt_ctn] = sym__br_mtl_dqt_ctn, + [sym__r_sqt_str_val] = sym__r_prp_val, + [sym__br_sqt_str_val] = sym__r_prp_val, + [sym__r_sgl_sqt_str_val] = sym__r_prp_val, + [sym__br_sgl_sqt_str_val] = sym__r_prp_val, + [sym__b_sgl_sqt_str_val] = sym__r_prp_val, + [sym__r_sqt_str] = sym__r_sqt_str, + [sym__br_sqt_str] = sym__r_sqt_str, + [sym__r_sgl_sqt_str] = sym__r_sqt_str, + [sym__br_sgl_sqt_str] = sym__r_sqt_str, + [sym__b_sgl_sqt_str] = sym__r_sqt_str, + [aux_sym__r_sgl_sqt_ctn] = aux_sym__r_sgl_sqt_ctn, + [sym__br_mtl_sqt_ctn] = sym__br_mtl_sqt_ctn, + [sym__r_pln_blk_val] = sym__r_prp_val, + [sym__br_pln_blk_val] = sym__r_prp_val, + [sym__r_sgl_pln_blk_val] = sym__r_prp_val, + [sym__br_sgl_pln_blk_val] = sym__r_prp_val, + [sym__b_sgl_pln_blk_val] = sym__r_prp_val, + [sym__r_pln_flw_val] = sym__r_prp_val, + [sym__br_pln_flw_val] = sym__r_prp_val, + [sym__r_sgl_pln_flw_val] = sym__r_prp_val, + [sym__r_sgl_pln_blk] = sym__r_sgl_pln_blk, + [sym__br_sgl_pln_blk] = sym__r_sgl_pln_blk, + [sym__b_sgl_pln_blk] = sym__r_sgl_pln_blk, + [sym__r_sgl_pln_flw] = sym__r_sgl_pln_blk, + [sym__br_sgl_pln_flw] = sym__r_sgl_pln_blk, + [sym__r_mtl_pln_blk] = sym__r_sgl_pln_blk, + [sym__br_mtl_pln_blk] = sym__r_sgl_pln_blk, + [sym__r_mtl_pln_flw] = sym__r_sgl_pln_blk, + [sym__br_mtl_pln_flw] = sym__r_sgl_pln_blk, + [sym__r_als_val] = sym__r_prp_val, + [sym__br_als_val] = sym__r_prp_val, + [sym__b_als_val] = sym__r_prp_val, + [sym__r_als] = sym__r_als, + [sym__br_als] = sym__r_als, + [sym__b_als] = sym__r_als, + [sym__r_acr] = sym__r_acr, + [sym__br_acr] = sym__r_acr, + [sym__b_acr] = sym__r_acr, + [aux_sym__drs_doc_repeat1] = aux_sym__drs_doc_repeat1, + [aux_sym__s_dir_rsv_repeat1] = aux_sym__s_dir_rsv_repeat1, + [aux_sym__r_blk_seq_repeat1] = aux_sym__r_blk_seq_repeat1, + [aux_sym__r_blk_map_repeat1] = aux_sym__r_blk_map_repeat1, + [aux_sym__r_blk_str_repeat1] = aux_sym__r_blk_str_repeat1, + [aux_sym__r_flw_seq_dat_repeat1] = aux_sym__r_flw_seq_dat_repeat1, + [aux_sym__r_flw_map_dat_repeat1] = aux_sym__r_flw_map_dat_repeat1, + [aux_sym__r_sgl_flw_col_dat_repeat1] = aux_sym__r_sgl_flw_col_dat_repeat1, + [aux_sym__r_dqt_str_repeat1] = aux_sym__r_dqt_str_repeat1, + [aux_sym__br_mtl_dqt_ctn_repeat1] = aux_sym__br_mtl_dqt_ctn_repeat1, + [aux_sym__r_sqt_str_repeat1] = aux_sym__r_sqt_str_repeat1, + [aux_sym__br_mtl_sqt_ctn_repeat1] = aux_sym__br_mtl_sqt_ctn_repeat1, +}; + +static const TSSymbolMetadata ts_symbol_metadata[] = { + [ts_builtin_sym_end] = { + .visible = false, + .named = true, + }, + [sym__eof] = { + .visible = false, + .named = true, + }, + [sym__s_dir_yml_bgn] = { + .visible = false, + .named = true, + }, + [sym__r_dir_yml_ver] = { + .visible = true, + .named = true, + }, + [sym__s_dir_tag_bgn] = { + .visible = false, + .named = true, + }, + [sym__r_dir_tag_hdl] = { + .visible = true, + .named = true, + }, + [sym__r_dir_tag_pfx] = { + .visible = true, + .named = true, + }, + [sym__s_dir_rsv_bgn] = { + .visible = true, + .named = true, + }, + [sym__r_dir_rsv_prm] = { + .visible = true, + .named = true, + }, + [sym__s_drs_end] = { + .visible = true, + .named = false, + }, + [sym__s_doc_end] = { + .visible = true, + .named = false, + }, + [sym__r_blk_seq_bgn] = { + .visible = true, + .named = false, + }, + [sym__br_blk_seq_bgn] = { + .visible = true, + .named = false, + }, + [sym__b_blk_seq_bgn] = { + .visible = true, + .named = false, + }, + [sym__r_blk_key_bgn] = { + .visible = true, + .named = false, + }, + [sym__br_blk_key_bgn] = { + .visible = true, + .named = false, + }, + [sym__b_blk_key_bgn] = { + .visible = true, + .named = false, + }, + [sym__r_blk_val_bgn] = { + .visible = true, + .named = false, + }, + [sym__br_blk_val_bgn] = { + .visible = true, + .named = false, + }, + [sym__b_blk_val_bgn] = { + .visible = true, + .named = false, + }, + [sym__r_blk_imp_bgn] = { + .visible = true, + .named = false, + }, + [sym__r_blk_lit_bgn] = { + .visible = true, + .named = false, + }, + [sym__br_blk_lit_bgn] = { + .visible = true, + .named = false, + }, + [sym__r_blk_fld_bgn] = { + .visible = true, + .named = false, + }, + [sym__br_blk_fld_bgn] = { + .visible = true, + .named = false, + }, + [sym__br_blk_str_ctn] = { + .visible = false, + .named = true, + }, + [sym__r_flw_seq_bgn] = { + .visible = true, + .named = false, + }, + [sym__br_flw_seq_bgn] = { + .visible = true, + .named = false, + }, + [sym__b_flw_seq_bgn] = { + .visible = true, + .named = false, + }, + [sym__r_flw_seq_end] = { + .visible = true, + .named = false, + }, + [sym__br_flw_seq_end] = { + .visible = true, + .named = false, + }, + [sym__b_flw_seq_end] = { + .visible = true, + .named = false, + }, + [sym__r_flw_map_bgn] = { + .visible = true, + .named = false, + }, + [sym__br_flw_map_bgn] = { + .visible = true, + .named = false, + }, + [sym__b_flw_map_bgn] = { + .visible = true, + .named = false, + }, + [sym__r_flw_map_end] = { + .visible = true, + .named = false, + }, + [sym__br_flw_map_end] = { + .visible = true, + .named = false, + }, + [sym__b_flw_map_end] = { + .visible = true, + .named = false, + }, + [sym__r_flw_sep_bgn] = { + .visible = true, + .named = false, + }, + [sym__br_flw_sep_bgn] = { + .visible = true, + .named = false, + }, + [sym__r_flw_key_bgn] = { + .visible = true, + .named = false, + }, + [sym__br_flw_key_bgn] = { + .visible = true, + .named = false, + }, + [sym__r_flw_jsv_bgn] = { + .visible = true, + .named = false, + }, + [sym__br_flw_jsv_bgn] = { + .visible = true, + .named = false, + }, + [sym__r_flw_njv_bgn] = { + .visible = true, + .named = false, + }, + [sym__br_flw_njv_bgn] = { + .visible = true, + .named = false, + }, + [sym__r_dqt_str_bgn] = { + .visible = true, + .named = false, + }, + [sym__br_dqt_str_bgn] = { + .visible = true, + .named = false, + }, + [sym__b_dqt_str_bgn] = { + .visible = true, + .named = false, + }, + [sym__r_dqt_str_ctn] = { + .visible = false, + .named = true, + }, + [sym__br_dqt_str_ctn] = { + .visible = false, + .named = true, + }, + [sym__r_dqt_esc_nwl] = { + .visible = true, + .named = true, + }, + [sym__br_dqt_esc_nwl] = { + .visible = true, + .named = true, + }, + [sym__r_dqt_esc_seq] = { + .visible = true, + .named = true, + }, + [sym__br_dqt_esc_seq] = { + .visible = true, + .named = true, + }, + [sym__r_dqt_str_end] = { + .visible = true, + .named = false, + }, + [sym__br_dqt_str_end] = { + .visible = true, + .named = false, + }, + [sym__r_sqt_str_bgn] = { + .visible = true, + .named = false, + }, + [sym__br_sqt_str_bgn] = { + .visible = true, + .named = false, + }, + [sym__b_sqt_str_bgn] = { + .visible = true, + .named = false, + }, + [sym__r_sqt_str_ctn] = { + .visible = false, + .named = true, + }, + [sym__br_sqt_str_ctn] = { + .visible = false, + .named = true, + }, + [sym__r_sqt_esc_sqt] = { + .visible = true, + .named = true, + }, + [sym__br_sqt_esc_sqt] = { + .visible = true, + .named = true, + }, + [sym__r_sqt_str_end] = { + .visible = true, + .named = false, + }, + [sym__br_sqt_str_end] = { + .visible = true, + .named = false, + }, + [sym__r_sgl_pln_nul_blk] = { + .visible = true, + .named = true, + }, + [sym__br_sgl_pln_nul_blk] = { + .visible = true, + .named = true, + }, + [sym__b_sgl_pln_nul_blk] = { + .visible = true, + .named = true, + }, + [sym__r_sgl_pln_nul_flw] = { + .visible = true, + .named = true, + }, + [sym__br_sgl_pln_nul_flw] = { + .visible = true, + .named = true, + }, + [sym__r_sgl_pln_bol_blk] = { + .visible = true, + .named = true, + }, + [sym__br_sgl_pln_bol_blk] = { + .visible = true, + .named = true, + }, + [sym__b_sgl_pln_bol_blk] = { + .visible = true, + .named = true, + }, + [sym__r_sgl_pln_bol_flw] = { + .visible = true, + .named = true, + }, + [sym__br_sgl_pln_bol_flw] = { + .visible = true, + .named = true, + }, + [sym__r_sgl_pln_int_blk] = { + .visible = true, + .named = true, + }, + [sym__br_sgl_pln_int_blk] = { + .visible = true, + .named = true, + }, + [sym__b_sgl_pln_int_blk] = { + .visible = true, + .named = true, + }, + [sym__r_sgl_pln_int_flw] = { + .visible = true, + .named = true, + }, + [sym__br_sgl_pln_int_flw] = { + .visible = true, + .named = true, + }, + [sym__r_sgl_pln_flt_blk] = { + .visible = true, + .named = true, + }, + [sym__br_sgl_pln_flt_blk] = { + .visible = true, + .named = true, + }, + [sym__b_sgl_pln_flt_blk] = { + .visible = true, + .named = true, + }, + [sym__r_sgl_pln_flt_flw] = { + .visible = true, + .named = true, + }, + [sym__br_sgl_pln_flt_flw] = { + .visible = true, + .named = true, + }, + [sym__r_sgl_pln_tms_blk] = { + .visible = true, + .named = true, + }, + [sym__br_sgl_pln_tms_blk] = { + .visible = true, + .named = true, + }, + [sym__b_sgl_pln_tms_blk] = { + .visible = true, + .named = true, + }, + [sym__r_sgl_pln_tms_flw] = { + .visible = true, + .named = true, + }, + [sym__br_sgl_pln_tms_flw] = { + .visible = true, + .named = true, + }, + [sym__r_sgl_pln_str_blk] = { + .visible = true, + .named = true, + }, + [sym__br_sgl_pln_str_blk] = { + .visible = true, + .named = true, + }, + [sym__b_sgl_pln_str_blk] = { + .visible = true, + .named = true, + }, + [sym__r_sgl_pln_str_flw] = { + .visible = true, + .named = true, + }, + [sym__br_sgl_pln_str_flw] = { + .visible = true, + .named = true, + }, + [sym__r_mtl_pln_str_blk] = { + .visible = true, + .named = true, + }, + [sym__br_mtl_pln_str_blk] = { + .visible = true, + .named = true, + }, + [sym__r_mtl_pln_str_flw] = { + .visible = true, + .named = true, + }, + [sym__br_mtl_pln_str_flw] = { + .visible = true, + .named = true, + }, + [sym__r_tag] = { + .visible = true, + .named = true, + }, + [sym__br_tag] = { + .visible = true, + .named = true, + }, + [sym__b_tag] = { + .visible = true, + .named = true, + }, + [sym__r_acr_bgn] = { + .visible = true, + .named = false, + }, + [sym__br_acr_bgn] = { + .visible = true, + .named = false, + }, + [sym__b_acr_bgn] = { + .visible = true, + .named = false, + }, + [sym__r_acr_ctn] = { + .visible = true, + .named = true, + }, + [sym__r_als_bgn] = { + .visible = true, + .named = false, + }, + [sym__br_als_bgn] = { + .visible = true, + .named = false, + }, + [sym__b_als_bgn] = { + .visible = true, + .named = false, + }, + [sym__r_als_ctn] = { + .visible = true, + .named = true, + }, + [sym__bl] = { + .visible = false, + .named = true, + }, + [sym_comment] = { + .visible = true, + .named = true, + }, + [sym__err_rec] = { + .visible = false, + .named = true, + }, + [sym_stream] = { + .visible = true, + .named = true, + }, + [sym__doc_w_bgn_w_end_seq] = { + .visible = false, + .named = true, + }, + [sym__doc_w_bgn_wo_end_seq] = { + .visible = false, + .named = true, + }, + [sym__doc_wo_bgn_w_end_seq] = { + .visible = false, + .named = true, + }, + [sym__doc_wo_bgn_wo_end_seq] = { + .visible = false, + .named = true, + }, + [sym__doc_w_bgn_w_end] = { + .visible = false, + .named = true, + }, + [sym__doc_w_bgn_wo_end] = { + .visible = false, + .named = true, + }, + [sym__doc_wo_bgn_w_end] = { + .visible = false, + .named = true, + }, + [sym__doc_wo_bgn_wo_end] = { + .visible = false, + .named = true, + }, + [sym__bgn_imp_doc] = { + .visible = false, + .named = true, + }, + [sym__drs_doc] = { + .visible = false, + .named = true, + }, + [sym__exp_doc] = { + .visible = false, + .named = true, + }, + [sym__imp_doc] = { + .visible = false, + .named = true, + }, + [sym__drs_doc_end] = { + .visible = true, + .named = true, + }, + [sym__exp_doc_end] = { + .visible = true, + .named = true, + }, + [sym__imp_doc_end] = { + .visible = true, + .named = true, + }, + [sym__bgn_imp_doc_end] = { + .visible = true, + .named = true, + }, + [sym__doc_end] = { + .visible = true, + .named = true, + }, + [sym__exp_doc_tal] = { + .visible = false, + .named = true, + }, + [sym__s_dir] = { + .visible = false, + .named = true, + }, + [sym__s_dir_yml] = { + .visible = true, + .named = true, + }, + [sym__s_dir_tag] = { + .visible = true, + .named = true, + }, + [sym__s_dir_rsv] = { + .visible = true, + .named = true, + }, + [sym__r_prp_val] = { + .visible = true, + .named = true, + }, + [sym__br_prp_val] = { + .visible = true, + .named = true, + }, + [sym__r_sgl_prp_val] = { + .visible = true, + .named = true, + }, + [sym__br_sgl_prp_val] = { + .visible = true, + .named = true, + }, + [sym__b_sgl_prp_val] = { + .visible = true, + .named = true, + }, + [sym__r_prp] = { + .visible = false, + .named = true, + }, + [sym__br_prp] = { + .visible = false, + .named = true, + }, + [sym__r_sgl_prp] = { + .visible = false, + .named = true, + }, + [sym__br_sgl_prp] = { + .visible = false, + .named = true, + }, + [sym__b_sgl_prp] = { + .visible = false, + .named = true, + }, + [sym__r_blk_seq_r_val] = { + .visible = true, + .named = true, + }, + [sym__r_blk_seq_br_val] = { + .visible = true, + .named = true, + }, + [sym__br_blk_seq_val] = { + .visible = true, + .named = true, + }, + [sym__r_blk_seq_spc_val] = { + .visible = true, + .named = true, + }, + [sym__br_blk_seq_spc_val] = { + .visible = true, + .named = true, + }, + [sym__b_blk_seq_spc_val] = { + .visible = true, + .named = true, + }, + [sym__r_blk_seq] = { + .visible = true, + .named = true, + }, + [sym__br_blk_seq] = { + .visible = true, + .named = true, + }, + [sym__b_blk_seq_spc] = { + .visible = true, + .named = true, + }, + [sym__r_blk_seq_itm] = { + .visible = true, + .named = true, + }, + [sym__br_blk_seq_itm] = { + .visible = true, + .named = true, + }, + [sym__b_blk_seq_itm] = { + .visible = true, + .named = true, + }, + [sym__blk_seq_itm_tal] = { + .visible = false, + .named = true, + }, + [sym__r_blk_map_r_val] = { + .visible = true, + .named = true, + }, + [sym__r_blk_map_br_val] = { + .visible = true, + .named = true, + }, + [sym__br_blk_map_val] = { + .visible = true, + .named = true, + }, + [sym__r_blk_map] = { + .visible = true, + .named = true, + }, + [sym__br_blk_map] = { + .visible = true, + .named = true, + }, + [sym__r_blk_map_itm] = { + .visible = false, + .named = true, + }, + [sym__br_blk_map_itm] = { + .visible = false, + .named = true, + }, + [sym__b_blk_map_itm] = { + .visible = false, + .named = true, + }, + [sym__r_blk_exp_itm] = { + .visible = true, + .named = true, + }, + [sym__br_blk_exp_itm] = { + .visible = true, + .named = true, + }, + [sym__b_blk_exp_itm] = { + .visible = true, + .named = true, + }, + [sym__r_blk_key_itm] = { + .visible = false, + .named = true, + }, + [sym__br_blk_key_itm] = { + .visible = false, + .named = true, + }, + [sym__b_blk_key_itm] = { + .visible = false, + .named = true, + }, + [sym__r_blk_val_itm] = { + .visible = false, + .named = true, + }, + [sym__br_blk_val_itm] = { + .visible = false, + .named = true, + }, + [sym__b_blk_val_itm] = { + .visible = false, + .named = true, + }, + [sym__r_blk_imp_itm] = { + .visible = true, + .named = true, + }, + [sym__br_blk_imp_itm] = { + .visible = true, + .named = true, + }, + [sym__b_blk_imp_itm] = { + .visible = true, + .named = true, + }, + [sym__blk_exp_itm_tal] = { + .visible = false, + .named = true, + }, + [sym__blk_imp_itm_tal] = { + .visible = false, + .named = true, + }, + [sym__r_blk_str_val] = { + .visible = true, + .named = true, + }, + [sym__br_blk_str_val] = { + .visible = true, + .named = true, + }, + [sym__r_blk_str] = { + .visible = true, + .named = true, + }, + [sym__br_blk_str] = { + .visible = true, + .named = true, + }, + [sym__r_flw_seq_val] = { + .visible = true, + .named = true, + }, + [sym__br_flw_seq_val] = { + .visible = true, + .named = true, + }, + [sym__r_sgl_flw_seq_val] = { + .visible = true, + .named = true, + }, + [sym__br_sgl_flw_seq_val] = { + .visible = true, + .named = true, + }, + [sym__b_sgl_flw_seq_val] = { + .visible = true, + .named = true, + }, + [sym__r_flw_seq] = { + .visible = true, + .named = true, + }, + [sym__br_flw_seq] = { + .visible = true, + .named = true, + }, + [sym__r_sgl_flw_seq] = { + .visible = true, + .named = true, + }, + [sym__br_sgl_flw_seq] = { + .visible = true, + .named = true, + }, + [sym__b_sgl_flw_seq] = { + .visible = true, + .named = true, + }, + [sym__flw_seq_tal] = { + .visible = false, + .named = true, + }, + [sym__sgl_flw_seq_tal] = { + .visible = false, + .named = true, + }, + [sym__r_flw_map_val] = { + .visible = true, + .named = true, + }, + [sym__br_flw_map_val] = { + .visible = true, + .named = true, + }, + [sym__r_sgl_flw_map_val] = { + .visible = true, + .named = true, + }, + [sym__br_sgl_flw_map_val] = { + .visible = true, + .named = true, + }, + [sym__b_sgl_flw_map_val] = { + .visible = true, + .named = true, + }, + [sym__r_flw_map] = { + .visible = true, + .named = true, + }, + [sym__br_flw_map] = { + .visible = true, + .named = true, + }, + [sym__r_sgl_flw_map] = { + .visible = true, + .named = true, + }, + [sym__br_sgl_flw_map] = { + .visible = true, + .named = true, + }, + [sym__b_sgl_flw_map] = { + .visible = true, + .named = true, + }, + [sym__flw_map_tal] = { + .visible = false, + .named = true, + }, + [sym__sgl_flw_map_tal] = { + .visible = false, + .named = true, + }, + [sym__r_flw_seq_dat] = { + .visible = false, + .named = true, + }, + [sym__br_flw_seq_dat] = { + .visible = false, + .named = true, + }, + [sym__r_flw_map_dat] = { + .visible = false, + .named = true, + }, + [sym__br_flw_map_dat] = { + .visible = false, + .named = true, + }, + [sym__r_sgl_flw_col_dat] = { + .visible = false, + .named = true, + }, + [sym__flw_seq_dat_rpt] = { + .visible = false, + .named = true, + }, + [sym__flw_map_dat_rpt] = { + .visible = false, + .named = true, + }, + [sym__sgl_flw_col_dat_rpt] = { + .visible = false, + .named = true, + }, + [sym__r_flw_seq_itm] = { + .visible = false, + .named = true, + }, + [sym__br_flw_seq_itm] = { + .visible = false, + .named = true, + }, + [sym__r_flw_map_itm] = { + .visible = false, + .named = true, + }, + [sym__br_flw_map_itm] = { + .visible = false, + .named = true, + }, + [sym__r_sgl_flw_col_itm] = { + .visible = false, + .named = true, + }, + [sym__r_flw_exp_par] = { + .visible = true, + .named = true, + }, + [sym__br_flw_exp_par] = { + .visible = true, + .named = true, + }, + [sym__r_sgl_flw_exp_par] = { + .visible = true, + .named = true, + }, + [sym__r_flw_imp_r_par] = { + .visible = false, + .named = true, + }, + [sym__r_flw_imp_br_par] = { + .visible = false, + .named = true, + }, + [sym__br_flw_imp_r_par] = { + .visible = false, + .named = true, + }, + [sym__br_flw_imp_br_par] = { + .visible = false, + .named = true, + }, + [sym__r_sgl_flw_imp_par] = { + .visible = false, + .named = true, + }, + [sym__r_flw_jsl_ann_par] = { + .visible = false, + .named = true, + }, + [sym__br_flw_jsl_ann_par] = { + .visible = false, + .named = true, + }, + [sym__r_sgl_flw_jsl_ann_par] = { + .visible = false, + .named = true, + }, + [sym__r_flw_njl_ann_par] = { + .visible = false, + .named = true, + }, + [sym__br_flw_njl_ann_par] = { + .visible = false, + .named = true, + }, + [sym__r_sgl_flw_njl_ann_par] = { + .visible = false, + .named = true, + }, + [sym__flw_ann_par_tal] = { + .visible = false, + .named = true, + }, + [sym__sgl_flw_ann_par_tal] = { + .visible = false, + .named = true, + }, + [sym__r_dqt_str_val] = { + .visible = true, + .named = true, + }, + [sym__br_dqt_str_val] = { + .visible = true, + .named = true, + }, + [sym__r_sgl_dqt_str_val] = { + .visible = true, + .named = true, + }, + [sym__br_sgl_dqt_str_val] = { + .visible = true, + .named = true, + }, + [sym__b_sgl_dqt_str_val] = { + .visible = true, + .named = true, + }, + [sym__r_dqt_str] = { + .visible = true, + .named = true, + }, + [sym__br_dqt_str] = { + .visible = true, + .named = true, + }, + [sym__r_sgl_dqt_str] = { + .visible = true, + .named = true, + }, + [sym__br_sgl_dqt_str] = { + .visible = true, + .named = true, + }, + [sym__b_sgl_dqt_str] = { + .visible = true, + .named = true, + }, + [aux_sym__r_sgl_dqt_ctn] = { + .visible = false, + .named = false, + }, + [sym__br_mtl_dqt_ctn] = { + .visible = false, + .named = true, + }, + [sym__r_sqt_str_val] = { + .visible = true, + .named = true, + }, + [sym__br_sqt_str_val] = { + .visible = true, + .named = true, + }, + [sym__r_sgl_sqt_str_val] = { + .visible = true, + .named = true, + }, + [sym__br_sgl_sqt_str_val] = { + .visible = true, + .named = true, + }, + [sym__b_sgl_sqt_str_val] = { + .visible = true, + .named = true, + }, + [sym__r_sqt_str] = { + .visible = true, + .named = true, + }, + [sym__br_sqt_str] = { + .visible = true, + .named = true, + }, + [sym__r_sgl_sqt_str] = { + .visible = true, + .named = true, + }, + [sym__br_sgl_sqt_str] = { + .visible = true, + .named = true, + }, + [sym__b_sgl_sqt_str] = { + .visible = true, + .named = true, + }, + [aux_sym__r_sgl_sqt_ctn] = { + .visible = false, + .named = false, + }, + [sym__br_mtl_sqt_ctn] = { + .visible = false, + .named = true, + }, + [sym__r_pln_blk_val] = { + .visible = true, + .named = true, + }, + [sym__br_pln_blk_val] = { + .visible = true, + .named = true, + }, + [sym__r_sgl_pln_blk_val] = { + .visible = true, + .named = true, + }, + [sym__br_sgl_pln_blk_val] = { + .visible = true, + .named = true, + }, + [sym__b_sgl_pln_blk_val] = { + .visible = true, + .named = true, + }, + [sym__r_pln_flw_val] = { + .visible = true, + .named = true, + }, + [sym__br_pln_flw_val] = { + .visible = true, + .named = true, + }, + [sym__r_sgl_pln_flw_val] = { + .visible = true, + .named = true, + }, + [sym__r_sgl_pln_blk] = { + .visible = true, + .named = true, + }, + [sym__br_sgl_pln_blk] = { + .visible = true, + .named = true, + }, + [sym__b_sgl_pln_blk] = { + .visible = true, + .named = true, + }, + [sym__r_sgl_pln_flw] = { + .visible = true, + .named = true, + }, + [sym__br_sgl_pln_flw] = { + .visible = true, + .named = true, + }, + [sym__r_mtl_pln_blk] = { + .visible = true, + .named = true, + }, + [sym__br_mtl_pln_blk] = { + .visible = true, + .named = true, + }, + [sym__r_mtl_pln_flw] = { + .visible = true, + .named = true, + }, + [sym__br_mtl_pln_flw] = { + .visible = true, + .named = true, + }, + [sym__r_als_val] = { + .visible = true, + .named = true, + }, + [sym__br_als_val] = { + .visible = true, + .named = true, + }, + [sym__b_als_val] = { + .visible = true, + .named = true, + }, + [sym__r_als] = { + .visible = true, + .named = true, + }, + [sym__br_als] = { + .visible = true, + .named = true, + }, + [sym__b_als] = { + .visible = true, + .named = true, + }, + [sym__r_acr] = { + .visible = true, + .named = true, + }, + [sym__br_acr] = { + .visible = true, + .named = true, + }, + [sym__b_acr] = { + .visible = true, + .named = true, + }, + [aux_sym__drs_doc_repeat1] = { + .visible = false, + .named = false, + }, + [aux_sym__s_dir_rsv_repeat1] = { + .visible = false, + .named = false, + }, + [aux_sym__r_blk_seq_repeat1] = { + .visible = false, + .named = false, + }, + [aux_sym__r_blk_map_repeat1] = { + .visible = false, + .named = false, + }, + [aux_sym__r_blk_str_repeat1] = { + .visible = false, + .named = false, + }, + [aux_sym__r_flw_seq_dat_repeat1] = { + .visible = false, + .named = false, + }, + [aux_sym__r_flw_map_dat_repeat1] = { + .visible = false, + .named = false, + }, + [aux_sym__r_sgl_flw_col_dat_repeat1] = { + .visible = false, + .named = false, + }, + [aux_sym__r_dqt_str_repeat1] = { + .visible = false, + .named = false, + }, + [aux_sym__br_mtl_dqt_ctn_repeat1] = { + .visible = false, + .named = false, + }, + [aux_sym__r_sqt_str_repeat1] = { + .visible = false, + .named = false, + }, + [aux_sym__br_mtl_sqt_ctn_repeat1] = { + .visible = false, + .named = false, + }, +}; + +enum ts_field_identifiers { + field_key = 1, + field_value = 2, +}; + +static const char * const ts_field_names[] = { + [0] = NULL, + [field_key] = "key", + [field_value] = "value", +}; + +static const TSMapSlice ts_field_map_slices[PRODUCTION_ID_COUNT] = { + [1] = {.index = 0, .length = 2}, + [2] = {.index = 2, .length = 1}, + [3] = {.index = 3, .length = 1}, + [4] = {.index = 4, .length = 1}, + [5] = {.index = 5, .length = 1}, + [6] = {.index = 0, .length = 2}, + [7] = {.index = 3, .length = 1}, + [9] = {.index = 6, .length = 2}, + [10] = {.index = 8, .length = 2}, + [11] = {.index = 10, .length = 2}, +}; + +static const TSFieldMapEntry ts_field_map_entries[] = { + [0] = + {field_key, 0, .inherited = true}, + {field_value, 0, .inherited = true}, + [2] = + {field_key, 0, .inherited = true}, + [3] = + {field_value, 0, .inherited = true}, + [4] = + {field_key, 1}, + [5] = + {field_value, 1}, + [6] = + {field_key, 0}, + {field_value, 1, .inherited = true}, + [8] = + {field_key, 0, .inherited = true}, + {field_value, 1, .inherited = true}, + [10] = + {field_key, 1, .inherited = true}, + {field_value, 1, .inherited = true}, +}; + +static const TSSymbol ts_alias_sequences[PRODUCTION_ID_COUNT][MAX_ALIAS_SEQUENCE_LENGTH] = { + [0] = {0}, + [6] = { + [0] = sym__r_flw_exp_par, + }, + [7] = { + [0] = sym__r_flw_exp_par, + }, + [8] = { + [0] = sym__drs_doc_end, + }, +}; + +static const uint16_t ts_non_terminal_alias_map[] = { + sym__bgn_imp_doc, 2, + sym__bgn_imp_doc, + sym__drs_doc_end, + sym__drs_doc, 2, + sym__drs_doc, + sym__drs_doc_end, + sym__exp_doc, 2, + sym__exp_doc, + sym__drs_doc_end, + sym__imp_doc, 2, + sym__imp_doc, + sym__drs_doc_end, + sym__r_flw_imp_r_par, 2, + sym__r_flw_imp_r_par, + sym__r_flw_exp_par, + sym__r_flw_imp_br_par, 2, + sym__r_flw_imp_br_par, + sym__r_flw_exp_par, + sym__br_flw_imp_r_par, 2, + sym__br_flw_imp_r_par, + sym__r_flw_exp_par, + sym__br_flw_imp_br_par, 2, + sym__br_flw_imp_br_par, + sym__r_flw_exp_par, + sym__r_sgl_flw_imp_par, 2, + sym__r_sgl_flw_imp_par, + sym__r_flw_exp_par, + sym__r_flw_njl_ann_par, 2, + sym__r_flw_njl_ann_par, + sym__r_flw_exp_par, + sym__br_flw_njl_ann_par, 2, + sym__br_flw_njl_ann_par, + sym__r_flw_exp_par, + sym__r_sgl_flw_njl_ann_par, 2, + sym__r_sgl_flw_njl_ann_par, + sym__r_flw_exp_par, + 0, +}; + +static const TSStateId ts_primary_state_ids[STATE_COUNT] = { + [0] = 0, + [1] = 1, + [2] = 2, + [3] = 3, + [4] = 4, + [5] = 5, + [6] = 6, + [7] = 7, + [8] = 8, + [9] = 9, + [10] = 10, + [11] = 11, + [12] = 12, + [13] = 13, + [14] = 14, + [15] = 13, + [16] = 14, + [17] = 14, + [18] = 13, + [19] = 13, + [20] = 13, + [21] = 13, + [22] = 13, + [23] = 13, + [24] = 24, + [25] = 25, + [26] = 24, + [27] = 25, + [28] = 24, + [29] = 25, + [30] = 24, + [31] = 24, + [32] = 24, + [33] = 24, + [34] = 24, + [35] = 35, + [36] = 36, + [37] = 37, + [38] = 38, + [39] = 39, + [40] = 40, + [41] = 40, + [42] = 42, + [43] = 43, + [44] = 43, + [45] = 43, + [46] = 43, + [47] = 42, + [48] = 42, + [49] = 43, + [50] = 42, + [51] = 43, + [52] = 43, + [53] = 42, + [54] = 43, + [55] = 55, + [56] = 56, + [57] = 56, + [58] = 58, + [59] = 56, + [60] = 58, + [61] = 56, + [62] = 56, + [63] = 58, + [64] = 58, + [65] = 56, + [66] = 58, + [67] = 56, + [68] = 56, + [69] = 55, + [70] = 70, + [71] = 71, + [72] = 72, + [73] = 73, + [74] = 74, + [75] = 75, + [76] = 76, + [77] = 77, + [78] = 78, + [79] = 79, + [80] = 80, + [81] = 81, + [82] = 81, + [83] = 80, + [84] = 84, + [85] = 85, + [86] = 84, + [87] = 85, + [88] = 88, + [89] = 89, + [90] = 90, + [91] = 88, + [92] = 89, + [93] = 90, + [94] = 94, + [95] = 94, + [96] = 96, + [97] = 97, + [98] = 98, + [99] = 99, + [100] = 100, + [101] = 101, + [102] = 102, + [103] = 103, + [104] = 104, + [105] = 105, + [106] = 101, + [107] = 101, + [108] = 108, + [109] = 109, + [110] = 102, + [111] = 101, + [112] = 112, + [113] = 113, + [114] = 112, + [115] = 113, + [116] = 97, + [117] = 112, + [118] = 96, + [119] = 113, + [120] = 112, + [121] = 113, + [122] = 96, + [123] = 97, + [124] = 98, + [125] = 125, + [126] = 126, + [127] = 101, + [128] = 128, + [129] = 102, + [130] = 130, + [131] = 100, + [132] = 132, + [133] = 126, + [134] = 125, + [135] = 130, + [136] = 132, + [137] = 126, + [138] = 138, + [139] = 139, + [140] = 140, + [141] = 141, + [142] = 125, + [143] = 130, + [144] = 138, + [145] = 139, + [146] = 99, + [147] = 132, + [148] = 126, + [149] = 138, + [150] = 139, + [151] = 132, + [152] = 126, + [153] = 132, + [154] = 126, + [155] = 132, + [156] = 102, + [157] = 100, + [158] = 99, + [159] = 101, + [160] = 105, + [161] = 101, + [162] = 113, + [163] = 101, + [164] = 112, + [165] = 103, + [166] = 104, + [167] = 167, + [168] = 103, + [169] = 109, + [170] = 101, + [171] = 102, + [172] = 104, + [173] = 101, + [174] = 167, + [175] = 175, + [176] = 108, + [177] = 175, + [178] = 108, + [179] = 109, + [180] = 102, + [181] = 181, + [182] = 181, + [183] = 96, + [184] = 184, + [185] = 98, + [186] = 184, + [187] = 98, + [188] = 96, + [189] = 189, + [190] = 105, + [191] = 100, + [192] = 98, + [193] = 184, + [194] = 102, + [195] = 98, + [196] = 101, + [197] = 197, + [198] = 96, + [199] = 199, + [200] = 199, + [201] = 96, + [202] = 202, + [203] = 202, + [204] = 184, + [205] = 189, + [206] = 101, + [207] = 100, + [208] = 102, + [209] = 105, + [210] = 197, + [211] = 101, + [212] = 102, + [213] = 105, + [214] = 105, + [215] = 100, + [216] = 102, + [217] = 101, + [218] = 197, + [219] = 103, + [220] = 100, + [221] = 108, + [222] = 109, + [223] = 101, + [224] = 197, + [225] = 102, + [226] = 96, + [227] = 101, + [228] = 102, + [229] = 98, + [230] = 103, + [231] = 108, + [232] = 109, + [233] = 184, + [234] = 109, + [235] = 102, + [236] = 108, + [237] = 102, + [238] = 103, + [239] = 101, + [240] = 108, + [241] = 101, + [242] = 103, + [243] = 109, + [244] = 100, + [245] = 105, + [246] = 101, + [247] = 102, + [248] = 197, + [249] = 249, + [250] = 250, + [251] = 251, + [252] = 252, + [253] = 253, + [254] = 254, + [255] = 255, + [256] = 101, + [257] = 103, + [258] = 108, + [259] = 102, + [260] = 109, + [261] = 261, + [262] = 262, + [263] = 263, + [264] = 264, + [265] = 261, + [266] = 266, + [267] = 267, + [268] = 268, + [269] = 269, + [270] = 270, + [271] = 271, + [272] = 272, + [273] = 273, + [274] = 261, + [275] = 275, + [276] = 261, + [277] = 277, + [278] = 278, + [279] = 279, + [280] = 280, + [281] = 281, + [282] = 282, + [283] = 283, + [284] = 284, + [285] = 285, + [286] = 286, + [287] = 287, + [288] = 288, + [289] = 289, + [290] = 290, + [291] = 291, + [292] = 292, + [293] = 293, + [294] = 294, + [295] = 295, + [296] = 296, + [297] = 297, + [298] = 298, + [299] = 299, + [300] = 300, + [301] = 301, + [302] = 302, + [303] = 303, + [304] = 304, + [305] = 305, + [306] = 306, + [307] = 307, + [308] = 308, + [309] = 309, + [310] = 310, + [311] = 311, + [312] = 312, + [313] = 313, + [314] = 314, + [315] = 273, + [316] = 316, + [317] = 317, + [318] = 318, + [319] = 319, + [320] = 320, + [321] = 321, + [322] = 322, + [323] = 323, + [324] = 324, + [325] = 325, + [326] = 326, + [327] = 327, + [328] = 328, + [329] = 329, + [330] = 266, + [331] = 331, + [332] = 332, + [333] = 275, + [334] = 334, + [335] = 335, + [336] = 336, + [337] = 337, + [338] = 338, + [339] = 339, + [340] = 340, + [341] = 341, + [342] = 342, + [343] = 343, + [344] = 344, + [345] = 345, + [346] = 346, + [347] = 347, + [348] = 348, + [349] = 349, + [350] = 350, + [351] = 351, + [352] = 352, + [353] = 353, + [354] = 354, + [355] = 355, + [356] = 356, + [357] = 357, + [358] = 358, + [359] = 359, + [360] = 360, + [361] = 361, + [362] = 362, + [363] = 363, + [364] = 364, + [365] = 261, + [366] = 366, + [367] = 367, + [368] = 368, + [369] = 369, + [370] = 370, + [371] = 371, + [372] = 372, + [373] = 373, + [374] = 374, + [375] = 375, + [376] = 376, + [377] = 377, + [378] = 378, + [379] = 379, + [380] = 380, + [381] = 381, + [382] = 382, + [383] = 383, + [384] = 384, + [385] = 385, + [386] = 386, + [387] = 387, + [388] = 388, + [389] = 389, + [390] = 390, + [391] = 391, + [392] = 392, + [393] = 392, + [394] = 392, + [395] = 395, + [396] = 392, + [397] = 101, + [398] = 395, + [399] = 101, + [400] = 101, + [401] = 395, + [402] = 101, + [403] = 392, + [404] = 395, + [405] = 405, + [406] = 406, + [407] = 101, + [408] = 406, + [409] = 409, + [410] = 101, + [411] = 101, + [412] = 101, + [413] = 395, + [414] = 101, + [415] = 415, + [416] = 416, + [417] = 406, + [418] = 102, + [419] = 406, + [420] = 420, + [421] = 421, + [422] = 422, + [423] = 423, + [424] = 101, + [425] = 425, + [426] = 423, + [427] = 427, + [428] = 428, + [429] = 421, + [430] = 421, + [431] = 431, + [432] = 432, + [433] = 433, + [434] = 433, + [435] = 422, + [436] = 423, + [437] = 427, + [438] = 101, + [439] = 421, + [440] = 431, + [441] = 431, + [442] = 432, + [443] = 427, + [444] = 422, + [445] = 406, + [446] = 427, + [447] = 428, + [448] = 427, + [449] = 421, + [450] = 431, + [451] = 432, + [452] = 422, + [453] = 423, + [454] = 427, + [455] = 422, + [456] = 432, + [457] = 421, + [458] = 422, + [459] = 428, + [460] = 432, + [461] = 427, + [462] = 431, + [463] = 421, + [464] = 432, + [465] = 432, + [466] = 422, + [467] = 433, + [468] = 427, + [469] = 469, + [470] = 421, + [471] = 432, + [472] = 422, + [473] = 423, + [474] = 474, + [475] = 475, + [476] = 476, + [477] = 477, + [478] = 478, + [479] = 479, + [480] = 480, + [481] = 481, + [482] = 482, + [483] = 483, + [484] = 484, + [485] = 485, + [486] = 486, + [487] = 482, + [488] = 488, + [489] = 489, + [490] = 485, + [491] = 488, + [492] = 492, + [493] = 493, + [494] = 483, + [495] = 495, + [496] = 484, + [497] = 484, + [498] = 498, + [499] = 499, + [500] = 495, + [501] = 482, + [502] = 502, + [503] = 503, + [504] = 504, + [505] = 485, + [506] = 484, + [507] = 488, + [508] = 495, + [509] = 489, + [510] = 495, + [511] = 485, + [512] = 503, + [513] = 482, + [514] = 482, + [515] = 482, + [516] = 482, + [517] = 489, + [518] = 488, + [519] = 485, + [520] = 485, + [521] = 488, + [522] = 522, + [523] = 485, + [524] = 495, + [525] = 483, + [526] = 488, + [527] = 489, + [528] = 482, + [529] = 503, + [530] = 484, + [531] = 488, + [532] = 485, + [533] = 489, + [534] = 488, + [535] = 495, + [536] = 495, + [537] = 495, + [538] = 538, + [539] = 539, + [540] = 347, + [541] = 541, + [542] = 348, + [543] = 543, + [544] = 544, + [545] = 349, + [546] = 546, + [547] = 350, + [548] = 351, + [549] = 352, + [550] = 353, + [551] = 283, + [552] = 552, + [553] = 553, + [554] = 554, + [555] = 284, + [556] = 556, + [557] = 557, + [558] = 553, + [559] = 559, + [560] = 560, + [561] = 539, + [562] = 562, + [563] = 563, + [564] = 564, + [565] = 565, + [566] = 366, + [567] = 567, + [568] = 367, + [569] = 285, + [570] = 369, + [571] = 370, + [572] = 286, + [573] = 372, + [574] = 373, + [575] = 541, + [576] = 288, + [577] = 543, + [578] = 544, + [579] = 546, + [580] = 374, + [581] = 376, + [582] = 559, + [583] = 560, + [584] = 539, + [585] = 562, + [586] = 586, + [587] = 557, + [588] = 553, + [589] = 559, + [590] = 560, + [591] = 539, + [592] = 562, + [593] = 290, + [594] = 382, + [595] = 383, + [596] = 384, + [597] = 385, + [598] = 378, + [599] = 327, + [600] = 298, + [601] = 355, + [602] = 320, + [603] = 321, + [604] = 324, + [605] = 541, + [606] = 269, + [607] = 543, + [608] = 544, + [609] = 546, + [610] = 354, + [611] = 271, + [612] = 363, + [613] = 371, + [614] = 614, + [615] = 615, + [616] = 293, + [617] = 557, + [618] = 553, + [619] = 559, + [620] = 560, + [621] = 539, + [622] = 562, + [623] = 346, + [624] = 295, + [625] = 541, + [626] = 296, + [627] = 543, + [628] = 544, + [629] = 543, + [630] = 546, + [631] = 541, + [632] = 297, + [633] = 543, + [634] = 544, + [635] = 546, + [636] = 391, + [637] = 637, + [638] = 266, + [639] = 639, + [640] = 544, + [641] = 557, + [642] = 553, + [643] = 559, + [644] = 560, + [645] = 645, + [646] = 562, + [647] = 546, + [648] = 648, + [649] = 649, + [650] = 557, + [651] = 553, + [652] = 559, + [653] = 560, + [654] = 539, + [655] = 541, + [656] = 562, + [657] = 543, + [658] = 544, + [659] = 546, + [660] = 660, + [661] = 661, + [662] = 275, + [663] = 663, + [664] = 557, + [665] = 553, + [666] = 559, + [667] = 560, + [668] = 539, + [669] = 562, + [670] = 670, + [671] = 671, + [672] = 672, + [673] = 673, + [674] = 674, + [675] = 675, + [676] = 541, + [677] = 677, + [678] = 541, + [679] = 679, + [680] = 543, + [681] = 544, + [682] = 546, + [683] = 683, + [684] = 684, + [685] = 557, + [686] = 557, + [687] = 553, + [688] = 559, + [689] = 560, + [690] = 539, + [691] = 562, + [692] = 294, + [693] = 693, + [694] = 694, + [695] = 677, + [696] = 679, + [697] = 683, + [698] = 698, + [699] = 684, + [700] = 637, + [701] = 639, + [702] = 346, + [703] = 347, + [704] = 348, + [705] = 349, + [706] = 350, + [707] = 351, + [708] = 352, + [709] = 353, + [710] = 283, + [711] = 284, + [712] = 366, + [713] = 367, + [714] = 285, + [715] = 369, + [716] = 370, + [717] = 286, + [718] = 372, + [719] = 373, + [720] = 288, + [721] = 374, + [722] = 376, + [723] = 290, + [724] = 382, + [725] = 383, + [726] = 384, + [727] = 385, + [728] = 378, + [729] = 327, + [730] = 298, + [731] = 355, + [732] = 320, + [733] = 321, + [734] = 324, + [735] = 269, + [736] = 354, + [737] = 271, + [738] = 363, + [739] = 371, + [740] = 293, + [741] = 741, + [742] = 295, + [743] = 296, + [744] = 297, + [745] = 391, + [746] = 266, + [747] = 556, + [748] = 563, + [749] = 564, + [750] = 750, + [751] = 751, + [752] = 741, + [753] = 275, + [754] = 754, + [755] = 754, + [756] = 693, + [757] = 693, + [758] = 758, + [759] = 750, + [760] = 741, + [761] = 754, + [762] = 693, + [763] = 750, + [764] = 741, + [765] = 754, + [766] = 693, + [767] = 750, + [768] = 741, + [769] = 754, + [770] = 693, + [771] = 750, + [772] = 741, + [773] = 754, + [774] = 693, + [775] = 750, + [776] = 741, + [777] = 754, + [778] = 750, + [779] = 741, + [780] = 754, + [781] = 693, + [782] = 750, + [783] = 294, + [784] = 366, + [785] = 556, + [786] = 563, + [787] = 787, + [788] = 788, + [789] = 789, + [790] = 790, + [791] = 791, + [792] = 564, + [793] = 793, + [794] = 794, + [795] = 795, + [796] = 679, + [797] = 683, + [798] = 684, + [799] = 799, + [800] = 800, + [801] = 556, + [802] = 563, + [803] = 564, + [804] = 804, + [805] = 805, + [806] = 806, + [807] = 807, + [808] = 808, + [809] = 809, + [810] = 810, + [811] = 637, + [812] = 639, + [813] = 677, + [814] = 814, + [815] = 815, + [816] = 816, + [817] = 346, + [818] = 347, + [819] = 348, + [820] = 349, + [821] = 350, + [822] = 351, + [823] = 352, + [824] = 353, + [825] = 825, + [826] = 826, + [827] = 284, + [828] = 366, + [829] = 367, + [830] = 285, + [831] = 369, + [832] = 370, + [833] = 286, + [834] = 372, + [835] = 373, + [836] = 288, + [837] = 374, + [838] = 376, + [839] = 839, + [840] = 840, + [841] = 841, + [842] = 382, + [843] = 383, + [844] = 384, + [845] = 385, + [846] = 378, + [847] = 327, + [848] = 298, + [849] = 355, + [850] = 320, + [851] = 321, + [852] = 324, + [853] = 269, + [854] = 354, + [855] = 271, + [856] = 363, + [857] = 371, + [858] = 293, + [859] = 294, + [860] = 295, + [861] = 296, + [862] = 297, + [863] = 391, + [864] = 864, + [865] = 346, + [866] = 347, + [867] = 348, + [868] = 349, + [869] = 350, + [870] = 351, + [871] = 352, + [872] = 353, + [873] = 266, + [874] = 283, + [875] = 875, + [876] = 284, + [877] = 367, + [878] = 285, + [879] = 369, + [880] = 370, + [881] = 286, + [882] = 372, + [883] = 373, + [884] = 288, + [885] = 374, + [886] = 376, + [887] = 887, + [888] = 888, + [889] = 889, + [890] = 275, + [891] = 290, + [892] = 382, + [893] = 383, + [894] = 384, + [895] = 385, + [896] = 378, + [897] = 327, + [898] = 298, + [899] = 355, + [900] = 320, + [901] = 321, + [902] = 269, + [903] = 354, + [904] = 271, + [905] = 363, + [906] = 371, + [907] = 293, + [908] = 294, + [909] = 295, + [910] = 296, + [911] = 297, + [912] = 391, + [913] = 266, + [914] = 283, + [915] = 275, + [916] = 290, + [917] = 917, + [918] = 918, + [919] = 919, + [920] = 920, + [921] = 921, + [922] = 922, + [923] = 923, + [924] = 924, + [925] = 925, + [926] = 926, + [927] = 804, + [928] = 805, + [929] = 806, + [930] = 637, + [931] = 807, + [932] = 808, + [933] = 809, + [934] = 810, + [935] = 919, + [936] = 920, + [937] = 921, + [938] = 923, + [939] = 939, + [940] = 940, + [941] = 941, + [942] = 639, + [943] = 922, + [944] = 944, + [945] = 945, + [946] = 787, + [947] = 788, + [948] = 924, + [949] = 793, + [950] = 940, + [951] = 816, + [952] = 941, + [953] = 925, + [954] = 864, + [955] = 677, + [956] = 944, + [957] = 679, + [958] = 683, + [959] = 684, + [960] = 926, + [961] = 945, + [962] = 324, + [963] = 963, + [964] = 964, + [965] = 965, + [966] = 966, + [967] = 262, + [968] = 968, + [969] = 264, + [970] = 970, + [971] = 971, + [972] = 972, + [973] = 973, + [974] = 974, + [975] = 975, + [976] = 976, + [977] = 977, + [978] = 978, + [979] = 979, + [980] = 980, + [981] = 980, + [982] = 971, + [983] = 972, + [984] = 984, + [985] = 272, + [986] = 964, + [987] = 271, + [988] = 285, + [989] = 269, + [990] = 270, + [991] = 984, + [992] = 977, + [993] = 977, + [994] = 978, + [995] = 974, + [996] = 286, + [997] = 282, + [998] = 973, + [999] = 266, + [1000] = 287, + [1001] = 283, + [1002] = 965, + [1003] = 966, + [1004] = 965, + [1005] = 288, + [1006] = 977, + [1007] = 978, + [1008] = 289, + [1009] = 1009, + [1010] = 971, + [1011] = 972, + [1012] = 1012, + [1013] = 978, + [1014] = 1014, + [1015] = 1015, + [1016] = 1012, + [1017] = 971, + [1018] = 1018, + [1019] = 972, + [1020] = 977, + [1021] = 978, + [1022] = 973, + [1023] = 502, + [1024] = 615, + [1025] = 1025, + [1026] = 974, + [1027] = 971, + [1028] = 972, + [1029] = 1029, + [1030] = 273, + [1031] = 1009, + [1032] = 977, + [1033] = 978, + [1034] = 963, + [1035] = 1018, + [1036] = 280, + [1037] = 267, + [1038] = 976, + [1039] = 275, + [1040] = 268, + [1041] = 1041, + [1042] = 971, + [1043] = 972, + [1044] = 290, + [1045] = 1025, + [1046] = 281, + [1047] = 284, + [1048] = 966, + [1049] = 266, + [1050] = 1050, + [1051] = 1051, + [1052] = 1052, + [1053] = 1053, + [1054] = 1054, + [1055] = 305, + [1056] = 1056, + [1057] = 307, + [1058] = 1058, + [1059] = 677, + [1060] = 350, + [1061] = 1061, + [1062] = 1062, + [1063] = 362, + [1064] = 1064, + [1065] = 299, + [1066] = 1066, + [1067] = 1067, + [1068] = 1068, + [1069] = 292, + [1070] = 348, + [1071] = 349, + [1072] = 1072, + [1073] = 321, + [1074] = 1074, + [1075] = 324, + [1076] = 370, + [1077] = 677, + [1078] = 1078, + [1079] = 275, + [1080] = 301, + [1081] = 1081, + [1082] = 354, + [1083] = 344, + [1084] = 1084, + [1085] = 1085, + [1086] = 363, + [1087] = 351, + [1088] = 361, + [1089] = 1089, + [1090] = 371, + [1091] = 368, + [1092] = 293, + [1093] = 294, + [1094] = 356, + [1095] = 357, + [1096] = 295, + [1097] = 266, + [1098] = 296, + [1099] = 275, + [1100] = 266, + [1101] = 275, + [1102] = 372, + [1103] = 345, + [1104] = 297, + [1105] = 391, + [1106] = 273, + [1107] = 280, + [1108] = 373, + [1109] = 367, + [1110] = 1110, + [1111] = 1078, + [1112] = 1081, + [1113] = 1113, + [1114] = 1114, + [1115] = 346, + [1116] = 1116, + [1117] = 281, + [1118] = 282, + [1119] = 358, + [1120] = 1089, + [1121] = 1066, + [1122] = 283, + [1123] = 1123, + [1124] = 1058, + [1125] = 1125, + [1126] = 374, + [1127] = 352, + [1128] = 284, + [1129] = 353, + [1130] = 376, + [1131] = 366, + [1132] = 1132, + [1133] = 369, + [1134] = 320, + [1135] = 336, + [1136] = 375, + [1137] = 266, + [1138] = 1125, + [1139] = 1050, + [1140] = 1078, + [1141] = 1081, + [1142] = 337, + [1143] = 1143, + [1144] = 285, + [1145] = 1064, + [1146] = 286, + [1147] = 1089, + [1148] = 1066, + [1149] = 287, + [1150] = 288, + [1151] = 1058, + [1152] = 1125, + [1153] = 289, + [1154] = 340, + [1155] = 1155, + [1156] = 347, + [1157] = 275, + [1158] = 290, + [1159] = 267, + [1160] = 268, + [1161] = 1051, + [1162] = 1052, + [1163] = 1053, + [1164] = 1054, + [1165] = 1058, + [1166] = 1125, + [1167] = 1167, + [1168] = 1168, + [1169] = 1169, + [1170] = 341, + [1171] = 1084, + [1172] = 1058, + [1173] = 1125, + [1174] = 1061, + [1175] = 342, + [1176] = 387, + [1177] = 379, + [1178] = 1062, + [1179] = 269, + [1180] = 270, + [1181] = 271, + [1182] = 1058, + [1183] = 1125, + [1184] = 272, + [1185] = 380, + [1186] = 381, + [1187] = 1132, + [1188] = 382, + [1189] = 1067, + [1190] = 1068, + [1191] = 383, + [1192] = 384, + [1193] = 1058, + [1194] = 1125, + [1195] = 1072, + [1196] = 1074, + [1197] = 385, + [1198] = 273, + [1199] = 386, + [1200] = 343, + [1201] = 388, + [1202] = 389, + [1203] = 390, + [1204] = 378, + [1205] = 327, + [1206] = 298, + [1207] = 355, + [1208] = 335, + [1209] = 1110, + [1210] = 1113, + [1211] = 1058, + [1212] = 1125, + [1213] = 1114, + [1214] = 1116, + [1215] = 377, + [1216] = 679, + [1217] = 352, + [1218] = 353, + [1219] = 1110, + [1220] = 356, + [1221] = 357, + [1222] = 564, + [1223] = 1113, + [1224] = 1114, + [1225] = 1225, + [1226] = 1226, + [1227] = 1227, + [1228] = 1116, + [1229] = 361, + [1230] = 362, + [1231] = 1051, + [1232] = 1052, + [1233] = 1053, + [1234] = 1054, + [1235] = 1235, + [1236] = 1084, + [1237] = 1237, + [1238] = 1061, + [1239] = 1239, + [1240] = 1240, + [1241] = 1062, + [1242] = 1242, + [1243] = 556, + [1244] = 1242, + [1245] = 1245, + [1246] = 266, + [1247] = 366, + [1248] = 275, + [1249] = 1067, + [1250] = 1225, + [1251] = 1240, + [1252] = 1252, + [1253] = 1252, + [1254] = 290, + [1255] = 1068, + [1256] = 367, + [1257] = 1050, + [1258] = 369, + [1259] = 370, + [1260] = 372, + [1261] = 373, + [1262] = 683, + [1263] = 684, + [1264] = 1064, + [1265] = 374, + [1266] = 376, + [1267] = 1267, + [1268] = 1268, + [1269] = 1084, + [1270] = 1072, + [1271] = 1074, + [1272] = 283, + [1273] = 379, + [1274] = 380, + [1275] = 381, + [1276] = 382, + [1277] = 383, + [1278] = 384, + [1279] = 385, + [1280] = 386, + [1281] = 273, + [1282] = 346, + [1283] = 347, + [1284] = 388, + [1285] = 389, + [1286] = 390, + [1287] = 378, + [1288] = 327, + [1289] = 298, + [1290] = 355, + [1291] = 335, + [1292] = 1292, + [1293] = 677, + [1294] = 358, + [1295] = 368, + [1296] = 299, + [1297] = 301, + [1298] = 677, + [1299] = 1299, + [1300] = 305, + [1301] = 1110, + [1302] = 348, + [1303] = 307, + [1304] = 349, + [1305] = 1113, + [1306] = 350, + [1307] = 351, + [1308] = 1114, + [1309] = 352, + [1310] = 353, + [1311] = 1116, + [1312] = 1292, + [1313] = 1313, + [1314] = 284, + [1315] = 677, + [1316] = 366, + [1317] = 1050, + [1318] = 367, + [1319] = 1319, + [1320] = 285, + [1321] = 369, + [1322] = 1064, + [1323] = 370, + [1324] = 391, + [1325] = 286, + [1326] = 1132, + [1327] = 1327, + [1328] = 372, + [1329] = 373, + [1330] = 288, + [1331] = 374, + [1332] = 1235, + [1333] = 320, + [1334] = 376, + [1335] = 1335, + [1336] = 1132, + [1337] = 1335, + [1338] = 382, + [1339] = 383, + [1340] = 384, + [1341] = 385, + [1342] = 378, + [1343] = 327, + [1344] = 321, + [1345] = 563, + [1346] = 298, + [1347] = 324, + [1348] = 266, + [1349] = 355, + [1350] = 354, + [1351] = 363, + [1352] = 275, + [1353] = 266, + [1354] = 1051, + [1355] = 371, + [1356] = 275, + [1357] = 1052, + [1358] = 1053, + [1359] = 1239, + [1360] = 1054, + [1361] = 320, + [1362] = 375, + [1363] = 377, + [1364] = 387, + [1365] = 292, + [1366] = 1061, + [1367] = 321, + [1368] = 1062, + [1369] = 324, + [1370] = 269, + [1371] = 1327, + [1372] = 1245, + [1373] = 354, + [1374] = 271, + [1375] = 293, + [1376] = 294, + [1377] = 295, + [1378] = 296, + [1379] = 1319, + [1380] = 336, + [1381] = 337, + [1382] = 297, + [1383] = 391, + [1384] = 363, + [1385] = 371, + [1386] = 340, + [1387] = 341, + [1388] = 342, + [1389] = 343, + [1390] = 344, + [1391] = 1067, + [1392] = 1068, + [1393] = 345, + [1394] = 346, + [1395] = 347, + [1396] = 293, + [1397] = 294, + [1398] = 637, + [1399] = 295, + [1400] = 639, + [1401] = 348, + [1402] = 349, + [1403] = 296, + [1404] = 350, + [1405] = 1072, + [1406] = 1074, + [1407] = 351, + [1408] = 297, + [1409] = 1226, + [1410] = 1410, + [1411] = 1116, + [1412] = 1412, + [1413] = 1062, + [1414] = 1061, + [1415] = 1415, + [1416] = 1416, + [1417] = 1417, + [1418] = 1418, + [1419] = 1419, + [1420] = 1110, + [1421] = 1072, + [1422] = 1064, + [1423] = 1050, + [1424] = 290, + [1425] = 1074, + [1426] = 1426, + [1427] = 1427, + [1428] = 1428, + [1429] = 1429, + [1430] = 1410, + [1431] = 1431, + [1432] = 1432, + [1433] = 1410, + [1434] = 1431, + [1435] = 1432, + [1436] = 1436, + [1437] = 1436, + [1438] = 1410, + [1439] = 1431, + [1440] = 1432, + [1441] = 1436, + [1442] = 1113, + [1443] = 1443, + [1444] = 1444, + [1445] = 1445, + [1446] = 1446, + [1447] = 1447, + [1448] = 1062, + [1449] = 1449, + [1450] = 1450, + [1451] = 1067, + [1452] = 1452, + [1453] = 1114, + [1454] = 1454, + [1455] = 266, + [1456] = 1456, + [1457] = 1447, + [1458] = 1068, + [1459] = 1447, + [1460] = 1449, + [1461] = 1461, + [1462] = 275, + [1463] = 1114, + [1464] = 1464, + [1465] = 1465, + [1466] = 1052, + [1467] = 1116, + [1468] = 1447, + [1469] = 1053, + [1470] = 1084, + [1471] = 1449, + [1472] = 1410, + [1473] = 1447, + [1474] = 1432, + [1475] = 677, + [1476] = 1449, + [1477] = 1067, + [1478] = 1410, + [1479] = 1431, + [1480] = 1432, + [1481] = 1436, + [1482] = 1054, + [1483] = 1431, + [1484] = 1484, + [1485] = 1485, + [1486] = 1436, + [1487] = 283, + [1488] = 1488, + [1489] = 1489, + [1490] = 1490, + [1491] = 1491, + [1492] = 1492, + [1493] = 1493, + [1494] = 1432, + [1495] = 1072, + [1496] = 1496, + [1497] = 1497, + [1498] = 1410, + [1499] = 1499, + [1500] = 1068, + [1501] = 1061, + [1502] = 1502, + [1503] = 1431, + [1504] = 1432, + [1505] = 1436, + [1506] = 1110, + [1507] = 1074, + [1508] = 1436, + [1509] = 1050, + [1510] = 1410, + [1511] = 1431, + [1512] = 1432, + [1513] = 1436, + [1514] = 1514, + [1515] = 1515, + [1516] = 1449, + [1517] = 1064, + [1518] = 1132, + [1519] = 1431, + [1520] = 1520, + [1521] = 1051, + [1522] = 273, + [1523] = 1052, + [1524] = 1053, + [1525] = 1447, + [1526] = 1526, + [1527] = 1449, + [1528] = 1054, + [1529] = 1529, + [1530] = 1530, + [1531] = 1531, + [1532] = 1532, + [1533] = 1533, + [1534] = 1113, + [1535] = 1051, + [1536] = 1536, + [1537] = 1537, + [1538] = 1410, + [1539] = 1431, + [1540] = 1432, + [1541] = 1436, + [1542] = 1410, + [1543] = 1431, + [1544] = 1432, + [1545] = 1410, + [1546] = 1431, + [1547] = 1432, + [1548] = 1410, + [1549] = 1431, + [1550] = 1432, + [1551] = 1551, + [1552] = 1431, + [1553] = 1432, + [1554] = 1410, + [1555] = 1431, + [1556] = 1432, + [1557] = 1410, + [1558] = 1431, + [1559] = 1432, + [1560] = 1410, + [1561] = 1431, + [1562] = 1410, + [1563] = 1431, + [1564] = 1410, + [1565] = 1410, + [1566] = 1410, + [1567] = 1410, + [1568] = 1410, + [1569] = 1410, + [1570] = 1410, + [1571] = 1410, + [1572] = 1410, + [1573] = 1410, + [1574] = 1410, + [1575] = 1410, + [1576] = 1410, + [1577] = 1410, + [1578] = 1410, +}; + +static bool ts_lex(TSLexer *lexer, TSStateId state) { + START_LEXER(); + eof = lexer->eof(lexer); + switch (state) { + case 0: + ACCEPT_TOKEN(ts_builtin_sym_end); + if (eof) ADVANCE(1); + END_STATE(); + case 1: + ACCEPT_TOKEN(ts_builtin_sym_end); + END_STATE(); + default: + return false; + } +} + +static const TSLexMode ts_lex_modes[STATE_COUNT] = { + [0] = {.lex_state = 0, .external_lex_state = 1}, + [1] = {.lex_state = 0, .external_lex_state = 2}, + [2] = {.lex_state = 0, .external_lex_state = 3}, + [3] = {.lex_state = 0, .external_lex_state = 3}, + [4] = {.lex_state = 0, .external_lex_state = 3}, + [5] = {.lex_state = 0, .external_lex_state = 3}, + [6] = {.lex_state = 0, .external_lex_state = 3}, + [7] = {.lex_state = 0, .external_lex_state = 3}, + [8] = {.lex_state = 0, .external_lex_state = 4}, + [9] = {.lex_state = 0, .external_lex_state = 4}, + [10] = {.lex_state = 0, .external_lex_state = 4}, + [11] = {.lex_state = 0, .external_lex_state = 5}, + [12] = {.lex_state = 0, .external_lex_state = 6}, + [13] = {.lex_state = 0, .external_lex_state = 7}, + [14] = {.lex_state = 0, .external_lex_state = 7}, + [15] = {.lex_state = 0, .external_lex_state = 7}, + [16] = {.lex_state = 0, .external_lex_state = 7}, + [17] = {.lex_state = 0, .external_lex_state = 7}, + [18] = {.lex_state = 0, .external_lex_state = 7}, + [19] = {.lex_state = 0, .external_lex_state = 7}, + [20] = {.lex_state = 0, .external_lex_state = 7}, + [21] = {.lex_state = 0, .external_lex_state = 7}, + [22] = {.lex_state = 0, .external_lex_state = 7}, + [23] = {.lex_state = 0, .external_lex_state = 7}, + [24] = {.lex_state = 0, .external_lex_state = 8}, + [25] = {.lex_state = 0, .external_lex_state = 8}, + [26] = {.lex_state = 0, .external_lex_state = 8}, + [27] = {.lex_state = 0, .external_lex_state = 8}, + [28] = {.lex_state = 0, .external_lex_state = 8}, + [29] = {.lex_state = 0, .external_lex_state = 8}, + [30] = {.lex_state = 0, .external_lex_state = 8}, + [31] = {.lex_state = 0, .external_lex_state = 8}, + [32] = {.lex_state = 0, .external_lex_state = 8}, + [33] = {.lex_state = 0, .external_lex_state = 8}, + [34] = {.lex_state = 0, .external_lex_state = 8}, + [35] = {.lex_state = 0, .external_lex_state = 9}, + [36] = {.lex_state = 0, .external_lex_state = 9}, + [37] = {.lex_state = 0, .external_lex_state = 10}, + [38] = {.lex_state = 0, .external_lex_state = 10}, + [39] = {.lex_state = 0, .external_lex_state = 10}, + [40] = {.lex_state = 0, .external_lex_state = 11}, + [41] = {.lex_state = 0, .external_lex_state = 12}, + [42] = {.lex_state = 0, .external_lex_state = 7}, + [43] = {.lex_state = 0, .external_lex_state = 7}, + [44] = {.lex_state = 0, .external_lex_state = 7}, + [45] = {.lex_state = 0, .external_lex_state = 7}, + [46] = {.lex_state = 0, .external_lex_state = 7}, + [47] = {.lex_state = 0, .external_lex_state = 7}, + [48] = {.lex_state = 0, .external_lex_state = 7}, + [49] = {.lex_state = 0, .external_lex_state = 7}, + [50] = {.lex_state = 0, .external_lex_state = 7}, + [51] = {.lex_state = 0, .external_lex_state = 7}, + [52] = {.lex_state = 0, .external_lex_state = 7}, + [53] = {.lex_state = 0, .external_lex_state = 7}, + [54] = {.lex_state = 0, .external_lex_state = 7}, + [55] = {.lex_state = 0, .external_lex_state = 12}, + [56] = {.lex_state = 0, .external_lex_state = 8}, + [57] = {.lex_state = 0, .external_lex_state = 8}, + [58] = {.lex_state = 0, .external_lex_state = 8}, + [59] = {.lex_state = 0, .external_lex_state = 8}, + [60] = {.lex_state = 0, .external_lex_state = 8}, + [61] = {.lex_state = 0, .external_lex_state = 8}, + [62] = {.lex_state = 0, .external_lex_state = 8}, + [63] = {.lex_state = 0, .external_lex_state = 8}, + [64] = {.lex_state = 0, .external_lex_state = 8}, + [65] = {.lex_state = 0, .external_lex_state = 8}, + [66] = {.lex_state = 0, .external_lex_state = 8}, + [67] = {.lex_state = 0, .external_lex_state = 8}, + [68] = {.lex_state = 0, .external_lex_state = 8}, + [69] = {.lex_state = 0, .external_lex_state = 11}, + [70] = {.lex_state = 0, .external_lex_state = 7}, + [71] = {.lex_state = 0, .external_lex_state = 7}, + [72] = {.lex_state = 0, .external_lex_state = 7}, + [73] = {.lex_state = 0, .external_lex_state = 7}, + [74] = {.lex_state = 0, .external_lex_state = 8}, + [75] = {.lex_state = 0, .external_lex_state = 8}, + [76] = {.lex_state = 0, .external_lex_state = 8}, + [77] = {.lex_state = 0, .external_lex_state = 8}, + [78] = {.lex_state = 0, .external_lex_state = 13}, + [79] = {.lex_state = 0, .external_lex_state = 13}, + [80] = {.lex_state = 0, .external_lex_state = 14}, + [81] = {.lex_state = 0, .external_lex_state = 14}, + [82] = {.lex_state = 0, .external_lex_state = 15}, + [83] = {.lex_state = 0, .external_lex_state = 15}, + [84] = {.lex_state = 0, .external_lex_state = 11}, + [85] = {.lex_state = 0, .external_lex_state = 12}, + [86] = {.lex_state = 0, .external_lex_state = 12}, + [87] = {.lex_state = 0, .external_lex_state = 11}, + [88] = {.lex_state = 0, .external_lex_state = 11}, + [89] = {.lex_state = 0, .external_lex_state = 11}, + [90] = {.lex_state = 0, .external_lex_state = 12}, + [91] = {.lex_state = 0, .external_lex_state = 12}, + [92] = {.lex_state = 0, .external_lex_state = 12}, + [93] = {.lex_state = 0, .external_lex_state = 11}, + [94] = {.lex_state = 0, .external_lex_state = 11}, + [95] = {.lex_state = 0, .external_lex_state = 12}, + [96] = {.lex_state = 0, .external_lex_state = 16}, + [97] = {.lex_state = 0, .external_lex_state = 16}, + [98] = {.lex_state = 0, .external_lex_state = 17}, + [99] = {.lex_state = 0, .external_lex_state = 18}, + [100] = {.lex_state = 0, .external_lex_state = 18}, + [101] = {.lex_state = 0, .external_lex_state = 18}, + [102] = {.lex_state = 0, .external_lex_state = 18}, + [103] = {.lex_state = 0, .external_lex_state = 19}, + [104] = {.lex_state = 0, .external_lex_state = 19}, + [105] = {.lex_state = 0, .external_lex_state = 20}, + [106] = {.lex_state = 0, .external_lex_state = 20}, + [107] = {.lex_state = 0, .external_lex_state = 19}, + [108] = {.lex_state = 0, .external_lex_state = 9}, + [109] = {.lex_state = 0, .external_lex_state = 9}, + [110] = {.lex_state = 0, .external_lex_state = 9}, + [111] = {.lex_state = 0, .external_lex_state = 9}, + [112] = {.lex_state = 0, .external_lex_state = 21}, + [113] = {.lex_state = 0, .external_lex_state = 21}, + [114] = {.lex_state = 0, .external_lex_state = 22}, + [115] = {.lex_state = 0, .external_lex_state = 22}, + [116] = {.lex_state = 0, .external_lex_state = 23}, + [117] = {.lex_state = 0, .external_lex_state = 24}, + [118] = {.lex_state = 0, .external_lex_state = 23}, + [119] = {.lex_state = 0, .external_lex_state = 25}, + [120] = {.lex_state = 0, .external_lex_state = 25}, + [121] = {.lex_state = 0, .external_lex_state = 24}, + [122] = {.lex_state = 0, .external_lex_state = 26}, + [123] = {.lex_state = 0, .external_lex_state = 26}, + [124] = {.lex_state = 0, .external_lex_state = 27}, + [125] = {.lex_state = 0, .external_lex_state = 28}, + [126] = {.lex_state = 0, .external_lex_state = 29}, + [127] = {.lex_state = 0, .external_lex_state = 30}, + [128] = {.lex_state = 0, .external_lex_state = 28}, + [129] = {.lex_state = 0, .external_lex_state = 30}, + [130] = {.lex_state = 0, .external_lex_state = 28}, + [131] = {.lex_state = 0, .external_lex_state = 30}, + [132] = {.lex_state = 0, .external_lex_state = 31}, + [133] = {.lex_state = 0, .external_lex_state = 29}, + [134] = {.lex_state = 0, .external_lex_state = 28}, + [135] = {.lex_state = 0, .external_lex_state = 28}, + [136] = {.lex_state = 0, .external_lex_state = 31}, + [137] = {.lex_state = 0, .external_lex_state = 29}, + [138] = {.lex_state = 0, .external_lex_state = 28}, + [139] = {.lex_state = 0, .external_lex_state = 28}, + [140] = {.lex_state = 0, .external_lex_state = 31}, + [141] = {.lex_state = 0, .external_lex_state = 29}, + [142] = {.lex_state = 0, .external_lex_state = 28}, + [143] = {.lex_state = 0, .external_lex_state = 28}, + [144] = {.lex_state = 0, .external_lex_state = 28}, + [145] = {.lex_state = 0, .external_lex_state = 28}, + [146] = {.lex_state = 0, .external_lex_state = 30}, + [147] = {.lex_state = 0, .external_lex_state = 31}, + [148] = {.lex_state = 0, .external_lex_state = 29}, + [149] = {.lex_state = 0, .external_lex_state = 28}, + [150] = {.lex_state = 0, .external_lex_state = 28}, + [151] = {.lex_state = 0, .external_lex_state = 31}, + [152] = {.lex_state = 0, .external_lex_state = 29}, + [153] = {.lex_state = 0, .external_lex_state = 31}, + [154] = {.lex_state = 0, .external_lex_state = 29}, + [155] = {.lex_state = 0, .external_lex_state = 31}, + [156] = {.lex_state = 0, .external_lex_state = 32}, + [157] = {.lex_state = 0, .external_lex_state = 32}, + [158] = {.lex_state = 0, .external_lex_state = 32}, + [159] = {.lex_state = 0, .external_lex_state = 33}, + [160] = {.lex_state = 0, .external_lex_state = 34}, + [161] = {.lex_state = 0, .external_lex_state = 34}, + [162] = {.lex_state = 0, .external_lex_state = 35}, + [163] = {.lex_state = 0, .external_lex_state = 32}, + [164] = {.lex_state = 0, .external_lex_state = 35}, + [165] = {.lex_state = 0, .external_lex_state = 33}, + [166] = {.lex_state = 0, .external_lex_state = 33}, + [167] = {.lex_state = 0, .external_lex_state = 31}, + [168] = {.lex_state = 0, .external_lex_state = 36}, + [169] = {.lex_state = 0, .external_lex_state = 14}, + [170] = {.lex_state = 0, .external_lex_state = 14}, + [171] = {.lex_state = 0, .external_lex_state = 14}, + [172] = {.lex_state = 0, .external_lex_state = 36}, + [173] = {.lex_state = 0, .external_lex_state = 36}, + [174] = {.lex_state = 0, .external_lex_state = 29}, + [175] = {.lex_state = 0, .external_lex_state = 29}, + [176] = {.lex_state = 0, .external_lex_state = 14}, + [177] = {.lex_state = 0, .external_lex_state = 31}, + [178] = {.lex_state = 0, .external_lex_state = 15}, + [179] = {.lex_state = 0, .external_lex_state = 15}, + [180] = {.lex_state = 0, .external_lex_state = 15}, + [181] = {.lex_state = 0, .external_lex_state = 37}, + [182] = {.lex_state = 0, .external_lex_state = 37}, + [183] = {.lex_state = 0, .external_lex_state = 38}, + [184] = {.lex_state = 0, .external_lex_state = 38}, + [185] = {.lex_state = 0, .external_lex_state = 38}, + [186] = {.lex_state = 0, .external_lex_state = 39}, + [187] = {.lex_state = 0, .external_lex_state = 39}, + [188] = {.lex_state = 0, .external_lex_state = 39}, + [189] = {.lex_state = 0, .external_lex_state = 40}, + [190] = {.lex_state = 0, .external_lex_state = 41}, + [191] = {.lex_state = 0, .external_lex_state = 41}, + [192] = {.lex_state = 0, .external_lex_state = 42}, + [193] = {.lex_state = 0, .external_lex_state = 43}, + [194] = {.lex_state = 0, .external_lex_state = 41}, + [195] = {.lex_state = 0, .external_lex_state = 43}, + [196] = {.lex_state = 0, .external_lex_state = 41}, + [197] = {.lex_state = 0, .external_lex_state = 41}, + [198] = {.lex_state = 0, .external_lex_state = 42}, + [199] = {.lex_state = 0, .external_lex_state = 44}, + [200] = {.lex_state = 0, .external_lex_state = 40}, + [201] = {.lex_state = 0, .external_lex_state = 43}, + [202] = {.lex_state = 0, .external_lex_state = 40}, + [203] = {.lex_state = 0, .external_lex_state = 44}, + [204] = {.lex_state = 0, .external_lex_state = 42}, + [205] = {.lex_state = 0, .external_lex_state = 44}, + [206] = {.lex_state = 0, .external_lex_state = 45}, + [207] = {.lex_state = 0, .external_lex_state = 45}, + [208] = {.lex_state = 0, .external_lex_state = 45}, + [209] = {.lex_state = 0, .external_lex_state = 45}, + [210] = {.lex_state = 0, .external_lex_state = 45}, + [211] = {.lex_state = 0, .external_lex_state = 46}, + [212] = {.lex_state = 0, .external_lex_state = 46}, + [213] = {.lex_state = 0, .external_lex_state = 46}, + [214] = {.lex_state = 0, .external_lex_state = 47}, + [215] = {.lex_state = 0, .external_lex_state = 47}, + [216] = {.lex_state = 0, .external_lex_state = 21}, + [217] = {.lex_state = 0, .external_lex_state = 21}, + [218] = {.lex_state = 0, .external_lex_state = 46}, + [219] = {.lex_state = 0, .external_lex_state = 21}, + [220] = {.lex_state = 0, .external_lex_state = 46}, + [221] = {.lex_state = 0, .external_lex_state = 21}, + [222] = {.lex_state = 0, .external_lex_state = 21}, + [223] = {.lex_state = 0, .external_lex_state = 47}, + [224] = {.lex_state = 0, .external_lex_state = 47}, + [225] = {.lex_state = 0, .external_lex_state = 47}, + [226] = {.lex_state = 0, .external_lex_state = 48}, + [227] = {.lex_state = 0, .external_lex_state = 22}, + [228] = {.lex_state = 0, .external_lex_state = 22}, + [229] = {.lex_state = 0, .external_lex_state = 48}, + [230] = {.lex_state = 0, .external_lex_state = 22}, + [231] = {.lex_state = 0, .external_lex_state = 22}, + [232] = {.lex_state = 0, .external_lex_state = 22}, + [233] = {.lex_state = 0, .external_lex_state = 48}, + [234] = {.lex_state = 0, .external_lex_state = 24}, + [235] = {.lex_state = 0, .external_lex_state = 24}, + [236] = {.lex_state = 0, .external_lex_state = 24}, + [237] = {.lex_state = 0, .external_lex_state = 25}, + [238] = {.lex_state = 0, .external_lex_state = 24}, + [239] = {.lex_state = 0, .external_lex_state = 24}, + [240] = {.lex_state = 0, .external_lex_state = 25}, + [241] = {.lex_state = 0, .external_lex_state = 25}, + [242] = {.lex_state = 0, .external_lex_state = 25}, + [243] = {.lex_state = 0, .external_lex_state = 25}, + [244] = {.lex_state = 0, .external_lex_state = 49}, + [245] = {.lex_state = 0, .external_lex_state = 49}, + [246] = {.lex_state = 0, .external_lex_state = 49}, + [247] = {.lex_state = 0, .external_lex_state = 49}, + [248] = {.lex_state = 0, .external_lex_state = 49}, + [249] = {.lex_state = 0, .external_lex_state = 10}, + [250] = {.lex_state = 0, .external_lex_state = 10}, + [251] = {.lex_state = 0, .external_lex_state = 10}, + [252] = {.lex_state = 0, .external_lex_state = 10}, + [253] = {.lex_state = 0, .external_lex_state = 10}, + [254] = {.lex_state = 0, .external_lex_state = 10}, + [255] = {.lex_state = 0, .external_lex_state = 10}, + [256] = {.lex_state = 0, .external_lex_state = 35}, + [257] = {.lex_state = 0, .external_lex_state = 35}, + [258] = {.lex_state = 0, .external_lex_state = 35}, + [259] = {.lex_state = 0, .external_lex_state = 35}, + [260] = {.lex_state = 0, .external_lex_state = 35}, + [261] = {.lex_state = 0, .external_lex_state = 50}, + [262] = {.lex_state = 0, .external_lex_state = 51}, + [263] = {.lex_state = 0, .external_lex_state = 51}, + [264] = {.lex_state = 0, .external_lex_state = 51}, + [265] = {.lex_state = 0, .external_lex_state = 52}, + [266] = {.lex_state = 0, .external_lex_state = 51}, + [267] = {.lex_state = 0, .external_lex_state = 51}, + [268] = {.lex_state = 0, .external_lex_state = 51}, + [269] = {.lex_state = 0, .external_lex_state = 51}, + [270] = {.lex_state = 0, .external_lex_state = 51}, + [271] = {.lex_state = 0, .external_lex_state = 51}, + [272] = {.lex_state = 0, .external_lex_state = 51}, + [273] = {.lex_state = 0, .external_lex_state = 51}, + [274] = {.lex_state = 0, .external_lex_state = 53}, + [275] = {.lex_state = 0, .external_lex_state = 51}, + [276] = {.lex_state = 0, .external_lex_state = 54}, + [277] = {.lex_state = 0, .external_lex_state = 28}, + [278] = {.lex_state = 0, .external_lex_state = 28}, + [279] = {.lex_state = 0, .external_lex_state = 28}, + [280] = {.lex_state = 0, .external_lex_state = 51}, + [281] = {.lex_state = 0, .external_lex_state = 51}, + [282] = {.lex_state = 0, .external_lex_state = 51}, + [283] = {.lex_state = 0, .external_lex_state = 51}, + [284] = {.lex_state = 0, .external_lex_state = 51}, + [285] = {.lex_state = 0, .external_lex_state = 51}, + [286] = {.lex_state = 0, .external_lex_state = 51}, + [287] = {.lex_state = 0, .external_lex_state = 51}, + [288] = {.lex_state = 0, .external_lex_state = 51}, + [289] = {.lex_state = 0, .external_lex_state = 51}, + [290] = {.lex_state = 0, .external_lex_state = 51}, + [291] = {.lex_state = 0, .external_lex_state = 28}, + [292] = {.lex_state = 0, .external_lex_state = 28}, + [293] = {.lex_state = 0, .external_lex_state = 28}, + [294] = {.lex_state = 0, .external_lex_state = 28}, + [295] = {.lex_state = 0, .external_lex_state = 28}, + [296] = {.lex_state = 0, .external_lex_state = 28}, + [297] = {.lex_state = 0, .external_lex_state = 28}, + [298] = {.lex_state = 0, .external_lex_state = 28}, + [299] = {.lex_state = 0, .external_lex_state = 28}, + [300] = {.lex_state = 0, .external_lex_state = 28}, + [301] = {.lex_state = 0, .external_lex_state = 28}, + [302] = {.lex_state = 0, .external_lex_state = 28}, + [303] = {.lex_state = 0, .external_lex_state = 28}, + [304] = {.lex_state = 0, .external_lex_state = 28}, + [305] = {.lex_state = 0, .external_lex_state = 28}, + [306] = {.lex_state = 0, .external_lex_state = 28}, + [307] = {.lex_state = 0, .external_lex_state = 28}, + [308] = {.lex_state = 0, .external_lex_state = 55}, + [309] = {.lex_state = 0, .external_lex_state = 55}, + [310] = {.lex_state = 0, .external_lex_state = 28}, + [311] = {.lex_state = 0, .external_lex_state = 28}, + [312] = {.lex_state = 0, .external_lex_state = 28}, + [313] = {.lex_state = 0, .external_lex_state = 28}, + [314] = {.lex_state = 0, .external_lex_state = 28}, + [315] = {.lex_state = 0, .external_lex_state = 28}, + [316] = {.lex_state = 0, .external_lex_state = 28}, + [317] = {.lex_state = 0, .external_lex_state = 28}, + [318] = {.lex_state = 0, .external_lex_state = 28}, + [319] = {.lex_state = 0, .external_lex_state = 28}, + [320] = {.lex_state = 0, .external_lex_state = 28}, + [321] = {.lex_state = 0, .external_lex_state = 28}, + [322] = {.lex_state = 0, .external_lex_state = 55}, + [323] = {.lex_state = 0, .external_lex_state = 28}, + [324] = {.lex_state = 0, .external_lex_state = 28}, + [325] = {.lex_state = 0, .external_lex_state = 28}, + [326] = {.lex_state = 0, .external_lex_state = 28}, + [327] = {.lex_state = 0, .external_lex_state = 28}, + [328] = {.lex_state = 0, .external_lex_state = 28}, + [329] = {.lex_state = 0, .external_lex_state = 28}, + [330] = {.lex_state = 0, .external_lex_state = 28}, + [331] = {.lex_state = 0, .external_lex_state = 28}, + [332] = {.lex_state = 0, .external_lex_state = 28}, + [333] = {.lex_state = 0, .external_lex_state = 28}, + [334] = {.lex_state = 0, .external_lex_state = 28}, + [335] = {.lex_state = 0, .external_lex_state = 28}, + [336] = {.lex_state = 0, .external_lex_state = 28}, + [337] = {.lex_state = 0, .external_lex_state = 28}, + [338] = {.lex_state = 0, .external_lex_state = 28}, + [339] = {.lex_state = 0, .external_lex_state = 28}, + [340] = {.lex_state = 0, .external_lex_state = 28}, + [341] = {.lex_state = 0, .external_lex_state = 28}, + [342] = {.lex_state = 0, .external_lex_state = 28}, + [343] = {.lex_state = 0, .external_lex_state = 28}, + [344] = {.lex_state = 0, .external_lex_state = 28}, + [345] = {.lex_state = 0, .external_lex_state = 28}, + [346] = {.lex_state = 0, .external_lex_state = 28}, + [347] = {.lex_state = 0, .external_lex_state = 28}, + [348] = {.lex_state = 0, .external_lex_state = 28}, + [349] = {.lex_state = 0, .external_lex_state = 28}, + [350] = {.lex_state = 0, .external_lex_state = 28}, + [351] = {.lex_state = 0, .external_lex_state = 28}, + [352] = {.lex_state = 0, .external_lex_state = 28}, + [353] = {.lex_state = 0, .external_lex_state = 28}, + [354] = {.lex_state = 0, .external_lex_state = 28}, + [355] = {.lex_state = 0, .external_lex_state = 28}, + [356] = {.lex_state = 0, .external_lex_state = 28}, + [357] = {.lex_state = 0, .external_lex_state = 28}, + [358] = {.lex_state = 0, .external_lex_state = 28}, + [359] = {.lex_state = 0, .external_lex_state = 28}, + [360] = {.lex_state = 0, .external_lex_state = 28}, + [361] = {.lex_state = 0, .external_lex_state = 28}, + [362] = {.lex_state = 0, .external_lex_state = 28}, + [363] = {.lex_state = 0, .external_lex_state = 28}, + [364] = {.lex_state = 0, .external_lex_state = 28}, + [365] = {.lex_state = 0, .external_lex_state = 56}, + [366] = {.lex_state = 0, .external_lex_state = 28}, + [367] = {.lex_state = 0, .external_lex_state = 28}, + [368] = {.lex_state = 0, .external_lex_state = 28}, + [369] = {.lex_state = 0, .external_lex_state = 28}, + [370] = {.lex_state = 0, .external_lex_state = 28}, + [371] = {.lex_state = 0, .external_lex_state = 28}, + [372] = {.lex_state = 0, .external_lex_state = 28}, + [373] = {.lex_state = 0, .external_lex_state = 28}, + [374] = {.lex_state = 0, .external_lex_state = 28}, + [375] = {.lex_state = 0, .external_lex_state = 28}, + [376] = {.lex_state = 0, .external_lex_state = 28}, + [377] = {.lex_state = 0, .external_lex_state = 28}, + [378] = {.lex_state = 0, .external_lex_state = 28}, + [379] = {.lex_state = 0, .external_lex_state = 28}, + [380] = {.lex_state = 0, .external_lex_state = 28}, + [381] = {.lex_state = 0, .external_lex_state = 28}, + [382] = {.lex_state = 0, .external_lex_state = 28}, + [383] = {.lex_state = 0, .external_lex_state = 28}, + [384] = {.lex_state = 0, .external_lex_state = 28}, + [385] = {.lex_state = 0, .external_lex_state = 28}, + [386] = {.lex_state = 0, .external_lex_state = 28}, + [387] = {.lex_state = 0, .external_lex_state = 28}, + [388] = {.lex_state = 0, .external_lex_state = 28}, + [389] = {.lex_state = 0, .external_lex_state = 28}, + [390] = {.lex_state = 0, .external_lex_state = 28}, + [391] = {.lex_state = 0, .external_lex_state = 28}, + [392] = {.lex_state = 0, .external_lex_state = 57}, + [393] = {.lex_state = 0, .external_lex_state = 58}, + [394] = {.lex_state = 0, .external_lex_state = 59}, + [395] = {.lex_state = 0, .external_lex_state = 60}, + [396] = {.lex_state = 0, .external_lex_state = 61}, + [397] = {.lex_state = 0, .external_lex_state = 60}, + [398] = {.lex_state = 0, .external_lex_state = 62}, + [399] = {.lex_state = 0, .external_lex_state = 62}, + [400] = {.lex_state = 0, .external_lex_state = 52}, + [401] = {.lex_state = 0, .external_lex_state = 63}, + [402] = {.lex_state = 0, .external_lex_state = 50}, + [403] = {.lex_state = 0, .external_lex_state = 64}, + [404] = {.lex_state = 0, .external_lex_state = 65}, + [405] = {.lex_state = 0, .external_lex_state = 66}, + [406] = {.lex_state = 0, .external_lex_state = 50}, + [407] = {.lex_state = 0, .external_lex_state = 63}, + [408] = {.lex_state = 0, .external_lex_state = 52}, + [409] = {.lex_state = 0, .external_lex_state = 66}, + [410] = {.lex_state = 0, .external_lex_state = 65}, + [411] = {.lex_state = 0, .external_lex_state = 53}, + [412] = {.lex_state = 0, .external_lex_state = 67}, + [413] = {.lex_state = 0, .external_lex_state = 67}, + [414] = {.lex_state = 0, .external_lex_state = 54}, + [415] = {.lex_state = 0, .external_lex_state = 68}, + [416] = {.lex_state = 0, .external_lex_state = 68}, + [417] = {.lex_state = 0, .external_lex_state = 53}, + [418] = {.lex_state = 0, .external_lex_state = 68}, + [419] = {.lex_state = 0, .external_lex_state = 54}, + [420] = {.lex_state = 0, .external_lex_state = 68}, + [421] = {.lex_state = 0, .external_lex_state = 69}, + [422] = {.lex_state = 0, .external_lex_state = 69}, + [423] = {.lex_state = 0, .external_lex_state = 69}, + [424] = {.lex_state = 0, .external_lex_state = 55}, + [425] = {.lex_state = 0, .external_lex_state = 55}, + [426] = {.lex_state = 0, .external_lex_state = 69}, + [427] = {.lex_state = 0, .external_lex_state = 69}, + [428] = {.lex_state = 0, .external_lex_state = 69}, + [429] = {.lex_state = 0, .external_lex_state = 69}, + [430] = {.lex_state = 0, .external_lex_state = 69}, + [431] = {.lex_state = 0, .external_lex_state = 69}, + [432] = {.lex_state = 0, .external_lex_state = 69}, + [433] = {.lex_state = 0, .external_lex_state = 69}, + [434] = {.lex_state = 0, .external_lex_state = 69}, + [435] = {.lex_state = 0, .external_lex_state = 69}, + [436] = {.lex_state = 0, .external_lex_state = 69}, + [437] = {.lex_state = 0, .external_lex_state = 69}, + [438] = {.lex_state = 0, .external_lex_state = 56}, + [439] = {.lex_state = 0, .external_lex_state = 69}, + [440] = {.lex_state = 0, .external_lex_state = 69}, + [441] = {.lex_state = 0, .external_lex_state = 69}, + [442] = {.lex_state = 0, .external_lex_state = 69}, + [443] = {.lex_state = 0, .external_lex_state = 69}, + [444] = {.lex_state = 0, .external_lex_state = 69}, + [445] = {.lex_state = 0, .external_lex_state = 56}, + [446] = {.lex_state = 0, .external_lex_state = 69}, + [447] = {.lex_state = 0, .external_lex_state = 69}, + [448] = {.lex_state = 0, .external_lex_state = 69}, + [449] = {.lex_state = 0, .external_lex_state = 69}, + [450] = {.lex_state = 0, .external_lex_state = 69}, + [451] = {.lex_state = 0, .external_lex_state = 69}, + [452] = {.lex_state = 0, .external_lex_state = 69}, + [453] = {.lex_state = 0, .external_lex_state = 69}, + [454] = {.lex_state = 0, .external_lex_state = 69}, + [455] = {.lex_state = 0, .external_lex_state = 69}, + [456] = {.lex_state = 0, .external_lex_state = 69}, + [457] = {.lex_state = 0, .external_lex_state = 69}, + [458] = {.lex_state = 0, .external_lex_state = 69}, + [459] = {.lex_state = 0, .external_lex_state = 69}, + [460] = {.lex_state = 0, .external_lex_state = 69}, + [461] = {.lex_state = 0, .external_lex_state = 69}, + [462] = {.lex_state = 0, .external_lex_state = 69}, + [463] = {.lex_state = 0, .external_lex_state = 69}, + [464] = {.lex_state = 0, .external_lex_state = 69}, + [465] = {.lex_state = 0, .external_lex_state = 69}, + [466] = {.lex_state = 0, .external_lex_state = 69}, + [467] = {.lex_state = 0, .external_lex_state = 69}, + [468] = {.lex_state = 0, .external_lex_state = 69}, + [469] = {.lex_state = 0, .external_lex_state = 55}, + [470] = {.lex_state = 0, .external_lex_state = 69}, + [471] = {.lex_state = 0, .external_lex_state = 69}, + [472] = {.lex_state = 0, .external_lex_state = 69}, + [473] = {.lex_state = 0, .external_lex_state = 69}, + [474] = {.lex_state = 0, .external_lex_state = 70}, + [475] = {.lex_state = 0, .external_lex_state = 71}, + [476] = {.lex_state = 0, .external_lex_state = 70}, + [477] = {.lex_state = 0, .external_lex_state = 70}, + [478] = {.lex_state = 0, .external_lex_state = 72}, + [479] = {.lex_state = 0, .external_lex_state = 70}, + [480] = {.lex_state = 0, .external_lex_state = 70}, + [481] = {.lex_state = 0, .external_lex_state = 69}, + [482] = {.lex_state = 0, .external_lex_state = 73}, + [483] = {.lex_state = 0, .external_lex_state = 73}, + [484] = {.lex_state = 0, .external_lex_state = 73}, + [485] = {.lex_state = 0, .external_lex_state = 73}, + [486] = {.lex_state = 0, .external_lex_state = 69}, + [487] = {.lex_state = 0, .external_lex_state = 73}, + [488] = {.lex_state = 0, .external_lex_state = 73}, + [489] = {.lex_state = 0, .external_lex_state = 73}, + [490] = {.lex_state = 0, .external_lex_state = 73}, + [491] = {.lex_state = 0, .external_lex_state = 73}, + [492] = {.lex_state = 0, .external_lex_state = 71}, + [493] = {.lex_state = 0, .external_lex_state = 71}, + [494] = {.lex_state = 0, .external_lex_state = 73}, + [495] = {.lex_state = 0, .external_lex_state = 73}, + [496] = {.lex_state = 0, .external_lex_state = 73}, + [497] = {.lex_state = 0, .external_lex_state = 73}, + [498] = {.lex_state = 0, .external_lex_state = 74}, + [499] = {.lex_state = 0, .external_lex_state = 69}, + [500] = {.lex_state = 0, .external_lex_state = 73}, + [501] = {.lex_state = 0, .external_lex_state = 73}, + [502] = {.lex_state = 0, .external_lex_state = 69}, + [503] = {.lex_state = 0, .external_lex_state = 73}, + [504] = {.lex_state = 0, .external_lex_state = 74}, + [505] = {.lex_state = 0, .external_lex_state = 73}, + [506] = {.lex_state = 0, .external_lex_state = 73}, + [507] = {.lex_state = 0, .external_lex_state = 73}, + [508] = {.lex_state = 0, .external_lex_state = 73}, + [509] = {.lex_state = 0, .external_lex_state = 73}, + [510] = {.lex_state = 0, .external_lex_state = 73}, + [511] = {.lex_state = 0, .external_lex_state = 73}, + [512] = {.lex_state = 0, .external_lex_state = 73}, + [513] = {.lex_state = 0, .external_lex_state = 73}, + [514] = {.lex_state = 0, .external_lex_state = 73}, + [515] = {.lex_state = 0, .external_lex_state = 73}, + [516] = {.lex_state = 0, .external_lex_state = 73}, + [517] = {.lex_state = 0, .external_lex_state = 73}, + [518] = {.lex_state = 0, .external_lex_state = 73}, + [519] = {.lex_state = 0, .external_lex_state = 73}, + [520] = {.lex_state = 0, .external_lex_state = 73}, + [521] = {.lex_state = 0, .external_lex_state = 73}, + [522] = {.lex_state = 0, .external_lex_state = 72}, + [523] = {.lex_state = 0, .external_lex_state = 73}, + [524] = {.lex_state = 0, .external_lex_state = 73}, + [525] = {.lex_state = 0, .external_lex_state = 73}, + [526] = {.lex_state = 0, .external_lex_state = 73}, + [527] = {.lex_state = 0, .external_lex_state = 73}, + [528] = {.lex_state = 0, .external_lex_state = 73}, + [529] = {.lex_state = 0, .external_lex_state = 73}, + [530] = {.lex_state = 0, .external_lex_state = 73}, + [531] = {.lex_state = 0, .external_lex_state = 73}, + [532] = {.lex_state = 0, .external_lex_state = 73}, + [533] = {.lex_state = 0, .external_lex_state = 73}, + [534] = {.lex_state = 0, .external_lex_state = 73}, + [535] = {.lex_state = 0, .external_lex_state = 73}, + [536] = {.lex_state = 0, .external_lex_state = 73}, + [537] = {.lex_state = 0, .external_lex_state = 73}, + [538] = {.lex_state = 0, .external_lex_state = 75}, + [539] = {.lex_state = 0, .external_lex_state = 76}, + [540] = {.lex_state = 0, .external_lex_state = 74}, + [541] = {.lex_state = 0, .external_lex_state = 76}, + [542] = {.lex_state = 0, .external_lex_state = 74}, + [543] = {.lex_state = 0, .external_lex_state = 76}, + [544] = {.lex_state = 0, .external_lex_state = 76}, + [545] = {.lex_state = 0, .external_lex_state = 74}, + [546] = {.lex_state = 0, .external_lex_state = 76}, + [547] = {.lex_state = 0, .external_lex_state = 74}, + [548] = {.lex_state = 0, .external_lex_state = 74}, + [549] = {.lex_state = 0, .external_lex_state = 74}, + [550] = {.lex_state = 0, .external_lex_state = 74}, + [551] = {.lex_state = 0, .external_lex_state = 71}, + [552] = {.lex_state = 0, .external_lex_state = 77}, + [553] = {.lex_state = 0, .external_lex_state = 76}, + [554] = {.lex_state = 0, .external_lex_state = 78}, + [555] = {.lex_state = 0, .external_lex_state = 74}, + [556] = {.lex_state = 0, .external_lex_state = 71}, + [557] = {.lex_state = 0, .external_lex_state = 76}, + [558] = {.lex_state = 0, .external_lex_state = 76}, + [559] = {.lex_state = 0, .external_lex_state = 76}, + [560] = {.lex_state = 0, .external_lex_state = 76}, + [561] = {.lex_state = 0, .external_lex_state = 76}, + [562] = {.lex_state = 0, .external_lex_state = 76}, + [563] = {.lex_state = 0, .external_lex_state = 71}, + [564] = {.lex_state = 0, .external_lex_state = 71}, + [565] = {.lex_state = 0, .external_lex_state = 76}, + [566] = {.lex_state = 0, .external_lex_state = 74}, + [567] = {.lex_state = 0, .external_lex_state = 79}, + [568] = {.lex_state = 0, .external_lex_state = 74}, + [569] = {.lex_state = 0, .external_lex_state = 74}, + [570] = {.lex_state = 0, .external_lex_state = 74}, + [571] = {.lex_state = 0, .external_lex_state = 74}, + [572] = {.lex_state = 0, .external_lex_state = 74}, + [573] = {.lex_state = 0, .external_lex_state = 74}, + [574] = {.lex_state = 0, .external_lex_state = 74}, + [575] = {.lex_state = 0, .external_lex_state = 76}, + [576] = {.lex_state = 0, .external_lex_state = 74}, + [577] = {.lex_state = 0, .external_lex_state = 76}, + [578] = {.lex_state = 0, .external_lex_state = 76}, + [579] = {.lex_state = 0, .external_lex_state = 76}, + [580] = {.lex_state = 0, .external_lex_state = 74}, + [581] = {.lex_state = 0, .external_lex_state = 74}, + [582] = {.lex_state = 0, .external_lex_state = 76}, + [583] = {.lex_state = 0, .external_lex_state = 76}, + [584] = {.lex_state = 0, .external_lex_state = 76}, + [585] = {.lex_state = 0, .external_lex_state = 76}, + [586] = {.lex_state = 0, .external_lex_state = 73}, + [587] = {.lex_state = 0, .external_lex_state = 76}, + [588] = {.lex_state = 0, .external_lex_state = 76}, + [589] = {.lex_state = 0, .external_lex_state = 76}, + [590] = {.lex_state = 0, .external_lex_state = 76}, + [591] = {.lex_state = 0, .external_lex_state = 76}, + [592] = {.lex_state = 0, .external_lex_state = 76}, + [593] = {.lex_state = 0, .external_lex_state = 71}, + [594] = {.lex_state = 0, .external_lex_state = 74}, + [595] = {.lex_state = 0, .external_lex_state = 74}, + [596] = {.lex_state = 0, .external_lex_state = 74}, + [597] = {.lex_state = 0, .external_lex_state = 74}, + [598] = {.lex_state = 0, .external_lex_state = 74}, + [599] = {.lex_state = 0, .external_lex_state = 74}, + [600] = {.lex_state = 0, .external_lex_state = 74}, + [601] = {.lex_state = 0, .external_lex_state = 74}, + [602] = {.lex_state = 0, .external_lex_state = 74}, + [603] = {.lex_state = 0, .external_lex_state = 74}, + [604] = {.lex_state = 0, .external_lex_state = 74}, + [605] = {.lex_state = 0, .external_lex_state = 76}, + [606] = {.lex_state = 0, .external_lex_state = 74}, + [607] = {.lex_state = 0, .external_lex_state = 76}, + [608] = {.lex_state = 0, .external_lex_state = 76}, + [609] = {.lex_state = 0, .external_lex_state = 76}, + [610] = {.lex_state = 0, .external_lex_state = 74}, + [611] = {.lex_state = 0, .external_lex_state = 74}, + [612] = {.lex_state = 0, .external_lex_state = 74}, + [613] = {.lex_state = 0, .external_lex_state = 74}, + [614] = {.lex_state = 0, .external_lex_state = 73}, + [615] = {.lex_state = 0, .external_lex_state = 73}, + [616] = {.lex_state = 0, .external_lex_state = 74}, + [617] = {.lex_state = 0, .external_lex_state = 76}, + [618] = {.lex_state = 0, .external_lex_state = 76}, + [619] = {.lex_state = 0, .external_lex_state = 76}, + [620] = {.lex_state = 0, .external_lex_state = 76}, + [621] = {.lex_state = 0, .external_lex_state = 76}, + [622] = {.lex_state = 0, .external_lex_state = 76}, + [623] = {.lex_state = 0, .external_lex_state = 74}, + [624] = {.lex_state = 0, .external_lex_state = 74}, + [625] = {.lex_state = 0, .external_lex_state = 76}, + [626] = {.lex_state = 0, .external_lex_state = 74}, + [627] = {.lex_state = 0, .external_lex_state = 76}, + [628] = {.lex_state = 0, .external_lex_state = 76}, + [629] = {.lex_state = 0, .external_lex_state = 76}, + [630] = {.lex_state = 0, .external_lex_state = 76}, + [631] = {.lex_state = 0, .external_lex_state = 76}, + [632] = {.lex_state = 0, .external_lex_state = 74}, + [633] = {.lex_state = 0, .external_lex_state = 76}, + [634] = {.lex_state = 0, .external_lex_state = 76}, + [635] = {.lex_state = 0, .external_lex_state = 76}, + [636] = {.lex_state = 0, .external_lex_state = 74}, + [637] = {.lex_state = 0, .external_lex_state = 71}, + [638] = {.lex_state = 0, .external_lex_state = 71}, + [639] = {.lex_state = 0, .external_lex_state = 71}, + [640] = {.lex_state = 0, .external_lex_state = 76}, + [641] = {.lex_state = 0, .external_lex_state = 76}, + [642] = {.lex_state = 0, .external_lex_state = 76}, + [643] = {.lex_state = 0, .external_lex_state = 76}, + [644] = {.lex_state = 0, .external_lex_state = 76}, + [645] = {.lex_state = 0, .external_lex_state = 78}, + [646] = {.lex_state = 0, .external_lex_state = 76}, + [647] = {.lex_state = 0, .external_lex_state = 76}, + [648] = {.lex_state = 0, .external_lex_state = 73}, + [649] = {.lex_state = 0, .external_lex_state = 77}, + [650] = {.lex_state = 0, .external_lex_state = 76}, + [651] = {.lex_state = 0, .external_lex_state = 76}, + [652] = {.lex_state = 0, .external_lex_state = 76}, + [653] = {.lex_state = 0, .external_lex_state = 76}, + [654] = {.lex_state = 0, .external_lex_state = 76}, + [655] = {.lex_state = 0, .external_lex_state = 76}, + [656] = {.lex_state = 0, .external_lex_state = 76}, + [657] = {.lex_state = 0, .external_lex_state = 76}, + [658] = {.lex_state = 0, .external_lex_state = 76}, + [659] = {.lex_state = 0, .external_lex_state = 76}, + [660] = {.lex_state = 0, .external_lex_state = 77}, + [661] = {.lex_state = 0, .external_lex_state = 77}, + [662] = {.lex_state = 0, .external_lex_state = 71}, + [663] = {.lex_state = 0, .external_lex_state = 77}, + [664] = {.lex_state = 0, .external_lex_state = 76}, + [665] = {.lex_state = 0, .external_lex_state = 76}, + [666] = {.lex_state = 0, .external_lex_state = 76}, + [667] = {.lex_state = 0, .external_lex_state = 76}, + [668] = {.lex_state = 0, .external_lex_state = 76}, + [669] = {.lex_state = 0, .external_lex_state = 76}, + [670] = {.lex_state = 0, .external_lex_state = 79}, + [671] = {.lex_state = 0, .external_lex_state = 79}, + [672] = {.lex_state = 0, .external_lex_state = 75}, + [673] = {.lex_state = 0, .external_lex_state = 79}, + [674] = {.lex_state = 0, .external_lex_state = 75}, + [675] = {.lex_state = 0, .external_lex_state = 79}, + [676] = {.lex_state = 0, .external_lex_state = 76}, + [677] = {.lex_state = 0, .external_lex_state = 71}, + [678] = {.lex_state = 0, .external_lex_state = 76}, + [679] = {.lex_state = 0, .external_lex_state = 71}, + [680] = {.lex_state = 0, .external_lex_state = 76}, + [681] = {.lex_state = 0, .external_lex_state = 76}, + [682] = {.lex_state = 0, .external_lex_state = 76}, + [683] = {.lex_state = 0, .external_lex_state = 71}, + [684] = {.lex_state = 0, .external_lex_state = 71}, + [685] = {.lex_state = 0, .external_lex_state = 76}, + [686] = {.lex_state = 0, .external_lex_state = 76}, + [687] = {.lex_state = 0, .external_lex_state = 76}, + [688] = {.lex_state = 0, .external_lex_state = 76}, + [689] = {.lex_state = 0, .external_lex_state = 76}, + [690] = {.lex_state = 0, .external_lex_state = 76}, + [691] = {.lex_state = 0, .external_lex_state = 76}, + [692] = {.lex_state = 0, .external_lex_state = 74}, + [693] = {.lex_state = 0, .external_lex_state = 80}, + [694] = {.lex_state = 0, .external_lex_state = 81}, + [695] = {.lex_state = 0, .external_lex_state = 75}, + [696] = {.lex_state = 0, .external_lex_state = 75}, + [697] = {.lex_state = 0, .external_lex_state = 75}, + [698] = {.lex_state = 0, .external_lex_state = 81}, + [699] = {.lex_state = 0, .external_lex_state = 75}, + [700] = {.lex_state = 0, .external_lex_state = 75}, + [701] = {.lex_state = 0, .external_lex_state = 75}, + [702] = {.lex_state = 0, .external_lex_state = 78}, + [703] = {.lex_state = 0, .external_lex_state = 78}, + [704] = {.lex_state = 0, .external_lex_state = 78}, + [705] = {.lex_state = 0, .external_lex_state = 78}, + [706] = {.lex_state = 0, .external_lex_state = 78}, + [707] = {.lex_state = 0, .external_lex_state = 78}, + [708] = {.lex_state = 0, .external_lex_state = 78}, + [709] = {.lex_state = 0, .external_lex_state = 78}, + [710] = {.lex_state = 0, .external_lex_state = 75}, + [711] = {.lex_state = 0, .external_lex_state = 78}, + [712] = {.lex_state = 0, .external_lex_state = 78}, + [713] = {.lex_state = 0, .external_lex_state = 78}, + [714] = {.lex_state = 0, .external_lex_state = 78}, + [715] = {.lex_state = 0, .external_lex_state = 78}, + [716] = {.lex_state = 0, .external_lex_state = 78}, + [717] = {.lex_state = 0, .external_lex_state = 78}, + [718] = {.lex_state = 0, .external_lex_state = 78}, + [719] = {.lex_state = 0, .external_lex_state = 78}, + [720] = {.lex_state = 0, .external_lex_state = 78}, + [721] = {.lex_state = 0, .external_lex_state = 78}, + [722] = {.lex_state = 0, .external_lex_state = 78}, + [723] = {.lex_state = 0, .external_lex_state = 75}, + [724] = {.lex_state = 0, .external_lex_state = 78}, + [725] = {.lex_state = 0, .external_lex_state = 78}, + [726] = {.lex_state = 0, .external_lex_state = 78}, + [727] = {.lex_state = 0, .external_lex_state = 78}, + [728] = {.lex_state = 0, .external_lex_state = 78}, + [729] = {.lex_state = 0, .external_lex_state = 78}, + [730] = {.lex_state = 0, .external_lex_state = 78}, + [731] = {.lex_state = 0, .external_lex_state = 78}, + [732] = {.lex_state = 0, .external_lex_state = 78}, + [733] = {.lex_state = 0, .external_lex_state = 78}, + [734] = {.lex_state = 0, .external_lex_state = 78}, + [735] = {.lex_state = 0, .external_lex_state = 78}, + [736] = {.lex_state = 0, .external_lex_state = 78}, + [737] = {.lex_state = 0, .external_lex_state = 78}, + [738] = {.lex_state = 0, .external_lex_state = 78}, + [739] = {.lex_state = 0, .external_lex_state = 78}, + [740] = {.lex_state = 0, .external_lex_state = 78}, + [741] = {.lex_state = 0, .external_lex_state = 80}, + [742] = {.lex_state = 0, .external_lex_state = 78}, + [743] = {.lex_state = 0, .external_lex_state = 78}, + [744] = {.lex_state = 0, .external_lex_state = 78}, + [745] = {.lex_state = 0, .external_lex_state = 78}, + [746] = {.lex_state = 0, .external_lex_state = 75}, + [747] = {.lex_state = 0, .external_lex_state = 75}, + [748] = {.lex_state = 0, .external_lex_state = 75}, + [749] = {.lex_state = 0, .external_lex_state = 75}, + [750] = {.lex_state = 0, .external_lex_state = 80}, + [751] = {.lex_state = 0, .external_lex_state = 80}, + [752] = {.lex_state = 0, .external_lex_state = 80}, + [753] = {.lex_state = 0, .external_lex_state = 75}, + [754] = {.lex_state = 0, .external_lex_state = 80}, + [755] = {.lex_state = 0, .external_lex_state = 80}, + [756] = {.lex_state = 0, .external_lex_state = 80}, + [757] = {.lex_state = 0, .external_lex_state = 80}, + [758] = {.lex_state = 0, .external_lex_state = 81}, + [759] = {.lex_state = 0, .external_lex_state = 80}, + [760] = {.lex_state = 0, .external_lex_state = 80}, + [761] = {.lex_state = 0, .external_lex_state = 80}, + [762] = {.lex_state = 0, .external_lex_state = 80}, + [763] = {.lex_state = 0, .external_lex_state = 80}, + [764] = {.lex_state = 0, .external_lex_state = 80}, + [765] = {.lex_state = 0, .external_lex_state = 80}, + [766] = {.lex_state = 0, .external_lex_state = 80}, + [767] = {.lex_state = 0, .external_lex_state = 80}, + [768] = {.lex_state = 0, .external_lex_state = 80}, + [769] = {.lex_state = 0, .external_lex_state = 80}, + [770] = {.lex_state = 0, .external_lex_state = 80}, + [771] = {.lex_state = 0, .external_lex_state = 80}, + [772] = {.lex_state = 0, .external_lex_state = 80}, + [773] = {.lex_state = 0, .external_lex_state = 80}, + [774] = {.lex_state = 0, .external_lex_state = 80}, + [775] = {.lex_state = 0, .external_lex_state = 80}, + [776] = {.lex_state = 0, .external_lex_state = 80}, + [777] = {.lex_state = 0, .external_lex_state = 80}, + [778] = {.lex_state = 0, .external_lex_state = 80}, + [779] = {.lex_state = 0, .external_lex_state = 80}, + [780] = {.lex_state = 0, .external_lex_state = 80}, + [781] = {.lex_state = 0, .external_lex_state = 80}, + [782] = {.lex_state = 0, .external_lex_state = 80}, + [783] = {.lex_state = 0, .external_lex_state = 78}, + [784] = {.lex_state = 0, .external_lex_state = 79}, + [785] = {.lex_state = 0, .external_lex_state = 77}, + [786] = {.lex_state = 0, .external_lex_state = 77}, + [787] = {.lex_state = 0, .external_lex_state = 79}, + [788] = {.lex_state = 0, .external_lex_state = 79}, + [789] = {.lex_state = 0, .external_lex_state = 77}, + [790] = {.lex_state = 0, .external_lex_state = 77}, + [791] = {.lex_state = 0, .external_lex_state = 77}, + [792] = {.lex_state = 0, .external_lex_state = 77}, + [793] = {.lex_state = 0, .external_lex_state = 79}, + [794] = {.lex_state = 0, .external_lex_state = 76}, + [795] = {.lex_state = 0, .external_lex_state = 77}, + [796] = {.lex_state = 0, .external_lex_state = 79}, + [797] = {.lex_state = 0, .external_lex_state = 79}, + [798] = {.lex_state = 0, .external_lex_state = 79}, + [799] = {.lex_state = 0, .external_lex_state = 77}, + [800] = {.lex_state = 0, .external_lex_state = 77}, + [801] = {.lex_state = 0, .external_lex_state = 79}, + [802] = {.lex_state = 0, .external_lex_state = 79}, + [803] = {.lex_state = 0, .external_lex_state = 79}, + [804] = {.lex_state = 0, .external_lex_state = 77}, + [805] = {.lex_state = 0, .external_lex_state = 82}, + [806] = {.lex_state = 0, .external_lex_state = 77}, + [807] = {.lex_state = 0, .external_lex_state = 77}, + [808] = {.lex_state = 0, .external_lex_state = 77}, + [809] = {.lex_state = 0, .external_lex_state = 77}, + [810] = {.lex_state = 0, .external_lex_state = 77}, + [811] = {.lex_state = 0, .external_lex_state = 79}, + [812] = {.lex_state = 0, .external_lex_state = 79}, + [813] = {.lex_state = 0, .external_lex_state = 79}, + [814] = {.lex_state = 0, .external_lex_state = 79}, + [815] = {.lex_state = 0, .external_lex_state = 79}, + [816] = {.lex_state = 0, .external_lex_state = 77}, + [817] = {.lex_state = 0, .external_lex_state = 77}, + [818] = {.lex_state = 0, .external_lex_state = 77}, + [819] = {.lex_state = 0, .external_lex_state = 77}, + [820] = {.lex_state = 0, .external_lex_state = 77}, + [821] = {.lex_state = 0, .external_lex_state = 77}, + [822] = {.lex_state = 0, .external_lex_state = 77}, + [823] = {.lex_state = 0, .external_lex_state = 77}, + [824] = {.lex_state = 0, .external_lex_state = 77}, + [825] = {.lex_state = 0, .external_lex_state = 77}, + [826] = {.lex_state = 0, .external_lex_state = 79}, + [827] = {.lex_state = 0, .external_lex_state = 77}, + [828] = {.lex_state = 0, .external_lex_state = 77}, + [829] = {.lex_state = 0, .external_lex_state = 77}, + [830] = {.lex_state = 0, .external_lex_state = 77}, + [831] = {.lex_state = 0, .external_lex_state = 77}, + [832] = {.lex_state = 0, .external_lex_state = 77}, + [833] = {.lex_state = 0, .external_lex_state = 77}, + [834] = {.lex_state = 0, .external_lex_state = 77}, + [835] = {.lex_state = 0, .external_lex_state = 77}, + [836] = {.lex_state = 0, .external_lex_state = 77}, + [837] = {.lex_state = 0, .external_lex_state = 77}, + [838] = {.lex_state = 0, .external_lex_state = 77}, + [839] = {.lex_state = 0, .external_lex_state = 79}, + [840] = {.lex_state = 0, .external_lex_state = 79}, + [841] = {.lex_state = 0, .external_lex_state = 79}, + [842] = {.lex_state = 0, .external_lex_state = 77}, + [843] = {.lex_state = 0, .external_lex_state = 77}, + [844] = {.lex_state = 0, .external_lex_state = 77}, + [845] = {.lex_state = 0, .external_lex_state = 77}, + [846] = {.lex_state = 0, .external_lex_state = 77}, + [847] = {.lex_state = 0, .external_lex_state = 77}, + [848] = {.lex_state = 0, .external_lex_state = 77}, + [849] = {.lex_state = 0, .external_lex_state = 77}, + [850] = {.lex_state = 0, .external_lex_state = 77}, + [851] = {.lex_state = 0, .external_lex_state = 77}, + [852] = {.lex_state = 0, .external_lex_state = 77}, + [853] = {.lex_state = 0, .external_lex_state = 77}, + [854] = {.lex_state = 0, .external_lex_state = 77}, + [855] = {.lex_state = 0, .external_lex_state = 77}, + [856] = {.lex_state = 0, .external_lex_state = 77}, + [857] = {.lex_state = 0, .external_lex_state = 77}, + [858] = {.lex_state = 0, .external_lex_state = 77}, + [859] = {.lex_state = 0, .external_lex_state = 77}, + [860] = {.lex_state = 0, .external_lex_state = 77}, + [861] = {.lex_state = 0, .external_lex_state = 77}, + [862] = {.lex_state = 0, .external_lex_state = 77}, + [863] = {.lex_state = 0, .external_lex_state = 77}, + [864] = {.lex_state = 0, .external_lex_state = 79}, + [865] = {.lex_state = 0, .external_lex_state = 79}, + [866] = {.lex_state = 0, .external_lex_state = 79}, + [867] = {.lex_state = 0, .external_lex_state = 79}, + [868] = {.lex_state = 0, .external_lex_state = 79}, + [869] = {.lex_state = 0, .external_lex_state = 79}, + [870] = {.lex_state = 0, .external_lex_state = 79}, + [871] = {.lex_state = 0, .external_lex_state = 79}, + [872] = {.lex_state = 0, .external_lex_state = 79}, + [873] = {.lex_state = 0, .external_lex_state = 77}, + [874] = {.lex_state = 0, .external_lex_state = 77}, + [875] = {.lex_state = 0, .external_lex_state = 79}, + [876] = {.lex_state = 0, .external_lex_state = 79}, + [877] = {.lex_state = 0, .external_lex_state = 79}, + [878] = {.lex_state = 0, .external_lex_state = 79}, + [879] = {.lex_state = 0, .external_lex_state = 79}, + [880] = {.lex_state = 0, .external_lex_state = 79}, + [881] = {.lex_state = 0, .external_lex_state = 79}, + [882] = {.lex_state = 0, .external_lex_state = 79}, + [883] = {.lex_state = 0, .external_lex_state = 79}, + [884] = {.lex_state = 0, .external_lex_state = 79}, + [885] = {.lex_state = 0, .external_lex_state = 79}, + [886] = {.lex_state = 0, .external_lex_state = 79}, + [887] = {.lex_state = 0, .external_lex_state = 79}, + [888] = {.lex_state = 0, .external_lex_state = 79}, + [889] = {.lex_state = 0, .external_lex_state = 76}, + [890] = {.lex_state = 0, .external_lex_state = 77}, + [891] = {.lex_state = 0, .external_lex_state = 77}, + [892] = {.lex_state = 0, .external_lex_state = 79}, + [893] = {.lex_state = 0, .external_lex_state = 79}, + [894] = {.lex_state = 0, .external_lex_state = 79}, + [895] = {.lex_state = 0, .external_lex_state = 79}, + [896] = {.lex_state = 0, .external_lex_state = 79}, + [897] = {.lex_state = 0, .external_lex_state = 79}, + [898] = {.lex_state = 0, .external_lex_state = 79}, + [899] = {.lex_state = 0, .external_lex_state = 79}, + [900] = {.lex_state = 0, .external_lex_state = 79}, + [901] = {.lex_state = 0, .external_lex_state = 79}, + [902] = {.lex_state = 0, .external_lex_state = 79}, + [903] = {.lex_state = 0, .external_lex_state = 79}, + [904] = {.lex_state = 0, .external_lex_state = 79}, + [905] = {.lex_state = 0, .external_lex_state = 79}, + [906] = {.lex_state = 0, .external_lex_state = 79}, + [907] = {.lex_state = 0, .external_lex_state = 79}, + [908] = {.lex_state = 0, .external_lex_state = 79}, + [909] = {.lex_state = 0, .external_lex_state = 79}, + [910] = {.lex_state = 0, .external_lex_state = 79}, + [911] = {.lex_state = 0, .external_lex_state = 79}, + [912] = {.lex_state = 0, .external_lex_state = 79}, + [913] = {.lex_state = 0, .external_lex_state = 79}, + [914] = {.lex_state = 0, .external_lex_state = 79}, + [915] = {.lex_state = 0, .external_lex_state = 79}, + [916] = {.lex_state = 0, .external_lex_state = 79}, + [917] = {.lex_state = 0, .external_lex_state = 83}, + [918] = {.lex_state = 0, .external_lex_state = 83}, + [919] = {.lex_state = 0, .external_lex_state = 77}, + [920] = {.lex_state = 0, .external_lex_state = 77}, + [921] = {.lex_state = 0, .external_lex_state = 77}, + [922] = {.lex_state = 0, .external_lex_state = 77}, + [923] = {.lex_state = 0, .external_lex_state = 77}, + [924] = {.lex_state = 0, .external_lex_state = 79}, + [925] = {.lex_state = 0, .external_lex_state = 79}, + [926] = {.lex_state = 0, .external_lex_state = 79}, + [927] = {.lex_state = 0, .external_lex_state = 79}, + [928] = {.lex_state = 0, .external_lex_state = 82}, + [929] = {.lex_state = 0, .external_lex_state = 79}, + [930] = {.lex_state = 0, .external_lex_state = 77}, + [931] = {.lex_state = 0, .external_lex_state = 79}, + [932] = {.lex_state = 0, .external_lex_state = 79}, + [933] = {.lex_state = 0, .external_lex_state = 79}, + [934] = {.lex_state = 0, .external_lex_state = 79}, + [935] = {.lex_state = 0, .external_lex_state = 79}, + [936] = {.lex_state = 0, .external_lex_state = 79}, + [937] = {.lex_state = 0, .external_lex_state = 79}, + [938] = {.lex_state = 0, .external_lex_state = 79}, + [939] = {.lex_state = 0, .external_lex_state = 83}, + [940] = {.lex_state = 0, .external_lex_state = 79}, + [941] = {.lex_state = 0, .external_lex_state = 79}, + [942] = {.lex_state = 0, .external_lex_state = 77}, + [943] = {.lex_state = 0, .external_lex_state = 79}, + [944] = {.lex_state = 0, .external_lex_state = 77}, + [945] = {.lex_state = 0, .external_lex_state = 77}, + [946] = {.lex_state = 0, .external_lex_state = 77}, + [947] = {.lex_state = 0, .external_lex_state = 77}, + [948] = {.lex_state = 0, .external_lex_state = 77}, + [949] = {.lex_state = 0, .external_lex_state = 77}, + [950] = {.lex_state = 0, .external_lex_state = 77}, + [951] = {.lex_state = 0, .external_lex_state = 79}, + [952] = {.lex_state = 0, .external_lex_state = 77}, + [953] = {.lex_state = 0, .external_lex_state = 77}, + [954] = {.lex_state = 0, .external_lex_state = 77}, + [955] = {.lex_state = 0, .external_lex_state = 77}, + [956] = {.lex_state = 0, .external_lex_state = 79}, + [957] = {.lex_state = 0, .external_lex_state = 77}, + [958] = {.lex_state = 0, .external_lex_state = 77}, + [959] = {.lex_state = 0, .external_lex_state = 77}, + [960] = {.lex_state = 0, .external_lex_state = 77}, + [961] = {.lex_state = 0, .external_lex_state = 79}, + [962] = {.lex_state = 0, .external_lex_state = 79}, + [963] = {.lex_state = 0, .external_lex_state = 84}, + [964] = {.lex_state = 0, .external_lex_state = 85}, + [965] = {.lex_state = 0, .external_lex_state = 86}, + [966] = {.lex_state = 0, .external_lex_state = 86}, + [967] = {.lex_state = 0, .external_lex_state = 87}, + [968] = {.lex_state = 0, .external_lex_state = 72}, + [969] = {.lex_state = 0, .external_lex_state = 87}, + [970] = {.lex_state = 0, .external_lex_state = 88}, + [971] = {.lex_state = 0, .external_lex_state = 88}, + [972] = {.lex_state = 0, .external_lex_state = 89}, + [973] = {.lex_state = 0, .external_lex_state = 86}, + [974] = {.lex_state = 0, .external_lex_state = 86}, + [975] = {.lex_state = 0, .external_lex_state = 89}, + [976] = {.lex_state = 0, .external_lex_state = 90}, + [977] = {.lex_state = 0, .external_lex_state = 88}, + [978] = {.lex_state = 0, .external_lex_state = 89}, + [979] = {.lex_state = 0, .external_lex_state = 86}, + [980] = {.lex_state = 0, .external_lex_state = 82}, + [981] = {.lex_state = 0, .external_lex_state = 82}, + [982] = {.lex_state = 0, .external_lex_state = 88}, + [983] = {.lex_state = 0, .external_lex_state = 89}, + [984] = {.lex_state = 0, .external_lex_state = 82}, + [985] = {.lex_state = 0, .external_lex_state = 83}, + [986] = {.lex_state = 0, .external_lex_state = 84}, + [987] = {.lex_state = 0, .external_lex_state = 83}, + [988] = {.lex_state = 0, .external_lex_state = 83}, + [989] = {.lex_state = 0, .external_lex_state = 83}, + [990] = {.lex_state = 0, .external_lex_state = 83}, + [991] = {.lex_state = 0, .external_lex_state = 82}, + [992] = {.lex_state = 0, .external_lex_state = 88}, + [993] = {.lex_state = 0, .external_lex_state = 88}, + [994] = {.lex_state = 0, .external_lex_state = 89}, + [995] = {.lex_state = 0, .external_lex_state = 86}, + [996] = {.lex_state = 0, .external_lex_state = 83}, + [997] = {.lex_state = 0, .external_lex_state = 83}, + [998] = {.lex_state = 0, .external_lex_state = 86}, + [999] = {.lex_state = 0, .external_lex_state = 83}, + [1000] = {.lex_state = 0, .external_lex_state = 83}, + [1001] = {.lex_state = 0, .external_lex_state = 83}, + [1002] = {.lex_state = 0, .external_lex_state = 86}, + [1003] = {.lex_state = 0, .external_lex_state = 86}, + [1004] = {.lex_state = 0, .external_lex_state = 86}, + [1005] = {.lex_state = 0, .external_lex_state = 83}, + [1006] = {.lex_state = 0, .external_lex_state = 88}, + [1007] = {.lex_state = 0, .external_lex_state = 89}, + [1008] = {.lex_state = 0, .external_lex_state = 83}, + [1009] = {.lex_state = 0, .external_lex_state = 91}, + [1010] = {.lex_state = 0, .external_lex_state = 88}, + [1011] = {.lex_state = 0, .external_lex_state = 89}, + [1012] = {.lex_state = 0, .external_lex_state = 85}, + [1013] = {.lex_state = 0, .external_lex_state = 89}, + [1014] = {.lex_state = 0, .external_lex_state = 88}, + [1015] = {.lex_state = 0, .external_lex_state = 72}, + [1016] = {.lex_state = 0, .external_lex_state = 84}, + [1017] = {.lex_state = 0, .external_lex_state = 88}, + [1018] = {.lex_state = 0, .external_lex_state = 91}, + [1019] = {.lex_state = 0, .external_lex_state = 89}, + [1020] = {.lex_state = 0, .external_lex_state = 88}, + [1021] = {.lex_state = 0, .external_lex_state = 89}, + [1022] = {.lex_state = 0, .external_lex_state = 86}, + [1023] = {.lex_state = 0, .external_lex_state = 88}, + [1024] = {.lex_state = 0, .external_lex_state = 89}, + [1025] = {.lex_state = 0, .external_lex_state = 92}, + [1026] = {.lex_state = 0, .external_lex_state = 86}, + [1027] = {.lex_state = 0, .external_lex_state = 88}, + [1028] = {.lex_state = 0, .external_lex_state = 89}, + [1029] = {.lex_state = 0, .external_lex_state = 89}, + [1030] = {.lex_state = 0, .external_lex_state = 83}, + [1031] = {.lex_state = 0, .external_lex_state = 91}, + [1032] = {.lex_state = 0, .external_lex_state = 88}, + [1033] = {.lex_state = 0, .external_lex_state = 89}, + [1034] = {.lex_state = 0, .external_lex_state = 85}, + [1035] = {.lex_state = 0, .external_lex_state = 91}, + [1036] = {.lex_state = 0, .external_lex_state = 83}, + [1037] = {.lex_state = 0, .external_lex_state = 83}, + [1038] = {.lex_state = 0, .external_lex_state = 93}, + [1039] = {.lex_state = 0, .external_lex_state = 83}, + [1040] = {.lex_state = 0, .external_lex_state = 83}, + [1041] = {.lex_state = 0, .external_lex_state = 86}, + [1042] = {.lex_state = 0, .external_lex_state = 88}, + [1043] = {.lex_state = 0, .external_lex_state = 89}, + [1044] = {.lex_state = 0, .external_lex_state = 83}, + [1045] = {.lex_state = 0, .external_lex_state = 94}, + [1046] = {.lex_state = 0, .external_lex_state = 83}, + [1047] = {.lex_state = 0, .external_lex_state = 83}, + [1048] = {.lex_state = 0, .external_lex_state = 86}, + [1049] = {.lex_state = 0, .external_lex_state = 70}, + [1050] = {.lex_state = 0, .external_lex_state = 94}, + [1051] = {.lex_state = 0, .external_lex_state = 94}, + [1052] = {.lex_state = 0, .external_lex_state = 94}, + [1053] = {.lex_state = 0, .external_lex_state = 94}, + [1054] = {.lex_state = 0, .external_lex_state = 94}, + [1055] = {.lex_state = 0, .external_lex_state = 70}, + [1056] = {.lex_state = 0, .external_lex_state = 95}, + [1057] = {.lex_state = 0, .external_lex_state = 70}, + [1058] = {.lex_state = 0, .external_lex_state = 96}, + [1059] = {.lex_state = 0, .external_lex_state = 93}, + [1060] = {.lex_state = 0, .external_lex_state = 70}, + [1061] = {.lex_state = 0, .external_lex_state = 94}, + [1062] = {.lex_state = 0, .external_lex_state = 94}, + [1063] = {.lex_state = 0, .external_lex_state = 70}, + [1064] = {.lex_state = 0, .external_lex_state = 94}, + [1065] = {.lex_state = 0, .external_lex_state = 70}, + [1066] = {.lex_state = 0, .external_lex_state = 95}, + [1067] = {.lex_state = 0, .external_lex_state = 94}, + [1068] = {.lex_state = 0, .external_lex_state = 94}, + [1069] = {.lex_state = 0, .external_lex_state = 70}, + [1070] = {.lex_state = 0, .external_lex_state = 70}, + [1071] = {.lex_state = 0, .external_lex_state = 70}, + [1072] = {.lex_state = 0, .external_lex_state = 94}, + [1073] = {.lex_state = 0, .external_lex_state = 70}, + [1074] = {.lex_state = 0, .external_lex_state = 94}, + [1075] = {.lex_state = 0, .external_lex_state = 70}, + [1076] = {.lex_state = 0, .external_lex_state = 70}, + [1077] = {.lex_state = 0, .external_lex_state = 90}, + [1078] = {.lex_state = 0, .external_lex_state = 95}, + [1079] = {.lex_state = 0, .external_lex_state = 87}, + [1080] = {.lex_state = 0, .external_lex_state = 70}, + [1081] = {.lex_state = 0, .external_lex_state = 95}, + [1082] = {.lex_state = 0, .external_lex_state = 70}, + [1083] = {.lex_state = 0, .external_lex_state = 70}, + [1084] = {.lex_state = 0, .external_lex_state = 90}, + [1085] = {.lex_state = 0, .external_lex_state = 70}, + [1086] = {.lex_state = 0, .external_lex_state = 70}, + [1087] = {.lex_state = 0, .external_lex_state = 70}, + [1088] = {.lex_state = 0, .external_lex_state = 70}, + [1089] = {.lex_state = 0, .external_lex_state = 95}, + [1090] = {.lex_state = 0, .external_lex_state = 70}, + [1091] = {.lex_state = 0, .external_lex_state = 70}, + [1092] = {.lex_state = 0, .external_lex_state = 70}, + [1093] = {.lex_state = 0, .external_lex_state = 70}, + [1094] = {.lex_state = 0, .external_lex_state = 70}, + [1095] = {.lex_state = 0, .external_lex_state = 70}, + [1096] = {.lex_state = 0, .external_lex_state = 70}, + [1097] = {.lex_state = 0, .external_lex_state = 90}, + [1098] = {.lex_state = 0, .external_lex_state = 70}, + [1099] = {.lex_state = 0, .external_lex_state = 90}, + [1100] = {.lex_state = 0, .external_lex_state = 93}, + [1101] = {.lex_state = 0, .external_lex_state = 93}, + [1102] = {.lex_state = 0, .external_lex_state = 70}, + [1103] = {.lex_state = 0, .external_lex_state = 70}, + [1104] = {.lex_state = 0, .external_lex_state = 70}, + [1105] = {.lex_state = 0, .external_lex_state = 70}, + [1106] = {.lex_state = 0, .external_lex_state = 70}, + [1107] = {.lex_state = 0, .external_lex_state = 87}, + [1108] = {.lex_state = 0, .external_lex_state = 70}, + [1109] = {.lex_state = 0, .external_lex_state = 70}, + [1110] = {.lex_state = 0, .external_lex_state = 92}, + [1111] = {.lex_state = 0, .external_lex_state = 95}, + [1112] = {.lex_state = 0, .external_lex_state = 95}, + [1113] = {.lex_state = 0, .external_lex_state = 92}, + [1114] = {.lex_state = 0, .external_lex_state = 92}, + [1115] = {.lex_state = 0, .external_lex_state = 70}, + [1116] = {.lex_state = 0, .external_lex_state = 92}, + [1117] = {.lex_state = 0, .external_lex_state = 87}, + [1118] = {.lex_state = 0, .external_lex_state = 87}, + [1119] = {.lex_state = 0, .external_lex_state = 70}, + [1120] = {.lex_state = 0, .external_lex_state = 95}, + [1121] = {.lex_state = 0, .external_lex_state = 95}, + [1122] = {.lex_state = 0, .external_lex_state = 87}, + [1123] = {.lex_state = 0, .external_lex_state = 70}, + [1124] = {.lex_state = 0, .external_lex_state = 96}, + [1125] = {.lex_state = 0, .external_lex_state = 97}, + [1126] = {.lex_state = 0, .external_lex_state = 70}, + [1127] = {.lex_state = 0, .external_lex_state = 70}, + [1128] = {.lex_state = 0, .external_lex_state = 87}, + [1129] = {.lex_state = 0, .external_lex_state = 70}, + [1130] = {.lex_state = 0, .external_lex_state = 70}, + [1131] = {.lex_state = 0, .external_lex_state = 70}, + [1132] = {.lex_state = 0, .external_lex_state = 90}, + [1133] = {.lex_state = 0, .external_lex_state = 70}, + [1134] = {.lex_state = 0, .external_lex_state = 70}, + [1135] = {.lex_state = 0, .external_lex_state = 70}, + [1136] = {.lex_state = 0, .external_lex_state = 70}, + [1137] = {.lex_state = 0, .external_lex_state = 87}, + [1138] = {.lex_state = 0, .external_lex_state = 97}, + [1139] = {.lex_state = 0, .external_lex_state = 92}, + [1140] = {.lex_state = 0, .external_lex_state = 95}, + [1141] = {.lex_state = 0, .external_lex_state = 95}, + [1142] = {.lex_state = 0, .external_lex_state = 70}, + [1143] = {.lex_state = 0, .external_lex_state = 70}, + [1144] = {.lex_state = 0, .external_lex_state = 87}, + [1145] = {.lex_state = 0, .external_lex_state = 92}, + [1146] = {.lex_state = 0, .external_lex_state = 87}, + [1147] = {.lex_state = 0, .external_lex_state = 95}, + [1148] = {.lex_state = 0, .external_lex_state = 95}, + [1149] = {.lex_state = 0, .external_lex_state = 87}, + [1150] = {.lex_state = 0, .external_lex_state = 87}, + [1151] = {.lex_state = 0, .external_lex_state = 96}, + [1152] = {.lex_state = 0, .external_lex_state = 97}, + [1153] = {.lex_state = 0, .external_lex_state = 87}, + [1154] = {.lex_state = 0, .external_lex_state = 70}, + [1155] = {.lex_state = 0, .external_lex_state = 70}, + [1156] = {.lex_state = 0, .external_lex_state = 70}, + [1157] = {.lex_state = 0, .external_lex_state = 70}, + [1158] = {.lex_state = 0, .external_lex_state = 87}, + [1159] = {.lex_state = 0, .external_lex_state = 87}, + [1160] = {.lex_state = 0, .external_lex_state = 87}, + [1161] = {.lex_state = 0, .external_lex_state = 92}, + [1162] = {.lex_state = 0, .external_lex_state = 92}, + [1163] = {.lex_state = 0, .external_lex_state = 92}, + [1164] = {.lex_state = 0, .external_lex_state = 92}, + [1165] = {.lex_state = 0, .external_lex_state = 96}, + [1166] = {.lex_state = 0, .external_lex_state = 97}, + [1167] = {.lex_state = 0, .external_lex_state = 70}, + [1168] = {.lex_state = 0, .external_lex_state = 70}, + [1169] = {.lex_state = 0, .external_lex_state = 70}, + [1170] = {.lex_state = 0, .external_lex_state = 70}, + [1171] = {.lex_state = 0, .external_lex_state = 93}, + [1172] = {.lex_state = 0, .external_lex_state = 96}, + [1173] = {.lex_state = 0, .external_lex_state = 97}, + [1174] = {.lex_state = 0, .external_lex_state = 92}, + [1175] = {.lex_state = 0, .external_lex_state = 70}, + [1176] = {.lex_state = 0, .external_lex_state = 70}, + [1177] = {.lex_state = 0, .external_lex_state = 70}, + [1178] = {.lex_state = 0, .external_lex_state = 92}, + [1179] = {.lex_state = 0, .external_lex_state = 87}, + [1180] = {.lex_state = 0, .external_lex_state = 87}, + [1181] = {.lex_state = 0, .external_lex_state = 87}, + [1182] = {.lex_state = 0, .external_lex_state = 96}, + [1183] = {.lex_state = 0, .external_lex_state = 97}, + [1184] = {.lex_state = 0, .external_lex_state = 87}, + [1185] = {.lex_state = 0, .external_lex_state = 70}, + [1186] = {.lex_state = 0, .external_lex_state = 70}, + [1187] = {.lex_state = 0, .external_lex_state = 93}, + [1188] = {.lex_state = 0, .external_lex_state = 70}, + [1189] = {.lex_state = 0, .external_lex_state = 92}, + [1190] = {.lex_state = 0, .external_lex_state = 92}, + [1191] = {.lex_state = 0, .external_lex_state = 70}, + [1192] = {.lex_state = 0, .external_lex_state = 70}, + [1193] = {.lex_state = 0, .external_lex_state = 96}, + [1194] = {.lex_state = 0, .external_lex_state = 97}, + [1195] = {.lex_state = 0, .external_lex_state = 92}, + [1196] = {.lex_state = 0, .external_lex_state = 92}, + [1197] = {.lex_state = 0, .external_lex_state = 70}, + [1198] = {.lex_state = 0, .external_lex_state = 87}, + [1199] = {.lex_state = 0, .external_lex_state = 70}, + [1200] = {.lex_state = 0, .external_lex_state = 70}, + [1201] = {.lex_state = 0, .external_lex_state = 70}, + [1202] = {.lex_state = 0, .external_lex_state = 70}, + [1203] = {.lex_state = 0, .external_lex_state = 70}, + [1204] = {.lex_state = 0, .external_lex_state = 70}, + [1205] = {.lex_state = 0, .external_lex_state = 70}, + [1206] = {.lex_state = 0, .external_lex_state = 70}, + [1207] = {.lex_state = 0, .external_lex_state = 70}, + [1208] = {.lex_state = 0, .external_lex_state = 70}, + [1209] = {.lex_state = 0, .external_lex_state = 94}, + [1210] = {.lex_state = 0, .external_lex_state = 94}, + [1211] = {.lex_state = 0, .external_lex_state = 96}, + [1212] = {.lex_state = 0, .external_lex_state = 97}, + [1213] = {.lex_state = 0, .external_lex_state = 94}, + [1214] = {.lex_state = 0, .external_lex_state = 94}, + [1215] = {.lex_state = 0, .external_lex_state = 70}, + [1216] = {.lex_state = 0, .external_lex_state = 82}, + [1217] = {.lex_state = 0, .external_lex_state = 86}, + [1218] = {.lex_state = 0, .external_lex_state = 86}, + [1219] = {.lex_state = 0, .external_lex_state = 84}, + [1220] = {.lex_state = 0, .external_lex_state = 86}, + [1221] = {.lex_state = 0, .external_lex_state = 86}, + [1222] = {.lex_state = 0, .external_lex_state = 82}, + [1223] = {.lex_state = 0, .external_lex_state = 84}, + [1224] = {.lex_state = 0, .external_lex_state = 84}, + [1225] = {.lex_state = 0, .external_lex_state = 84}, + [1226] = {.lex_state = 0, .external_lex_state = 84}, + [1227] = {.lex_state = 0, .external_lex_state = 98}, + [1228] = {.lex_state = 0, .external_lex_state = 84}, + [1229] = {.lex_state = 0, .external_lex_state = 86}, + [1230] = {.lex_state = 0, .external_lex_state = 86}, + [1231] = {.lex_state = 0, .external_lex_state = 84}, + [1232] = {.lex_state = 0, .external_lex_state = 84}, + [1233] = {.lex_state = 0, .external_lex_state = 84}, + [1234] = {.lex_state = 0, .external_lex_state = 84}, + [1235] = {.lex_state = 0, .external_lex_state = 84}, + [1236] = {.lex_state = 0, .external_lex_state = 85}, + [1237] = {.lex_state = 0, .external_lex_state = 98}, + [1238] = {.lex_state = 0, .external_lex_state = 84}, + [1239] = {.lex_state = 0, .external_lex_state = 99}, + [1240] = {.lex_state = 0, .external_lex_state = 84}, + [1241] = {.lex_state = 0, .external_lex_state = 84}, + [1242] = {.lex_state = 0, .external_lex_state = 100}, + [1243] = {.lex_state = 0, .external_lex_state = 82}, + [1244] = {.lex_state = 0, .external_lex_state = 100}, + [1245] = {.lex_state = 0, .external_lex_state = 84}, + [1246] = {.lex_state = 0, .external_lex_state = 82}, + [1247] = {.lex_state = 0, .external_lex_state = 86}, + [1248] = {.lex_state = 0, .external_lex_state = 82}, + [1249] = {.lex_state = 0, .external_lex_state = 84}, + [1250] = {.lex_state = 0, .external_lex_state = 85}, + [1251] = {.lex_state = 0, .external_lex_state = 85}, + [1252] = {.lex_state = 0, .external_lex_state = 85}, + [1253] = {.lex_state = 0, .external_lex_state = 84}, + [1254] = {.lex_state = 0, .external_lex_state = 82}, + [1255] = {.lex_state = 0, .external_lex_state = 84}, + [1256] = {.lex_state = 0, .external_lex_state = 86}, + [1257] = {.lex_state = 0, .external_lex_state = 84}, + [1258] = {.lex_state = 0, .external_lex_state = 86}, + [1259] = {.lex_state = 0, .external_lex_state = 86}, + [1260] = {.lex_state = 0, .external_lex_state = 86}, + [1261] = {.lex_state = 0, .external_lex_state = 86}, + [1262] = {.lex_state = 0, .external_lex_state = 82}, + [1263] = {.lex_state = 0, .external_lex_state = 82}, + [1264] = {.lex_state = 0, .external_lex_state = 84}, + [1265] = {.lex_state = 0, .external_lex_state = 86}, + [1266] = {.lex_state = 0, .external_lex_state = 86}, + [1267] = {.lex_state = 0, .external_lex_state = 86}, + [1268] = {.lex_state = 0, .external_lex_state = 86}, + [1269] = {.lex_state = 0, .external_lex_state = 84}, + [1270] = {.lex_state = 0, .external_lex_state = 84}, + [1271] = {.lex_state = 0, .external_lex_state = 84}, + [1272] = {.lex_state = 0, .external_lex_state = 82}, + [1273] = {.lex_state = 0, .external_lex_state = 86}, + [1274] = {.lex_state = 0, .external_lex_state = 86}, + [1275] = {.lex_state = 0, .external_lex_state = 86}, + [1276] = {.lex_state = 0, .external_lex_state = 86}, + [1277] = {.lex_state = 0, .external_lex_state = 86}, + [1278] = {.lex_state = 0, .external_lex_state = 86}, + [1279] = {.lex_state = 0, .external_lex_state = 86}, + [1280] = {.lex_state = 0, .external_lex_state = 86}, + [1281] = {.lex_state = 0, .external_lex_state = 86}, + [1282] = {.lex_state = 0, .external_lex_state = 91}, + [1283] = {.lex_state = 0, .external_lex_state = 91}, + [1284] = {.lex_state = 0, .external_lex_state = 86}, + [1285] = {.lex_state = 0, .external_lex_state = 86}, + [1286] = {.lex_state = 0, .external_lex_state = 86}, + [1287] = {.lex_state = 0, .external_lex_state = 86}, + [1288] = {.lex_state = 0, .external_lex_state = 86}, + [1289] = {.lex_state = 0, .external_lex_state = 86}, + [1290] = {.lex_state = 0, .external_lex_state = 86}, + [1291] = {.lex_state = 0, .external_lex_state = 86}, + [1292] = {.lex_state = 0, .external_lex_state = 84}, + [1293] = {.lex_state = 0, .external_lex_state = 84}, + [1294] = {.lex_state = 0, .external_lex_state = 86}, + [1295] = {.lex_state = 0, .external_lex_state = 86}, + [1296] = {.lex_state = 0, .external_lex_state = 86}, + [1297] = {.lex_state = 0, .external_lex_state = 86}, + [1298] = {.lex_state = 0, .external_lex_state = 85}, + [1299] = {.lex_state = 0, .external_lex_state = 98}, + [1300] = {.lex_state = 0, .external_lex_state = 86}, + [1301] = {.lex_state = 0, .external_lex_state = 85}, + [1302] = {.lex_state = 0, .external_lex_state = 91}, + [1303] = {.lex_state = 0, .external_lex_state = 86}, + [1304] = {.lex_state = 0, .external_lex_state = 91}, + [1305] = {.lex_state = 0, .external_lex_state = 85}, + [1306] = {.lex_state = 0, .external_lex_state = 91}, + [1307] = {.lex_state = 0, .external_lex_state = 91}, + [1308] = {.lex_state = 0, .external_lex_state = 85}, + [1309] = {.lex_state = 0, .external_lex_state = 91}, + [1310] = {.lex_state = 0, .external_lex_state = 91}, + [1311] = {.lex_state = 0, .external_lex_state = 85}, + [1312] = {.lex_state = 0, .external_lex_state = 85}, + [1313] = {.lex_state = 0, .external_lex_state = 86}, + [1314] = {.lex_state = 0, .external_lex_state = 91}, + [1315] = {.lex_state = 0, .external_lex_state = 82}, + [1316] = {.lex_state = 0, .external_lex_state = 91}, + [1317] = {.lex_state = 0, .external_lex_state = 85}, + [1318] = {.lex_state = 0, .external_lex_state = 91}, + [1319] = {.lex_state = 0, .external_lex_state = 85}, + [1320] = {.lex_state = 0, .external_lex_state = 91}, + [1321] = {.lex_state = 0, .external_lex_state = 91}, + [1322] = {.lex_state = 0, .external_lex_state = 85}, + [1323] = {.lex_state = 0, .external_lex_state = 91}, + [1324] = {.lex_state = 0, .external_lex_state = 91}, + [1325] = {.lex_state = 0, .external_lex_state = 91}, + [1326] = {.lex_state = 0, .external_lex_state = 84}, + [1327] = {.lex_state = 0, .external_lex_state = 84}, + [1328] = {.lex_state = 0, .external_lex_state = 91}, + [1329] = {.lex_state = 0, .external_lex_state = 91}, + [1330] = {.lex_state = 0, .external_lex_state = 91}, + [1331] = {.lex_state = 0, .external_lex_state = 91}, + [1332] = {.lex_state = 0, .external_lex_state = 85}, + [1333] = {.lex_state = 0, .external_lex_state = 86}, + [1334] = {.lex_state = 0, .external_lex_state = 91}, + [1335] = {.lex_state = 0, .external_lex_state = 84}, + [1336] = {.lex_state = 0, .external_lex_state = 85}, + [1337] = {.lex_state = 0, .external_lex_state = 85}, + [1338] = {.lex_state = 0, .external_lex_state = 91}, + [1339] = {.lex_state = 0, .external_lex_state = 91}, + [1340] = {.lex_state = 0, .external_lex_state = 91}, + [1341] = {.lex_state = 0, .external_lex_state = 91}, + [1342] = {.lex_state = 0, .external_lex_state = 91}, + [1343] = {.lex_state = 0, .external_lex_state = 91}, + [1344] = {.lex_state = 0, .external_lex_state = 86}, + [1345] = {.lex_state = 0, .external_lex_state = 82}, + [1346] = {.lex_state = 0, .external_lex_state = 91}, + [1347] = {.lex_state = 0, .external_lex_state = 86}, + [1348] = {.lex_state = 0, .external_lex_state = 84}, + [1349] = {.lex_state = 0, .external_lex_state = 91}, + [1350] = {.lex_state = 0, .external_lex_state = 86}, + [1351] = {.lex_state = 0, .external_lex_state = 86}, + [1352] = {.lex_state = 0, .external_lex_state = 84}, + [1353] = {.lex_state = 0, .external_lex_state = 85}, + [1354] = {.lex_state = 0, .external_lex_state = 85}, + [1355] = {.lex_state = 0, .external_lex_state = 86}, + [1356] = {.lex_state = 0, .external_lex_state = 85}, + [1357] = {.lex_state = 0, .external_lex_state = 85}, + [1358] = {.lex_state = 0, .external_lex_state = 85}, + [1359] = {.lex_state = 0, .external_lex_state = 99}, + [1360] = {.lex_state = 0, .external_lex_state = 85}, + [1361] = {.lex_state = 0, .external_lex_state = 91}, + [1362] = {.lex_state = 0, .external_lex_state = 86}, + [1363] = {.lex_state = 0, .external_lex_state = 86}, + [1364] = {.lex_state = 0, .external_lex_state = 86}, + [1365] = {.lex_state = 0, .external_lex_state = 86}, + [1366] = {.lex_state = 0, .external_lex_state = 85}, + [1367] = {.lex_state = 0, .external_lex_state = 91}, + [1368] = {.lex_state = 0, .external_lex_state = 85}, + [1369] = {.lex_state = 0, .external_lex_state = 91}, + [1370] = {.lex_state = 0, .external_lex_state = 91}, + [1371] = {.lex_state = 0, .external_lex_state = 85}, + [1372] = {.lex_state = 0, .external_lex_state = 85}, + [1373] = {.lex_state = 0, .external_lex_state = 91}, + [1374] = {.lex_state = 0, .external_lex_state = 91}, + [1375] = {.lex_state = 0, .external_lex_state = 86}, + [1376] = {.lex_state = 0, .external_lex_state = 86}, + [1377] = {.lex_state = 0, .external_lex_state = 86}, + [1378] = {.lex_state = 0, .external_lex_state = 86}, + [1379] = {.lex_state = 0, .external_lex_state = 84}, + [1380] = {.lex_state = 0, .external_lex_state = 86}, + [1381] = {.lex_state = 0, .external_lex_state = 86}, + [1382] = {.lex_state = 0, .external_lex_state = 86}, + [1383] = {.lex_state = 0, .external_lex_state = 86}, + [1384] = {.lex_state = 0, .external_lex_state = 91}, + [1385] = {.lex_state = 0, .external_lex_state = 91}, + [1386] = {.lex_state = 0, .external_lex_state = 86}, + [1387] = {.lex_state = 0, .external_lex_state = 86}, + [1388] = {.lex_state = 0, .external_lex_state = 86}, + [1389] = {.lex_state = 0, .external_lex_state = 86}, + [1390] = {.lex_state = 0, .external_lex_state = 86}, + [1391] = {.lex_state = 0, .external_lex_state = 85}, + [1392] = {.lex_state = 0, .external_lex_state = 85}, + [1393] = {.lex_state = 0, .external_lex_state = 86}, + [1394] = {.lex_state = 0, .external_lex_state = 86}, + [1395] = {.lex_state = 0, .external_lex_state = 86}, + [1396] = {.lex_state = 0, .external_lex_state = 91}, + [1397] = {.lex_state = 0, .external_lex_state = 91}, + [1398] = {.lex_state = 0, .external_lex_state = 82}, + [1399] = {.lex_state = 0, .external_lex_state = 91}, + [1400] = {.lex_state = 0, .external_lex_state = 82}, + [1401] = {.lex_state = 0, .external_lex_state = 86}, + [1402] = {.lex_state = 0, .external_lex_state = 86}, + [1403] = {.lex_state = 0, .external_lex_state = 91}, + [1404] = {.lex_state = 0, .external_lex_state = 86}, + [1405] = {.lex_state = 0, .external_lex_state = 85}, + [1406] = {.lex_state = 0, .external_lex_state = 85}, + [1407] = {.lex_state = 0, .external_lex_state = 86}, + [1408] = {.lex_state = 0, .external_lex_state = 91}, + [1409] = {.lex_state = 0, .external_lex_state = 85}, + [1410] = {.lex_state = 0, .external_lex_state = 101}, + [1411] = {.lex_state = 0, .external_lex_state = 98}, + [1412] = {.lex_state = 0, .external_lex_state = 98}, + [1413] = {.lex_state = 0, .external_lex_state = 98}, + [1414] = {.lex_state = 0, .external_lex_state = 100}, + [1415] = {.lex_state = 0, .external_lex_state = 98}, + [1416] = {.lex_state = 0, .external_lex_state = 98}, + [1417] = {.lex_state = 0, .external_lex_state = 98}, + [1418] = {.lex_state = 0, .external_lex_state = 98}, + [1419] = {.lex_state = 0, .external_lex_state = 98}, + [1420] = {.lex_state = 0, .external_lex_state = 98}, + [1421] = {.lex_state = 0, .external_lex_state = 98}, + [1422] = {.lex_state = 0, .external_lex_state = 100}, + [1423] = {.lex_state = 0, .external_lex_state = 98}, + [1424] = {.lex_state = 0, .external_lex_state = 98}, + [1425] = {.lex_state = 0, .external_lex_state = 98}, + [1426] = {.lex_state = 0, .external_lex_state = 102}, + [1427] = {.lex_state = 0, .external_lex_state = 103}, + [1428] = {.lex_state = 0, .external_lex_state = 104}, + [1429] = {.lex_state = 0, .external_lex_state = 102}, + [1430] = {.lex_state = 0, .external_lex_state = 101}, + [1431] = {.lex_state = 0, .external_lex_state = 101}, + [1432] = {.lex_state = 0, .external_lex_state = 105}, + [1433] = {.lex_state = 0, .external_lex_state = 101}, + [1434] = {.lex_state = 0, .external_lex_state = 101}, + [1435] = {.lex_state = 0, .external_lex_state = 105}, + [1436] = {.lex_state = 0, .external_lex_state = 105}, + [1437] = {.lex_state = 0, .external_lex_state = 105}, + [1438] = {.lex_state = 0, .external_lex_state = 101}, + [1439] = {.lex_state = 0, .external_lex_state = 101}, + [1440] = {.lex_state = 0, .external_lex_state = 105}, + [1441] = {.lex_state = 0, .external_lex_state = 105}, + [1442] = {.lex_state = 0, .external_lex_state = 98}, + [1443] = {.lex_state = 0, .external_lex_state = 98}, + [1444] = {.lex_state = 0, .external_lex_state = 98}, + [1445] = {.lex_state = 0, .external_lex_state = 98}, + [1446] = {.lex_state = 0, .external_lex_state = 98}, + [1447] = {.lex_state = 0, .external_lex_state = 106}, + [1448] = {.lex_state = 0, .external_lex_state = 100}, + [1449] = {.lex_state = 0, .external_lex_state = 107}, + [1450] = {.lex_state = 0, .external_lex_state = 98}, + [1451] = {.lex_state = 0, .external_lex_state = 100}, + [1452] = {.lex_state = 0, .external_lex_state = 102}, + [1453] = {.lex_state = 0, .external_lex_state = 98}, + [1454] = {.lex_state = 0, .external_lex_state = 108}, + [1455] = {.lex_state = 0, .external_lex_state = 99}, + [1456] = {.lex_state = 0, .external_lex_state = 104}, + [1457] = {.lex_state = 0, .external_lex_state = 106}, + [1458] = {.lex_state = 0, .external_lex_state = 100}, + [1459] = {.lex_state = 0, .external_lex_state = 106}, + [1460] = {.lex_state = 0, .external_lex_state = 107}, + [1461] = {.lex_state = 0, .external_lex_state = 98}, + [1462] = {.lex_state = 0, .external_lex_state = 99}, + [1463] = {.lex_state = 0, .external_lex_state = 100}, + [1464] = {.lex_state = 0, .external_lex_state = 98}, + [1465] = {.lex_state = 0, .external_lex_state = 102}, + [1466] = {.lex_state = 0, .external_lex_state = 100}, + [1467] = {.lex_state = 0, .external_lex_state = 100}, + [1468] = {.lex_state = 0, .external_lex_state = 106}, + [1469] = {.lex_state = 0, .external_lex_state = 100}, + [1470] = {.lex_state = 0, .external_lex_state = 99}, + [1471] = {.lex_state = 0, .external_lex_state = 107}, + [1472] = {.lex_state = 0, .external_lex_state = 101}, + [1473] = {.lex_state = 0, .external_lex_state = 106}, + [1474] = {.lex_state = 0, .external_lex_state = 105}, + [1475] = {.lex_state = 0, .external_lex_state = 99}, + [1476] = {.lex_state = 0, .external_lex_state = 107}, + [1477] = {.lex_state = 0, .external_lex_state = 98}, + [1478] = {.lex_state = 0, .external_lex_state = 101}, + [1479] = {.lex_state = 0, .external_lex_state = 101}, + [1480] = {.lex_state = 0, .external_lex_state = 105}, + [1481] = {.lex_state = 0, .external_lex_state = 105}, + [1482] = {.lex_state = 0, .external_lex_state = 100}, + [1483] = {.lex_state = 0, .external_lex_state = 101}, + [1484] = {.lex_state = 0, .external_lex_state = 101}, + [1485] = {.lex_state = 0, .external_lex_state = 98}, + [1486] = {.lex_state = 0, .external_lex_state = 105}, + [1487] = {.lex_state = 0, .external_lex_state = 98}, + [1488] = {.lex_state = 0, .external_lex_state = 105}, + [1489] = {.lex_state = 0, .external_lex_state = 104}, + [1490] = {.lex_state = 0, .external_lex_state = 104}, + [1491] = {.lex_state = 0, .external_lex_state = 98}, + [1492] = {.lex_state = 0, .external_lex_state = 98}, + [1493] = {.lex_state = 0, .external_lex_state = 98}, + [1494] = {.lex_state = 0, .external_lex_state = 105}, + [1495] = {.lex_state = 0, .external_lex_state = 100}, + [1496] = {.lex_state = 0, .external_lex_state = 98}, + [1497] = {.lex_state = 0, .external_lex_state = 98}, + [1498] = {.lex_state = 0, .external_lex_state = 101}, + [1499] = {.lex_state = 0, .external_lex_state = 98}, + [1500] = {.lex_state = 0, .external_lex_state = 98}, + [1501] = {.lex_state = 0, .external_lex_state = 98}, + [1502] = {.lex_state = 0, .external_lex_state = 98}, + [1503] = {.lex_state = 0, .external_lex_state = 101}, + [1504] = {.lex_state = 0, .external_lex_state = 105}, + [1505] = {.lex_state = 0, .external_lex_state = 105}, + [1506] = {.lex_state = 0, .external_lex_state = 100}, + [1507] = {.lex_state = 0, .external_lex_state = 100}, + [1508] = {.lex_state = 0, .external_lex_state = 105}, + [1509] = {.lex_state = 0, .external_lex_state = 100}, + [1510] = {.lex_state = 0, .external_lex_state = 101}, + [1511] = {.lex_state = 0, .external_lex_state = 101}, + [1512] = {.lex_state = 0, .external_lex_state = 105}, + [1513] = {.lex_state = 0, .external_lex_state = 105}, + [1514] = {.lex_state = 0, .external_lex_state = 98}, + [1515] = {.lex_state = 0, .external_lex_state = 109}, + [1516] = {.lex_state = 0, .external_lex_state = 107}, + [1517] = {.lex_state = 0, .external_lex_state = 98}, + [1518] = {.lex_state = 0, .external_lex_state = 99}, + [1519] = {.lex_state = 0, .external_lex_state = 101}, + [1520] = {.lex_state = 0, .external_lex_state = 98}, + [1521] = {.lex_state = 0, .external_lex_state = 98}, + [1522] = {.lex_state = 0, .external_lex_state = 98}, + [1523] = {.lex_state = 0, .external_lex_state = 98}, + [1524] = {.lex_state = 0, .external_lex_state = 98}, + [1525] = {.lex_state = 0, .external_lex_state = 106}, + [1526] = {.lex_state = 0, .external_lex_state = 104}, + [1527] = {.lex_state = 0, .external_lex_state = 107}, + [1528] = {.lex_state = 0, .external_lex_state = 98}, + [1529] = {.lex_state = 0, .external_lex_state = 98}, + [1530] = {.lex_state = 0, .external_lex_state = 98}, + [1531] = {.lex_state = 0, .external_lex_state = 98}, + [1532] = {.lex_state = 0, .external_lex_state = 98}, + [1533] = {.lex_state = 0, .external_lex_state = 98}, + [1534] = {.lex_state = 0, .external_lex_state = 100}, + [1535] = {.lex_state = 0, .external_lex_state = 100}, + [1536] = {.lex_state = 0, .external_lex_state = 98}, + [1537] = {.lex_state = 0, .external_lex_state = 98}, + [1538] = {.lex_state = 0, .external_lex_state = 101}, + [1539] = {.lex_state = 0, .external_lex_state = 101}, + [1540] = {.lex_state = 0, .external_lex_state = 105}, + [1541] = {.lex_state = 0, .external_lex_state = 105}, + [1542] = {.lex_state = 0, .external_lex_state = 101}, + [1543] = {.lex_state = 0, .external_lex_state = 101}, + [1544] = {.lex_state = 0, .external_lex_state = 105}, + [1545] = {.lex_state = 0, .external_lex_state = 101}, + [1546] = {.lex_state = 0, .external_lex_state = 101}, + [1547] = {.lex_state = 0, .external_lex_state = 105}, + [1548] = {.lex_state = 0, .external_lex_state = 101}, + [1549] = {.lex_state = 0, .external_lex_state = 101}, + [1550] = {.lex_state = 0, .external_lex_state = 105}, + [1551] = {.lex_state = 0, .external_lex_state = 98}, + [1552] = {.lex_state = 0, .external_lex_state = 101}, + [1553] = {.lex_state = 0, .external_lex_state = 105}, + [1554] = {.lex_state = 0, .external_lex_state = 101}, + [1555] = {.lex_state = 0, .external_lex_state = 101}, + [1556] = {.lex_state = 0, .external_lex_state = 105}, + [1557] = {.lex_state = 0, .external_lex_state = 101}, + [1558] = {.lex_state = 0, .external_lex_state = 101}, + [1559] = {.lex_state = 0, .external_lex_state = 105}, + [1560] = {.lex_state = 0, .external_lex_state = 101}, + [1561] = {.lex_state = 0, .external_lex_state = 101}, + [1562] = {.lex_state = 0, .external_lex_state = 101}, + [1563] = {.lex_state = 0, .external_lex_state = 101}, + [1564] = {.lex_state = 0, .external_lex_state = 101}, + [1565] = {.lex_state = 0, .external_lex_state = 101}, + [1566] = {.lex_state = 0, .external_lex_state = 101}, + [1567] = {.lex_state = 0, .external_lex_state = 101}, + [1568] = {.lex_state = 0, .external_lex_state = 101}, + [1569] = {.lex_state = 0, .external_lex_state = 101}, + [1570] = {.lex_state = 0, .external_lex_state = 101}, + [1571] = {.lex_state = 0, .external_lex_state = 101}, + [1572] = {.lex_state = 0, .external_lex_state = 101}, + [1573] = {.lex_state = 0, .external_lex_state = 101}, + [1574] = {.lex_state = 0, .external_lex_state = 101}, + [1575] = {.lex_state = 0, .external_lex_state = 101}, + [1576] = {.lex_state = 0, .external_lex_state = 101}, + [1577] = {.lex_state = 0, .external_lex_state = 101}, + [1578] = {.lex_state = 0, .external_lex_state = 101}, +}; + +static const uint16_t ts_parse_table[LARGE_STATE_COUNT][SYMBOL_COUNT] = { + [STATE(0)] = { + [ts_builtin_sym_end] = ACTIONS(1), + [sym__eof] = ACTIONS(1), + [sym__s_dir_yml_bgn] = ACTIONS(1), + [sym__r_dir_yml_ver] = ACTIONS(1), + [sym__s_dir_tag_bgn] = ACTIONS(1), + [sym__r_dir_tag_hdl] = ACTIONS(1), + [sym__r_dir_tag_pfx] = ACTIONS(1), + [sym__s_dir_rsv_bgn] = ACTIONS(1), + [sym__r_dir_rsv_prm] = ACTIONS(1), + [sym__s_drs_end] = ACTIONS(1), + [sym__s_doc_end] = ACTIONS(1), + [sym__r_blk_seq_bgn] = ACTIONS(1), + [sym__br_blk_seq_bgn] = ACTIONS(1), + [sym__b_blk_seq_bgn] = ACTIONS(1), + [sym__r_blk_key_bgn] = ACTIONS(1), + [sym__br_blk_key_bgn] = ACTIONS(1), + [sym__b_blk_key_bgn] = ACTIONS(1), + [sym__r_blk_val_bgn] = ACTIONS(1), + [sym__br_blk_val_bgn] = ACTIONS(1), + [sym__b_blk_val_bgn] = ACTIONS(1), + [sym__r_blk_imp_bgn] = ACTIONS(1), + [sym__r_blk_lit_bgn] = ACTIONS(1), + [sym__br_blk_lit_bgn] = ACTIONS(1), + [sym__r_blk_fld_bgn] = ACTIONS(1), + [sym__br_blk_fld_bgn] = ACTIONS(1), + [sym__br_blk_str_ctn] = ACTIONS(1), + [sym__r_flw_seq_bgn] = ACTIONS(1), + [sym__br_flw_seq_bgn] = ACTIONS(1), + [sym__b_flw_seq_bgn] = ACTIONS(1), + [sym__r_flw_seq_end] = ACTIONS(1), + [sym__br_flw_seq_end] = ACTIONS(1), + [sym__b_flw_seq_end] = ACTIONS(1), + [sym__r_flw_map_bgn] = ACTIONS(1), + [sym__br_flw_map_bgn] = ACTIONS(1), + [sym__b_flw_map_bgn] = ACTIONS(1), + [sym__r_flw_map_end] = ACTIONS(1), + [sym__br_flw_map_end] = ACTIONS(1), + [sym__b_flw_map_end] = ACTIONS(1), + [sym__r_flw_sep_bgn] = ACTIONS(1), + [sym__br_flw_sep_bgn] = ACTIONS(1), + [sym__r_flw_key_bgn] = ACTIONS(1), + [sym__br_flw_key_bgn] = ACTIONS(1), + [sym__r_flw_jsv_bgn] = ACTIONS(1), + [sym__br_flw_jsv_bgn] = ACTIONS(1), + [sym__r_flw_njv_bgn] = ACTIONS(1), + [sym__br_flw_njv_bgn] = ACTIONS(1), + [sym__r_dqt_str_bgn] = ACTIONS(1), + [sym__br_dqt_str_bgn] = ACTIONS(1), + [sym__b_dqt_str_bgn] = ACTIONS(1), + [sym__r_dqt_str_ctn] = ACTIONS(1), + [sym__br_dqt_str_ctn] = ACTIONS(1), + [sym__r_dqt_esc_nwl] = ACTIONS(1), + [sym__br_dqt_esc_nwl] = ACTIONS(1), + [sym__r_dqt_esc_seq] = ACTIONS(1), + [sym__br_dqt_esc_seq] = ACTIONS(1), + [sym__r_dqt_str_end] = ACTIONS(1), + [sym__br_dqt_str_end] = ACTIONS(1), + [sym__r_sqt_str_bgn] = ACTIONS(1), + [sym__br_sqt_str_bgn] = ACTIONS(1), + [sym__b_sqt_str_bgn] = ACTIONS(1), + [sym__r_sqt_str_ctn] = ACTIONS(1), + [sym__br_sqt_str_ctn] = ACTIONS(1), + [sym__r_sqt_esc_sqt] = ACTIONS(1), + [sym__br_sqt_esc_sqt] = ACTIONS(1), + [sym__r_sqt_str_end] = ACTIONS(1), + [sym__br_sqt_str_end] = ACTIONS(1), + [sym__r_sgl_pln_nul_blk] = ACTIONS(1), + [sym__br_sgl_pln_nul_blk] = ACTIONS(1), + [sym__b_sgl_pln_nul_blk] = ACTIONS(1), + [sym__r_sgl_pln_nul_flw] = ACTIONS(1), + [sym__br_sgl_pln_nul_flw] = ACTIONS(1), + [sym__r_sgl_pln_bol_blk] = ACTIONS(1), + [sym__br_sgl_pln_bol_blk] = ACTIONS(1), + [sym__b_sgl_pln_bol_blk] = ACTIONS(1), + [sym__r_sgl_pln_bol_flw] = ACTIONS(1), + [sym__br_sgl_pln_bol_flw] = ACTIONS(1), + [sym__r_sgl_pln_int_blk] = ACTIONS(1), + [sym__br_sgl_pln_int_blk] = ACTIONS(1), + [sym__b_sgl_pln_int_blk] = ACTIONS(1), + [sym__r_sgl_pln_int_flw] = ACTIONS(1), + [sym__br_sgl_pln_int_flw] = ACTIONS(1), + [sym__r_sgl_pln_flt_blk] = ACTIONS(1), + [sym__br_sgl_pln_flt_blk] = ACTIONS(1), + [sym__b_sgl_pln_flt_blk] = ACTIONS(1), + [sym__r_sgl_pln_flt_flw] = ACTIONS(1), + [sym__br_sgl_pln_flt_flw] = ACTIONS(1), + [sym__r_sgl_pln_tms_blk] = ACTIONS(1), + [sym__br_sgl_pln_tms_blk] = ACTIONS(1), + [sym__b_sgl_pln_tms_blk] = ACTIONS(1), + [sym__r_sgl_pln_tms_flw] = ACTIONS(1), + [sym__br_sgl_pln_tms_flw] = ACTIONS(1), + [sym__r_sgl_pln_str_blk] = ACTIONS(1), + [sym__br_sgl_pln_str_blk] = ACTIONS(1), + [sym__b_sgl_pln_str_blk] = ACTIONS(1), + [sym__r_sgl_pln_str_flw] = ACTIONS(1), + [sym__br_sgl_pln_str_flw] = ACTIONS(1), + [sym__r_mtl_pln_str_blk] = ACTIONS(1), + [sym__br_mtl_pln_str_blk] = ACTIONS(1), + [sym__r_mtl_pln_str_flw] = ACTIONS(1), + [sym__br_mtl_pln_str_flw] = ACTIONS(1), + [sym__r_tag] = ACTIONS(1), + [sym__br_tag] = ACTIONS(1), + [sym__b_tag] = ACTIONS(1), + [sym__r_acr_bgn] = ACTIONS(1), + [sym__br_acr_bgn] = ACTIONS(1), + [sym__b_acr_bgn] = ACTIONS(1), + [sym__r_acr_ctn] = ACTIONS(1), + [sym__r_als_bgn] = ACTIONS(1), + [sym__br_als_bgn] = ACTIONS(1), + [sym__b_als_bgn] = ACTIONS(1), + [sym__r_als_ctn] = ACTIONS(1), + [sym__bl] = ACTIONS(1), + [sym_comment] = ACTIONS(3), + [sym__err_rec] = ACTIONS(1), + }, + [STATE(1)] = { + [sym_stream] = STATE(1429), + [sym__bgn_imp_doc] = STATE(474), + [sym__drs_doc] = STATE(477), + [sym__exp_doc] = STATE(479), + [sym__drs_doc_end] = STATE(37), + [sym__exp_doc_end] = STATE(37), + [sym__bgn_imp_doc_end] = STATE(37), + [sym__doc_end] = STATE(37), + [sym__exp_doc_tal] = STATE(1123), + [sym__s_dir] = STATE(478), + [sym__s_dir_yml] = STATE(478), + [sym__s_dir_tag] = STATE(478), + [sym__s_dir_rsv] = STATE(478), + [sym__r_prp_val] = STATE(1123), + [sym__br_prp_val] = STATE(1123), + [sym__r_sgl_prp_val] = STATE(1227), + [sym__br_sgl_prp_val] = STATE(1237), + [sym__r_prp] = STATE(81), + [sym__br_prp] = STATE(80), + [sym__r_sgl_prp] = STATE(308), + [sym__br_sgl_prp] = STATE(309), + [sym__r_blk_seq_r_val] = STATE(1123), + [sym__r_blk_seq_br_val] = STATE(1123), + [sym__br_blk_seq_val] = STATE(1123), + [sym__r_blk_seq] = STATE(1154), + [sym__br_blk_seq] = STATE(1170), + [sym__r_blk_seq_itm] = STATE(1004), + [sym__br_blk_seq_itm] = STATE(1048), + [sym__r_blk_map_r_val] = STATE(1123), + [sym__r_blk_map_br_val] = STATE(1123), + [sym__br_blk_map_val] = STATE(1123), + [sym__r_blk_map] = STATE(1175), + [sym__br_blk_map] = STATE(1200), + [sym__r_blk_map_itm] = STATE(125), + [sym__br_blk_map_itm] = STATE(130), + [sym__r_blk_exp_itm] = STATE(318), + [sym__br_blk_exp_itm] = STATE(319), + [sym__r_blk_key_itm] = STATE(277), + [sym__br_blk_key_itm] = STATE(278), + [sym__r_blk_val_itm] = STATE(291), + [sym__br_blk_val_itm] = STATE(328), + [sym__r_blk_imp_itm] = STATE(360), + [sym__br_blk_imp_itm] = STATE(364), + [sym__r_blk_str_val] = STATE(1123), + [sym__br_blk_str_val] = STATE(1123), + [sym__r_blk_str] = STATE(1083), + [sym__br_blk_str] = STATE(1103), + [sym__r_flw_seq_val] = STATE(1123), + [sym__br_flw_seq_val] = STATE(1123), + [sym__r_sgl_flw_seq_val] = STATE(1227), + [sym__br_sgl_flw_seq_val] = STATE(1237), + [sym__r_flw_seq] = STATE(1115), + [sym__br_flw_seq] = STATE(1156), + [sym__r_sgl_flw_seq] = STATE(1420), + [sym__br_sgl_flw_seq] = STATE(1551), + [sym__r_flw_map_val] = STATE(1123), + [sym__br_flw_map_val] = STATE(1123), + [sym__r_sgl_flw_map_val] = STATE(1227), + [sym__br_sgl_flw_map_val] = STATE(1237), + [sym__r_flw_map] = STATE(1070), + [sym__br_flw_map] = STATE(1071), + [sym__r_sgl_flw_map] = STATE(1442), + [sym__br_sgl_flw_map] = STATE(1514), + [sym__r_dqt_str_val] = STATE(1123), + [sym__br_dqt_str_val] = STATE(1123), + [sym__r_sgl_dqt_str_val] = STATE(1227), + [sym__br_sgl_dqt_str_val] = STATE(1237), + [sym__r_dqt_str] = STATE(1060), + [sym__br_dqt_str] = STATE(1087), + [sym__r_sgl_dqt_str] = STATE(1453), + [sym__br_sgl_dqt_str] = STATE(1446), + [sym__r_sqt_str_val] = STATE(1123), + [sym__br_sqt_str_val] = STATE(1123), + [sym__r_sgl_sqt_str_val] = STATE(1227), + [sym__br_sgl_sqt_str_val] = STATE(1237), + [sym__r_sqt_str] = STATE(1127), + [sym__br_sqt_str] = STATE(1129), + [sym__r_sgl_sqt_str] = STATE(1411), + [sym__br_sgl_sqt_str] = STATE(1417), + [sym__r_pln_blk_val] = STATE(1123), + [sym__br_pln_blk_val] = STATE(1123), + [sym__r_sgl_pln_blk_val] = STATE(1227), + [sym__br_sgl_pln_blk_val] = STATE(1237), + [sym__r_sgl_pln_blk] = STATE(1046), + [sym__br_sgl_pln_blk] = STATE(997), + [sym__r_mtl_pln_blk] = STATE(1094), + [sym__br_mtl_pln_blk] = STATE(1095), + [sym__r_als_val] = STATE(917), + [sym__br_als_val] = STATE(918), + [sym__r_als] = STATE(999), + [sym__br_als] = STATE(1001), + [sym__r_acr] = STATE(131), + [sym__br_acr] = STATE(146), + [aux_sym__drs_doc_repeat1] = STATE(478), + [sym__eof] = ACTIONS(5), + [sym__s_dir_yml_bgn] = ACTIONS(7), + [sym__s_dir_tag_bgn] = ACTIONS(9), + [sym__s_dir_rsv_bgn] = ACTIONS(11), + [sym__s_drs_end] = ACTIONS(13), + [sym__s_doc_end] = ACTIONS(15), + [sym__r_blk_seq_bgn] = ACTIONS(17), + [sym__br_blk_seq_bgn] = ACTIONS(19), + [sym__r_blk_key_bgn] = ACTIONS(21), + [sym__br_blk_key_bgn] = ACTIONS(23), + [sym__r_blk_val_bgn] = ACTIONS(25), + [sym__br_blk_val_bgn] = ACTIONS(27), + [sym__r_blk_lit_bgn] = ACTIONS(29), + [sym__br_blk_lit_bgn] = ACTIONS(31), + [sym__r_blk_fld_bgn] = ACTIONS(29), + [sym__br_blk_fld_bgn] = ACTIONS(31), + [sym__r_flw_seq_bgn] = ACTIONS(33), + [sym__br_flw_seq_bgn] = ACTIONS(35), + [sym__r_flw_map_bgn] = ACTIONS(37), + [sym__br_flw_map_bgn] = ACTIONS(39), + [sym__r_dqt_str_bgn] = ACTIONS(41), + [sym__br_dqt_str_bgn] = ACTIONS(43), + [sym__r_sqt_str_bgn] = ACTIONS(45), + [sym__br_sqt_str_bgn] = ACTIONS(47), + [sym__r_sgl_pln_nul_blk] = ACTIONS(49), + [sym__br_sgl_pln_nul_blk] = ACTIONS(51), + [sym__r_sgl_pln_bol_blk] = ACTIONS(49), + [sym__br_sgl_pln_bol_blk] = ACTIONS(51), + [sym__r_sgl_pln_int_blk] = ACTIONS(49), + [sym__br_sgl_pln_int_blk] = ACTIONS(51), + [sym__r_sgl_pln_flt_blk] = ACTIONS(49), + [sym__br_sgl_pln_flt_blk] = ACTIONS(51), + [sym__r_sgl_pln_tms_blk] = ACTIONS(49), + [sym__br_sgl_pln_tms_blk] = ACTIONS(51), + [sym__r_sgl_pln_str_blk] = ACTIONS(49), + [sym__br_sgl_pln_str_blk] = ACTIONS(51), + [sym__r_mtl_pln_str_blk] = ACTIONS(53), + [sym__br_mtl_pln_str_blk] = ACTIONS(55), + [sym__r_tag] = ACTIONS(57), + [sym__br_tag] = ACTIONS(59), + [sym__r_acr_bgn] = ACTIONS(61), + [sym__br_acr_bgn] = ACTIONS(63), + [sym__r_als_bgn] = ACTIONS(65), + [sym__br_als_bgn] = ACTIONS(67), + [sym_comment] = ACTIONS(3), + }, + [STATE(2)] = { + [sym__r_prp_val] = STATE(316), + [sym__br_prp_val] = STATE(316), + [sym__r_sgl_prp_val] = STATE(1227), + [sym__br_sgl_prp_val] = STATE(1237), + [sym__r_prp] = STATE(36), + [sym__br_prp] = STATE(35), + [sym__r_sgl_prp] = STATE(308), + [sym__br_sgl_prp] = STATE(309), + [sym__r_blk_seq_r_val] = STATE(316), + [sym__r_blk_seq_br_val] = STATE(316), + [sym__br_blk_seq_val] = STATE(316), + [sym__r_blk_seq_spc_val] = STATE(316), + [sym__br_blk_seq_spc_val] = STATE(316), + [sym__b_blk_seq_spc_val] = STATE(316), + [sym__r_blk_seq] = STATE(340), + [sym__br_blk_seq] = STATE(341), + [sym__b_blk_seq_spc] = STATE(310), + [sym__r_blk_seq_itm] = STATE(965), + [sym__br_blk_seq_itm] = STATE(966), + [sym__b_blk_seq_itm] = STATE(1041), + [sym__blk_seq_itm_tal] = STATE(316), + [sym__r_blk_map_r_val] = STATE(316), + [sym__r_blk_map_br_val] = STATE(316), + [sym__br_blk_map_val] = STATE(316), + [sym__r_blk_map] = STATE(342), + [sym__br_blk_map] = STATE(343), + [sym__r_blk_map_itm] = STATE(142), + [sym__br_blk_map_itm] = STATE(143), + [sym__r_blk_exp_itm] = STATE(318), + [sym__br_blk_exp_itm] = STATE(319), + [sym__r_blk_key_itm] = STATE(277), + [sym__br_blk_key_itm] = STATE(278), + [sym__r_blk_val_itm] = STATE(291), + [sym__br_blk_val_itm] = STATE(328), + [sym__r_blk_imp_itm] = STATE(360), + [sym__br_blk_imp_itm] = STATE(364), + [sym__blk_exp_itm_tal] = STATE(316), + [sym__r_blk_str_val] = STATE(316), + [sym__br_blk_str_val] = STATE(316), + [sym__r_blk_str] = STATE(344), + [sym__br_blk_str] = STATE(345), + [sym__r_flw_seq_val] = STATE(316), + [sym__br_flw_seq_val] = STATE(316), + [sym__r_sgl_flw_seq_val] = STATE(1227), + [sym__br_sgl_flw_seq_val] = STATE(1237), + [sym__r_flw_seq] = STATE(346), + [sym__br_flw_seq] = STATE(347), + [sym__r_sgl_flw_seq] = STATE(1420), + [sym__br_sgl_flw_seq] = STATE(1551), + [sym__r_flw_map_val] = STATE(316), + [sym__br_flw_map_val] = STATE(316), + [sym__r_sgl_flw_map_val] = STATE(1227), + [sym__br_sgl_flw_map_val] = STATE(1237), + [sym__r_flw_map] = STATE(348), + [sym__br_flw_map] = STATE(349), + [sym__r_sgl_flw_map] = STATE(1442), + [sym__br_sgl_flw_map] = STATE(1514), + [sym__r_dqt_str_val] = STATE(316), + [sym__br_dqt_str_val] = STATE(316), + [sym__r_sgl_dqt_str_val] = STATE(1227), + [sym__br_sgl_dqt_str_val] = STATE(1237), + [sym__r_dqt_str] = STATE(350), + [sym__br_dqt_str] = STATE(351), + [sym__r_sgl_dqt_str] = STATE(1453), + [sym__br_sgl_dqt_str] = STATE(1446), + [sym__r_sqt_str_val] = STATE(316), + [sym__br_sqt_str_val] = STATE(316), + [sym__r_sgl_sqt_str_val] = STATE(1227), + [sym__br_sgl_sqt_str_val] = STATE(1237), + [sym__r_sqt_str] = STATE(352), + [sym__br_sqt_str] = STATE(353), + [sym__r_sgl_sqt_str] = STATE(1411), + [sym__br_sgl_sqt_str] = STATE(1417), + [sym__r_pln_blk_val] = STATE(316), + [sym__br_pln_blk_val] = STATE(316), + [sym__r_sgl_pln_blk_val] = STATE(1227), + [sym__br_sgl_pln_blk_val] = STATE(1237), + [sym__r_sgl_pln_blk] = STATE(281), + [sym__br_sgl_pln_blk] = STATE(282), + [sym__r_mtl_pln_blk] = STATE(356), + [sym__br_mtl_pln_blk] = STATE(357), + [sym__r_als_val] = STATE(262), + [sym__br_als_val] = STATE(264), + [sym__r_als] = STATE(266), + [sym__br_als] = STATE(283), + [sym__r_acr] = STATE(100), + [sym__br_acr] = STATE(99), + [aux_sym__r_blk_seq_repeat1] = STATE(1041), + [sym__r_blk_seq_bgn] = ACTIONS(17), + [sym__br_blk_seq_bgn] = ACTIONS(19), + [sym__b_blk_seq_bgn] = ACTIONS(69), + [sym__r_blk_key_bgn] = ACTIONS(21), + [sym__br_blk_key_bgn] = ACTIONS(23), + [sym__b_blk_key_bgn] = ACTIONS(71), + [sym__r_blk_val_bgn] = ACTIONS(25), + [sym__br_blk_val_bgn] = ACTIONS(27), + [sym__b_blk_val_bgn] = ACTIONS(71), + [sym__r_blk_lit_bgn] = ACTIONS(73), + [sym__br_blk_lit_bgn] = ACTIONS(75), + [sym__r_blk_fld_bgn] = ACTIONS(73), + [sym__br_blk_fld_bgn] = ACTIONS(75), + [sym__r_flw_seq_bgn] = ACTIONS(77), + [sym__br_flw_seq_bgn] = ACTIONS(79), + [sym__b_flw_seq_bgn] = ACTIONS(71), + [sym__r_flw_map_bgn] = ACTIONS(81), + [sym__br_flw_map_bgn] = ACTIONS(83), + [sym__b_flw_map_bgn] = ACTIONS(71), + [sym__r_dqt_str_bgn] = ACTIONS(85), + [sym__br_dqt_str_bgn] = ACTIONS(87), + [sym__b_dqt_str_bgn] = ACTIONS(71), + [sym__r_sqt_str_bgn] = ACTIONS(89), + [sym__br_sqt_str_bgn] = ACTIONS(91), + [sym__b_sqt_str_bgn] = ACTIONS(71), + [sym__r_sgl_pln_nul_blk] = ACTIONS(93), + [sym__br_sgl_pln_nul_blk] = ACTIONS(95), + [sym__b_sgl_pln_nul_blk] = ACTIONS(71), + [sym__r_sgl_pln_bol_blk] = ACTIONS(93), + [sym__br_sgl_pln_bol_blk] = ACTIONS(95), + [sym__b_sgl_pln_bol_blk] = ACTIONS(71), + [sym__r_sgl_pln_int_blk] = ACTIONS(93), + [sym__br_sgl_pln_int_blk] = ACTIONS(95), + [sym__b_sgl_pln_int_blk] = ACTIONS(71), + [sym__r_sgl_pln_flt_blk] = ACTIONS(93), + [sym__br_sgl_pln_flt_blk] = ACTIONS(95), + [sym__b_sgl_pln_flt_blk] = ACTIONS(71), + [sym__r_sgl_pln_tms_blk] = ACTIONS(93), + [sym__br_sgl_pln_tms_blk] = ACTIONS(95), + [sym__b_sgl_pln_tms_blk] = ACTIONS(71), + [sym__r_sgl_pln_str_blk] = ACTIONS(93), + [sym__br_sgl_pln_str_blk] = ACTIONS(95), + [sym__b_sgl_pln_str_blk] = ACTIONS(71), + [sym__r_mtl_pln_str_blk] = ACTIONS(97), + [sym__br_mtl_pln_str_blk] = ACTIONS(99), + [sym__r_tag] = ACTIONS(101), + [sym__br_tag] = ACTIONS(103), + [sym__b_tag] = ACTIONS(71), + [sym__r_acr_bgn] = ACTIONS(105), + [sym__br_acr_bgn] = ACTIONS(107), + [sym__b_acr_bgn] = ACTIONS(71), + [sym__r_als_bgn] = ACTIONS(109), + [sym__br_als_bgn] = ACTIONS(111), + [sym__b_als_bgn] = ACTIONS(71), + [sym__bl] = ACTIONS(71), + [sym_comment] = ACTIONS(3), + }, + [STATE(3)] = { + [sym__r_prp_val] = STATE(311), + [sym__br_prp_val] = STATE(311), + [sym__r_sgl_prp_val] = STATE(1227), + [sym__br_sgl_prp_val] = STATE(1237), + [sym__r_prp] = STATE(36), + [sym__br_prp] = STATE(35), + [sym__r_sgl_prp] = STATE(308), + [sym__br_sgl_prp] = STATE(309), + [sym__r_blk_seq_r_val] = STATE(311), + [sym__r_blk_seq_br_val] = STATE(311), + [sym__br_blk_seq_val] = STATE(311), + [sym__r_blk_seq_spc_val] = STATE(311), + [sym__br_blk_seq_spc_val] = STATE(311), + [sym__b_blk_seq_spc_val] = STATE(311), + [sym__r_blk_seq] = STATE(340), + [sym__br_blk_seq] = STATE(341), + [sym__b_blk_seq_spc] = STATE(310), + [sym__r_blk_seq_itm] = STATE(965), + [sym__br_blk_seq_itm] = STATE(966), + [sym__b_blk_seq_itm] = STATE(1041), + [sym__blk_seq_itm_tal] = STATE(311), + [sym__r_blk_map_r_val] = STATE(311), + [sym__r_blk_map_br_val] = STATE(311), + [sym__br_blk_map_val] = STATE(311), + [sym__r_blk_map] = STATE(342), + [sym__br_blk_map] = STATE(343), + [sym__r_blk_map_itm] = STATE(142), + [sym__br_blk_map_itm] = STATE(143), + [sym__r_blk_exp_itm] = STATE(318), + [sym__br_blk_exp_itm] = STATE(319), + [sym__r_blk_key_itm] = STATE(277), + [sym__br_blk_key_itm] = STATE(278), + [sym__r_blk_val_itm] = STATE(291), + [sym__br_blk_val_itm] = STATE(328), + [sym__r_blk_imp_itm] = STATE(360), + [sym__br_blk_imp_itm] = STATE(364), + [sym__blk_exp_itm_tal] = STATE(311), + [sym__r_blk_str_val] = STATE(311), + [sym__br_blk_str_val] = STATE(311), + [sym__r_blk_str] = STATE(344), + [sym__br_blk_str] = STATE(345), + [sym__r_flw_seq_val] = STATE(311), + [sym__br_flw_seq_val] = STATE(311), + [sym__r_sgl_flw_seq_val] = STATE(1227), + [sym__br_sgl_flw_seq_val] = STATE(1237), + [sym__r_flw_seq] = STATE(346), + [sym__br_flw_seq] = STATE(347), + [sym__r_sgl_flw_seq] = STATE(1420), + [sym__br_sgl_flw_seq] = STATE(1551), + [sym__r_flw_map_val] = STATE(311), + [sym__br_flw_map_val] = STATE(311), + [sym__r_sgl_flw_map_val] = STATE(1227), + [sym__br_sgl_flw_map_val] = STATE(1237), + [sym__r_flw_map] = STATE(348), + [sym__br_flw_map] = STATE(349), + [sym__r_sgl_flw_map] = STATE(1442), + [sym__br_sgl_flw_map] = STATE(1514), + [sym__r_dqt_str_val] = STATE(311), + [sym__br_dqt_str_val] = STATE(311), + [sym__r_sgl_dqt_str_val] = STATE(1227), + [sym__br_sgl_dqt_str_val] = STATE(1237), + [sym__r_dqt_str] = STATE(350), + [sym__br_dqt_str] = STATE(351), + [sym__r_sgl_dqt_str] = STATE(1453), + [sym__br_sgl_dqt_str] = STATE(1446), + [sym__r_sqt_str_val] = STATE(311), + [sym__br_sqt_str_val] = STATE(311), + [sym__r_sgl_sqt_str_val] = STATE(1227), + [sym__br_sgl_sqt_str_val] = STATE(1237), + [sym__r_sqt_str] = STATE(352), + [sym__br_sqt_str] = STATE(353), + [sym__r_sgl_sqt_str] = STATE(1411), + [sym__br_sgl_sqt_str] = STATE(1417), + [sym__r_pln_blk_val] = STATE(311), + [sym__br_pln_blk_val] = STATE(311), + [sym__r_sgl_pln_blk_val] = STATE(1227), + [sym__br_sgl_pln_blk_val] = STATE(1237), + [sym__r_sgl_pln_blk] = STATE(281), + [sym__br_sgl_pln_blk] = STATE(282), + [sym__r_mtl_pln_blk] = STATE(356), + [sym__br_mtl_pln_blk] = STATE(357), + [sym__r_als_val] = STATE(262), + [sym__br_als_val] = STATE(264), + [sym__r_als] = STATE(266), + [sym__br_als] = STATE(283), + [sym__r_acr] = STATE(100), + [sym__br_acr] = STATE(99), + [aux_sym__r_blk_seq_repeat1] = STATE(1041), + [sym__r_blk_seq_bgn] = ACTIONS(17), + [sym__br_blk_seq_bgn] = ACTIONS(19), + [sym__b_blk_seq_bgn] = ACTIONS(69), + [sym__r_blk_key_bgn] = ACTIONS(21), + [sym__br_blk_key_bgn] = ACTIONS(23), + [sym__b_blk_key_bgn] = ACTIONS(113), + [sym__r_blk_val_bgn] = ACTIONS(25), + [sym__br_blk_val_bgn] = ACTIONS(27), + [sym__b_blk_val_bgn] = ACTIONS(113), + [sym__r_blk_lit_bgn] = ACTIONS(73), + [sym__br_blk_lit_bgn] = ACTIONS(75), + [sym__r_blk_fld_bgn] = ACTIONS(73), + [sym__br_blk_fld_bgn] = ACTIONS(75), + [sym__r_flw_seq_bgn] = ACTIONS(77), + [sym__br_flw_seq_bgn] = ACTIONS(79), + [sym__b_flw_seq_bgn] = ACTIONS(113), + [sym__r_flw_map_bgn] = ACTIONS(81), + [sym__br_flw_map_bgn] = ACTIONS(83), + [sym__b_flw_map_bgn] = ACTIONS(113), + [sym__r_dqt_str_bgn] = ACTIONS(85), + [sym__br_dqt_str_bgn] = ACTIONS(87), + [sym__b_dqt_str_bgn] = ACTIONS(113), + [sym__r_sqt_str_bgn] = ACTIONS(89), + [sym__br_sqt_str_bgn] = ACTIONS(91), + [sym__b_sqt_str_bgn] = ACTIONS(113), + [sym__r_sgl_pln_nul_blk] = ACTIONS(93), + [sym__br_sgl_pln_nul_blk] = ACTIONS(95), + [sym__b_sgl_pln_nul_blk] = ACTIONS(113), + [sym__r_sgl_pln_bol_blk] = ACTIONS(93), + [sym__br_sgl_pln_bol_blk] = ACTIONS(95), + [sym__b_sgl_pln_bol_blk] = ACTIONS(113), + [sym__r_sgl_pln_int_blk] = ACTIONS(93), + [sym__br_sgl_pln_int_blk] = ACTIONS(95), + [sym__b_sgl_pln_int_blk] = ACTIONS(113), + [sym__r_sgl_pln_flt_blk] = ACTIONS(93), + [sym__br_sgl_pln_flt_blk] = ACTIONS(95), + [sym__b_sgl_pln_flt_blk] = ACTIONS(113), + [sym__r_sgl_pln_tms_blk] = ACTIONS(93), + [sym__br_sgl_pln_tms_blk] = ACTIONS(95), + [sym__b_sgl_pln_tms_blk] = ACTIONS(113), + [sym__r_sgl_pln_str_blk] = ACTIONS(93), + [sym__br_sgl_pln_str_blk] = ACTIONS(95), + [sym__b_sgl_pln_str_blk] = ACTIONS(113), + [sym__r_mtl_pln_str_blk] = ACTIONS(97), + [sym__br_mtl_pln_str_blk] = ACTIONS(99), + [sym__r_tag] = ACTIONS(101), + [sym__br_tag] = ACTIONS(103), + [sym__b_tag] = ACTIONS(113), + [sym__r_acr_bgn] = ACTIONS(105), + [sym__br_acr_bgn] = ACTIONS(107), + [sym__b_acr_bgn] = ACTIONS(113), + [sym__r_als_bgn] = ACTIONS(109), + [sym__br_als_bgn] = ACTIONS(111), + [sym__b_als_bgn] = ACTIONS(113), + [sym__bl] = ACTIONS(113), + [sym_comment] = ACTIONS(3), + }, + [STATE(4)] = { + [sym__r_prp_val] = STATE(312), + [sym__br_prp_val] = STATE(312), + [sym__r_sgl_prp_val] = STATE(1227), + [sym__br_sgl_prp_val] = STATE(1237), + [sym__r_prp] = STATE(36), + [sym__br_prp] = STATE(35), + [sym__r_sgl_prp] = STATE(308), + [sym__br_sgl_prp] = STATE(309), + [sym__r_blk_seq_r_val] = STATE(312), + [sym__r_blk_seq_br_val] = STATE(312), + [sym__br_blk_seq_val] = STATE(312), + [sym__r_blk_seq_spc_val] = STATE(312), + [sym__br_blk_seq_spc_val] = STATE(312), + [sym__b_blk_seq_spc_val] = STATE(312), + [sym__r_blk_seq] = STATE(340), + [sym__br_blk_seq] = STATE(341), + [sym__b_blk_seq_spc] = STATE(310), + [sym__r_blk_seq_itm] = STATE(965), + [sym__br_blk_seq_itm] = STATE(966), + [sym__b_blk_seq_itm] = STATE(1041), + [sym__blk_seq_itm_tal] = STATE(312), + [sym__r_blk_map_r_val] = STATE(312), + [sym__r_blk_map_br_val] = STATE(312), + [sym__br_blk_map_val] = STATE(312), + [sym__r_blk_map] = STATE(342), + [sym__br_blk_map] = STATE(343), + [sym__r_blk_map_itm] = STATE(142), + [sym__br_blk_map_itm] = STATE(143), + [sym__r_blk_exp_itm] = STATE(318), + [sym__br_blk_exp_itm] = STATE(319), + [sym__r_blk_key_itm] = STATE(277), + [sym__br_blk_key_itm] = STATE(278), + [sym__r_blk_val_itm] = STATE(291), + [sym__br_blk_val_itm] = STATE(328), + [sym__r_blk_imp_itm] = STATE(360), + [sym__br_blk_imp_itm] = STATE(364), + [sym__blk_exp_itm_tal] = STATE(312), + [sym__r_blk_str_val] = STATE(312), + [sym__br_blk_str_val] = STATE(312), + [sym__r_blk_str] = STATE(344), + [sym__br_blk_str] = STATE(345), + [sym__r_flw_seq_val] = STATE(312), + [sym__br_flw_seq_val] = STATE(312), + [sym__r_sgl_flw_seq_val] = STATE(1227), + [sym__br_sgl_flw_seq_val] = STATE(1237), + [sym__r_flw_seq] = STATE(346), + [sym__br_flw_seq] = STATE(347), + [sym__r_sgl_flw_seq] = STATE(1420), + [sym__br_sgl_flw_seq] = STATE(1551), + [sym__r_flw_map_val] = STATE(312), + [sym__br_flw_map_val] = STATE(312), + [sym__r_sgl_flw_map_val] = STATE(1227), + [sym__br_sgl_flw_map_val] = STATE(1237), + [sym__r_flw_map] = STATE(348), + [sym__br_flw_map] = STATE(349), + [sym__r_sgl_flw_map] = STATE(1442), + [sym__br_sgl_flw_map] = STATE(1514), + [sym__r_dqt_str_val] = STATE(312), + [sym__br_dqt_str_val] = STATE(312), + [sym__r_sgl_dqt_str_val] = STATE(1227), + [sym__br_sgl_dqt_str_val] = STATE(1237), + [sym__r_dqt_str] = STATE(350), + [sym__br_dqt_str] = STATE(351), + [sym__r_sgl_dqt_str] = STATE(1453), + [sym__br_sgl_dqt_str] = STATE(1446), + [sym__r_sqt_str_val] = STATE(312), + [sym__br_sqt_str_val] = STATE(312), + [sym__r_sgl_sqt_str_val] = STATE(1227), + [sym__br_sgl_sqt_str_val] = STATE(1237), + [sym__r_sqt_str] = STATE(352), + [sym__br_sqt_str] = STATE(353), + [sym__r_sgl_sqt_str] = STATE(1411), + [sym__br_sgl_sqt_str] = STATE(1417), + [sym__r_pln_blk_val] = STATE(312), + [sym__br_pln_blk_val] = STATE(312), + [sym__r_sgl_pln_blk_val] = STATE(1227), + [sym__br_sgl_pln_blk_val] = STATE(1237), + [sym__r_sgl_pln_blk] = STATE(281), + [sym__br_sgl_pln_blk] = STATE(282), + [sym__r_mtl_pln_blk] = STATE(356), + [sym__br_mtl_pln_blk] = STATE(357), + [sym__r_als_val] = STATE(262), + [sym__br_als_val] = STATE(264), + [sym__r_als] = STATE(266), + [sym__br_als] = STATE(283), + [sym__r_acr] = STATE(100), + [sym__br_acr] = STATE(99), + [aux_sym__r_blk_seq_repeat1] = STATE(1041), + [sym__r_blk_seq_bgn] = ACTIONS(17), + [sym__br_blk_seq_bgn] = ACTIONS(19), + [sym__b_blk_seq_bgn] = ACTIONS(69), + [sym__r_blk_key_bgn] = ACTIONS(21), + [sym__br_blk_key_bgn] = ACTIONS(23), + [sym__b_blk_key_bgn] = ACTIONS(115), + [sym__r_blk_val_bgn] = ACTIONS(25), + [sym__br_blk_val_bgn] = ACTIONS(27), + [sym__b_blk_val_bgn] = ACTIONS(115), + [sym__r_blk_lit_bgn] = ACTIONS(73), + [sym__br_blk_lit_bgn] = ACTIONS(75), + [sym__r_blk_fld_bgn] = ACTIONS(73), + [sym__br_blk_fld_bgn] = ACTIONS(75), + [sym__r_flw_seq_bgn] = ACTIONS(77), + [sym__br_flw_seq_bgn] = ACTIONS(79), + [sym__b_flw_seq_bgn] = ACTIONS(115), + [sym__r_flw_map_bgn] = ACTIONS(81), + [sym__br_flw_map_bgn] = ACTIONS(83), + [sym__b_flw_map_bgn] = ACTIONS(115), + [sym__r_dqt_str_bgn] = ACTIONS(85), + [sym__br_dqt_str_bgn] = ACTIONS(87), + [sym__b_dqt_str_bgn] = ACTIONS(115), + [sym__r_sqt_str_bgn] = ACTIONS(89), + [sym__br_sqt_str_bgn] = ACTIONS(91), + [sym__b_sqt_str_bgn] = ACTIONS(115), + [sym__r_sgl_pln_nul_blk] = ACTIONS(93), + [sym__br_sgl_pln_nul_blk] = ACTIONS(95), + [sym__b_sgl_pln_nul_blk] = ACTIONS(115), + [sym__r_sgl_pln_bol_blk] = ACTIONS(93), + [sym__br_sgl_pln_bol_blk] = ACTIONS(95), + [sym__b_sgl_pln_bol_blk] = ACTIONS(115), + [sym__r_sgl_pln_int_blk] = ACTIONS(93), + [sym__br_sgl_pln_int_blk] = ACTIONS(95), + [sym__b_sgl_pln_int_blk] = ACTIONS(115), + [sym__r_sgl_pln_flt_blk] = ACTIONS(93), + [sym__br_sgl_pln_flt_blk] = ACTIONS(95), + [sym__b_sgl_pln_flt_blk] = ACTIONS(115), + [sym__r_sgl_pln_tms_blk] = ACTIONS(93), + [sym__br_sgl_pln_tms_blk] = ACTIONS(95), + [sym__b_sgl_pln_tms_blk] = ACTIONS(115), + [sym__r_sgl_pln_str_blk] = ACTIONS(93), + [sym__br_sgl_pln_str_blk] = ACTIONS(95), + [sym__b_sgl_pln_str_blk] = ACTIONS(115), + [sym__r_mtl_pln_str_blk] = ACTIONS(97), + [sym__br_mtl_pln_str_blk] = ACTIONS(99), + [sym__r_tag] = ACTIONS(101), + [sym__br_tag] = ACTIONS(103), + [sym__b_tag] = ACTIONS(115), + [sym__r_acr_bgn] = ACTIONS(105), + [sym__br_acr_bgn] = ACTIONS(107), + [sym__b_acr_bgn] = ACTIONS(115), + [sym__r_als_bgn] = ACTIONS(109), + [sym__br_als_bgn] = ACTIONS(111), + [sym__b_als_bgn] = ACTIONS(115), + [sym__bl] = ACTIONS(115), + [sym_comment] = ACTIONS(3), + }, + [STATE(5)] = { + [sym__r_prp_val] = STATE(317), + [sym__br_prp_val] = STATE(317), + [sym__r_sgl_prp_val] = STATE(1227), + [sym__br_sgl_prp_val] = STATE(1237), + [sym__r_prp] = STATE(36), + [sym__br_prp] = STATE(35), + [sym__r_sgl_prp] = STATE(308), + [sym__br_sgl_prp] = STATE(309), + [sym__r_blk_seq_r_val] = STATE(317), + [sym__r_blk_seq_br_val] = STATE(317), + [sym__br_blk_seq_val] = STATE(317), + [sym__r_blk_seq_spc_val] = STATE(317), + [sym__br_blk_seq_spc_val] = STATE(317), + [sym__b_blk_seq_spc_val] = STATE(317), + [sym__r_blk_seq] = STATE(340), + [sym__br_blk_seq] = STATE(341), + [sym__b_blk_seq_spc] = STATE(310), + [sym__r_blk_seq_itm] = STATE(965), + [sym__br_blk_seq_itm] = STATE(966), + [sym__b_blk_seq_itm] = STATE(1041), + [sym__blk_seq_itm_tal] = STATE(317), + [sym__r_blk_map_r_val] = STATE(317), + [sym__r_blk_map_br_val] = STATE(317), + [sym__br_blk_map_val] = STATE(317), + [sym__r_blk_map] = STATE(342), + [sym__br_blk_map] = STATE(343), + [sym__r_blk_map_itm] = STATE(142), + [sym__br_blk_map_itm] = STATE(143), + [sym__r_blk_exp_itm] = STATE(318), + [sym__br_blk_exp_itm] = STATE(319), + [sym__r_blk_key_itm] = STATE(277), + [sym__br_blk_key_itm] = STATE(278), + [sym__r_blk_val_itm] = STATE(291), + [sym__br_blk_val_itm] = STATE(328), + [sym__r_blk_imp_itm] = STATE(360), + [sym__br_blk_imp_itm] = STATE(364), + [sym__blk_exp_itm_tal] = STATE(317), + [sym__r_blk_str_val] = STATE(317), + [sym__br_blk_str_val] = STATE(317), + [sym__r_blk_str] = STATE(344), + [sym__br_blk_str] = STATE(345), + [sym__r_flw_seq_val] = STATE(317), + [sym__br_flw_seq_val] = STATE(317), + [sym__r_sgl_flw_seq_val] = STATE(1227), + [sym__br_sgl_flw_seq_val] = STATE(1237), + [sym__r_flw_seq] = STATE(346), + [sym__br_flw_seq] = STATE(347), + [sym__r_sgl_flw_seq] = STATE(1420), + [sym__br_sgl_flw_seq] = STATE(1551), + [sym__r_flw_map_val] = STATE(317), + [sym__br_flw_map_val] = STATE(317), + [sym__r_sgl_flw_map_val] = STATE(1227), + [sym__br_sgl_flw_map_val] = STATE(1237), + [sym__r_flw_map] = STATE(348), + [sym__br_flw_map] = STATE(349), + [sym__r_sgl_flw_map] = STATE(1442), + [sym__br_sgl_flw_map] = STATE(1514), + [sym__r_dqt_str_val] = STATE(317), + [sym__br_dqt_str_val] = STATE(317), + [sym__r_sgl_dqt_str_val] = STATE(1227), + [sym__br_sgl_dqt_str_val] = STATE(1237), + [sym__r_dqt_str] = STATE(350), + [sym__br_dqt_str] = STATE(351), + [sym__r_sgl_dqt_str] = STATE(1453), + [sym__br_sgl_dqt_str] = STATE(1446), + [sym__r_sqt_str_val] = STATE(317), + [sym__br_sqt_str_val] = STATE(317), + [sym__r_sgl_sqt_str_val] = STATE(1227), + [sym__br_sgl_sqt_str_val] = STATE(1237), + [sym__r_sqt_str] = STATE(352), + [sym__br_sqt_str] = STATE(353), + [sym__r_sgl_sqt_str] = STATE(1411), + [sym__br_sgl_sqt_str] = STATE(1417), + [sym__r_pln_blk_val] = STATE(317), + [sym__br_pln_blk_val] = STATE(317), + [sym__r_sgl_pln_blk_val] = STATE(1227), + [sym__br_sgl_pln_blk_val] = STATE(1237), + [sym__r_sgl_pln_blk] = STATE(281), + [sym__br_sgl_pln_blk] = STATE(282), + [sym__r_mtl_pln_blk] = STATE(356), + [sym__br_mtl_pln_blk] = STATE(357), + [sym__r_als_val] = STATE(262), + [sym__br_als_val] = STATE(264), + [sym__r_als] = STATE(266), + [sym__br_als] = STATE(283), + [sym__r_acr] = STATE(100), + [sym__br_acr] = STATE(99), + [aux_sym__r_blk_seq_repeat1] = STATE(1041), + [sym__r_blk_seq_bgn] = ACTIONS(17), + [sym__br_blk_seq_bgn] = ACTIONS(19), + [sym__b_blk_seq_bgn] = ACTIONS(69), + [sym__r_blk_key_bgn] = ACTIONS(21), + [sym__br_blk_key_bgn] = ACTIONS(23), + [sym__b_blk_key_bgn] = ACTIONS(117), + [sym__r_blk_val_bgn] = ACTIONS(25), + [sym__br_blk_val_bgn] = ACTIONS(27), + [sym__b_blk_val_bgn] = ACTIONS(117), + [sym__r_blk_lit_bgn] = ACTIONS(73), + [sym__br_blk_lit_bgn] = ACTIONS(75), + [sym__r_blk_fld_bgn] = ACTIONS(73), + [sym__br_blk_fld_bgn] = ACTIONS(75), + [sym__r_flw_seq_bgn] = ACTIONS(77), + [sym__br_flw_seq_bgn] = ACTIONS(79), + [sym__b_flw_seq_bgn] = ACTIONS(117), + [sym__r_flw_map_bgn] = ACTIONS(81), + [sym__br_flw_map_bgn] = ACTIONS(83), + [sym__b_flw_map_bgn] = ACTIONS(117), + [sym__r_dqt_str_bgn] = ACTIONS(85), + [sym__br_dqt_str_bgn] = ACTIONS(87), + [sym__b_dqt_str_bgn] = ACTIONS(117), + [sym__r_sqt_str_bgn] = ACTIONS(89), + [sym__br_sqt_str_bgn] = ACTIONS(91), + [sym__b_sqt_str_bgn] = ACTIONS(117), + [sym__r_sgl_pln_nul_blk] = ACTIONS(93), + [sym__br_sgl_pln_nul_blk] = ACTIONS(95), + [sym__b_sgl_pln_nul_blk] = ACTIONS(117), + [sym__r_sgl_pln_bol_blk] = ACTIONS(93), + [sym__br_sgl_pln_bol_blk] = ACTIONS(95), + [sym__b_sgl_pln_bol_blk] = ACTIONS(117), + [sym__r_sgl_pln_int_blk] = ACTIONS(93), + [sym__br_sgl_pln_int_blk] = ACTIONS(95), + [sym__b_sgl_pln_int_blk] = ACTIONS(117), + [sym__r_sgl_pln_flt_blk] = ACTIONS(93), + [sym__br_sgl_pln_flt_blk] = ACTIONS(95), + [sym__b_sgl_pln_flt_blk] = ACTIONS(117), + [sym__r_sgl_pln_tms_blk] = ACTIONS(93), + [sym__br_sgl_pln_tms_blk] = ACTIONS(95), + [sym__b_sgl_pln_tms_blk] = ACTIONS(117), + [sym__r_sgl_pln_str_blk] = ACTIONS(93), + [sym__br_sgl_pln_str_blk] = ACTIONS(95), + [sym__b_sgl_pln_str_blk] = ACTIONS(117), + [sym__r_mtl_pln_str_blk] = ACTIONS(97), + [sym__br_mtl_pln_str_blk] = ACTIONS(99), + [sym__r_tag] = ACTIONS(101), + [sym__br_tag] = ACTIONS(103), + [sym__b_tag] = ACTIONS(117), + [sym__r_acr_bgn] = ACTIONS(105), + [sym__br_acr_bgn] = ACTIONS(107), + [sym__b_acr_bgn] = ACTIONS(117), + [sym__r_als_bgn] = ACTIONS(109), + [sym__br_als_bgn] = ACTIONS(111), + [sym__b_als_bgn] = ACTIONS(117), + [sym__bl] = ACTIONS(117), + [sym_comment] = ACTIONS(3), + }, + [STATE(6)] = { + [sym__r_prp_val] = STATE(302), + [sym__br_prp_val] = STATE(302), + [sym__r_sgl_prp_val] = STATE(1227), + [sym__br_sgl_prp_val] = STATE(1237), + [sym__r_prp] = STATE(36), + [sym__br_prp] = STATE(35), + [sym__r_sgl_prp] = STATE(308), + [sym__br_sgl_prp] = STATE(309), + [sym__r_blk_seq_r_val] = STATE(302), + [sym__r_blk_seq_br_val] = STATE(302), + [sym__br_blk_seq_val] = STATE(302), + [sym__r_blk_seq_spc_val] = STATE(302), + [sym__br_blk_seq_spc_val] = STATE(302), + [sym__b_blk_seq_spc_val] = STATE(302), + [sym__r_blk_seq] = STATE(340), + [sym__br_blk_seq] = STATE(341), + [sym__b_blk_seq_spc] = STATE(310), + [sym__r_blk_seq_itm] = STATE(965), + [sym__br_blk_seq_itm] = STATE(966), + [sym__b_blk_seq_itm] = STATE(1041), + [sym__blk_seq_itm_tal] = STATE(302), + [sym__r_blk_map_r_val] = STATE(302), + [sym__r_blk_map_br_val] = STATE(302), + [sym__br_blk_map_val] = STATE(302), + [sym__r_blk_map] = STATE(342), + [sym__br_blk_map] = STATE(343), + [sym__r_blk_map_itm] = STATE(142), + [sym__br_blk_map_itm] = STATE(143), + [sym__r_blk_exp_itm] = STATE(318), + [sym__br_blk_exp_itm] = STATE(319), + [sym__r_blk_key_itm] = STATE(277), + [sym__br_blk_key_itm] = STATE(278), + [sym__r_blk_val_itm] = STATE(291), + [sym__br_blk_val_itm] = STATE(328), + [sym__r_blk_imp_itm] = STATE(360), + [sym__br_blk_imp_itm] = STATE(364), + [sym__blk_exp_itm_tal] = STATE(302), + [sym__r_blk_str_val] = STATE(302), + [sym__br_blk_str_val] = STATE(302), + [sym__r_blk_str] = STATE(344), + [sym__br_blk_str] = STATE(345), + [sym__r_flw_seq_val] = STATE(302), + [sym__br_flw_seq_val] = STATE(302), + [sym__r_sgl_flw_seq_val] = STATE(1227), + [sym__br_sgl_flw_seq_val] = STATE(1237), + [sym__r_flw_seq] = STATE(346), + [sym__br_flw_seq] = STATE(347), + [sym__r_sgl_flw_seq] = STATE(1420), + [sym__br_sgl_flw_seq] = STATE(1551), + [sym__r_flw_map_val] = STATE(302), + [sym__br_flw_map_val] = STATE(302), + [sym__r_sgl_flw_map_val] = STATE(1227), + [sym__br_sgl_flw_map_val] = STATE(1237), + [sym__r_flw_map] = STATE(348), + [sym__br_flw_map] = STATE(349), + [sym__r_sgl_flw_map] = STATE(1442), + [sym__br_sgl_flw_map] = STATE(1514), + [sym__r_dqt_str_val] = STATE(302), + [sym__br_dqt_str_val] = STATE(302), + [sym__r_sgl_dqt_str_val] = STATE(1227), + [sym__br_sgl_dqt_str_val] = STATE(1237), + [sym__r_dqt_str] = STATE(350), + [sym__br_dqt_str] = STATE(351), + [sym__r_sgl_dqt_str] = STATE(1453), + [sym__br_sgl_dqt_str] = STATE(1446), + [sym__r_sqt_str_val] = STATE(302), + [sym__br_sqt_str_val] = STATE(302), + [sym__r_sgl_sqt_str_val] = STATE(1227), + [sym__br_sgl_sqt_str_val] = STATE(1237), + [sym__r_sqt_str] = STATE(352), + [sym__br_sqt_str] = STATE(353), + [sym__r_sgl_sqt_str] = STATE(1411), + [sym__br_sgl_sqt_str] = STATE(1417), + [sym__r_pln_blk_val] = STATE(302), + [sym__br_pln_blk_val] = STATE(302), + [sym__r_sgl_pln_blk_val] = STATE(1227), + [sym__br_sgl_pln_blk_val] = STATE(1237), + [sym__r_sgl_pln_blk] = STATE(281), + [sym__br_sgl_pln_blk] = STATE(282), + [sym__r_mtl_pln_blk] = STATE(356), + [sym__br_mtl_pln_blk] = STATE(357), + [sym__r_als_val] = STATE(262), + [sym__br_als_val] = STATE(264), + [sym__r_als] = STATE(266), + [sym__br_als] = STATE(283), + [sym__r_acr] = STATE(100), + [sym__br_acr] = STATE(99), + [aux_sym__r_blk_seq_repeat1] = STATE(1041), + [sym__r_blk_seq_bgn] = ACTIONS(17), + [sym__br_blk_seq_bgn] = ACTIONS(19), + [sym__b_blk_seq_bgn] = ACTIONS(69), + [sym__r_blk_key_bgn] = ACTIONS(21), + [sym__br_blk_key_bgn] = ACTIONS(23), + [sym__b_blk_key_bgn] = ACTIONS(119), + [sym__r_blk_val_bgn] = ACTIONS(25), + [sym__br_blk_val_bgn] = ACTIONS(27), + [sym__b_blk_val_bgn] = ACTIONS(119), + [sym__r_blk_lit_bgn] = ACTIONS(73), + [sym__br_blk_lit_bgn] = ACTIONS(75), + [sym__r_blk_fld_bgn] = ACTIONS(73), + [sym__br_blk_fld_bgn] = ACTIONS(75), + [sym__r_flw_seq_bgn] = ACTIONS(77), + [sym__br_flw_seq_bgn] = ACTIONS(79), + [sym__b_flw_seq_bgn] = ACTIONS(119), + [sym__r_flw_map_bgn] = ACTIONS(81), + [sym__br_flw_map_bgn] = ACTIONS(83), + [sym__b_flw_map_bgn] = ACTIONS(119), + [sym__r_dqt_str_bgn] = ACTIONS(85), + [sym__br_dqt_str_bgn] = ACTIONS(87), + [sym__b_dqt_str_bgn] = ACTIONS(119), + [sym__r_sqt_str_bgn] = ACTIONS(89), + [sym__br_sqt_str_bgn] = ACTIONS(91), + [sym__b_sqt_str_bgn] = ACTIONS(119), + [sym__r_sgl_pln_nul_blk] = ACTIONS(93), + [sym__br_sgl_pln_nul_blk] = ACTIONS(95), + [sym__b_sgl_pln_nul_blk] = ACTIONS(119), + [sym__r_sgl_pln_bol_blk] = ACTIONS(93), + [sym__br_sgl_pln_bol_blk] = ACTIONS(95), + [sym__b_sgl_pln_bol_blk] = ACTIONS(119), + [sym__r_sgl_pln_int_blk] = ACTIONS(93), + [sym__br_sgl_pln_int_blk] = ACTIONS(95), + [sym__b_sgl_pln_int_blk] = ACTIONS(119), + [sym__r_sgl_pln_flt_blk] = ACTIONS(93), + [sym__br_sgl_pln_flt_blk] = ACTIONS(95), + [sym__b_sgl_pln_flt_blk] = ACTIONS(119), + [sym__r_sgl_pln_tms_blk] = ACTIONS(93), + [sym__br_sgl_pln_tms_blk] = ACTIONS(95), + [sym__b_sgl_pln_tms_blk] = ACTIONS(119), + [sym__r_sgl_pln_str_blk] = ACTIONS(93), + [sym__br_sgl_pln_str_blk] = ACTIONS(95), + [sym__b_sgl_pln_str_blk] = ACTIONS(119), + [sym__r_mtl_pln_str_blk] = ACTIONS(97), + [sym__br_mtl_pln_str_blk] = ACTIONS(99), + [sym__r_tag] = ACTIONS(101), + [sym__br_tag] = ACTIONS(103), + [sym__b_tag] = ACTIONS(119), + [sym__r_acr_bgn] = ACTIONS(105), + [sym__br_acr_bgn] = ACTIONS(107), + [sym__b_acr_bgn] = ACTIONS(119), + [sym__r_als_bgn] = ACTIONS(109), + [sym__br_als_bgn] = ACTIONS(111), + [sym__b_als_bgn] = ACTIONS(119), + [sym__bl] = ACTIONS(119), + [sym_comment] = ACTIONS(3), + }, + [STATE(7)] = { + [sym__r_prp_val] = STATE(303), + [sym__br_prp_val] = STATE(303), + [sym__r_sgl_prp_val] = STATE(1227), + [sym__br_sgl_prp_val] = STATE(1237), + [sym__r_prp] = STATE(36), + [sym__br_prp] = STATE(35), + [sym__r_sgl_prp] = STATE(308), + [sym__br_sgl_prp] = STATE(309), + [sym__r_blk_seq_r_val] = STATE(303), + [sym__r_blk_seq_br_val] = STATE(303), + [sym__br_blk_seq_val] = STATE(303), + [sym__r_blk_seq_spc_val] = STATE(303), + [sym__br_blk_seq_spc_val] = STATE(303), + [sym__b_blk_seq_spc_val] = STATE(303), + [sym__r_blk_seq] = STATE(340), + [sym__br_blk_seq] = STATE(341), + [sym__b_blk_seq_spc] = STATE(310), + [sym__r_blk_seq_itm] = STATE(965), + [sym__br_blk_seq_itm] = STATE(966), + [sym__b_blk_seq_itm] = STATE(1041), + [sym__blk_seq_itm_tal] = STATE(303), + [sym__r_blk_map_r_val] = STATE(303), + [sym__r_blk_map_br_val] = STATE(303), + [sym__br_blk_map_val] = STATE(303), + [sym__r_blk_map] = STATE(342), + [sym__br_blk_map] = STATE(343), + [sym__r_blk_map_itm] = STATE(142), + [sym__br_blk_map_itm] = STATE(143), + [sym__r_blk_exp_itm] = STATE(318), + [sym__br_blk_exp_itm] = STATE(319), + [sym__r_blk_key_itm] = STATE(277), + [sym__br_blk_key_itm] = STATE(278), + [sym__r_blk_val_itm] = STATE(291), + [sym__br_blk_val_itm] = STATE(328), + [sym__r_blk_imp_itm] = STATE(360), + [sym__br_blk_imp_itm] = STATE(364), + [sym__blk_exp_itm_tal] = STATE(303), + [sym__r_blk_str_val] = STATE(303), + [sym__br_blk_str_val] = STATE(303), + [sym__r_blk_str] = STATE(344), + [sym__br_blk_str] = STATE(345), + [sym__r_flw_seq_val] = STATE(303), + [sym__br_flw_seq_val] = STATE(303), + [sym__r_sgl_flw_seq_val] = STATE(1227), + [sym__br_sgl_flw_seq_val] = STATE(1237), + [sym__r_flw_seq] = STATE(346), + [sym__br_flw_seq] = STATE(347), + [sym__r_sgl_flw_seq] = STATE(1420), + [sym__br_sgl_flw_seq] = STATE(1551), + [sym__r_flw_map_val] = STATE(303), + [sym__br_flw_map_val] = STATE(303), + [sym__r_sgl_flw_map_val] = STATE(1227), + [sym__br_sgl_flw_map_val] = STATE(1237), + [sym__r_flw_map] = STATE(348), + [sym__br_flw_map] = STATE(349), + [sym__r_sgl_flw_map] = STATE(1442), + [sym__br_sgl_flw_map] = STATE(1514), + [sym__r_dqt_str_val] = STATE(303), + [sym__br_dqt_str_val] = STATE(303), + [sym__r_sgl_dqt_str_val] = STATE(1227), + [sym__br_sgl_dqt_str_val] = STATE(1237), + [sym__r_dqt_str] = STATE(350), + [sym__br_dqt_str] = STATE(351), + [sym__r_sgl_dqt_str] = STATE(1453), + [sym__br_sgl_dqt_str] = STATE(1446), + [sym__r_sqt_str_val] = STATE(303), + [sym__br_sqt_str_val] = STATE(303), + [sym__r_sgl_sqt_str_val] = STATE(1227), + [sym__br_sgl_sqt_str_val] = STATE(1237), + [sym__r_sqt_str] = STATE(352), + [sym__br_sqt_str] = STATE(353), + [sym__r_sgl_sqt_str] = STATE(1411), + [sym__br_sgl_sqt_str] = STATE(1417), + [sym__r_pln_blk_val] = STATE(303), + [sym__br_pln_blk_val] = STATE(303), + [sym__r_sgl_pln_blk_val] = STATE(1227), + [sym__br_sgl_pln_blk_val] = STATE(1237), + [sym__r_sgl_pln_blk] = STATE(281), + [sym__br_sgl_pln_blk] = STATE(282), + [sym__r_mtl_pln_blk] = STATE(356), + [sym__br_mtl_pln_blk] = STATE(357), + [sym__r_als_val] = STATE(262), + [sym__br_als_val] = STATE(264), + [sym__r_als] = STATE(266), + [sym__br_als] = STATE(283), + [sym__r_acr] = STATE(100), + [sym__br_acr] = STATE(99), + [aux_sym__r_blk_seq_repeat1] = STATE(1041), + [sym__r_blk_seq_bgn] = ACTIONS(17), + [sym__br_blk_seq_bgn] = ACTIONS(19), + [sym__b_blk_seq_bgn] = ACTIONS(69), + [sym__r_blk_key_bgn] = ACTIONS(21), + [sym__br_blk_key_bgn] = ACTIONS(23), + [sym__b_blk_key_bgn] = ACTIONS(121), + [sym__r_blk_val_bgn] = ACTIONS(25), + [sym__br_blk_val_bgn] = ACTIONS(27), + [sym__b_blk_val_bgn] = ACTIONS(121), + [sym__r_blk_lit_bgn] = ACTIONS(73), + [sym__br_blk_lit_bgn] = ACTIONS(75), + [sym__r_blk_fld_bgn] = ACTIONS(73), + [sym__br_blk_fld_bgn] = ACTIONS(75), + [sym__r_flw_seq_bgn] = ACTIONS(77), + [sym__br_flw_seq_bgn] = ACTIONS(79), + [sym__b_flw_seq_bgn] = ACTIONS(121), + [sym__r_flw_map_bgn] = ACTIONS(81), + [sym__br_flw_map_bgn] = ACTIONS(83), + [sym__b_flw_map_bgn] = ACTIONS(121), + [sym__r_dqt_str_bgn] = ACTIONS(85), + [sym__br_dqt_str_bgn] = ACTIONS(87), + [sym__b_dqt_str_bgn] = ACTIONS(121), + [sym__r_sqt_str_bgn] = ACTIONS(89), + [sym__br_sqt_str_bgn] = ACTIONS(91), + [sym__b_sqt_str_bgn] = ACTIONS(121), + [sym__r_sgl_pln_nul_blk] = ACTIONS(93), + [sym__br_sgl_pln_nul_blk] = ACTIONS(95), + [sym__b_sgl_pln_nul_blk] = ACTIONS(121), + [sym__r_sgl_pln_bol_blk] = ACTIONS(93), + [sym__br_sgl_pln_bol_blk] = ACTIONS(95), + [sym__b_sgl_pln_bol_blk] = ACTIONS(121), + [sym__r_sgl_pln_int_blk] = ACTIONS(93), + [sym__br_sgl_pln_int_blk] = ACTIONS(95), + [sym__b_sgl_pln_int_blk] = ACTIONS(121), + [sym__r_sgl_pln_flt_blk] = ACTIONS(93), + [sym__br_sgl_pln_flt_blk] = ACTIONS(95), + [sym__b_sgl_pln_flt_blk] = ACTIONS(121), + [sym__r_sgl_pln_tms_blk] = ACTIONS(93), + [sym__br_sgl_pln_tms_blk] = ACTIONS(95), + [sym__b_sgl_pln_tms_blk] = ACTIONS(121), + [sym__r_sgl_pln_str_blk] = ACTIONS(93), + [sym__br_sgl_pln_str_blk] = ACTIONS(95), + [sym__b_sgl_pln_str_blk] = ACTIONS(121), + [sym__r_mtl_pln_str_blk] = ACTIONS(97), + [sym__br_mtl_pln_str_blk] = ACTIONS(99), + [sym__r_tag] = ACTIONS(101), + [sym__br_tag] = ACTIONS(103), + [sym__b_tag] = ACTIONS(121), + [sym__r_acr_bgn] = ACTIONS(105), + [sym__br_acr_bgn] = ACTIONS(107), + [sym__b_acr_bgn] = ACTIONS(121), + [sym__r_als_bgn] = ACTIONS(109), + [sym__br_als_bgn] = ACTIONS(111), + [sym__b_als_bgn] = ACTIONS(121), + [sym__bl] = ACTIONS(121), + [sym_comment] = ACTIONS(3), + }, + [STATE(8)] = { + [sym__r_prp_val] = STATE(1268), + [sym__br_prp_val] = STATE(1268), + [sym__r_sgl_prp_val] = STATE(1227), + [sym__br_sgl_prp_val] = STATE(1237), + [sym__r_prp] = STATE(82), + [sym__br_prp] = STATE(83), + [sym__r_sgl_prp] = STATE(308), + [sym__br_sgl_prp] = STATE(309), + [sym__r_blk_seq_r_val] = STATE(1268), + [sym__r_blk_seq_br_val] = STATE(1268), + [sym__br_blk_seq_val] = STATE(1268), + [sym__r_blk_seq] = STATE(1386), + [sym__br_blk_seq] = STATE(1387), + [sym__r_blk_seq_itm] = STATE(1002), + [sym__br_blk_seq_itm] = STATE(1003), + [sym__blk_seq_itm_tal] = STATE(1268), + [sym__r_blk_map_r_val] = STATE(1268), + [sym__r_blk_map_br_val] = STATE(1268), + [sym__br_blk_map_val] = STATE(1268), + [sym__r_blk_map] = STATE(1388), + [sym__br_blk_map] = STATE(1389), + [sym__r_blk_map_itm] = STATE(134), + [sym__br_blk_map_itm] = STATE(135), + [sym__r_blk_exp_itm] = STATE(318), + [sym__br_blk_exp_itm] = STATE(319), + [sym__r_blk_key_itm] = STATE(277), + [sym__br_blk_key_itm] = STATE(278), + [sym__r_blk_val_itm] = STATE(291), + [sym__br_blk_val_itm] = STATE(328), + [sym__r_blk_imp_itm] = STATE(360), + [sym__br_blk_imp_itm] = STATE(364), + [sym__r_blk_str_val] = STATE(1268), + [sym__br_blk_str_val] = STATE(1268), + [sym__r_blk_str] = STATE(1390), + [sym__br_blk_str] = STATE(1393), + [sym__r_flw_seq_val] = STATE(1268), + [sym__br_flw_seq_val] = STATE(1268), + [sym__r_sgl_flw_seq_val] = STATE(1227), + [sym__br_sgl_flw_seq_val] = STATE(1237), + [sym__r_flw_seq] = STATE(1394), + [sym__br_flw_seq] = STATE(1395), + [sym__r_sgl_flw_seq] = STATE(1420), + [sym__br_sgl_flw_seq] = STATE(1551), + [sym__r_flw_map_val] = STATE(1268), + [sym__br_flw_map_val] = STATE(1268), + [sym__r_sgl_flw_map_val] = STATE(1227), + [sym__br_sgl_flw_map_val] = STATE(1237), + [sym__r_flw_map] = STATE(1401), + [sym__br_flw_map] = STATE(1402), + [sym__r_sgl_flw_map] = STATE(1442), + [sym__br_sgl_flw_map] = STATE(1514), + [sym__r_dqt_str_val] = STATE(1268), + [sym__br_dqt_str_val] = STATE(1268), + [sym__r_sgl_dqt_str_val] = STATE(1227), + [sym__br_sgl_dqt_str_val] = STATE(1237), + [sym__r_dqt_str] = STATE(1404), + [sym__br_dqt_str] = STATE(1407), + [sym__r_sgl_dqt_str] = STATE(1453), + [sym__br_sgl_dqt_str] = STATE(1446), + [sym__r_sqt_str_val] = STATE(1268), + [sym__br_sqt_str_val] = STATE(1268), + [sym__r_sgl_sqt_str_val] = STATE(1227), + [sym__br_sgl_sqt_str_val] = STATE(1237), + [sym__r_sqt_str] = STATE(1217), + [sym__br_sqt_str] = STATE(1218), + [sym__r_sgl_sqt_str] = STATE(1411), + [sym__br_sgl_sqt_str] = STATE(1417), + [sym__r_pln_blk_val] = STATE(1268), + [sym__br_pln_blk_val] = STATE(1268), + [sym__r_sgl_pln_blk_val] = STATE(1227), + [sym__br_sgl_pln_blk_val] = STATE(1237), + [sym__r_sgl_pln_blk] = STATE(1117), + [sym__br_sgl_pln_blk] = STATE(1118), + [sym__r_mtl_pln_blk] = STATE(1220), + [sym__br_mtl_pln_blk] = STATE(1221), + [sym__r_als_val] = STATE(967), + [sym__br_als_val] = STATE(969), + [sym__r_als] = STATE(1137), + [sym__br_als] = STATE(1122), + [sym__r_acr] = STATE(157), + [sym__br_acr] = STATE(158), + [sym__r_blk_seq_bgn] = ACTIONS(17), + [sym__br_blk_seq_bgn] = ACTIONS(19), + [sym__b_blk_seq_bgn] = ACTIONS(123), + [sym__r_blk_key_bgn] = ACTIONS(21), + [sym__br_blk_key_bgn] = ACTIONS(23), + [sym__r_blk_val_bgn] = ACTIONS(25), + [sym__br_blk_val_bgn] = ACTIONS(27), + [sym__r_blk_lit_bgn] = ACTIONS(125), + [sym__br_blk_lit_bgn] = ACTIONS(127), + [sym__r_blk_fld_bgn] = ACTIONS(125), + [sym__br_blk_fld_bgn] = ACTIONS(127), + [sym__r_flw_seq_bgn] = ACTIONS(129), + [sym__br_flw_seq_bgn] = ACTIONS(131), + [sym__r_flw_map_bgn] = ACTIONS(133), + [sym__br_flw_map_bgn] = ACTIONS(135), + [sym__r_dqt_str_bgn] = ACTIONS(137), + [sym__br_dqt_str_bgn] = ACTIONS(139), + [sym__r_sqt_str_bgn] = ACTIONS(141), + [sym__br_sqt_str_bgn] = ACTIONS(143), + [sym__r_sgl_pln_nul_blk] = ACTIONS(145), + [sym__br_sgl_pln_nul_blk] = ACTIONS(147), + [sym__r_sgl_pln_bol_blk] = ACTIONS(145), + [sym__br_sgl_pln_bol_blk] = ACTIONS(147), + [sym__r_sgl_pln_int_blk] = ACTIONS(145), + [sym__br_sgl_pln_int_blk] = ACTIONS(147), + [sym__r_sgl_pln_flt_blk] = ACTIONS(145), + [sym__br_sgl_pln_flt_blk] = ACTIONS(147), + [sym__r_sgl_pln_tms_blk] = ACTIONS(145), + [sym__br_sgl_pln_tms_blk] = ACTIONS(147), + [sym__r_sgl_pln_str_blk] = ACTIONS(145), + [sym__br_sgl_pln_str_blk] = ACTIONS(147), + [sym__r_mtl_pln_str_blk] = ACTIONS(149), + [sym__br_mtl_pln_str_blk] = ACTIONS(151), + [sym__r_tag] = ACTIONS(153), + [sym__br_tag] = ACTIONS(155), + [sym__r_acr_bgn] = ACTIONS(157), + [sym__br_acr_bgn] = ACTIONS(159), + [sym__r_als_bgn] = ACTIONS(161), + [sym__br_als_bgn] = ACTIONS(163), + [sym__bl] = ACTIONS(123), + [sym_comment] = ACTIONS(3), + }, + [STATE(9)] = { + [sym__r_prp_val] = STATE(1313), + [sym__br_prp_val] = STATE(1313), + [sym__r_sgl_prp_val] = STATE(1227), + [sym__br_sgl_prp_val] = STATE(1237), + [sym__r_prp] = STATE(82), + [sym__br_prp] = STATE(83), + [sym__r_sgl_prp] = STATE(308), + [sym__br_sgl_prp] = STATE(309), + [sym__r_blk_seq_r_val] = STATE(1313), + [sym__r_blk_seq_br_val] = STATE(1313), + [sym__br_blk_seq_val] = STATE(1313), + [sym__r_blk_seq] = STATE(1386), + [sym__br_blk_seq] = STATE(1387), + [sym__r_blk_seq_itm] = STATE(1002), + [sym__br_blk_seq_itm] = STATE(1003), + [sym__blk_seq_itm_tal] = STATE(1313), + [sym__r_blk_map_r_val] = STATE(1313), + [sym__r_blk_map_br_val] = STATE(1313), + [sym__br_blk_map_val] = STATE(1313), + [sym__r_blk_map] = STATE(1388), + [sym__br_blk_map] = STATE(1389), + [sym__r_blk_map_itm] = STATE(134), + [sym__br_blk_map_itm] = STATE(135), + [sym__r_blk_exp_itm] = STATE(318), + [sym__br_blk_exp_itm] = STATE(319), + [sym__r_blk_key_itm] = STATE(277), + [sym__br_blk_key_itm] = STATE(278), + [sym__r_blk_val_itm] = STATE(291), + [sym__br_blk_val_itm] = STATE(328), + [sym__r_blk_imp_itm] = STATE(360), + [sym__br_blk_imp_itm] = STATE(364), + [sym__r_blk_str_val] = STATE(1313), + [sym__br_blk_str_val] = STATE(1313), + [sym__r_blk_str] = STATE(1390), + [sym__br_blk_str] = STATE(1393), + [sym__r_flw_seq_val] = STATE(1313), + [sym__br_flw_seq_val] = STATE(1313), + [sym__r_sgl_flw_seq_val] = STATE(1227), + [sym__br_sgl_flw_seq_val] = STATE(1237), + [sym__r_flw_seq] = STATE(1394), + [sym__br_flw_seq] = STATE(1395), + [sym__r_sgl_flw_seq] = STATE(1420), + [sym__br_sgl_flw_seq] = STATE(1551), + [sym__r_flw_map_val] = STATE(1313), + [sym__br_flw_map_val] = STATE(1313), + [sym__r_sgl_flw_map_val] = STATE(1227), + [sym__br_sgl_flw_map_val] = STATE(1237), + [sym__r_flw_map] = STATE(1401), + [sym__br_flw_map] = STATE(1402), + [sym__r_sgl_flw_map] = STATE(1442), + [sym__br_sgl_flw_map] = STATE(1514), + [sym__r_dqt_str_val] = STATE(1313), + [sym__br_dqt_str_val] = STATE(1313), + [sym__r_sgl_dqt_str_val] = STATE(1227), + [sym__br_sgl_dqt_str_val] = STATE(1237), + [sym__r_dqt_str] = STATE(1404), + [sym__br_dqt_str] = STATE(1407), + [sym__r_sgl_dqt_str] = STATE(1453), + [sym__br_sgl_dqt_str] = STATE(1446), + [sym__r_sqt_str_val] = STATE(1313), + [sym__br_sqt_str_val] = STATE(1313), + [sym__r_sgl_sqt_str_val] = STATE(1227), + [sym__br_sgl_sqt_str_val] = STATE(1237), + [sym__r_sqt_str] = STATE(1217), + [sym__br_sqt_str] = STATE(1218), + [sym__r_sgl_sqt_str] = STATE(1411), + [sym__br_sgl_sqt_str] = STATE(1417), + [sym__r_pln_blk_val] = STATE(1313), + [sym__br_pln_blk_val] = STATE(1313), + [sym__r_sgl_pln_blk_val] = STATE(1227), + [sym__br_sgl_pln_blk_val] = STATE(1237), + [sym__r_sgl_pln_blk] = STATE(1117), + [sym__br_sgl_pln_blk] = STATE(1118), + [sym__r_mtl_pln_blk] = STATE(1220), + [sym__br_mtl_pln_blk] = STATE(1221), + [sym__r_als_val] = STATE(967), + [sym__br_als_val] = STATE(969), + [sym__r_als] = STATE(1137), + [sym__br_als] = STATE(1122), + [sym__r_acr] = STATE(157), + [sym__br_acr] = STATE(158), + [sym__r_blk_seq_bgn] = ACTIONS(17), + [sym__br_blk_seq_bgn] = ACTIONS(19), + [sym__b_blk_seq_bgn] = ACTIONS(165), + [sym__r_blk_key_bgn] = ACTIONS(21), + [sym__br_blk_key_bgn] = ACTIONS(23), + [sym__r_blk_val_bgn] = ACTIONS(25), + [sym__br_blk_val_bgn] = ACTIONS(27), + [sym__r_blk_lit_bgn] = ACTIONS(125), + [sym__br_blk_lit_bgn] = ACTIONS(127), + [sym__r_blk_fld_bgn] = ACTIONS(125), + [sym__br_blk_fld_bgn] = ACTIONS(127), + [sym__r_flw_seq_bgn] = ACTIONS(129), + [sym__br_flw_seq_bgn] = ACTIONS(131), + [sym__r_flw_map_bgn] = ACTIONS(133), + [sym__br_flw_map_bgn] = ACTIONS(135), + [sym__r_dqt_str_bgn] = ACTIONS(137), + [sym__br_dqt_str_bgn] = ACTIONS(139), + [sym__r_sqt_str_bgn] = ACTIONS(141), + [sym__br_sqt_str_bgn] = ACTIONS(143), + [sym__r_sgl_pln_nul_blk] = ACTIONS(145), + [sym__br_sgl_pln_nul_blk] = ACTIONS(147), + [sym__r_sgl_pln_bol_blk] = ACTIONS(145), + [sym__br_sgl_pln_bol_blk] = ACTIONS(147), + [sym__r_sgl_pln_int_blk] = ACTIONS(145), + [sym__br_sgl_pln_int_blk] = ACTIONS(147), + [sym__r_sgl_pln_flt_blk] = ACTIONS(145), + [sym__br_sgl_pln_flt_blk] = ACTIONS(147), + [sym__r_sgl_pln_tms_blk] = ACTIONS(145), + [sym__br_sgl_pln_tms_blk] = ACTIONS(147), + [sym__r_sgl_pln_str_blk] = ACTIONS(145), + [sym__br_sgl_pln_str_blk] = ACTIONS(147), + [sym__r_mtl_pln_str_blk] = ACTIONS(149), + [sym__br_mtl_pln_str_blk] = ACTIONS(151), + [sym__r_tag] = ACTIONS(153), + [sym__br_tag] = ACTIONS(155), + [sym__r_acr_bgn] = ACTIONS(157), + [sym__br_acr_bgn] = ACTIONS(159), + [sym__r_als_bgn] = ACTIONS(161), + [sym__br_als_bgn] = ACTIONS(163), + [sym__bl] = ACTIONS(165), + [sym_comment] = ACTIONS(3), + }, + [STATE(10)] = { + [sym__r_prp_val] = STATE(1267), + [sym__br_prp_val] = STATE(1267), + [sym__r_sgl_prp_val] = STATE(1227), + [sym__br_sgl_prp_val] = STATE(1237), + [sym__r_prp] = STATE(82), + [sym__br_prp] = STATE(83), + [sym__r_sgl_prp] = STATE(308), + [sym__br_sgl_prp] = STATE(309), + [sym__r_blk_seq_r_val] = STATE(1267), + [sym__r_blk_seq_br_val] = STATE(1267), + [sym__br_blk_seq_val] = STATE(1267), + [sym__r_blk_seq] = STATE(1386), + [sym__br_blk_seq] = STATE(1387), + [sym__r_blk_seq_itm] = STATE(1002), + [sym__br_blk_seq_itm] = STATE(1003), + [sym__blk_seq_itm_tal] = STATE(1267), + [sym__r_blk_map_r_val] = STATE(1267), + [sym__r_blk_map_br_val] = STATE(1267), + [sym__br_blk_map_val] = STATE(1267), + [sym__r_blk_map] = STATE(1388), + [sym__br_blk_map] = STATE(1389), + [sym__r_blk_map_itm] = STATE(134), + [sym__br_blk_map_itm] = STATE(135), + [sym__r_blk_exp_itm] = STATE(318), + [sym__br_blk_exp_itm] = STATE(319), + [sym__r_blk_key_itm] = STATE(277), + [sym__br_blk_key_itm] = STATE(278), + [sym__r_blk_val_itm] = STATE(291), + [sym__br_blk_val_itm] = STATE(328), + [sym__r_blk_imp_itm] = STATE(360), + [sym__br_blk_imp_itm] = STATE(364), + [sym__r_blk_str_val] = STATE(1267), + [sym__br_blk_str_val] = STATE(1267), + [sym__r_blk_str] = STATE(1390), + [sym__br_blk_str] = STATE(1393), + [sym__r_flw_seq_val] = STATE(1267), + [sym__br_flw_seq_val] = STATE(1267), + [sym__r_sgl_flw_seq_val] = STATE(1227), + [sym__br_sgl_flw_seq_val] = STATE(1237), + [sym__r_flw_seq] = STATE(1394), + [sym__br_flw_seq] = STATE(1395), + [sym__r_sgl_flw_seq] = STATE(1420), + [sym__br_sgl_flw_seq] = STATE(1551), + [sym__r_flw_map_val] = STATE(1267), + [sym__br_flw_map_val] = STATE(1267), + [sym__r_sgl_flw_map_val] = STATE(1227), + [sym__br_sgl_flw_map_val] = STATE(1237), + [sym__r_flw_map] = STATE(1401), + [sym__br_flw_map] = STATE(1402), + [sym__r_sgl_flw_map] = STATE(1442), + [sym__br_sgl_flw_map] = STATE(1514), + [sym__r_dqt_str_val] = STATE(1267), + [sym__br_dqt_str_val] = STATE(1267), + [sym__r_sgl_dqt_str_val] = STATE(1227), + [sym__br_sgl_dqt_str_val] = STATE(1237), + [sym__r_dqt_str] = STATE(1404), + [sym__br_dqt_str] = STATE(1407), + [sym__r_sgl_dqt_str] = STATE(1453), + [sym__br_sgl_dqt_str] = STATE(1446), + [sym__r_sqt_str_val] = STATE(1267), + [sym__br_sqt_str_val] = STATE(1267), + [sym__r_sgl_sqt_str_val] = STATE(1227), + [sym__br_sgl_sqt_str_val] = STATE(1237), + [sym__r_sqt_str] = STATE(1217), + [sym__br_sqt_str] = STATE(1218), + [sym__r_sgl_sqt_str] = STATE(1411), + [sym__br_sgl_sqt_str] = STATE(1417), + [sym__r_pln_blk_val] = STATE(1267), + [sym__br_pln_blk_val] = STATE(1267), + [sym__r_sgl_pln_blk_val] = STATE(1227), + [sym__br_sgl_pln_blk_val] = STATE(1237), + [sym__r_sgl_pln_blk] = STATE(1117), + [sym__br_sgl_pln_blk] = STATE(1118), + [sym__r_mtl_pln_blk] = STATE(1220), + [sym__br_mtl_pln_blk] = STATE(1221), + [sym__r_als_val] = STATE(967), + [sym__br_als_val] = STATE(969), + [sym__r_als] = STATE(1137), + [sym__br_als] = STATE(1122), + [sym__r_acr] = STATE(157), + [sym__br_acr] = STATE(158), + [sym__r_blk_seq_bgn] = ACTIONS(17), + [sym__br_blk_seq_bgn] = ACTIONS(19), + [sym__b_blk_seq_bgn] = ACTIONS(167), + [sym__r_blk_key_bgn] = ACTIONS(21), + [sym__br_blk_key_bgn] = ACTIONS(23), + [sym__r_blk_val_bgn] = ACTIONS(25), + [sym__br_blk_val_bgn] = ACTIONS(27), + [sym__r_blk_lit_bgn] = ACTIONS(125), + [sym__br_blk_lit_bgn] = ACTIONS(127), + [sym__r_blk_fld_bgn] = ACTIONS(125), + [sym__br_blk_fld_bgn] = ACTIONS(127), + [sym__r_flw_seq_bgn] = ACTIONS(129), + [sym__br_flw_seq_bgn] = ACTIONS(131), + [sym__r_flw_map_bgn] = ACTIONS(133), + [sym__br_flw_map_bgn] = ACTIONS(135), + [sym__r_dqt_str_bgn] = ACTIONS(137), + [sym__br_dqt_str_bgn] = ACTIONS(139), + [sym__r_sqt_str_bgn] = ACTIONS(141), + [sym__br_sqt_str_bgn] = ACTIONS(143), + [sym__r_sgl_pln_nul_blk] = ACTIONS(145), + [sym__br_sgl_pln_nul_blk] = ACTIONS(147), + [sym__r_sgl_pln_bol_blk] = ACTIONS(145), + [sym__br_sgl_pln_bol_blk] = ACTIONS(147), + [sym__r_sgl_pln_int_blk] = ACTIONS(145), + [sym__br_sgl_pln_int_blk] = ACTIONS(147), + [sym__r_sgl_pln_flt_blk] = ACTIONS(145), + [sym__br_sgl_pln_flt_blk] = ACTIONS(147), + [sym__r_sgl_pln_tms_blk] = ACTIONS(145), + [sym__br_sgl_pln_tms_blk] = ACTIONS(147), + [sym__r_sgl_pln_str_blk] = ACTIONS(145), + [sym__br_sgl_pln_str_blk] = ACTIONS(147), + [sym__r_mtl_pln_str_blk] = ACTIONS(149), + [sym__br_mtl_pln_str_blk] = ACTIONS(151), + [sym__r_tag] = ACTIONS(153), + [sym__br_tag] = ACTIONS(155), + [sym__r_acr_bgn] = ACTIONS(157), + [sym__br_acr_bgn] = ACTIONS(159), + [sym__r_als_bgn] = ACTIONS(161), + [sym__br_als_bgn] = ACTIONS(163), + [sym__bl] = ACTIONS(167), + [sym_comment] = ACTIONS(3), + }, + [STATE(11)] = { + [sym__r_prp_val] = STATE(300), + [sym__br_prp_val] = STATE(300), + [sym__br_sgl_prp_val] = STATE(1237), + [sym__r_prp] = STATE(36), + [sym__br_prp] = STATE(35), + [sym__br_sgl_prp] = STATE(309), + [sym__r_blk_seq_br_val] = STATE(300), + [sym__br_blk_seq_val] = STATE(300), + [sym__r_blk_seq_spc_val] = STATE(300), + [sym__br_blk_seq_spc_val] = STATE(300), + [sym__b_blk_seq_spc_val] = STATE(300), + [sym__br_blk_seq] = STATE(341), + [sym__b_blk_seq_spc] = STATE(310), + [sym__br_blk_seq_itm] = STATE(966), + [sym__b_blk_seq_itm] = STATE(1041), + [sym__r_blk_map_br_val] = STATE(300), + [sym__br_blk_map_val] = STATE(300), + [sym__br_blk_map] = STATE(343), + [sym__br_blk_map_itm] = STATE(143), + [sym__br_blk_exp_itm] = STATE(319), + [sym__br_blk_key_itm] = STATE(278), + [sym__br_blk_val_itm] = STATE(328), + [sym__br_blk_imp_itm] = STATE(364), + [sym__r_blk_str_val] = STATE(300), + [sym__br_blk_str_val] = STATE(300), + [sym__r_blk_str] = STATE(344), + [sym__br_blk_str] = STATE(345), + [sym__r_flw_seq_val] = STATE(300), + [sym__br_flw_seq_val] = STATE(300), + [sym__br_sgl_flw_seq_val] = STATE(1237), + [sym__r_flw_seq] = STATE(346), + [sym__br_flw_seq] = STATE(347), + [sym__br_sgl_flw_seq] = STATE(1551), + [sym__r_flw_map_val] = STATE(300), + [sym__br_flw_map_val] = STATE(300), + [sym__br_sgl_flw_map_val] = STATE(1237), + [sym__r_flw_map] = STATE(348), + [sym__br_flw_map] = STATE(349), + [sym__br_sgl_flw_map] = STATE(1514), + [sym__r_dqt_str_val] = STATE(300), + [sym__br_dqt_str_val] = STATE(300), + [sym__br_sgl_dqt_str_val] = STATE(1237), + [sym__r_dqt_str] = STATE(350), + [sym__br_dqt_str] = STATE(351), + [sym__br_sgl_dqt_str] = STATE(1446), + [sym__r_sqt_str_val] = STATE(300), + [sym__br_sqt_str_val] = STATE(300), + [sym__br_sgl_sqt_str_val] = STATE(1237), + [sym__r_sqt_str] = STATE(352), + [sym__br_sqt_str] = STATE(353), + [sym__br_sgl_sqt_str] = STATE(1417), + [sym__r_pln_blk_val] = STATE(300), + [sym__br_pln_blk_val] = STATE(300), + [sym__br_sgl_pln_blk_val] = STATE(1237), + [sym__r_sgl_pln_blk] = STATE(356), + [sym__br_sgl_pln_blk] = STATE(282), + [sym__r_mtl_pln_blk] = STATE(356), + [sym__br_mtl_pln_blk] = STATE(357), + [sym__r_als_val] = STATE(300), + [sym__br_als_val] = STATE(263), + [sym__r_als] = STATE(330), + [sym__br_als] = STATE(283), + [sym__r_acr] = STATE(105), + [sym__br_acr] = STATE(99), + [aux_sym__r_blk_seq_repeat1] = STATE(1041), + [sym__br_blk_seq_bgn] = ACTIONS(19), + [sym__b_blk_seq_bgn] = ACTIONS(69), + [sym__br_blk_key_bgn] = ACTIONS(23), + [sym__b_blk_key_bgn] = ACTIONS(169), + [sym__br_blk_val_bgn] = ACTIONS(27), + [sym__b_blk_val_bgn] = ACTIONS(169), + [sym__r_blk_lit_bgn] = ACTIONS(73), + [sym__br_blk_lit_bgn] = ACTIONS(75), + [sym__r_blk_fld_bgn] = ACTIONS(73), + [sym__br_blk_fld_bgn] = ACTIONS(75), + [sym__r_flw_seq_bgn] = ACTIONS(171), + [sym__br_flw_seq_bgn] = ACTIONS(79), + [sym__b_flw_seq_bgn] = ACTIONS(169), + [sym__r_flw_map_bgn] = ACTIONS(173), + [sym__br_flw_map_bgn] = ACTIONS(83), + [sym__b_flw_map_bgn] = ACTIONS(169), + [sym__r_dqt_str_bgn] = ACTIONS(175), + [sym__br_dqt_str_bgn] = ACTIONS(87), + [sym__b_dqt_str_bgn] = ACTIONS(169), + [sym__r_sqt_str_bgn] = ACTIONS(177), + [sym__br_sqt_str_bgn] = ACTIONS(91), + [sym__b_sqt_str_bgn] = ACTIONS(169), + [sym__r_sgl_pln_nul_blk] = ACTIONS(179), + [sym__br_sgl_pln_nul_blk] = ACTIONS(95), + [sym__b_sgl_pln_nul_blk] = ACTIONS(169), + [sym__r_sgl_pln_bol_blk] = ACTIONS(179), + [sym__br_sgl_pln_bol_blk] = ACTIONS(95), + [sym__b_sgl_pln_bol_blk] = ACTIONS(169), + [sym__r_sgl_pln_int_blk] = ACTIONS(179), + [sym__br_sgl_pln_int_blk] = ACTIONS(95), + [sym__b_sgl_pln_int_blk] = ACTIONS(169), + [sym__r_sgl_pln_flt_blk] = ACTIONS(179), + [sym__br_sgl_pln_flt_blk] = ACTIONS(95), + [sym__b_sgl_pln_flt_blk] = ACTIONS(169), + [sym__r_sgl_pln_tms_blk] = ACTIONS(179), + [sym__br_sgl_pln_tms_blk] = ACTIONS(95), + [sym__b_sgl_pln_tms_blk] = ACTIONS(169), + [sym__r_sgl_pln_str_blk] = ACTIONS(179), + [sym__br_sgl_pln_str_blk] = ACTIONS(95), + [sym__b_sgl_pln_str_blk] = ACTIONS(169), + [sym__r_mtl_pln_str_blk] = ACTIONS(97), + [sym__br_mtl_pln_str_blk] = ACTIONS(99), + [sym__r_tag] = ACTIONS(181), + [sym__br_tag] = ACTIONS(103), + [sym__b_tag] = ACTIONS(169), + [sym__r_acr_bgn] = ACTIONS(183), + [sym__br_acr_bgn] = ACTIONS(107), + [sym__b_acr_bgn] = ACTIONS(169), + [sym__r_als_bgn] = ACTIONS(185), + [sym__br_als_bgn] = ACTIONS(111), + [sym__b_als_bgn] = ACTIONS(169), + [sym__bl] = ACTIONS(169), + [sym_comment] = ACTIONS(3), + }, + [STATE(12)] = { + [sym__exp_doc_tal] = STATE(1143), + [sym__r_prp_val] = STATE(1143), + [sym__br_prp_val] = STATE(1143), + [sym__br_sgl_prp_val] = STATE(1237), + [sym__r_prp] = STATE(81), + [sym__br_prp] = STATE(80), + [sym__br_sgl_prp] = STATE(309), + [sym__r_blk_seq_br_val] = STATE(1143), + [sym__br_blk_seq_val] = STATE(1143), + [sym__br_blk_seq] = STATE(1170), + [sym__br_blk_seq_itm] = STATE(1048), + [sym__r_blk_map_br_val] = STATE(1143), + [sym__br_blk_map_val] = STATE(1143), + [sym__br_blk_map] = STATE(1200), + [sym__br_blk_map_itm] = STATE(130), + [sym__br_blk_exp_itm] = STATE(319), + [sym__br_blk_key_itm] = STATE(278), + [sym__br_blk_val_itm] = STATE(328), + [sym__br_blk_imp_itm] = STATE(364), + [sym__r_blk_str_val] = STATE(1143), + [sym__br_blk_str_val] = STATE(1143), + [sym__r_blk_str] = STATE(1083), + [sym__br_blk_str] = STATE(1103), + [sym__r_flw_seq_val] = STATE(1143), + [sym__br_flw_seq_val] = STATE(1143), + [sym__br_sgl_flw_seq_val] = STATE(1237), + [sym__r_flw_seq] = STATE(1115), + [sym__br_flw_seq] = STATE(1156), + [sym__br_sgl_flw_seq] = STATE(1551), + [sym__r_flw_map_val] = STATE(1143), + [sym__br_flw_map_val] = STATE(1143), + [sym__br_sgl_flw_map_val] = STATE(1237), + [sym__r_flw_map] = STATE(1070), + [sym__br_flw_map] = STATE(1071), + [sym__br_sgl_flw_map] = STATE(1514), + [sym__r_dqt_str_val] = STATE(1143), + [sym__br_dqt_str_val] = STATE(1143), + [sym__br_sgl_dqt_str_val] = STATE(1237), + [sym__r_dqt_str] = STATE(1060), + [sym__br_dqt_str] = STATE(1087), + [sym__br_sgl_dqt_str] = STATE(1446), + [sym__r_sqt_str_val] = STATE(1143), + [sym__br_sqt_str_val] = STATE(1143), + [sym__br_sgl_sqt_str_val] = STATE(1237), + [sym__r_sqt_str] = STATE(1127), + [sym__br_sqt_str] = STATE(1129), + [sym__br_sgl_sqt_str] = STATE(1417), + [sym__r_pln_blk_val] = STATE(1143), + [sym__br_pln_blk_val] = STATE(1143), + [sym__br_sgl_pln_blk_val] = STATE(1237), + [sym__r_sgl_pln_blk] = STATE(1094), + [sym__br_sgl_pln_blk] = STATE(997), + [sym__r_mtl_pln_blk] = STATE(1094), + [sym__br_mtl_pln_blk] = STATE(1095), + [sym__r_als_val] = STATE(1143), + [sym__br_als_val] = STATE(918), + [sym__r_als] = STATE(1049), + [sym__br_als] = STATE(1001), + [sym__r_acr] = STATE(160), + [sym__br_acr] = STATE(146), + [sym__eof] = ACTIONS(187), + [sym__s_drs_end] = ACTIONS(187), + [sym__s_doc_end] = ACTIONS(187), + [sym__br_blk_seq_bgn] = ACTIONS(19), + [sym__br_blk_key_bgn] = ACTIONS(23), + [sym__br_blk_val_bgn] = ACTIONS(27), + [sym__r_blk_lit_bgn] = ACTIONS(29), + [sym__br_blk_lit_bgn] = ACTIONS(31), + [sym__r_blk_fld_bgn] = ACTIONS(29), + [sym__br_blk_fld_bgn] = ACTIONS(31), + [sym__r_flw_seq_bgn] = ACTIONS(189), + [sym__br_flw_seq_bgn] = ACTIONS(35), + [sym__r_flw_map_bgn] = ACTIONS(191), + [sym__br_flw_map_bgn] = ACTIONS(39), + [sym__r_dqt_str_bgn] = ACTIONS(193), + [sym__br_dqt_str_bgn] = ACTIONS(43), + [sym__r_sqt_str_bgn] = ACTIONS(195), + [sym__br_sqt_str_bgn] = ACTIONS(47), + [sym__r_sgl_pln_nul_blk] = ACTIONS(197), + [sym__br_sgl_pln_nul_blk] = ACTIONS(51), + [sym__r_sgl_pln_bol_blk] = ACTIONS(197), + [sym__br_sgl_pln_bol_blk] = ACTIONS(51), + [sym__r_sgl_pln_int_blk] = ACTIONS(197), + [sym__br_sgl_pln_int_blk] = ACTIONS(51), + [sym__r_sgl_pln_flt_blk] = ACTIONS(197), + [sym__br_sgl_pln_flt_blk] = ACTIONS(51), + [sym__r_sgl_pln_tms_blk] = ACTIONS(197), + [sym__br_sgl_pln_tms_blk] = ACTIONS(51), + [sym__r_sgl_pln_str_blk] = ACTIONS(197), + [sym__br_sgl_pln_str_blk] = ACTIONS(51), + [sym__r_mtl_pln_str_blk] = ACTIONS(53), + [sym__br_mtl_pln_str_blk] = ACTIONS(55), + [sym__r_tag] = ACTIONS(199), + [sym__br_tag] = ACTIONS(59), + [sym__r_acr_bgn] = ACTIONS(201), + [sym__br_acr_bgn] = ACTIONS(63), + [sym__r_als_bgn] = ACTIONS(203), + [sym__br_als_bgn] = ACTIONS(67), + [sym_comment] = ACTIONS(3), + }, + [STATE(13)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_sgl_prp_val] = STATE(1038), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_sgl_prp] = STATE(265), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_sgl_flw_seq_val] = STATE(1045), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_sgl_flw_seq] = STATE(1209), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_sgl_flw_map_val] = STATE(1045), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__r_sgl_flw_map] = STATE(1210), + [sym__flw_map_tal] = STATE(1133), + [sym__sgl_flw_map_tal] = STATE(1517), + [sym__r_flw_map_dat] = STATE(1138), + [sym__br_flw_map_dat] = STATE(1138), + [sym__r_sgl_flw_col_dat] = STATE(1516), + [sym__r_flw_map_itm] = STATE(670), + [sym__br_flw_map_itm] = STATE(671), + [sym__r_sgl_flw_col_itm] = STATE(964), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_sgl_flw_exp_par] = STATE(1250), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_sgl_flw_imp_par] = STATE(1251), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_sgl_flw_njl_ann_par] = STATE(1252), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_sgl_dqt_str_val] = STATE(1045), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sgl_dqt_str] = STATE(1213), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sgl_sqt_str_val] = STATE(1045), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_sgl_sqt_str] = STATE(1214), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw_val] = STATE(1038), + [sym__r_sgl_pln_flw] = STATE(556), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(475), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(191), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(205), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(209), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(213), + [sym__br_flw_map_end] = ACTIONS(215), + [sym__b_flw_map_end] = ACTIONS(215), + [sym__r_flw_key_bgn] = ACTIONS(217), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(221), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(225), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(229), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(241), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(14)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_sgl_prp_val] = STATE(1038), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_sgl_prp] = STATE(265), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_sgl_flw_seq_val] = STATE(1045), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_sgl_flw_seq] = STATE(1209), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_sgl_flw_map_val] = STATE(1045), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__r_sgl_flw_map] = STATE(1210), + [sym__flw_map_tal] = STATE(1076), + [sym__sgl_flw_map_tal] = STATE(1450), + [sym__r_flw_map_dat] = STATE(1138), + [sym__br_flw_map_dat] = STATE(1138), + [sym__r_sgl_flw_col_dat] = STATE(1516), + [sym__r_flw_map_itm] = STATE(670), + [sym__br_flw_map_itm] = STATE(671), + [sym__r_sgl_flw_col_itm] = STATE(964), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_sgl_flw_exp_par] = STATE(1250), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_sgl_flw_imp_par] = STATE(1251), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_sgl_flw_njl_ann_par] = STATE(1252), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_sgl_dqt_str_val] = STATE(1045), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sgl_dqt_str] = STATE(1213), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sgl_sqt_str_val] = STATE(1045), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_sgl_sqt_str] = STATE(1214), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw_val] = STATE(1038), + [sym__r_sgl_pln_flw] = STATE(556), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(475), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(191), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(205), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(209), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(213), + [sym__br_flw_map_end] = ACTIONS(253), + [sym__b_flw_map_end] = ACTIONS(253), + [sym__r_flw_key_bgn] = ACTIONS(217), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(221), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(225), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(229), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(241), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(15)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_sgl_prp_val] = STATE(1038), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_sgl_prp] = STATE(265), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_sgl_flw_seq_val] = STATE(1045), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_sgl_flw_seq] = STATE(1209), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_sgl_flw_map_val] = STATE(1045), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__r_sgl_flw_map] = STATE(1210), + [sym__flw_map_tal] = STATE(1258), + [sym__sgl_flw_map_tal] = STATE(1517), + [sym__r_flw_map_dat] = STATE(1125), + [sym__br_flw_map_dat] = STATE(1125), + [sym__r_sgl_flw_col_dat] = STATE(1516), + [sym__r_flw_map_itm] = STATE(670), + [sym__br_flw_map_itm] = STATE(671), + [sym__r_sgl_flw_col_itm] = STATE(964), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_sgl_flw_exp_par] = STATE(1250), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_sgl_flw_imp_par] = STATE(1251), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_sgl_flw_njl_ann_par] = STATE(1252), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_sgl_dqt_str_val] = STATE(1045), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sgl_dqt_str] = STATE(1213), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sgl_sqt_str_val] = STATE(1045), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_sgl_sqt_str] = STATE(1214), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw_val] = STATE(1038), + [sym__r_sgl_pln_flw] = STATE(556), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(475), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(191), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(205), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(209), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(255), + [sym__br_flw_map_end] = ACTIONS(257), + [sym__b_flw_map_end] = ACTIONS(257), + [sym__r_flw_key_bgn] = ACTIONS(217), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(221), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(225), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(229), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(241), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(16)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_sgl_prp_val] = STATE(1038), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_sgl_prp] = STATE(265), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_sgl_flw_seq_val] = STATE(1045), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_sgl_flw_seq] = STATE(1209), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_sgl_flw_map_val] = STATE(1045), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__r_sgl_flw_map] = STATE(1210), + [sym__flw_map_tal] = STATE(370), + [sym__sgl_flw_map_tal] = STATE(1450), + [sym__r_flw_map_dat] = STATE(1152), + [sym__br_flw_map_dat] = STATE(1152), + [sym__r_sgl_flw_col_dat] = STATE(1516), + [sym__r_flw_map_itm] = STATE(670), + [sym__br_flw_map_itm] = STATE(671), + [sym__r_sgl_flw_col_itm] = STATE(964), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_sgl_flw_exp_par] = STATE(1250), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_sgl_flw_imp_par] = STATE(1251), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_sgl_flw_njl_ann_par] = STATE(1252), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_sgl_dqt_str_val] = STATE(1045), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sgl_dqt_str] = STATE(1213), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sgl_sqt_str_val] = STATE(1045), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_sgl_sqt_str] = STATE(1214), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw_val] = STATE(1038), + [sym__r_sgl_pln_flw] = STATE(556), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(475), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(191), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(205), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(209), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(259), + [sym__br_flw_map_end] = ACTIONS(261), + [sym__b_flw_map_end] = ACTIONS(261), + [sym__r_flw_key_bgn] = ACTIONS(217), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(221), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(225), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(229), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(241), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(17)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_sgl_prp_val] = STATE(1038), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_sgl_prp] = STATE(265), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_sgl_flw_seq_val] = STATE(1045), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_sgl_flw_seq] = STATE(1209), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_sgl_flw_map_val] = STATE(1045), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__r_sgl_flw_map] = STATE(1210), + [sym__flw_map_tal] = STATE(1259), + [sym__sgl_flw_map_tal] = STATE(1450), + [sym__r_flw_map_dat] = STATE(1125), + [sym__br_flw_map_dat] = STATE(1125), + [sym__r_sgl_flw_col_dat] = STATE(1516), + [sym__r_flw_map_itm] = STATE(670), + [sym__br_flw_map_itm] = STATE(671), + [sym__r_sgl_flw_col_itm] = STATE(964), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_sgl_flw_exp_par] = STATE(1250), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_sgl_flw_imp_par] = STATE(1251), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_sgl_flw_njl_ann_par] = STATE(1252), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_sgl_dqt_str_val] = STATE(1045), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sgl_dqt_str] = STATE(1213), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sgl_sqt_str_val] = STATE(1045), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_sgl_sqt_str] = STATE(1214), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw_val] = STATE(1038), + [sym__r_sgl_pln_flw] = STATE(556), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(475), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(191), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(205), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(209), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(255), + [sym__br_flw_map_end] = ACTIONS(263), + [sym__b_flw_map_end] = ACTIONS(263), + [sym__r_flw_key_bgn] = ACTIONS(217), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(221), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(225), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(229), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(241), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(18)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_sgl_prp_val] = STATE(1038), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_sgl_prp] = STATE(265), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_sgl_flw_seq_val] = STATE(1045), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_sgl_flw_seq] = STATE(1209), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_sgl_flw_map_val] = STATE(1045), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__r_sgl_flw_map] = STATE(1210), + [sym__flw_map_tal] = STATE(369), + [sym__sgl_flw_map_tal] = STATE(1517), + [sym__r_flw_map_dat] = STATE(1152), + [sym__br_flw_map_dat] = STATE(1152), + [sym__r_sgl_flw_col_dat] = STATE(1516), + [sym__r_flw_map_itm] = STATE(670), + [sym__br_flw_map_itm] = STATE(671), + [sym__r_sgl_flw_col_itm] = STATE(964), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_sgl_flw_exp_par] = STATE(1250), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_sgl_flw_imp_par] = STATE(1251), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_sgl_flw_njl_ann_par] = STATE(1252), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_sgl_dqt_str_val] = STATE(1045), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sgl_dqt_str] = STATE(1213), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sgl_sqt_str_val] = STATE(1045), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_sgl_sqt_str] = STATE(1214), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw_val] = STATE(1038), + [sym__r_sgl_pln_flw] = STATE(556), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(475), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(191), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(205), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(209), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(259), + [sym__br_flw_map_end] = ACTIONS(265), + [sym__b_flw_map_end] = ACTIONS(265), + [sym__r_flw_key_bgn] = ACTIONS(217), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(221), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(225), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(229), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(241), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(19)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_sgl_prp_val] = STATE(1038), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_sgl_prp] = STATE(265), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_sgl_flw_seq_val] = STATE(1045), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_sgl_flw_seq] = STATE(1209), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_sgl_flw_map_val] = STATE(1045), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__r_sgl_flw_map] = STATE(1210), + [sym__flw_map_tal] = STATE(570), + [sym__sgl_flw_map_tal] = STATE(1064), + [sym__r_flw_map_dat] = STATE(1173), + [sym__br_flw_map_dat] = STATE(1173), + [sym__r_sgl_flw_col_dat] = STATE(1476), + [sym__r_flw_map_itm] = STATE(670), + [sym__br_flw_map_itm] = STATE(671), + [sym__r_sgl_flw_col_itm] = STATE(964), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_sgl_flw_exp_par] = STATE(1250), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_sgl_flw_imp_par] = STATE(1251), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_sgl_flw_njl_ann_par] = STATE(1252), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_sgl_dqt_str_val] = STATE(1045), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sgl_dqt_str] = STATE(1213), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sgl_sqt_str_val] = STATE(1045), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_sgl_sqt_str] = STATE(1214), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw_val] = STATE(1038), + [sym__r_sgl_pln_flw] = STATE(556), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(475), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(191), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(205), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(209), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(267), + [sym__br_flw_map_end] = ACTIONS(269), + [sym__b_flw_map_end] = ACTIONS(269), + [sym__r_flw_key_bgn] = ACTIONS(217), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(221), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(225), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(229), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(241), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(20)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_sgl_prp_val] = STATE(1038), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_sgl_prp] = STATE(265), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_sgl_flw_seq_val] = STATE(1045), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_sgl_flw_seq] = STATE(1209), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_sgl_flw_map_val] = STATE(1045), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__r_sgl_flw_map] = STATE(1210), + [sym__flw_map_tal] = STATE(1321), + [sym__sgl_flw_map_tal] = STATE(1422), + [sym__r_flw_map_dat] = STATE(1183), + [sym__br_flw_map_dat] = STATE(1183), + [sym__r_sgl_flw_col_dat] = STATE(1460), + [sym__r_flw_map_itm] = STATE(670), + [sym__br_flw_map_itm] = STATE(671), + [sym__r_sgl_flw_col_itm] = STATE(964), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_sgl_flw_exp_par] = STATE(1250), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_sgl_flw_imp_par] = STATE(1251), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_sgl_flw_njl_ann_par] = STATE(1252), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_sgl_dqt_str_val] = STATE(1045), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sgl_dqt_str] = STATE(1213), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sgl_sqt_str_val] = STATE(1045), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_sgl_sqt_str] = STATE(1214), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw_val] = STATE(1038), + [sym__r_sgl_pln_flw] = STATE(556), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(475), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(191), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(205), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(209), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(271), + [sym__br_flw_map_end] = ACTIONS(273), + [sym__b_flw_map_end] = ACTIONS(273), + [sym__r_flw_key_bgn] = ACTIONS(217), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(221), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(225), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(229), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(241), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(21)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_sgl_prp_val] = STATE(1038), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_sgl_prp] = STATE(265), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_sgl_flw_seq_val] = STATE(1045), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_sgl_flw_seq] = STATE(1209), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_sgl_flw_map_val] = STATE(1045), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__r_sgl_flw_map] = STATE(1210), + [sym__flw_map_tal] = STATE(715), + [sym__sgl_flw_map_tal] = STATE(1145), + [sym__r_flw_map_dat] = STATE(1166), + [sym__br_flw_map_dat] = STATE(1166), + [sym__r_sgl_flw_col_dat] = STATE(1471), + [sym__r_flw_map_itm] = STATE(670), + [sym__br_flw_map_itm] = STATE(671), + [sym__r_sgl_flw_col_itm] = STATE(964), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_sgl_flw_exp_par] = STATE(1250), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_sgl_flw_imp_par] = STATE(1251), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_sgl_flw_njl_ann_par] = STATE(1252), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_sgl_dqt_str_val] = STATE(1045), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sgl_dqt_str] = STATE(1213), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sgl_sqt_str_val] = STATE(1045), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_sgl_sqt_str] = STATE(1214), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw_val] = STATE(1038), + [sym__r_sgl_pln_flw] = STATE(556), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(475), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(191), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(205), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(209), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(275), + [sym__br_flw_map_end] = ACTIONS(277), + [sym__b_flw_map_end] = ACTIONS(277), + [sym__r_flw_key_bgn] = ACTIONS(217), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(221), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(225), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(229), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(241), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(22)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_sgl_prp_val] = STATE(1038), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_sgl_prp] = STATE(265), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_sgl_flw_seq_val] = STATE(1045), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_sgl_flw_seq] = STATE(1209), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_sgl_flw_map_val] = STATE(1045), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__r_sgl_flw_map] = STATE(1210), + [sym__flw_map_tal] = STATE(831), + [sym__sgl_flw_map_tal] = STATE(1264), + [sym__r_flw_map_dat] = STATE(1194), + [sym__br_flw_map_dat] = STATE(1194), + [sym__r_sgl_flw_col_dat] = STATE(1527), + [sym__r_flw_map_itm] = STATE(670), + [sym__br_flw_map_itm] = STATE(671), + [sym__r_sgl_flw_col_itm] = STATE(964), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_sgl_flw_exp_par] = STATE(1250), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_sgl_flw_imp_par] = STATE(1251), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_sgl_flw_njl_ann_par] = STATE(1252), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_sgl_dqt_str_val] = STATE(1045), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sgl_dqt_str] = STATE(1213), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sgl_sqt_str_val] = STATE(1045), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_sgl_sqt_str] = STATE(1214), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw_val] = STATE(1038), + [sym__r_sgl_pln_flw] = STATE(556), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(475), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(191), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(205), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(209), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(279), + [sym__br_flw_map_end] = ACTIONS(281), + [sym__b_flw_map_end] = ACTIONS(281), + [sym__r_flw_key_bgn] = ACTIONS(217), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(221), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(225), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(229), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(241), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(23)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_sgl_prp_val] = STATE(1038), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_sgl_prp] = STATE(265), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_sgl_flw_seq_val] = STATE(1045), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_sgl_flw_seq] = STATE(1209), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_sgl_flw_map_val] = STATE(1045), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__r_sgl_flw_map] = STATE(1210), + [sym__flw_map_tal] = STATE(879), + [sym__sgl_flw_map_tal] = STATE(1322), + [sym__r_flw_map_dat] = STATE(1212), + [sym__br_flw_map_dat] = STATE(1212), + [sym__r_sgl_flw_col_dat] = STATE(1449), + [sym__r_flw_map_itm] = STATE(670), + [sym__br_flw_map_itm] = STATE(671), + [sym__r_sgl_flw_col_itm] = STATE(964), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_sgl_flw_exp_par] = STATE(1250), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_sgl_flw_imp_par] = STATE(1251), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_sgl_flw_njl_ann_par] = STATE(1252), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_sgl_dqt_str_val] = STATE(1045), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sgl_dqt_str] = STATE(1213), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sgl_sqt_str_val] = STATE(1045), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_sgl_sqt_str] = STATE(1214), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw_val] = STATE(1038), + [sym__r_sgl_pln_flw] = STATE(556), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(475), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(191), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(205), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(209), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(283), + [sym__br_flw_map_end] = ACTIONS(285), + [sym__b_flw_map_end] = ACTIONS(285), + [sym__r_flw_key_bgn] = ACTIONS(217), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(221), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(225), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(229), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(241), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(24)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_sgl_prp_val] = STATE(976), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_sgl_prp] = STATE(261), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_sgl_flw_seq_val] = STATE(1025), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__r_sgl_flw_seq] = STATE(1110), + [sym__flw_seq_tal] = STATE(566), + [sym__sgl_flw_seq_tal] = STATE(1050), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_sgl_flw_map_val] = STATE(1025), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_sgl_flw_map] = STATE(1113), + [sym__r_flw_seq_dat] = STATE(1172), + [sym__br_flw_seq_dat] = STATE(1172), + [sym__r_sgl_flw_col_dat] = STATE(1473), + [sym__r_flw_seq_itm] = STATE(649), + [sym__br_flw_seq_itm] = STATE(661), + [sym__r_sgl_flw_col_itm] = STATE(986), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_sgl_flw_exp_par] = STATE(1225), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_sgl_flw_imp_par] = STATE(1240), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_sgl_flw_njl_ann_par] = STATE(1253), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_sgl_dqt_str_val] = STATE(1025), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sgl_dqt_str] = STATE(1114), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sgl_sqt_str_val] = STATE(1025), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_sgl_sqt_str] = STATE(1116), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw_val] = STATE(976), + [sym__r_sgl_pln_flw] = STATE(747), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(538), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(207), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(287), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(291), + [sym__br_flw_seq_end] = ACTIONS(293), + [sym__b_flw_seq_end] = ACTIONS(293), + [sym__r_flw_map_bgn] = ACTIONS(295), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(299), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(303), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(307), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(311), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(323), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(25)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_sgl_prp_val] = STATE(976), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_sgl_prp] = STATE(261), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_sgl_flw_seq_val] = STATE(1025), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__r_sgl_flw_seq] = STATE(1110), + [sym__flw_seq_tal] = STATE(367), + [sym__sgl_flw_seq_tal] = STATE(1416), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_sgl_flw_map_val] = STATE(1025), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_sgl_flw_map] = STATE(1113), + [sym__r_flw_seq_dat] = STATE(1151), + [sym__br_flw_seq_dat] = STATE(1151), + [sym__r_sgl_flw_col_dat] = STATE(1459), + [sym__r_flw_seq_itm] = STATE(649), + [sym__br_flw_seq_itm] = STATE(661), + [sym__r_sgl_flw_col_itm] = STATE(986), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_sgl_flw_exp_par] = STATE(1225), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_sgl_flw_imp_par] = STATE(1240), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_sgl_flw_njl_ann_par] = STATE(1253), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_sgl_dqt_str_val] = STATE(1025), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sgl_dqt_str] = STATE(1114), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sgl_sqt_str_val] = STATE(1025), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_sgl_sqt_str] = STATE(1116), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw_val] = STATE(976), + [sym__r_sgl_pln_flw] = STATE(747), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(538), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(207), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(287), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(335), + [sym__br_flw_seq_end] = ACTIONS(337), + [sym__b_flw_seq_end] = ACTIONS(337), + [sym__r_flw_map_bgn] = ACTIONS(295), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(299), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(303), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(307), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(311), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(323), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(26)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_sgl_prp_val] = STATE(976), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_sgl_prp] = STATE(261), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_sgl_flw_seq_val] = STATE(1025), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__r_sgl_flw_seq] = STATE(1110), + [sym__flw_seq_tal] = STATE(366), + [sym__sgl_flw_seq_tal] = STATE(1423), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_sgl_flw_map_val] = STATE(1025), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_sgl_flw_map] = STATE(1113), + [sym__r_flw_seq_dat] = STATE(1151), + [sym__br_flw_seq_dat] = STATE(1151), + [sym__r_sgl_flw_col_dat] = STATE(1459), + [sym__r_flw_seq_itm] = STATE(649), + [sym__br_flw_seq_itm] = STATE(661), + [sym__r_sgl_flw_col_itm] = STATE(986), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_sgl_flw_exp_par] = STATE(1225), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_sgl_flw_imp_par] = STATE(1240), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_sgl_flw_njl_ann_par] = STATE(1253), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_sgl_dqt_str_val] = STATE(1025), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sgl_dqt_str] = STATE(1114), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sgl_sqt_str_val] = STATE(1025), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_sgl_sqt_str] = STATE(1116), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw_val] = STATE(976), + [sym__r_sgl_pln_flw] = STATE(747), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(538), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(207), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(287), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(335), + [sym__br_flw_seq_end] = ACTIONS(339), + [sym__b_flw_seq_end] = ACTIONS(339), + [sym__r_flw_map_bgn] = ACTIONS(295), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(299), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(303), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(307), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(311), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(323), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(27)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_sgl_prp_val] = STATE(976), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_sgl_prp] = STATE(261), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_sgl_flw_seq_val] = STATE(1025), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__r_sgl_flw_seq] = STATE(1110), + [sym__flw_seq_tal] = STATE(1109), + [sym__sgl_flw_seq_tal] = STATE(1416), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_sgl_flw_map_val] = STATE(1025), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_sgl_flw_map] = STATE(1113), + [sym__r_flw_seq_dat] = STATE(1058), + [sym__br_flw_seq_dat] = STATE(1058), + [sym__r_sgl_flw_col_dat] = STATE(1459), + [sym__r_flw_seq_itm] = STATE(649), + [sym__br_flw_seq_itm] = STATE(661), + [sym__r_sgl_flw_col_itm] = STATE(986), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_sgl_flw_exp_par] = STATE(1225), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_sgl_flw_imp_par] = STATE(1240), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_sgl_flw_njl_ann_par] = STATE(1253), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_sgl_dqt_str_val] = STATE(1025), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sgl_dqt_str] = STATE(1114), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sgl_sqt_str_val] = STATE(1025), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_sgl_sqt_str] = STATE(1116), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw_val] = STATE(976), + [sym__r_sgl_pln_flw] = STATE(747), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(538), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(207), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(287), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(341), + [sym__br_flw_seq_end] = ACTIONS(343), + [sym__b_flw_seq_end] = ACTIONS(343), + [sym__r_flw_map_bgn] = ACTIONS(295), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(299), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(303), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(307), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(311), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(323), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(28)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_sgl_prp_val] = STATE(976), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_sgl_prp] = STATE(261), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_sgl_flw_seq_val] = STATE(1025), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__r_sgl_flw_seq] = STATE(1110), + [sym__flw_seq_tal] = STATE(1247), + [sym__sgl_flw_seq_tal] = STATE(1423), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_sgl_flw_map_val] = STATE(1025), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_sgl_flw_map] = STATE(1113), + [sym__r_flw_seq_dat] = STATE(1124), + [sym__br_flw_seq_dat] = STATE(1124), + [sym__r_sgl_flw_col_dat] = STATE(1459), + [sym__r_flw_seq_itm] = STATE(649), + [sym__br_flw_seq_itm] = STATE(661), + [sym__r_sgl_flw_col_itm] = STATE(986), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_sgl_flw_exp_par] = STATE(1225), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_sgl_flw_imp_par] = STATE(1240), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_sgl_flw_njl_ann_par] = STATE(1253), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_sgl_dqt_str_val] = STATE(1025), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sgl_dqt_str] = STATE(1114), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sgl_sqt_str_val] = STATE(1025), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_sgl_sqt_str] = STATE(1116), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw_val] = STATE(976), + [sym__r_sgl_pln_flw] = STATE(747), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(538), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(207), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(287), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(345), + [sym__br_flw_seq_end] = ACTIONS(347), + [sym__b_flw_seq_end] = ACTIONS(347), + [sym__r_flw_map_bgn] = ACTIONS(295), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(299), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(303), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(307), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(311), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(323), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(29)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_sgl_prp_val] = STATE(976), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_sgl_prp] = STATE(261), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_sgl_flw_seq_val] = STATE(1025), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__r_sgl_flw_seq] = STATE(1110), + [sym__flw_seq_tal] = STATE(1256), + [sym__sgl_flw_seq_tal] = STATE(1416), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_sgl_flw_map_val] = STATE(1025), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_sgl_flw_map] = STATE(1113), + [sym__r_flw_seq_dat] = STATE(1124), + [sym__br_flw_seq_dat] = STATE(1124), + [sym__r_sgl_flw_col_dat] = STATE(1459), + [sym__r_flw_seq_itm] = STATE(649), + [sym__br_flw_seq_itm] = STATE(661), + [sym__r_sgl_flw_col_itm] = STATE(986), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_sgl_flw_exp_par] = STATE(1225), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_sgl_flw_imp_par] = STATE(1240), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_sgl_flw_njl_ann_par] = STATE(1253), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_sgl_dqt_str_val] = STATE(1025), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sgl_dqt_str] = STATE(1114), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sgl_sqt_str_val] = STATE(1025), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_sgl_sqt_str] = STATE(1116), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw_val] = STATE(976), + [sym__r_sgl_pln_flw] = STATE(747), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(538), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(207), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(287), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(345), + [sym__br_flw_seq_end] = ACTIONS(349), + [sym__b_flw_seq_end] = ACTIONS(349), + [sym__r_flw_map_bgn] = ACTIONS(295), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(299), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(303), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(307), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(311), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(323), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(30)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_sgl_prp_val] = STATE(976), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_sgl_prp] = STATE(261), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_sgl_flw_seq_val] = STATE(1025), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__r_sgl_flw_seq] = STATE(1110), + [sym__flw_seq_tal] = STATE(712), + [sym__sgl_flw_seq_tal] = STATE(1139), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_sgl_flw_map_val] = STATE(1025), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_sgl_flw_map] = STATE(1113), + [sym__r_flw_seq_dat] = STATE(1165), + [sym__br_flw_seq_dat] = STATE(1165), + [sym__r_sgl_flw_col_dat] = STATE(1468), + [sym__r_flw_seq_itm] = STATE(649), + [sym__br_flw_seq_itm] = STATE(661), + [sym__r_sgl_flw_col_itm] = STATE(986), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_sgl_flw_exp_par] = STATE(1225), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_sgl_flw_imp_par] = STATE(1240), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_sgl_flw_njl_ann_par] = STATE(1253), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_sgl_dqt_str_val] = STATE(1025), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sgl_dqt_str] = STATE(1114), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sgl_sqt_str_val] = STATE(1025), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_sgl_sqt_str] = STATE(1116), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw_val] = STATE(976), + [sym__r_sgl_pln_flw] = STATE(747), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(538), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(207), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(287), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(351), + [sym__br_flw_seq_end] = ACTIONS(353), + [sym__b_flw_seq_end] = ACTIONS(353), + [sym__r_flw_map_bgn] = ACTIONS(295), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(299), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(303), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(307), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(311), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(323), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(31)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_sgl_prp_val] = STATE(976), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_sgl_prp] = STATE(261), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_sgl_flw_seq_val] = STATE(1025), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__r_sgl_flw_seq] = STATE(1110), + [sym__flw_seq_tal] = STATE(828), + [sym__sgl_flw_seq_tal] = STATE(1257), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_sgl_flw_map_val] = STATE(1025), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_sgl_flw_map] = STATE(1113), + [sym__r_flw_seq_dat] = STATE(1193), + [sym__br_flw_seq_dat] = STATE(1193), + [sym__r_sgl_flw_col_dat] = STATE(1525), + [sym__r_flw_seq_itm] = STATE(649), + [sym__br_flw_seq_itm] = STATE(661), + [sym__r_sgl_flw_col_itm] = STATE(986), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_sgl_flw_exp_par] = STATE(1225), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_sgl_flw_imp_par] = STATE(1240), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_sgl_flw_njl_ann_par] = STATE(1253), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_sgl_dqt_str_val] = STATE(1025), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sgl_dqt_str] = STATE(1114), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sgl_sqt_str_val] = STATE(1025), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_sgl_sqt_str] = STATE(1116), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw_val] = STATE(976), + [sym__r_sgl_pln_flw] = STATE(747), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(538), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(207), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(287), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(355), + [sym__br_flw_seq_end] = ACTIONS(357), + [sym__b_flw_seq_end] = ACTIONS(357), + [sym__r_flw_map_bgn] = ACTIONS(295), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(299), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(303), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(307), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(311), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(323), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(32)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_sgl_prp_val] = STATE(976), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_sgl_prp] = STATE(261), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_sgl_flw_seq_val] = STATE(1025), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__r_sgl_flw_seq] = STATE(1110), + [sym__flw_seq_tal] = STATE(1131), + [sym__sgl_flw_seq_tal] = STATE(1423), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_sgl_flw_map_val] = STATE(1025), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_sgl_flw_map] = STATE(1113), + [sym__r_flw_seq_dat] = STATE(1058), + [sym__br_flw_seq_dat] = STATE(1058), + [sym__r_sgl_flw_col_dat] = STATE(1459), + [sym__r_flw_seq_itm] = STATE(649), + [sym__br_flw_seq_itm] = STATE(661), + [sym__r_sgl_flw_col_itm] = STATE(986), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_sgl_flw_exp_par] = STATE(1225), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_sgl_flw_imp_par] = STATE(1240), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_sgl_flw_njl_ann_par] = STATE(1253), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_sgl_dqt_str_val] = STATE(1025), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sgl_dqt_str] = STATE(1114), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sgl_sqt_str_val] = STATE(1025), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_sgl_sqt_str] = STATE(1116), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw_val] = STATE(976), + [sym__r_sgl_pln_flw] = STATE(747), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(538), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(207), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(287), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(341), + [sym__br_flw_seq_end] = ACTIONS(359), + [sym__b_flw_seq_end] = ACTIONS(359), + [sym__r_flw_map_bgn] = ACTIONS(295), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(299), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(303), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(307), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(311), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(323), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(33)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_sgl_prp_val] = STATE(976), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_sgl_prp] = STATE(261), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_sgl_flw_seq_val] = STATE(1025), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__r_sgl_flw_seq] = STATE(1110), + [sym__flw_seq_tal] = STATE(1316), + [sym__sgl_flw_seq_tal] = STATE(1509), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_sgl_flw_map_val] = STATE(1025), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_sgl_flw_map] = STATE(1113), + [sym__r_flw_seq_dat] = STATE(1182), + [sym__br_flw_seq_dat] = STATE(1182), + [sym__r_sgl_flw_col_dat] = STATE(1457), + [sym__r_flw_seq_itm] = STATE(649), + [sym__br_flw_seq_itm] = STATE(661), + [sym__r_sgl_flw_col_itm] = STATE(986), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_sgl_flw_exp_par] = STATE(1225), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_sgl_flw_imp_par] = STATE(1240), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_sgl_flw_njl_ann_par] = STATE(1253), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_sgl_dqt_str_val] = STATE(1025), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sgl_dqt_str] = STATE(1114), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sgl_sqt_str_val] = STATE(1025), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_sgl_sqt_str] = STATE(1116), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw_val] = STATE(976), + [sym__r_sgl_pln_flw] = STATE(747), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(538), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(207), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(287), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(361), + [sym__br_flw_seq_end] = ACTIONS(363), + [sym__b_flw_seq_end] = ACTIONS(363), + [sym__r_flw_map_bgn] = ACTIONS(295), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(299), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(303), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(307), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(311), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(323), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(34)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_sgl_prp_val] = STATE(976), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_sgl_prp] = STATE(261), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_sgl_flw_seq_val] = STATE(1025), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__r_sgl_flw_seq] = STATE(1110), + [sym__flw_seq_tal] = STATE(784), + [sym__sgl_flw_seq_tal] = STATE(1317), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_sgl_flw_map_val] = STATE(1025), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_sgl_flw_map] = STATE(1113), + [sym__r_flw_seq_dat] = STATE(1211), + [sym__br_flw_seq_dat] = STATE(1211), + [sym__r_sgl_flw_col_dat] = STATE(1447), + [sym__r_flw_seq_itm] = STATE(649), + [sym__br_flw_seq_itm] = STATE(661), + [sym__r_sgl_flw_col_itm] = STATE(986), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_sgl_flw_exp_par] = STATE(1225), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_sgl_flw_imp_par] = STATE(1240), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_sgl_flw_njl_ann_par] = STATE(1253), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_sgl_dqt_str_val] = STATE(1025), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sgl_dqt_str] = STATE(1114), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sgl_sqt_str_val] = STATE(1025), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_sgl_sqt_str] = STATE(1116), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw_val] = STATE(976), + [sym__r_sgl_pln_flw] = STATE(747), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(538), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(207), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(287), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(365), + [sym__br_flw_seq_end] = ACTIONS(367), + [sym__b_flw_seq_end] = ACTIONS(367), + [sym__r_flw_map_bgn] = ACTIONS(295), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(299), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(303), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(307), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(311), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(323), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(35)] = { + [sym__br_sgl_prp_val] = STATE(1237), + [sym__br_sgl_prp] = STATE(309), + [sym__br_blk_seq] = STATE(388), + [sym__b_blk_seq_spc] = STATE(339), + [sym__br_blk_seq_itm] = STATE(966), + [sym__b_blk_seq_itm] = STATE(1041), + [sym__br_blk_map] = STATE(389), + [sym__br_blk_map_itm] = STATE(143), + [sym__br_blk_exp_itm] = STATE(319), + [sym__br_blk_key_itm] = STATE(278), + [sym__br_blk_val_itm] = STATE(328), + [sym__br_blk_imp_itm] = STATE(364), + [sym__r_blk_str] = STATE(390), + [sym__br_blk_str] = STATE(390), + [sym__br_sgl_flw_seq_val] = STATE(1237), + [sym__r_flw_seq] = STATE(378), + [sym__br_flw_seq] = STATE(378), + [sym__br_sgl_flw_seq] = STATE(1551), + [sym__br_sgl_flw_map_val] = STATE(1237), + [sym__r_flw_map] = STATE(327), + [sym__br_flw_map] = STATE(327), + [sym__br_sgl_flw_map] = STATE(1514), + [sym__br_sgl_dqt_str_val] = STATE(1237), + [sym__r_dqt_str] = STATE(298), + [sym__br_dqt_str] = STATE(298), + [sym__br_sgl_dqt_str] = STATE(1446), + [sym__br_sgl_sqt_str_val] = STATE(1237), + [sym__r_sqt_str] = STATE(355), + [sym__br_sqt_str] = STATE(355), + [sym__br_sgl_sqt_str] = STATE(1417), + [sym__br_sgl_pln_blk_val] = STATE(1237), + [sym__r_sgl_pln_blk] = STATE(335), + [sym__br_sgl_pln_blk] = STATE(268), + [sym__r_mtl_pln_blk] = STATE(335), + [sym__br_mtl_pln_blk] = STATE(335), + [sym__br_als_val] = STATE(1237), + [sym__br_als] = STATE(1487), + [sym__br_acr] = STATE(415), + [aux_sym__r_blk_seq_repeat1] = STATE(1041), + [sym__br_blk_seq_bgn] = ACTIONS(19), + [sym__b_blk_seq_bgn] = ACTIONS(69), + [sym__br_blk_key_bgn] = ACTIONS(23), + [sym__b_blk_key_bgn] = ACTIONS(369), + [sym__br_blk_val_bgn] = ACTIONS(27), + [sym__b_blk_val_bgn] = ACTIONS(369), + [sym__r_blk_lit_bgn] = ACTIONS(73), + [sym__br_blk_lit_bgn] = ACTIONS(75), + [sym__r_blk_fld_bgn] = ACTIONS(73), + [sym__br_blk_fld_bgn] = ACTIONS(75), + [sym__r_flw_seq_bgn] = ACTIONS(171), + [sym__br_flw_seq_bgn] = ACTIONS(79), + [sym__b_flw_seq_bgn] = ACTIONS(369), + [sym__r_flw_map_bgn] = ACTIONS(173), + [sym__br_flw_map_bgn] = ACTIONS(83), + [sym__b_flw_map_bgn] = ACTIONS(369), + [sym__r_dqt_str_bgn] = ACTIONS(175), + [sym__br_dqt_str_bgn] = ACTIONS(87), + [sym__b_dqt_str_bgn] = ACTIONS(369), + [sym__r_sqt_str_bgn] = ACTIONS(177), + [sym__br_sqt_str_bgn] = ACTIONS(91), + [sym__b_sqt_str_bgn] = ACTIONS(369), + [sym__r_sgl_pln_nul_blk] = ACTIONS(179), + [sym__br_sgl_pln_nul_blk] = ACTIONS(95), + [sym__b_sgl_pln_nul_blk] = ACTIONS(369), + [sym__r_sgl_pln_bol_blk] = ACTIONS(179), + [sym__br_sgl_pln_bol_blk] = ACTIONS(95), + [sym__b_sgl_pln_bol_blk] = ACTIONS(369), + [sym__r_sgl_pln_int_blk] = ACTIONS(179), + [sym__br_sgl_pln_int_blk] = ACTIONS(95), + [sym__b_sgl_pln_int_blk] = ACTIONS(369), + [sym__r_sgl_pln_flt_blk] = ACTIONS(179), + [sym__br_sgl_pln_flt_blk] = ACTIONS(95), + [sym__b_sgl_pln_flt_blk] = ACTIONS(369), + [sym__r_sgl_pln_tms_blk] = ACTIONS(179), + [sym__br_sgl_pln_tms_blk] = ACTIONS(95), + [sym__b_sgl_pln_tms_blk] = ACTIONS(369), + [sym__r_sgl_pln_str_blk] = ACTIONS(179), + [sym__br_sgl_pln_str_blk] = ACTIONS(95), + [sym__b_sgl_pln_str_blk] = ACTIONS(369), + [sym__r_mtl_pln_str_blk] = ACTIONS(97), + [sym__br_mtl_pln_str_blk] = ACTIONS(99), + [sym__br_tag] = ACTIONS(371), + [sym__b_tag] = ACTIONS(369), + [sym__br_acr_bgn] = ACTIONS(373), + [sym__b_acr_bgn] = ACTIONS(369), + [sym__br_als_bgn] = ACTIONS(375), + [sym__b_als_bgn] = ACTIONS(369), + [sym__bl] = ACTIONS(369), + [sym_comment] = ACTIONS(3), + }, + [STATE(36)] = { + [sym__br_sgl_prp_val] = STATE(1237), + [sym__br_sgl_prp] = STATE(309), + [sym__br_blk_seq] = STATE(379), + [sym__b_blk_seq_spc] = STATE(338), + [sym__br_blk_seq_itm] = STATE(966), + [sym__b_blk_seq_itm] = STATE(1041), + [sym__br_blk_map] = STATE(380), + [sym__br_blk_map_itm] = STATE(143), + [sym__br_blk_exp_itm] = STATE(319), + [sym__br_blk_key_itm] = STATE(278), + [sym__br_blk_val_itm] = STATE(328), + [sym__br_blk_imp_itm] = STATE(364), + [sym__r_blk_str] = STATE(381), + [sym__br_blk_str] = STATE(381), + [sym__br_sgl_flw_seq_val] = STATE(1237), + [sym__r_flw_seq] = STATE(382), + [sym__br_flw_seq] = STATE(382), + [sym__br_sgl_flw_seq] = STATE(1551), + [sym__br_sgl_flw_map_val] = STATE(1237), + [sym__r_flw_map] = STATE(383), + [sym__br_flw_map] = STATE(383), + [sym__br_sgl_flw_map] = STATE(1514), + [sym__br_sgl_dqt_str_val] = STATE(1237), + [sym__r_dqt_str] = STATE(384), + [sym__br_dqt_str] = STATE(384), + [sym__br_sgl_dqt_str] = STATE(1446), + [sym__br_sgl_sqt_str_val] = STATE(1237), + [sym__r_sqt_str] = STATE(385), + [sym__br_sqt_str] = STATE(385), + [sym__br_sgl_sqt_str] = STATE(1417), + [sym__br_sgl_pln_blk_val] = STATE(1237), + [sym__r_sgl_pln_blk] = STATE(386), + [sym__br_sgl_pln_blk] = STATE(267), + [sym__r_mtl_pln_blk] = STATE(386), + [sym__br_mtl_pln_blk] = STATE(386), + [sym__br_als_val] = STATE(1237), + [sym__br_als] = STATE(1487), + [sym__br_acr] = STATE(415), + [aux_sym__r_blk_seq_repeat1] = STATE(1041), + [sym__br_blk_seq_bgn] = ACTIONS(19), + [sym__b_blk_seq_bgn] = ACTIONS(69), + [sym__br_blk_key_bgn] = ACTIONS(23), + [sym__b_blk_key_bgn] = ACTIONS(377), + [sym__br_blk_val_bgn] = ACTIONS(27), + [sym__b_blk_val_bgn] = ACTIONS(377), + [sym__r_blk_lit_bgn] = ACTIONS(73), + [sym__br_blk_lit_bgn] = ACTIONS(75), + [sym__r_blk_fld_bgn] = ACTIONS(73), + [sym__br_blk_fld_bgn] = ACTIONS(75), + [sym__r_flw_seq_bgn] = ACTIONS(171), + [sym__br_flw_seq_bgn] = ACTIONS(79), + [sym__b_flw_seq_bgn] = ACTIONS(377), + [sym__r_flw_map_bgn] = ACTIONS(173), + [sym__br_flw_map_bgn] = ACTIONS(83), + [sym__b_flw_map_bgn] = ACTIONS(377), + [sym__r_dqt_str_bgn] = ACTIONS(175), + [sym__br_dqt_str_bgn] = ACTIONS(87), + [sym__b_dqt_str_bgn] = ACTIONS(377), + [sym__r_sqt_str_bgn] = ACTIONS(177), + [sym__br_sqt_str_bgn] = ACTIONS(91), + [sym__b_sqt_str_bgn] = ACTIONS(377), + [sym__r_sgl_pln_nul_blk] = ACTIONS(179), + [sym__br_sgl_pln_nul_blk] = ACTIONS(95), + [sym__b_sgl_pln_nul_blk] = ACTIONS(377), + [sym__r_sgl_pln_bol_blk] = ACTIONS(179), + [sym__br_sgl_pln_bol_blk] = ACTIONS(95), + [sym__b_sgl_pln_bol_blk] = ACTIONS(377), + [sym__r_sgl_pln_int_blk] = ACTIONS(179), + [sym__br_sgl_pln_int_blk] = ACTIONS(95), + [sym__b_sgl_pln_int_blk] = ACTIONS(377), + [sym__r_sgl_pln_flt_blk] = ACTIONS(179), + [sym__br_sgl_pln_flt_blk] = ACTIONS(95), + [sym__b_sgl_pln_flt_blk] = ACTIONS(377), + [sym__r_sgl_pln_tms_blk] = ACTIONS(179), + [sym__br_sgl_pln_tms_blk] = ACTIONS(95), + [sym__b_sgl_pln_tms_blk] = ACTIONS(377), + [sym__r_sgl_pln_str_blk] = ACTIONS(179), + [sym__br_sgl_pln_str_blk] = ACTIONS(95), + [sym__b_sgl_pln_str_blk] = ACTIONS(377), + [sym__r_mtl_pln_str_blk] = ACTIONS(97), + [sym__br_mtl_pln_str_blk] = ACTIONS(99), + [sym__br_tag] = ACTIONS(371), + [sym__b_tag] = ACTIONS(377), + [sym__br_acr_bgn] = ACTIONS(373), + [sym__b_acr_bgn] = ACTIONS(377), + [sym__br_als_bgn] = ACTIONS(375), + [sym__b_als_bgn] = ACTIONS(377), + [sym__bl] = ACTIONS(377), + [sym_comment] = ACTIONS(3), + }, + [STATE(37)] = { + [sym__doc_w_bgn_w_end_seq] = STATE(1428), + [sym__doc_w_bgn_wo_end_seq] = STATE(1428), + [sym__doc_wo_bgn_w_end_seq] = STATE(1428), + [sym__doc_wo_bgn_wo_end_seq] = STATE(1428), + [sym__doc_w_bgn_w_end] = STATE(38), + [sym__doc_w_bgn_wo_end] = STATE(476), + [sym__doc_wo_bgn_w_end] = STATE(39), + [sym__doc_wo_bgn_wo_end] = STATE(480), + [sym__drs_doc] = STATE(1167), + [sym__exp_doc] = STATE(1155), + [sym__imp_doc] = STATE(1168), + [sym__drs_doc_end] = STATE(39), + [sym__exp_doc_end] = STATE(38), + [sym__imp_doc_end] = STATE(39), + [sym__doc_end] = STATE(38), + [sym__s_dir] = STATE(478), + [sym__s_dir_yml] = STATE(478), + [sym__s_dir_tag] = STATE(478), + [sym__s_dir_rsv] = STATE(478), + [sym__br_prp_val] = STATE(1169), + [sym__br_sgl_prp_val] = STATE(1237), + [sym__br_prp] = STATE(80), + [sym__br_sgl_prp] = STATE(309), + [sym__br_blk_seq_val] = STATE(1169), + [sym__br_blk_seq] = STATE(1170), + [sym__br_blk_seq_itm] = STATE(1048), + [sym__br_blk_map_val] = STATE(1169), + [sym__br_blk_map] = STATE(1200), + [sym__br_blk_map_itm] = STATE(130), + [sym__br_blk_exp_itm] = STATE(319), + [sym__br_blk_key_itm] = STATE(278), + [sym__br_blk_val_itm] = STATE(328), + [sym__br_blk_imp_itm] = STATE(364), + [sym__br_blk_str_val] = STATE(1169), + [sym__br_blk_str] = STATE(1103), + [sym__br_flw_seq_val] = STATE(1169), + [sym__br_sgl_flw_seq_val] = STATE(1237), + [sym__br_flw_seq] = STATE(1156), + [sym__br_sgl_flw_seq] = STATE(1551), + [sym__br_flw_map_val] = STATE(1169), + [sym__br_sgl_flw_map_val] = STATE(1237), + [sym__br_flw_map] = STATE(1071), + [sym__br_sgl_flw_map] = STATE(1514), + [sym__br_dqt_str_val] = STATE(1169), + [sym__br_sgl_dqt_str_val] = STATE(1237), + [sym__br_dqt_str] = STATE(1087), + [sym__br_sgl_dqt_str] = STATE(1446), + [sym__br_sqt_str_val] = STATE(1169), + [sym__br_sgl_sqt_str_val] = STATE(1237), + [sym__br_sqt_str] = STATE(1129), + [sym__br_sgl_sqt_str] = STATE(1417), + [sym__br_pln_blk_val] = STATE(1169), + [sym__br_sgl_pln_blk_val] = STATE(1237), + [sym__br_sgl_pln_blk] = STATE(997), + [sym__br_mtl_pln_blk] = STATE(1095), + [sym__br_als_val] = STATE(939), + [sym__br_als] = STATE(1001), + [sym__br_acr] = STATE(146), + [aux_sym__drs_doc_repeat1] = STATE(478), + [sym__eof] = ACTIONS(379), + [sym__s_dir_yml_bgn] = ACTIONS(7), + [sym__s_dir_tag_bgn] = ACTIONS(9), + [sym__s_dir_rsv_bgn] = ACTIONS(11), + [sym__s_drs_end] = ACTIONS(13), + [sym__s_doc_end] = ACTIONS(15), + [sym__br_blk_seq_bgn] = ACTIONS(19), + [sym__br_blk_key_bgn] = ACTIONS(23), + [sym__br_blk_val_bgn] = ACTIONS(27), + [sym__br_blk_lit_bgn] = ACTIONS(31), + [sym__br_blk_fld_bgn] = ACTIONS(31), + [sym__br_flw_seq_bgn] = ACTIONS(35), + [sym__br_flw_map_bgn] = ACTIONS(39), + [sym__br_dqt_str_bgn] = ACTIONS(43), + [sym__br_sqt_str_bgn] = ACTIONS(47), + [sym__br_sgl_pln_nul_blk] = ACTIONS(51), + [sym__br_sgl_pln_bol_blk] = ACTIONS(51), + [sym__br_sgl_pln_int_blk] = ACTIONS(51), + [sym__br_sgl_pln_flt_blk] = ACTIONS(51), + [sym__br_sgl_pln_tms_blk] = ACTIONS(51), + [sym__br_sgl_pln_str_blk] = ACTIONS(51), + [sym__br_mtl_pln_str_blk] = ACTIONS(55), + [sym__br_tag] = ACTIONS(59), + [sym__br_acr_bgn] = ACTIONS(63), + [sym__br_als_bgn] = ACTIONS(67), + [sym_comment] = ACTIONS(3), + }, + [STATE(38)] = { + [sym__doc_w_bgn_w_end_seq] = STATE(1456), + [sym__doc_w_bgn_wo_end_seq] = STATE(1456), + [sym__doc_wo_bgn_w_end_seq] = STATE(1456), + [sym__doc_wo_bgn_wo_end_seq] = STATE(1456), + [sym__doc_w_bgn_w_end] = STATE(38), + [sym__doc_w_bgn_wo_end] = STATE(476), + [sym__doc_wo_bgn_w_end] = STATE(39), + [sym__doc_wo_bgn_wo_end] = STATE(480), + [sym__drs_doc] = STATE(1167), + [sym__exp_doc] = STATE(1155), + [sym__imp_doc] = STATE(1168), + [sym__drs_doc_end] = STATE(39), + [sym__exp_doc_end] = STATE(38), + [sym__imp_doc_end] = STATE(39), + [sym__doc_end] = STATE(38), + [sym__s_dir] = STATE(478), + [sym__s_dir_yml] = STATE(478), + [sym__s_dir_tag] = STATE(478), + [sym__s_dir_rsv] = STATE(478), + [sym__br_prp_val] = STATE(1169), + [sym__br_sgl_prp_val] = STATE(1237), + [sym__br_prp] = STATE(80), + [sym__br_sgl_prp] = STATE(309), + [sym__br_blk_seq_val] = STATE(1169), + [sym__br_blk_seq] = STATE(1170), + [sym__br_blk_seq_itm] = STATE(1048), + [sym__br_blk_map_val] = STATE(1169), + [sym__br_blk_map] = STATE(1200), + [sym__br_blk_map_itm] = STATE(130), + [sym__br_blk_exp_itm] = STATE(319), + [sym__br_blk_key_itm] = STATE(278), + [sym__br_blk_val_itm] = STATE(328), + [sym__br_blk_imp_itm] = STATE(364), + [sym__br_blk_str_val] = STATE(1169), + [sym__br_blk_str] = STATE(1103), + [sym__br_flw_seq_val] = STATE(1169), + [sym__br_sgl_flw_seq_val] = STATE(1237), + [sym__br_flw_seq] = STATE(1156), + [sym__br_sgl_flw_seq] = STATE(1551), + [sym__br_flw_map_val] = STATE(1169), + [sym__br_sgl_flw_map_val] = STATE(1237), + [sym__br_flw_map] = STATE(1071), + [sym__br_sgl_flw_map] = STATE(1514), + [sym__br_dqt_str_val] = STATE(1169), + [sym__br_sgl_dqt_str_val] = STATE(1237), + [sym__br_dqt_str] = STATE(1087), + [sym__br_sgl_dqt_str] = STATE(1446), + [sym__br_sqt_str_val] = STATE(1169), + [sym__br_sgl_sqt_str_val] = STATE(1237), + [sym__br_sqt_str] = STATE(1129), + [sym__br_sgl_sqt_str] = STATE(1417), + [sym__br_pln_blk_val] = STATE(1169), + [sym__br_sgl_pln_blk_val] = STATE(1237), + [sym__br_sgl_pln_blk] = STATE(997), + [sym__br_mtl_pln_blk] = STATE(1095), + [sym__br_als_val] = STATE(939), + [sym__br_als] = STATE(1001), + [sym__br_acr] = STATE(146), + [aux_sym__drs_doc_repeat1] = STATE(478), + [sym__eof] = ACTIONS(381), + [sym__s_dir_yml_bgn] = ACTIONS(7), + [sym__s_dir_tag_bgn] = ACTIONS(9), + [sym__s_dir_rsv_bgn] = ACTIONS(11), + [sym__s_drs_end] = ACTIONS(13), + [sym__s_doc_end] = ACTIONS(15), + [sym__br_blk_seq_bgn] = ACTIONS(19), + [sym__br_blk_key_bgn] = ACTIONS(23), + [sym__br_blk_val_bgn] = ACTIONS(27), + [sym__br_blk_lit_bgn] = ACTIONS(31), + [sym__br_blk_fld_bgn] = ACTIONS(31), + [sym__br_flw_seq_bgn] = ACTIONS(35), + [sym__br_flw_map_bgn] = ACTIONS(39), + [sym__br_dqt_str_bgn] = ACTIONS(43), + [sym__br_sqt_str_bgn] = ACTIONS(47), + [sym__br_sgl_pln_nul_blk] = ACTIONS(51), + [sym__br_sgl_pln_bol_blk] = ACTIONS(51), + [sym__br_sgl_pln_int_blk] = ACTIONS(51), + [sym__br_sgl_pln_flt_blk] = ACTIONS(51), + [sym__br_sgl_pln_tms_blk] = ACTIONS(51), + [sym__br_sgl_pln_str_blk] = ACTIONS(51), + [sym__br_mtl_pln_str_blk] = ACTIONS(55), + [sym__br_tag] = ACTIONS(59), + [sym__br_acr_bgn] = ACTIONS(63), + [sym__br_als_bgn] = ACTIONS(67), + [sym_comment] = ACTIONS(3), + }, + [STATE(39)] = { + [sym__doc_w_bgn_w_end_seq] = STATE(1489), + [sym__doc_w_bgn_wo_end_seq] = STATE(1489), + [sym__doc_wo_bgn_w_end_seq] = STATE(1489), + [sym__doc_wo_bgn_wo_end_seq] = STATE(1489), + [sym__doc_w_bgn_w_end] = STATE(38), + [sym__doc_w_bgn_wo_end] = STATE(476), + [sym__doc_wo_bgn_w_end] = STATE(39), + [sym__doc_wo_bgn_wo_end] = STATE(480), + [sym__drs_doc] = STATE(1167), + [sym__exp_doc] = STATE(1155), + [sym__imp_doc] = STATE(1168), + [sym__drs_doc_end] = STATE(39), + [sym__exp_doc_end] = STATE(38), + [sym__imp_doc_end] = STATE(39), + [sym__doc_end] = STATE(38), + [sym__s_dir] = STATE(478), + [sym__s_dir_yml] = STATE(478), + [sym__s_dir_tag] = STATE(478), + [sym__s_dir_rsv] = STATE(478), + [sym__br_prp_val] = STATE(1169), + [sym__br_sgl_prp_val] = STATE(1237), + [sym__br_prp] = STATE(80), + [sym__br_sgl_prp] = STATE(309), + [sym__br_blk_seq_val] = STATE(1169), + [sym__br_blk_seq] = STATE(1170), + [sym__br_blk_seq_itm] = STATE(1048), + [sym__br_blk_map_val] = STATE(1169), + [sym__br_blk_map] = STATE(1200), + [sym__br_blk_map_itm] = STATE(130), + [sym__br_blk_exp_itm] = STATE(319), + [sym__br_blk_key_itm] = STATE(278), + [sym__br_blk_val_itm] = STATE(328), + [sym__br_blk_imp_itm] = STATE(364), + [sym__br_blk_str_val] = STATE(1169), + [sym__br_blk_str] = STATE(1103), + [sym__br_flw_seq_val] = STATE(1169), + [sym__br_sgl_flw_seq_val] = STATE(1237), + [sym__br_flw_seq] = STATE(1156), + [sym__br_sgl_flw_seq] = STATE(1551), + [sym__br_flw_map_val] = STATE(1169), + [sym__br_sgl_flw_map_val] = STATE(1237), + [sym__br_flw_map] = STATE(1071), + [sym__br_sgl_flw_map] = STATE(1514), + [sym__br_dqt_str_val] = STATE(1169), + [sym__br_sgl_dqt_str_val] = STATE(1237), + [sym__br_dqt_str] = STATE(1087), + [sym__br_sgl_dqt_str] = STATE(1446), + [sym__br_sqt_str_val] = STATE(1169), + [sym__br_sgl_sqt_str_val] = STATE(1237), + [sym__br_sqt_str] = STATE(1129), + [sym__br_sgl_sqt_str] = STATE(1417), + [sym__br_pln_blk_val] = STATE(1169), + [sym__br_sgl_pln_blk_val] = STATE(1237), + [sym__br_sgl_pln_blk] = STATE(997), + [sym__br_mtl_pln_blk] = STATE(1095), + [sym__br_als_val] = STATE(939), + [sym__br_als] = STATE(1001), + [sym__br_acr] = STATE(146), + [aux_sym__drs_doc_repeat1] = STATE(478), + [sym__eof] = ACTIONS(383), + [sym__s_dir_yml_bgn] = ACTIONS(7), + [sym__s_dir_tag_bgn] = ACTIONS(9), + [sym__s_dir_rsv_bgn] = ACTIONS(11), + [sym__s_drs_end] = ACTIONS(13), + [sym__s_doc_end] = ACTIONS(15), + [sym__br_blk_seq_bgn] = ACTIONS(19), + [sym__br_blk_key_bgn] = ACTIONS(23), + [sym__br_blk_val_bgn] = ACTIONS(27), + [sym__br_blk_lit_bgn] = ACTIONS(31), + [sym__br_blk_fld_bgn] = ACTIONS(31), + [sym__br_flw_seq_bgn] = ACTIONS(35), + [sym__br_flw_map_bgn] = ACTIONS(39), + [sym__br_dqt_str_bgn] = ACTIONS(43), + [sym__br_sqt_str_bgn] = ACTIONS(47), + [sym__br_sgl_pln_nul_blk] = ACTIONS(51), + [sym__br_sgl_pln_bol_blk] = ACTIONS(51), + [sym__br_sgl_pln_int_blk] = ACTIONS(51), + [sym__br_sgl_pln_flt_blk] = ACTIONS(51), + [sym__br_sgl_pln_tms_blk] = ACTIONS(51), + [sym__br_sgl_pln_str_blk] = ACTIONS(51), + [sym__br_mtl_pln_str_blk] = ACTIONS(55), + [sym__br_tag] = ACTIONS(59), + [sym__br_acr_bgn] = ACTIONS(63), + [sym__br_als_bgn] = ACTIONS(67), + [sym_comment] = ACTIONS(3), + }, + [STATE(40)] = { + [sym__r_prp_val] = STATE(981), + [sym__br_prp_val] = STATE(984), + [sym__r_sgl_prp_val] = STATE(1239), + [sym__r_prp] = STATE(162), + [sym__br_prp] = STATE(164), + [sym__r_sgl_prp] = STATE(365), + [sym__r_flw_seq_val] = STATE(1031), + [sym__br_flw_seq_val] = STATE(1035), + [sym__r_sgl_flw_seq_val] = STATE(1242), + [sym__r_flw_seq] = STATE(1282), + [sym__br_flw_seq] = STATE(1283), + [sym__r_sgl_flw_seq] = STATE(1506), + [sym__r_flw_map_val] = STATE(1031), + [sym__br_flw_map_val] = STATE(1035), + [sym__r_sgl_flw_map_val] = STATE(1242), + [sym__r_flw_map] = STATE(1302), + [sym__br_flw_map] = STATE(1304), + [sym__r_sgl_flw_map] = STATE(1534), + [sym__r_flw_imp_r_par] = STATE(924), + [sym__r_flw_imp_br_par] = STATE(925), + [sym__br_flw_imp_r_par] = STATE(926), + [sym__br_flw_imp_br_par] = STATE(927), + [sym__r_sgl_flw_imp_par] = STATE(1312), + [sym__r_dqt_str_val] = STATE(1031), + [sym__br_dqt_str_val] = STATE(1035), + [sym__r_sgl_dqt_str_val] = STATE(1242), + [sym__r_dqt_str] = STATE(1306), + [sym__br_dqt_str] = STATE(1307), + [sym__r_sgl_dqt_str] = STATE(1463), + [sym__r_sqt_str_val] = STATE(1031), + [sym__br_sqt_str_val] = STATE(1035), + [sym__r_sgl_sqt_str_val] = STATE(1242), + [sym__r_sqt_str] = STATE(1309), + [sym__br_sqt_str] = STATE(1310), + [sym__r_sgl_sqt_str] = STATE(1467), + [sym__r_pln_flw_val] = STATE(981), + [sym__br_pln_flw_val] = STATE(984), + [sym__r_sgl_pln_flw_val] = STATE(1239), + [sym__r_sgl_pln_flw] = STATE(1243), + [sym__br_sgl_pln_flw] = STATE(1345), + [sym__r_mtl_pln_flw] = STATE(1222), + [sym__br_mtl_pln_flw] = STATE(1345), + [sym__r_als_val] = STATE(928), + [sym__br_als_val] = STATE(984), + [sym__r_als] = STATE(1246), + [sym__br_als] = STATE(1272), + [sym__r_acr] = STATE(244), + [sym__br_acr] = STATE(248), + [sym__r_flw_seq_bgn] = ACTIONS(385), + [sym__br_flw_seq_bgn] = ACTIONS(387), + [sym__r_flw_map_bgn] = ACTIONS(389), + [sym__br_flw_map_bgn] = ACTIONS(391), + [sym__r_flw_map_end] = ACTIONS(393), + [sym__br_flw_map_end] = ACTIONS(396), + [sym__b_flw_map_end] = ACTIONS(396), + [sym__r_flw_sep_bgn] = ACTIONS(393), + [sym__br_flw_sep_bgn] = ACTIONS(396), + [sym__r_dqt_str_bgn] = ACTIONS(398), + [sym__br_dqt_str_bgn] = ACTIONS(400), + [sym__r_sqt_str_bgn] = ACTIONS(402), + [sym__br_sqt_str_bgn] = ACTIONS(404), + [sym__r_sgl_pln_nul_flw] = ACTIONS(406), + [sym__br_sgl_pln_nul_flw] = ACTIONS(408), + [sym__r_sgl_pln_bol_flw] = ACTIONS(406), + [sym__br_sgl_pln_bol_flw] = ACTIONS(408), + [sym__r_sgl_pln_int_flw] = ACTIONS(406), + [sym__br_sgl_pln_int_flw] = ACTIONS(408), + [sym__r_sgl_pln_flt_flw] = ACTIONS(406), + [sym__br_sgl_pln_flt_flw] = ACTIONS(408), + [sym__r_sgl_pln_tms_flw] = ACTIONS(406), + [sym__br_sgl_pln_tms_flw] = ACTIONS(408), + [sym__r_sgl_pln_str_flw] = ACTIONS(406), + [sym__br_sgl_pln_str_flw] = ACTIONS(408), + [sym__r_mtl_pln_str_flw] = ACTIONS(410), + [sym__br_mtl_pln_str_flw] = ACTIONS(412), + [sym__r_tag] = ACTIONS(414), + [sym__br_tag] = ACTIONS(416), + [sym__r_acr_bgn] = ACTIONS(418), + [sym__br_acr_bgn] = ACTIONS(420), + [sym__r_als_bgn] = ACTIONS(422), + [sym__br_als_bgn] = ACTIONS(424), + [sym_comment] = ACTIONS(3), + }, + [STATE(41)] = { + [sym__r_prp_val] = STATE(980), + [sym__br_prp_val] = STATE(991), + [sym__r_sgl_prp_val] = STATE(1359), + [sym__r_prp] = STATE(162), + [sym__br_prp] = STATE(164), + [sym__r_sgl_prp] = STATE(365), + [sym__r_flw_seq_val] = STATE(1009), + [sym__br_flw_seq_val] = STATE(1018), + [sym__r_sgl_flw_seq_val] = STATE(1244), + [sym__r_flw_seq] = STATE(1282), + [sym__br_flw_seq] = STATE(1283), + [sym__r_sgl_flw_seq] = STATE(1506), + [sym__r_flw_map_val] = STATE(1009), + [sym__br_flw_map_val] = STATE(1018), + [sym__r_sgl_flw_map_val] = STATE(1244), + [sym__r_flw_map] = STATE(1302), + [sym__br_flw_map] = STATE(1304), + [sym__r_sgl_flw_map] = STATE(1534), + [sym__r_flw_imp_r_par] = STATE(948), + [sym__r_flw_imp_br_par] = STATE(953), + [sym__br_flw_imp_r_par] = STATE(960), + [sym__br_flw_imp_br_par] = STATE(804), + [sym__r_sgl_flw_imp_par] = STATE(1292), + [sym__r_dqt_str_val] = STATE(1009), + [sym__br_dqt_str_val] = STATE(1018), + [sym__r_sgl_dqt_str_val] = STATE(1244), + [sym__r_dqt_str] = STATE(1306), + [sym__br_dqt_str] = STATE(1307), + [sym__r_sgl_dqt_str] = STATE(1463), + [sym__r_sqt_str_val] = STATE(1009), + [sym__br_sqt_str_val] = STATE(1018), + [sym__r_sgl_sqt_str_val] = STATE(1244), + [sym__r_sqt_str] = STATE(1309), + [sym__br_sqt_str] = STATE(1310), + [sym__r_sgl_sqt_str] = STATE(1467), + [sym__r_pln_flw_val] = STATE(980), + [sym__br_pln_flw_val] = STATE(991), + [sym__r_sgl_pln_flw_val] = STATE(1359), + [sym__r_sgl_pln_flw] = STATE(1243), + [sym__br_sgl_pln_flw] = STATE(1345), + [sym__r_mtl_pln_flw] = STATE(1222), + [sym__br_mtl_pln_flw] = STATE(1345), + [sym__r_als_val] = STATE(805), + [sym__br_als_val] = STATE(991), + [sym__r_als] = STATE(1246), + [sym__br_als] = STATE(1272), + [sym__r_acr] = STATE(244), + [sym__br_acr] = STATE(248), + [sym__r_flw_seq_bgn] = ACTIONS(385), + [sym__br_flw_seq_bgn] = ACTIONS(387), + [sym__r_flw_seq_end] = ACTIONS(393), + [sym__br_flw_seq_end] = ACTIONS(396), + [sym__b_flw_seq_end] = ACTIONS(396), + [sym__r_flw_map_bgn] = ACTIONS(389), + [sym__br_flw_map_bgn] = ACTIONS(391), + [sym__r_flw_sep_bgn] = ACTIONS(393), + [sym__br_flw_sep_bgn] = ACTIONS(396), + [sym__r_dqt_str_bgn] = ACTIONS(398), + [sym__br_dqt_str_bgn] = ACTIONS(400), + [sym__r_sqt_str_bgn] = ACTIONS(402), + [sym__br_sqt_str_bgn] = ACTIONS(404), + [sym__r_sgl_pln_nul_flw] = ACTIONS(406), + [sym__br_sgl_pln_nul_flw] = ACTIONS(408), + [sym__r_sgl_pln_bol_flw] = ACTIONS(406), + [sym__br_sgl_pln_bol_flw] = ACTIONS(408), + [sym__r_sgl_pln_int_flw] = ACTIONS(406), + [sym__br_sgl_pln_int_flw] = ACTIONS(408), + [sym__r_sgl_pln_flt_flw] = ACTIONS(406), + [sym__br_sgl_pln_flt_flw] = ACTIONS(408), + [sym__r_sgl_pln_tms_flw] = ACTIONS(406), + [sym__br_sgl_pln_tms_flw] = ACTIONS(408), + [sym__r_sgl_pln_str_flw] = ACTIONS(406), + [sym__br_sgl_pln_str_flw] = ACTIONS(408), + [sym__r_mtl_pln_str_flw] = ACTIONS(410), + [sym__br_mtl_pln_str_flw] = ACTIONS(412), + [sym__r_tag] = ACTIONS(414), + [sym__br_tag] = ACTIONS(416), + [sym__r_acr_bgn] = ACTIONS(418), + [sym__br_acr_bgn] = ACTIONS(420), + [sym__r_als_bgn] = ACTIONS(422), + [sym__br_als_bgn] = ACTIONS(424), + [sym_comment] = ACTIONS(3), + }, + [STATE(42)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__flw_map_tal] = STATE(571), + [sym__r_flw_map_dat] = STATE(1173), + [sym__br_flw_map_dat] = STATE(1173), + [sym__r_flw_map_itm] = STATE(670), + [sym__br_flw_map_itm] = STATE(671), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw] = STATE(564), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(492), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(190), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(426), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(428), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(430), + [sym__br_flw_map_end] = ACTIONS(430), + [sym__b_flw_map_end] = ACTIONS(430), + [sym__r_flw_key_bgn] = ACTIONS(432), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(434), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(436), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(438), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(440), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(43)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__flw_map_tal] = STATE(715), + [sym__r_flw_map_dat] = STATE(1166), + [sym__br_flw_map_dat] = STATE(1166), + [sym__r_flw_map_itm] = STATE(670), + [sym__br_flw_map_itm] = STATE(671), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw] = STATE(564), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(492), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(190), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(426), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(428), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(277), + [sym__br_flw_map_end] = ACTIONS(277), + [sym__b_flw_map_end] = ACTIONS(277), + [sym__r_flw_key_bgn] = ACTIONS(432), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(434), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(436), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(438), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(440), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(44)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__flw_map_tal] = STATE(879), + [sym__r_flw_map_dat] = STATE(1212), + [sym__br_flw_map_dat] = STATE(1212), + [sym__r_flw_map_itm] = STATE(670), + [sym__br_flw_map_itm] = STATE(671), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw] = STATE(564), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(492), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(190), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(426), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(428), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(285), + [sym__br_flw_map_end] = ACTIONS(285), + [sym__b_flw_map_end] = ACTIONS(285), + [sym__r_flw_key_bgn] = ACTIONS(432), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(434), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(436), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(438), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(440), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(45)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__flw_map_tal] = STATE(1133), + [sym__r_flw_map_dat] = STATE(1138), + [sym__br_flw_map_dat] = STATE(1138), + [sym__r_flw_map_itm] = STATE(670), + [sym__br_flw_map_itm] = STATE(671), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw] = STATE(564), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(492), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(190), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(426), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(428), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(215), + [sym__br_flw_map_end] = ACTIONS(215), + [sym__b_flw_map_end] = ACTIONS(215), + [sym__r_flw_key_bgn] = ACTIONS(432), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(434), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(436), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(438), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(440), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(46)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__flw_map_tal] = STATE(570), + [sym__r_flw_map_dat] = STATE(1173), + [sym__br_flw_map_dat] = STATE(1173), + [sym__r_flw_map_itm] = STATE(670), + [sym__br_flw_map_itm] = STATE(671), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw] = STATE(564), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(492), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(190), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(426), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(428), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(269), + [sym__br_flw_map_end] = ACTIONS(269), + [sym__b_flw_map_end] = ACTIONS(269), + [sym__r_flw_key_bgn] = ACTIONS(432), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(434), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(436), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(438), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(440), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(47)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__flw_map_tal] = STATE(1323), + [sym__r_flw_map_dat] = STATE(1183), + [sym__br_flw_map_dat] = STATE(1183), + [sym__r_flw_map_itm] = STATE(670), + [sym__br_flw_map_itm] = STATE(671), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw] = STATE(564), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(492), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(190), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(426), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(428), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(442), + [sym__br_flw_map_end] = ACTIONS(442), + [sym__b_flw_map_end] = ACTIONS(442), + [sym__r_flw_key_bgn] = ACTIONS(432), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(434), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(436), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(438), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(440), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(48)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__flw_map_tal] = STATE(832), + [sym__r_flw_map_dat] = STATE(1194), + [sym__br_flw_map_dat] = STATE(1194), + [sym__r_flw_map_itm] = STATE(670), + [sym__br_flw_map_itm] = STATE(671), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw] = STATE(564), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(492), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(190), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(426), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(428), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(444), + [sym__br_flw_map_end] = ACTIONS(444), + [sym__b_flw_map_end] = ACTIONS(444), + [sym__r_flw_key_bgn] = ACTIONS(432), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(434), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(436), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(438), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(440), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(49)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__flw_map_tal] = STATE(369), + [sym__r_flw_map_dat] = STATE(1152), + [sym__br_flw_map_dat] = STATE(1152), + [sym__r_flw_map_itm] = STATE(670), + [sym__br_flw_map_itm] = STATE(671), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw] = STATE(564), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(492), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(190), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(426), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(428), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(265), + [sym__br_flw_map_end] = ACTIONS(265), + [sym__b_flw_map_end] = ACTIONS(265), + [sym__r_flw_key_bgn] = ACTIONS(432), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(434), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(436), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(438), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(440), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(50)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__flw_map_tal] = STATE(880), + [sym__r_flw_map_dat] = STATE(1212), + [sym__br_flw_map_dat] = STATE(1212), + [sym__r_flw_map_itm] = STATE(670), + [sym__br_flw_map_itm] = STATE(671), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw] = STATE(564), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(492), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(190), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(426), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(428), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(446), + [sym__br_flw_map_end] = ACTIONS(446), + [sym__b_flw_map_end] = ACTIONS(446), + [sym__r_flw_key_bgn] = ACTIONS(432), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(434), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(436), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(438), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(440), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(51)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__flw_map_tal] = STATE(1321), + [sym__r_flw_map_dat] = STATE(1183), + [sym__br_flw_map_dat] = STATE(1183), + [sym__r_flw_map_itm] = STATE(670), + [sym__br_flw_map_itm] = STATE(671), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw] = STATE(564), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(492), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(190), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(426), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(428), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(273), + [sym__br_flw_map_end] = ACTIONS(273), + [sym__b_flw_map_end] = ACTIONS(273), + [sym__r_flw_key_bgn] = ACTIONS(432), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(434), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(436), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(438), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(440), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(52)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__flw_map_tal] = STATE(1258), + [sym__r_flw_map_dat] = STATE(1125), + [sym__br_flw_map_dat] = STATE(1125), + [sym__r_flw_map_itm] = STATE(670), + [sym__br_flw_map_itm] = STATE(671), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw] = STATE(564), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(492), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(190), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(426), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(428), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(257), + [sym__br_flw_map_end] = ACTIONS(257), + [sym__b_flw_map_end] = ACTIONS(257), + [sym__r_flw_key_bgn] = ACTIONS(432), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(434), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(436), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(438), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(440), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(53)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__flw_map_tal] = STATE(716), + [sym__r_flw_map_dat] = STATE(1166), + [sym__br_flw_map_dat] = STATE(1166), + [sym__r_flw_map_itm] = STATE(670), + [sym__br_flw_map_itm] = STATE(671), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw] = STATE(564), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(492), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(190), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(426), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(428), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(448), + [sym__br_flw_map_end] = ACTIONS(448), + [sym__b_flw_map_end] = ACTIONS(448), + [sym__r_flw_key_bgn] = ACTIONS(432), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(434), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(436), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(438), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(440), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(54)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__flw_map_tal] = STATE(831), + [sym__r_flw_map_dat] = STATE(1194), + [sym__br_flw_map_dat] = STATE(1194), + [sym__r_flw_map_itm] = STATE(670), + [sym__br_flw_map_itm] = STATE(671), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw] = STATE(564), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(492), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(190), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(426), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(428), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(281), + [sym__br_flw_map_end] = ACTIONS(281), + [sym__b_flw_map_end] = ACTIONS(281), + [sym__r_flw_key_bgn] = ACTIONS(432), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(434), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(436), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(438), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(440), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(55)] = { + [sym__r_prp_val] = STATE(810), + [sym__br_prp_val] = STATE(810), + [sym__r_sgl_prp_val] = STATE(1379), + [sym__r_prp] = STATE(121), + [sym__br_prp] = STATE(117), + [sym__r_sgl_prp] = STATE(274), + [sym__r_flw_seq_val] = STATE(810), + [sym__br_flw_seq_val] = STATE(810), + [sym__r_sgl_flw_seq_val] = STATE(1379), + [sym__r_flw_seq] = STATE(817), + [sym__br_flw_seq] = STATE(818), + [sym__r_sgl_flw_seq] = STATE(1219), + [sym__r_flw_map_val] = STATE(810), + [sym__br_flw_map_val] = STATE(810), + [sym__r_sgl_flw_map_val] = STATE(1379), + [sym__r_flw_map] = STATE(819), + [sym__br_flw_map] = STATE(820), + [sym__r_sgl_flw_map] = STATE(1223), + [sym__flw_ann_par_tal] = STATE(810), + [sym__sgl_flw_ann_par_tal] = STATE(1379), + [sym__r_dqt_str_val] = STATE(810), + [sym__br_dqt_str_val] = STATE(810), + [sym__r_sgl_dqt_str_val] = STATE(1379), + [sym__r_dqt_str] = STATE(821), + [sym__br_dqt_str] = STATE(822), + [sym__r_sgl_dqt_str] = STATE(1224), + [sym__r_sqt_str_val] = STATE(810), + [sym__br_sqt_str_val] = STATE(810), + [sym__r_sgl_sqt_str_val] = STATE(1379), + [sym__r_sqt_str] = STATE(823), + [sym__br_sqt_str] = STATE(824), + [sym__r_sgl_sqt_str] = STATE(1228), + [sym__r_pln_flw_val] = STATE(810), + [sym__br_pln_flw_val] = STATE(810), + [sym__r_sgl_pln_flw_val] = STATE(1379), + [sym__r_sgl_pln_flw] = STATE(785), + [sym__br_sgl_pln_flw] = STATE(786), + [sym__r_mtl_pln_flw] = STATE(792), + [sym__br_mtl_pln_flw] = STATE(786), + [sym__r_als_val] = STATE(919), + [sym__br_als_val] = STATE(810), + [sym__r_als] = STATE(873), + [sym__br_als] = STATE(874), + [sym__r_acr] = STATE(215), + [sym__br_acr] = STATE(224), + [sym__r_flw_seq_bgn] = ACTIONS(450), + [sym__br_flw_seq_bgn] = ACTIONS(452), + [sym__r_flw_seq_end] = ACTIONS(454), + [sym__br_flw_seq_end] = ACTIONS(457), + [sym__b_flw_seq_end] = ACTIONS(457), + [sym__r_flw_map_bgn] = ACTIONS(459), + [sym__br_flw_map_bgn] = ACTIONS(461), + [sym__r_flw_sep_bgn] = ACTIONS(454), + [sym__br_flw_sep_bgn] = ACTIONS(457), + [sym__r_dqt_str_bgn] = ACTIONS(463), + [sym__br_dqt_str_bgn] = ACTIONS(465), + [sym__r_sqt_str_bgn] = ACTIONS(467), + [sym__br_sqt_str_bgn] = ACTIONS(469), + [sym__r_sgl_pln_nul_flw] = ACTIONS(471), + [sym__br_sgl_pln_nul_flw] = ACTIONS(473), + [sym__r_sgl_pln_bol_flw] = ACTIONS(471), + [sym__br_sgl_pln_bol_flw] = ACTIONS(473), + [sym__r_sgl_pln_int_flw] = ACTIONS(471), + [sym__br_sgl_pln_int_flw] = ACTIONS(473), + [sym__r_sgl_pln_flt_flw] = ACTIONS(471), + [sym__br_sgl_pln_flt_flw] = ACTIONS(473), + [sym__r_sgl_pln_tms_flw] = ACTIONS(471), + [sym__br_sgl_pln_tms_flw] = ACTIONS(473), + [sym__r_sgl_pln_str_flw] = ACTIONS(471), + [sym__br_sgl_pln_str_flw] = ACTIONS(473), + [sym__r_mtl_pln_str_flw] = ACTIONS(475), + [sym__br_mtl_pln_str_flw] = ACTIONS(477), + [sym__r_tag] = ACTIONS(479), + [sym__br_tag] = ACTIONS(481), + [sym__r_acr_bgn] = ACTIONS(483), + [sym__br_acr_bgn] = ACTIONS(485), + [sym__r_als_bgn] = ACTIONS(487), + [sym__br_als_bgn] = ACTIONS(489), + [sym_comment] = ACTIONS(3), + }, + [STATE(56)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__flw_seq_tal] = STATE(784), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_flw_seq_dat] = STATE(1211), + [sym__br_flw_seq_dat] = STATE(1211), + [sym__r_flw_seq_itm] = STATE(649), + [sym__br_flw_seq_itm] = STATE(661), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw] = STATE(749), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(674), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(209), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(491), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(367), + [sym__br_flw_seq_end] = ACTIONS(367), + [sym__b_flw_seq_end] = ACTIONS(367), + [sym__r_flw_map_bgn] = ACTIONS(493), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(495), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(497), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(499), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(501), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(503), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(57)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__flw_seq_tal] = STATE(1131), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_flw_seq_dat] = STATE(1058), + [sym__br_flw_seq_dat] = STATE(1058), + [sym__r_flw_seq_itm] = STATE(649), + [sym__br_flw_seq_itm] = STATE(661), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw] = STATE(749), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(674), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(209), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(491), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(359), + [sym__br_flw_seq_end] = ACTIONS(359), + [sym__b_flw_seq_end] = ACTIONS(359), + [sym__r_flw_map_bgn] = ACTIONS(493), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(495), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(497), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(499), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(501), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(503), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(58)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__flw_seq_tal] = STATE(1318), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_flw_seq_dat] = STATE(1182), + [sym__br_flw_seq_dat] = STATE(1182), + [sym__r_flw_seq_itm] = STATE(649), + [sym__br_flw_seq_itm] = STATE(661), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw] = STATE(749), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(674), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(209), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(491), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(505), + [sym__br_flw_seq_end] = ACTIONS(505), + [sym__b_flw_seq_end] = ACTIONS(505), + [sym__r_flw_map_bgn] = ACTIONS(493), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(495), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(497), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(499), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(501), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(503), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(59)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__flw_seq_tal] = STATE(712), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_flw_seq_dat] = STATE(1165), + [sym__br_flw_seq_dat] = STATE(1165), + [sym__r_flw_seq_itm] = STATE(649), + [sym__br_flw_seq_itm] = STATE(661), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw] = STATE(749), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(674), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(209), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(491), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(353), + [sym__br_flw_seq_end] = ACTIONS(353), + [sym__b_flw_seq_end] = ACTIONS(353), + [sym__r_flw_map_bgn] = ACTIONS(493), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(495), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(497), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(499), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(501), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(503), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(60)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__flw_seq_tal] = STATE(568), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_flw_seq_dat] = STATE(1172), + [sym__br_flw_seq_dat] = STATE(1172), + [sym__r_flw_seq_itm] = STATE(649), + [sym__br_flw_seq_itm] = STATE(661), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw] = STATE(749), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(674), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(209), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(491), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(507), + [sym__br_flw_seq_end] = ACTIONS(507), + [sym__b_flw_seq_end] = ACTIONS(507), + [sym__r_flw_map_bgn] = ACTIONS(493), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(495), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(497), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(499), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(501), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(503), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(61)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__flw_seq_tal] = STATE(566), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_flw_seq_dat] = STATE(1172), + [sym__br_flw_seq_dat] = STATE(1172), + [sym__r_flw_seq_itm] = STATE(649), + [sym__br_flw_seq_itm] = STATE(661), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw] = STATE(749), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(674), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(209), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(491), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(293), + [sym__br_flw_seq_end] = ACTIONS(293), + [sym__b_flw_seq_end] = ACTIONS(293), + [sym__r_flw_map_bgn] = ACTIONS(493), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(495), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(497), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(499), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(501), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(503), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(62)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__flw_seq_tal] = STATE(1247), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_flw_seq_dat] = STATE(1124), + [sym__br_flw_seq_dat] = STATE(1124), + [sym__r_flw_seq_itm] = STATE(649), + [sym__br_flw_seq_itm] = STATE(661), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw] = STATE(749), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(674), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(209), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(491), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(347), + [sym__br_flw_seq_end] = ACTIONS(347), + [sym__b_flw_seq_end] = ACTIONS(347), + [sym__r_flw_map_bgn] = ACTIONS(493), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(495), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(497), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(499), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(501), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(503), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(63)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__flw_seq_tal] = STATE(829), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_flw_seq_dat] = STATE(1193), + [sym__br_flw_seq_dat] = STATE(1193), + [sym__r_flw_seq_itm] = STATE(649), + [sym__br_flw_seq_itm] = STATE(661), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw] = STATE(749), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(674), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(209), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(491), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(509), + [sym__br_flw_seq_end] = ACTIONS(509), + [sym__b_flw_seq_end] = ACTIONS(509), + [sym__r_flw_map_bgn] = ACTIONS(493), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(495), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(497), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(499), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(501), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(503), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(64)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__flw_seq_tal] = STATE(713), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_flw_seq_dat] = STATE(1165), + [sym__br_flw_seq_dat] = STATE(1165), + [sym__r_flw_seq_itm] = STATE(649), + [sym__br_flw_seq_itm] = STATE(661), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw] = STATE(749), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(674), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(209), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(491), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(511), + [sym__br_flw_seq_end] = ACTIONS(511), + [sym__b_flw_seq_end] = ACTIONS(511), + [sym__r_flw_map_bgn] = ACTIONS(493), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(495), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(497), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(499), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(501), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(503), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(65)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__flw_seq_tal] = STATE(366), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_flw_seq_dat] = STATE(1151), + [sym__br_flw_seq_dat] = STATE(1151), + [sym__r_flw_seq_itm] = STATE(649), + [sym__br_flw_seq_itm] = STATE(661), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw] = STATE(749), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(674), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(209), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(491), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(339), + [sym__br_flw_seq_end] = ACTIONS(339), + [sym__b_flw_seq_end] = ACTIONS(339), + [sym__r_flw_map_bgn] = ACTIONS(493), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(495), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(497), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(499), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(501), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(503), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(66)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__flw_seq_tal] = STATE(877), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_flw_seq_dat] = STATE(1211), + [sym__br_flw_seq_dat] = STATE(1211), + [sym__r_flw_seq_itm] = STATE(649), + [sym__br_flw_seq_itm] = STATE(661), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw] = STATE(749), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(674), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(209), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(491), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(513), + [sym__br_flw_seq_end] = ACTIONS(513), + [sym__b_flw_seq_end] = ACTIONS(513), + [sym__r_flw_map_bgn] = ACTIONS(493), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(495), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(497), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(499), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(501), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(503), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(67)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__flw_seq_tal] = STATE(1316), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_flw_seq_dat] = STATE(1182), + [sym__br_flw_seq_dat] = STATE(1182), + [sym__r_flw_seq_itm] = STATE(649), + [sym__br_flw_seq_itm] = STATE(661), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw] = STATE(749), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(674), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(209), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(491), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(363), + [sym__br_flw_seq_end] = ACTIONS(363), + [sym__b_flw_seq_end] = ACTIONS(363), + [sym__r_flw_map_bgn] = ACTIONS(493), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(495), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(497), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(499), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(501), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(503), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(68)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__flw_seq_tal] = STATE(828), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_flw_seq_dat] = STATE(1193), + [sym__br_flw_seq_dat] = STATE(1193), + [sym__r_flw_seq_itm] = STATE(649), + [sym__br_flw_seq_itm] = STATE(661), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw] = STATE(749), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(674), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(209), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(491), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(357), + [sym__br_flw_seq_end] = ACTIONS(357), + [sym__b_flw_seq_end] = ACTIONS(357), + [sym__r_flw_map_bgn] = ACTIONS(493), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(495), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(497), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(499), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(501), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(503), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(69)] = { + [sym__r_prp_val] = STATE(934), + [sym__br_prp_val] = STATE(934), + [sym__r_sgl_prp_val] = STATE(1319), + [sym__r_prp] = STATE(119), + [sym__br_prp] = STATE(120), + [sym__r_sgl_prp] = STATE(276), + [sym__r_flw_seq_val] = STATE(934), + [sym__br_flw_seq_val] = STATE(934), + [sym__r_sgl_flw_seq_val] = STATE(1319), + [sym__r_flw_seq] = STATE(865), + [sym__br_flw_seq] = STATE(866), + [sym__r_sgl_flw_seq] = STATE(1301), + [sym__r_flw_map_val] = STATE(934), + [sym__br_flw_map_val] = STATE(934), + [sym__r_sgl_flw_map_val] = STATE(1319), + [sym__r_flw_map] = STATE(867), + [sym__br_flw_map] = STATE(868), + [sym__r_sgl_flw_map] = STATE(1305), + [sym__flw_ann_par_tal] = STATE(934), + [sym__sgl_flw_ann_par_tal] = STATE(1319), + [sym__r_dqt_str_val] = STATE(934), + [sym__br_dqt_str_val] = STATE(934), + [sym__r_sgl_dqt_str_val] = STATE(1319), + [sym__r_dqt_str] = STATE(869), + [sym__br_dqt_str] = STATE(870), + [sym__r_sgl_dqt_str] = STATE(1308), + [sym__r_sqt_str_val] = STATE(934), + [sym__br_sqt_str_val] = STATE(934), + [sym__r_sgl_sqt_str_val] = STATE(1319), + [sym__r_sqt_str] = STATE(871), + [sym__br_sqt_str] = STATE(872), + [sym__r_sgl_sqt_str] = STATE(1311), + [sym__r_pln_flw_val] = STATE(934), + [sym__br_pln_flw_val] = STATE(934), + [sym__r_sgl_pln_flw_val] = STATE(1319), + [sym__r_sgl_pln_flw] = STATE(801), + [sym__br_sgl_pln_flw] = STATE(802), + [sym__r_mtl_pln_flw] = STATE(803), + [sym__br_mtl_pln_flw] = STATE(802), + [sym__r_als_val] = STATE(935), + [sym__br_als_val] = STATE(934), + [sym__r_als] = STATE(913), + [sym__br_als] = STATE(914), + [sym__r_acr] = STATE(220), + [sym__br_acr] = STATE(218), + [sym__r_flw_seq_bgn] = ACTIONS(515), + [sym__br_flw_seq_bgn] = ACTIONS(517), + [sym__r_flw_map_bgn] = ACTIONS(519), + [sym__br_flw_map_bgn] = ACTIONS(521), + [sym__r_flw_map_end] = ACTIONS(454), + [sym__br_flw_map_end] = ACTIONS(457), + [sym__b_flw_map_end] = ACTIONS(457), + [sym__r_flw_sep_bgn] = ACTIONS(454), + [sym__br_flw_sep_bgn] = ACTIONS(457), + [sym__r_dqt_str_bgn] = ACTIONS(523), + [sym__br_dqt_str_bgn] = ACTIONS(525), + [sym__r_sqt_str_bgn] = ACTIONS(527), + [sym__br_sqt_str_bgn] = ACTIONS(529), + [sym__r_sgl_pln_nul_flw] = ACTIONS(531), + [sym__br_sgl_pln_nul_flw] = ACTIONS(533), + [sym__r_sgl_pln_bol_flw] = ACTIONS(531), + [sym__br_sgl_pln_bol_flw] = ACTIONS(533), + [sym__r_sgl_pln_int_flw] = ACTIONS(531), + [sym__br_sgl_pln_int_flw] = ACTIONS(533), + [sym__r_sgl_pln_flt_flw] = ACTIONS(531), + [sym__br_sgl_pln_flt_flw] = ACTIONS(533), + [sym__r_sgl_pln_tms_flw] = ACTIONS(531), + [sym__br_sgl_pln_tms_flw] = ACTIONS(533), + [sym__r_sgl_pln_str_flw] = ACTIONS(531), + [sym__br_sgl_pln_str_flw] = ACTIONS(533), + [sym__r_mtl_pln_str_flw] = ACTIONS(535), + [sym__br_mtl_pln_str_flw] = ACTIONS(537), + [sym__r_tag] = ACTIONS(539), + [sym__br_tag] = ACTIONS(541), + [sym__r_acr_bgn] = ACTIONS(543), + [sym__br_acr_bgn] = ACTIONS(545), + [sym__r_als_bgn] = ACTIONS(547), + [sym__br_als_bgn] = ACTIONS(549), + [sym_comment] = ACTIONS(3), + }, + [STATE(70)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__r_flw_map_itm] = STATE(875), + [sym__br_flw_map_itm] = STATE(875), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw] = STATE(564), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(492), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(190), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(426), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(428), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(551), + [sym__br_flw_map_end] = ACTIONS(551), + [sym__b_flw_map_end] = ACTIONS(551), + [sym__r_flw_key_bgn] = ACTIONS(432), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(434), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(436), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(438), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(440), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(71)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__r_flw_map_itm] = STATE(875), + [sym__br_flw_map_itm] = STATE(875), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw] = STATE(564), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(492), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(190), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(426), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(428), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(553), + [sym__br_flw_map_end] = ACTIONS(553), + [sym__b_flw_map_end] = ACTIONS(553), + [sym__r_flw_key_bgn] = ACTIONS(432), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(434), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(436), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(438), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(440), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(72)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__r_flw_map_itm] = STATE(875), + [sym__br_flw_map_itm] = STATE(875), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw] = STATE(564), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(492), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(190), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(426), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(428), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(555), + [sym__br_flw_map_end] = ACTIONS(555), + [sym__b_flw_map_end] = ACTIONS(555), + [sym__r_flw_key_bgn] = ACTIONS(432), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(434), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(436), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(438), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(440), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(73)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__r_flw_map_itm] = STATE(875), + [sym__br_flw_map_itm] = STATE(875), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw] = STATE(564), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(492), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(190), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(426), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(428), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_map_end] = ACTIONS(557), + [sym__br_flw_map_end] = ACTIONS(557), + [sym__b_flw_map_end] = ACTIONS(557), + [sym__r_flw_key_bgn] = ACTIONS(432), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(434), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(436), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(438), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(440), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(74)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_flw_seq_itm] = STATE(825), + [sym__br_flw_seq_itm] = STATE(825), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw] = STATE(749), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(674), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(209), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(491), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(559), + [sym__br_flw_seq_end] = ACTIONS(559), + [sym__b_flw_seq_end] = ACTIONS(559), + [sym__r_flw_map_bgn] = ACTIONS(493), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(495), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(497), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(499), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(501), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(503), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(75)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_flw_seq_itm] = STATE(825), + [sym__br_flw_seq_itm] = STATE(825), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw] = STATE(749), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(674), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(209), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(491), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(561), + [sym__br_flw_seq_end] = ACTIONS(561), + [sym__b_flw_seq_end] = ACTIONS(561), + [sym__r_flw_map_bgn] = ACTIONS(493), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(495), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(497), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(499), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(501), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(503), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(76)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_flw_seq_itm] = STATE(825), + [sym__br_flw_seq_itm] = STATE(825), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw] = STATE(749), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(674), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(209), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(491), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(563), + [sym__br_flw_seq_end] = ACTIONS(563), + [sym__b_flw_seq_end] = ACTIONS(563), + [sym__r_flw_map_bgn] = ACTIONS(493), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(495), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(497), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(499), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(501), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(503), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(77)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_flw_seq_itm] = STATE(825), + [sym__br_flw_seq_itm] = STATE(825), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw] = STATE(749), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(674), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(209), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(491), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_seq_end] = ACTIONS(565), + [sym__br_flw_seq_end] = ACTIONS(565), + [sym__b_flw_seq_end] = ACTIONS(565), + [sym__r_flw_map_bgn] = ACTIONS(493), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(495), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(497), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(499), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(501), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(503), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(78)] = { + [sym__r_prp_val] = STATE(492), + [sym__br_prp_val] = STATE(493), + [sym__r_prp] = STATE(113), + [sym__br_prp] = STATE(112), + [sym__r_flw_seq_val] = STATE(498), + [sym__br_flw_seq_val] = STATE(504), + [sym__r_flw_seq] = STATE(623), + [sym__br_flw_seq] = STATE(540), + [sym__r_flw_map_val] = STATE(498), + [sym__br_flw_map_val] = STATE(504), + [sym__r_flw_map] = STATE(542), + [sym__br_flw_map] = STATE(545), + [sym__r_flw_map_itm] = STATE(875), + [sym__br_flw_map_itm] = STATE(875), + [sym__r_flw_exp_par] = STATE(814), + [sym__br_flw_exp_par] = STATE(815), + [sym__r_flw_imp_r_par] = STATE(826), + [sym__r_flw_imp_br_par] = STATE(839), + [sym__br_flw_imp_r_par] = STATE(840), + [sym__br_flw_imp_br_par] = STATE(841), + [sym__r_flw_njl_ann_par] = STATE(887), + [sym__br_flw_njl_ann_par] = STATE(888), + [sym__r_dqt_str_val] = STATE(498), + [sym__br_dqt_str_val] = STATE(504), + [sym__r_dqt_str] = STATE(547), + [sym__br_dqt_str] = STATE(548), + [sym__r_sqt_str_val] = STATE(498), + [sym__br_sqt_str_val] = STATE(504), + [sym__r_sqt_str] = STATE(549), + [sym__br_sqt_str] = STATE(550), + [sym__r_pln_flw_val] = STATE(492), + [sym__br_pln_flw_val] = STATE(493), + [sym__r_sgl_pln_flw] = STATE(564), + [sym__br_sgl_pln_flw] = STATE(563), + [sym__r_mtl_pln_flw] = STATE(564), + [sym__br_mtl_pln_flw] = STATE(563), + [sym__r_als_val] = STATE(492), + [sym__br_als_val] = STATE(493), + [sym__r_als] = STATE(638), + [sym__br_als] = STATE(551), + [sym__r_acr] = STATE(190), + [sym__br_acr] = STATE(197), + [sym__r_flw_seq_bgn] = ACTIONS(426), + [sym__br_flw_seq_bgn] = ACTIONS(207), + [sym__r_flw_map_bgn] = ACTIONS(428), + [sym__br_flw_map_bgn] = ACTIONS(211), + [sym__r_flw_key_bgn] = ACTIONS(432), + [sym__br_flw_key_bgn] = ACTIONS(219), + [sym__r_flw_njv_bgn] = ACTIONS(434), + [sym__br_flw_njv_bgn] = ACTIONS(223), + [sym__r_dqt_str_bgn] = ACTIONS(436), + [sym__br_dqt_str_bgn] = ACTIONS(227), + [sym__r_sqt_str_bgn] = ACTIONS(438), + [sym__br_sqt_str_bgn] = ACTIONS(231), + [sym__r_sgl_pln_nul_flw] = ACTIONS(233), + [sym__br_sgl_pln_nul_flw] = ACTIONS(235), + [sym__r_sgl_pln_bol_flw] = ACTIONS(233), + [sym__br_sgl_pln_bol_flw] = ACTIONS(235), + [sym__r_sgl_pln_int_flw] = ACTIONS(233), + [sym__br_sgl_pln_int_flw] = ACTIONS(235), + [sym__r_sgl_pln_flt_flw] = ACTIONS(233), + [sym__br_sgl_pln_flt_flw] = ACTIONS(235), + [sym__r_sgl_pln_tms_flw] = ACTIONS(233), + [sym__br_sgl_pln_tms_flw] = ACTIONS(235), + [sym__r_sgl_pln_str_flw] = ACTIONS(233), + [sym__br_sgl_pln_str_flw] = ACTIONS(235), + [sym__r_mtl_pln_str_flw] = ACTIONS(237), + [sym__br_mtl_pln_str_flw] = ACTIONS(239), + [sym__r_tag] = ACTIONS(440), + [sym__br_tag] = ACTIONS(243), + [sym__r_acr_bgn] = ACTIONS(245), + [sym__br_acr_bgn] = ACTIONS(247), + [sym__r_als_bgn] = ACTIONS(249), + [sym__br_als_bgn] = ACTIONS(251), + [sym_comment] = ACTIONS(3), + }, + [STATE(79)] = { + [sym__r_prp_val] = STATE(674), + [sym__br_prp_val] = STATE(672), + [sym__r_prp] = STATE(115), + [sym__br_prp] = STATE(114), + [sym__r_flw_seq_val] = STATE(554), + [sym__br_flw_seq_val] = STATE(645), + [sym__r_flw_seq] = STATE(702), + [sym__br_flw_seq] = STATE(703), + [sym__r_flw_map_val] = STATE(554), + [sym__br_flw_map_val] = STATE(645), + [sym__r_flw_map] = STATE(704), + [sym__br_flw_map] = STATE(705), + [sym__r_flw_seq_itm] = STATE(825), + [sym__br_flw_seq_itm] = STATE(825), + [sym__r_flw_exp_par] = STATE(789), + [sym__br_flw_exp_par] = STATE(790), + [sym__r_flw_imp_r_par] = STATE(791), + [sym__br_flw_imp_r_par] = STATE(795), + [sym__r_flw_njl_ann_par] = STATE(799), + [sym__br_flw_njl_ann_par] = STATE(800), + [sym__r_dqt_str_val] = STATE(554), + [sym__br_dqt_str_val] = STATE(645), + [sym__r_dqt_str] = STATE(706), + [sym__br_dqt_str] = STATE(707), + [sym__r_sqt_str_val] = STATE(554), + [sym__br_sqt_str_val] = STATE(645), + [sym__r_sqt_str] = STATE(708), + [sym__br_sqt_str] = STATE(709), + [sym__r_pln_flw_val] = STATE(674), + [sym__br_pln_flw_val] = STATE(672), + [sym__r_sgl_pln_flw] = STATE(749), + [sym__br_sgl_pln_flw] = STATE(748), + [sym__r_mtl_pln_flw] = STATE(749), + [sym__br_mtl_pln_flw] = STATE(748), + [sym__r_als_val] = STATE(674), + [sym__br_als_val] = STATE(672), + [sym__r_als] = STATE(746), + [sym__br_als] = STATE(710), + [sym__r_acr] = STATE(209), + [sym__br_acr] = STATE(210), + [sym__r_flw_seq_bgn] = ACTIONS(491), + [sym__br_flw_seq_bgn] = ACTIONS(289), + [sym__r_flw_map_bgn] = ACTIONS(493), + [sym__br_flw_map_bgn] = ACTIONS(297), + [sym__r_flw_key_bgn] = ACTIONS(495), + [sym__br_flw_key_bgn] = ACTIONS(301), + [sym__r_flw_njv_bgn] = ACTIONS(497), + [sym__br_flw_njv_bgn] = ACTIONS(305), + [sym__r_dqt_str_bgn] = ACTIONS(499), + [sym__br_dqt_str_bgn] = ACTIONS(309), + [sym__r_sqt_str_bgn] = ACTIONS(501), + [sym__br_sqt_str_bgn] = ACTIONS(313), + [sym__r_sgl_pln_nul_flw] = ACTIONS(315), + [sym__br_sgl_pln_nul_flw] = ACTIONS(317), + [sym__r_sgl_pln_bol_flw] = ACTIONS(315), + [sym__br_sgl_pln_bol_flw] = ACTIONS(317), + [sym__r_sgl_pln_int_flw] = ACTIONS(315), + [sym__br_sgl_pln_int_flw] = ACTIONS(317), + [sym__r_sgl_pln_flt_flw] = ACTIONS(315), + [sym__br_sgl_pln_flt_flw] = ACTIONS(317), + [sym__r_sgl_pln_tms_flw] = ACTIONS(315), + [sym__br_sgl_pln_tms_flw] = ACTIONS(317), + [sym__r_sgl_pln_str_flw] = ACTIONS(315), + [sym__br_sgl_pln_str_flw] = ACTIONS(317), + [sym__r_mtl_pln_str_flw] = ACTIONS(319), + [sym__br_mtl_pln_str_flw] = ACTIONS(321), + [sym__r_tag] = ACTIONS(503), + [sym__br_tag] = ACTIONS(325), + [sym__r_acr_bgn] = ACTIONS(327), + [sym__br_acr_bgn] = ACTIONS(329), + [sym__r_als_bgn] = ACTIONS(331), + [sym__br_als_bgn] = ACTIONS(333), + [sym_comment] = ACTIONS(3), + }, + [STATE(80)] = { + [sym__br_sgl_prp_val] = STATE(1237), + [sym__br_sgl_prp] = STATE(309), + [sym__br_blk_seq] = STATE(1201), + [sym__br_blk_seq_itm] = STATE(1048), + [sym__br_blk_map] = STATE(1202), + [sym__br_blk_map_itm] = STATE(130), + [sym__br_blk_exp_itm] = STATE(319), + [sym__br_blk_key_itm] = STATE(278), + [sym__br_blk_val_itm] = STATE(328), + [sym__br_blk_imp_itm] = STATE(364), + [sym__r_blk_str] = STATE(1203), + [sym__br_blk_str] = STATE(1203), + [sym__br_sgl_flw_seq_val] = STATE(1237), + [sym__r_flw_seq] = STATE(1204), + [sym__br_flw_seq] = STATE(1204), + [sym__br_sgl_flw_seq] = STATE(1551), + [sym__br_sgl_flw_map_val] = STATE(1237), + [sym__r_flw_map] = STATE(1205), + [sym__br_flw_map] = STATE(1205), + [sym__br_sgl_flw_map] = STATE(1514), + [sym__br_sgl_dqt_str_val] = STATE(1237), + [sym__r_dqt_str] = STATE(1206), + [sym__br_dqt_str] = STATE(1206), + [sym__br_sgl_dqt_str] = STATE(1446), + [sym__br_sgl_sqt_str_val] = STATE(1237), + [sym__r_sqt_str] = STATE(1207), + [sym__br_sqt_str] = STATE(1207), + [sym__br_sgl_sqt_str] = STATE(1417), + [sym__br_sgl_pln_blk_val] = STATE(1237), + [sym__r_sgl_pln_blk] = STATE(1208), + [sym__br_sgl_pln_blk] = STATE(1040), + [sym__r_mtl_pln_blk] = STATE(1208), + [sym__br_mtl_pln_blk] = STATE(1208), + [sym__br_als_val] = STATE(1237), + [sym__br_als] = STATE(1487), + [sym__br_acr] = STATE(415), + [sym__eof] = ACTIONS(369), + [sym__s_drs_end] = ACTIONS(369), + [sym__s_doc_end] = ACTIONS(369), + [sym__br_blk_seq_bgn] = ACTIONS(19), + [sym__br_blk_key_bgn] = ACTIONS(23), + [sym__br_blk_val_bgn] = ACTIONS(27), + [sym__r_blk_lit_bgn] = ACTIONS(29), + [sym__br_blk_lit_bgn] = ACTIONS(31), + [sym__r_blk_fld_bgn] = ACTIONS(29), + [sym__br_blk_fld_bgn] = ACTIONS(31), + [sym__r_flw_seq_bgn] = ACTIONS(189), + [sym__br_flw_seq_bgn] = ACTIONS(35), + [sym__r_flw_map_bgn] = ACTIONS(191), + [sym__br_flw_map_bgn] = ACTIONS(39), + [sym__r_dqt_str_bgn] = ACTIONS(193), + [sym__br_dqt_str_bgn] = ACTIONS(43), + [sym__r_sqt_str_bgn] = ACTIONS(195), + [sym__br_sqt_str_bgn] = ACTIONS(47), + [sym__r_sgl_pln_nul_blk] = ACTIONS(197), + [sym__br_sgl_pln_nul_blk] = ACTIONS(51), + [sym__r_sgl_pln_bol_blk] = ACTIONS(197), + [sym__br_sgl_pln_bol_blk] = ACTIONS(51), + [sym__r_sgl_pln_int_blk] = ACTIONS(197), + [sym__br_sgl_pln_int_blk] = ACTIONS(51), + [sym__r_sgl_pln_flt_blk] = ACTIONS(197), + [sym__br_sgl_pln_flt_blk] = ACTIONS(51), + [sym__r_sgl_pln_tms_blk] = ACTIONS(197), + [sym__br_sgl_pln_tms_blk] = ACTIONS(51), + [sym__r_sgl_pln_str_blk] = ACTIONS(197), + [sym__br_sgl_pln_str_blk] = ACTIONS(51), + [sym__r_mtl_pln_str_blk] = ACTIONS(53), + [sym__br_mtl_pln_str_blk] = ACTIONS(55), + [sym__br_tag] = ACTIONS(371), + [sym__br_acr_bgn] = ACTIONS(373), + [sym__br_als_bgn] = ACTIONS(375), + [sym_comment] = ACTIONS(3), + }, + [STATE(81)] = { + [sym__br_sgl_prp_val] = STATE(1237), + [sym__br_sgl_prp] = STATE(309), + [sym__br_blk_seq] = STATE(1177), + [sym__br_blk_seq_itm] = STATE(1048), + [sym__br_blk_map] = STATE(1185), + [sym__br_blk_map_itm] = STATE(130), + [sym__br_blk_exp_itm] = STATE(319), + [sym__br_blk_key_itm] = STATE(278), + [sym__br_blk_val_itm] = STATE(328), + [sym__br_blk_imp_itm] = STATE(364), + [sym__r_blk_str] = STATE(1186), + [sym__br_blk_str] = STATE(1186), + [sym__br_sgl_flw_seq_val] = STATE(1237), + [sym__r_flw_seq] = STATE(1188), + [sym__br_flw_seq] = STATE(1188), + [sym__br_sgl_flw_seq] = STATE(1551), + [sym__br_sgl_flw_map_val] = STATE(1237), + [sym__r_flw_map] = STATE(1191), + [sym__br_flw_map] = STATE(1191), + [sym__br_sgl_flw_map] = STATE(1514), + [sym__br_sgl_dqt_str_val] = STATE(1237), + [sym__r_dqt_str] = STATE(1192), + [sym__br_dqt_str] = STATE(1192), + [sym__br_sgl_dqt_str] = STATE(1446), + [sym__br_sgl_sqt_str_val] = STATE(1237), + [sym__r_sqt_str] = STATE(1197), + [sym__br_sqt_str] = STATE(1197), + [sym__br_sgl_sqt_str] = STATE(1417), + [sym__br_sgl_pln_blk_val] = STATE(1237), + [sym__r_sgl_pln_blk] = STATE(1199), + [sym__br_sgl_pln_blk] = STATE(1037), + [sym__r_mtl_pln_blk] = STATE(1199), + [sym__br_mtl_pln_blk] = STATE(1199), + [sym__br_als_val] = STATE(1237), + [sym__br_als] = STATE(1487), + [sym__br_acr] = STATE(415), + [sym__eof] = ACTIONS(377), + [sym__s_drs_end] = ACTIONS(377), + [sym__s_doc_end] = ACTIONS(377), + [sym__br_blk_seq_bgn] = ACTIONS(19), + [sym__br_blk_key_bgn] = ACTIONS(23), + [sym__br_blk_val_bgn] = ACTIONS(27), + [sym__r_blk_lit_bgn] = ACTIONS(29), + [sym__br_blk_lit_bgn] = ACTIONS(31), + [sym__r_blk_fld_bgn] = ACTIONS(29), + [sym__br_blk_fld_bgn] = ACTIONS(31), + [sym__r_flw_seq_bgn] = ACTIONS(189), + [sym__br_flw_seq_bgn] = ACTIONS(35), + [sym__r_flw_map_bgn] = ACTIONS(191), + [sym__br_flw_map_bgn] = ACTIONS(39), + [sym__r_dqt_str_bgn] = ACTIONS(193), + [sym__br_dqt_str_bgn] = ACTIONS(43), + [sym__r_sqt_str_bgn] = ACTIONS(195), + [sym__br_sqt_str_bgn] = ACTIONS(47), + [sym__r_sgl_pln_nul_blk] = ACTIONS(197), + [sym__br_sgl_pln_nul_blk] = ACTIONS(51), + [sym__r_sgl_pln_bol_blk] = ACTIONS(197), + [sym__br_sgl_pln_bol_blk] = ACTIONS(51), + [sym__r_sgl_pln_int_blk] = ACTIONS(197), + [sym__br_sgl_pln_int_blk] = ACTIONS(51), + [sym__r_sgl_pln_flt_blk] = ACTIONS(197), + [sym__br_sgl_pln_flt_blk] = ACTIONS(51), + [sym__r_sgl_pln_tms_blk] = ACTIONS(197), + [sym__br_sgl_pln_tms_blk] = ACTIONS(51), + [sym__r_sgl_pln_str_blk] = ACTIONS(197), + [sym__br_sgl_pln_str_blk] = ACTIONS(51), + [sym__r_mtl_pln_str_blk] = ACTIONS(53), + [sym__br_mtl_pln_str_blk] = ACTIONS(55), + [sym__br_tag] = ACTIONS(371), + [sym__br_acr_bgn] = ACTIONS(373), + [sym__br_als_bgn] = ACTIONS(375), + [sym_comment] = ACTIONS(3), + }, + [STATE(82)] = { + [sym__br_sgl_prp_val] = STATE(1237), + [sym__br_sgl_prp] = STATE(309), + [sym__br_blk_seq] = STATE(1273), + [sym__br_blk_seq_itm] = STATE(1003), + [sym__br_blk_map] = STATE(1274), + [sym__br_blk_map_itm] = STATE(135), + [sym__br_blk_exp_itm] = STATE(319), + [sym__br_blk_key_itm] = STATE(278), + [sym__br_blk_val_itm] = STATE(328), + [sym__br_blk_imp_itm] = STATE(364), + [sym__r_blk_str] = STATE(1275), + [sym__br_blk_str] = STATE(1275), + [sym__br_sgl_flw_seq_val] = STATE(1237), + [sym__r_flw_seq] = STATE(1276), + [sym__br_flw_seq] = STATE(1276), + [sym__br_sgl_flw_seq] = STATE(1551), + [sym__br_sgl_flw_map_val] = STATE(1237), + [sym__r_flw_map] = STATE(1277), + [sym__br_flw_map] = STATE(1277), + [sym__br_sgl_flw_map] = STATE(1514), + [sym__br_sgl_dqt_str_val] = STATE(1237), + [sym__r_dqt_str] = STATE(1278), + [sym__br_dqt_str] = STATE(1278), + [sym__br_sgl_dqt_str] = STATE(1446), + [sym__br_sgl_sqt_str_val] = STATE(1237), + [sym__r_sqt_str] = STATE(1279), + [sym__br_sqt_str] = STATE(1279), + [sym__br_sgl_sqt_str] = STATE(1417), + [sym__br_sgl_pln_blk_val] = STATE(1237), + [sym__r_sgl_pln_blk] = STATE(1280), + [sym__br_sgl_pln_blk] = STATE(1159), + [sym__r_mtl_pln_blk] = STATE(1280), + [sym__br_mtl_pln_blk] = STATE(1280), + [sym__br_als_val] = STATE(1237), + [sym__br_als] = STATE(1487), + [sym__br_acr] = STATE(415), + [sym__br_blk_seq_bgn] = ACTIONS(19), + [sym__b_blk_seq_bgn] = ACTIONS(377), + [sym__br_blk_key_bgn] = ACTIONS(23), + [sym__br_blk_val_bgn] = ACTIONS(27), + [sym__r_blk_lit_bgn] = ACTIONS(125), + [sym__br_blk_lit_bgn] = ACTIONS(127), + [sym__r_blk_fld_bgn] = ACTIONS(125), + [sym__br_blk_fld_bgn] = ACTIONS(127), + [sym__r_flw_seq_bgn] = ACTIONS(567), + [sym__br_flw_seq_bgn] = ACTIONS(131), + [sym__r_flw_map_bgn] = ACTIONS(569), + [sym__br_flw_map_bgn] = ACTIONS(135), + [sym__r_dqt_str_bgn] = ACTIONS(571), + [sym__br_dqt_str_bgn] = ACTIONS(139), + [sym__r_sqt_str_bgn] = ACTIONS(573), + [sym__br_sqt_str_bgn] = ACTIONS(143), + [sym__r_sgl_pln_nul_blk] = ACTIONS(575), + [sym__br_sgl_pln_nul_blk] = ACTIONS(147), + [sym__r_sgl_pln_bol_blk] = ACTIONS(575), + [sym__br_sgl_pln_bol_blk] = ACTIONS(147), + [sym__r_sgl_pln_int_blk] = ACTIONS(575), + [sym__br_sgl_pln_int_blk] = ACTIONS(147), + [sym__r_sgl_pln_flt_blk] = ACTIONS(575), + [sym__br_sgl_pln_flt_blk] = ACTIONS(147), + [sym__r_sgl_pln_tms_blk] = ACTIONS(575), + [sym__br_sgl_pln_tms_blk] = ACTIONS(147), + [sym__r_sgl_pln_str_blk] = ACTIONS(575), + [sym__br_sgl_pln_str_blk] = ACTIONS(147), + [sym__r_mtl_pln_str_blk] = ACTIONS(149), + [sym__br_mtl_pln_str_blk] = ACTIONS(151), + [sym__br_tag] = ACTIONS(371), + [sym__br_acr_bgn] = ACTIONS(373), + [sym__br_als_bgn] = ACTIONS(375), + [sym__bl] = ACTIONS(377), + [sym_comment] = ACTIONS(3), + }, + [STATE(83)] = { + [sym__br_sgl_prp_val] = STATE(1237), + [sym__br_sgl_prp] = STATE(309), + [sym__br_blk_seq] = STATE(1284), + [sym__br_blk_seq_itm] = STATE(1003), + [sym__br_blk_map] = STATE(1285), + [sym__br_blk_map_itm] = STATE(135), + [sym__br_blk_exp_itm] = STATE(319), + [sym__br_blk_key_itm] = STATE(278), + [sym__br_blk_val_itm] = STATE(328), + [sym__br_blk_imp_itm] = STATE(364), + [sym__r_blk_str] = STATE(1286), + [sym__br_blk_str] = STATE(1286), + [sym__br_sgl_flw_seq_val] = STATE(1237), + [sym__r_flw_seq] = STATE(1287), + [sym__br_flw_seq] = STATE(1287), + [sym__br_sgl_flw_seq] = STATE(1551), + [sym__br_sgl_flw_map_val] = STATE(1237), + [sym__r_flw_map] = STATE(1288), + [sym__br_flw_map] = STATE(1288), + [sym__br_sgl_flw_map] = STATE(1514), + [sym__br_sgl_dqt_str_val] = STATE(1237), + [sym__r_dqt_str] = STATE(1289), + [sym__br_dqt_str] = STATE(1289), + [sym__br_sgl_dqt_str] = STATE(1446), + [sym__br_sgl_sqt_str_val] = STATE(1237), + [sym__r_sqt_str] = STATE(1290), + [sym__br_sqt_str] = STATE(1290), + [sym__br_sgl_sqt_str] = STATE(1417), + [sym__br_sgl_pln_blk_val] = STATE(1237), + [sym__r_sgl_pln_blk] = STATE(1291), + [sym__br_sgl_pln_blk] = STATE(1160), + [sym__r_mtl_pln_blk] = STATE(1291), + [sym__br_mtl_pln_blk] = STATE(1291), + [sym__br_als_val] = STATE(1237), + [sym__br_als] = STATE(1487), + [sym__br_acr] = STATE(415), + [sym__br_blk_seq_bgn] = ACTIONS(19), + [sym__b_blk_seq_bgn] = ACTIONS(369), + [sym__br_blk_key_bgn] = ACTIONS(23), + [sym__br_blk_val_bgn] = ACTIONS(27), + [sym__r_blk_lit_bgn] = ACTIONS(125), + [sym__br_blk_lit_bgn] = ACTIONS(127), + [sym__r_blk_fld_bgn] = ACTIONS(125), + [sym__br_blk_fld_bgn] = ACTIONS(127), + [sym__r_flw_seq_bgn] = ACTIONS(567), + [sym__br_flw_seq_bgn] = ACTIONS(131), + [sym__r_flw_map_bgn] = ACTIONS(569), + [sym__br_flw_map_bgn] = ACTIONS(135), + [sym__r_dqt_str_bgn] = ACTIONS(571), + [sym__br_dqt_str_bgn] = ACTIONS(139), + [sym__r_sqt_str_bgn] = ACTIONS(573), + [sym__br_sqt_str_bgn] = ACTIONS(143), + [sym__r_sgl_pln_nul_blk] = ACTIONS(575), + [sym__br_sgl_pln_nul_blk] = ACTIONS(147), + [sym__r_sgl_pln_bol_blk] = ACTIONS(575), + [sym__br_sgl_pln_bol_blk] = ACTIONS(147), + [sym__r_sgl_pln_int_blk] = ACTIONS(575), + [sym__br_sgl_pln_int_blk] = ACTIONS(147), + [sym__r_sgl_pln_flt_blk] = ACTIONS(575), + [sym__br_sgl_pln_flt_blk] = ACTIONS(147), + [sym__r_sgl_pln_tms_blk] = ACTIONS(575), + [sym__br_sgl_pln_tms_blk] = ACTIONS(147), + [sym__r_sgl_pln_str_blk] = ACTIONS(575), + [sym__br_sgl_pln_str_blk] = ACTIONS(147), + [sym__r_mtl_pln_str_blk] = ACTIONS(149), + [sym__br_mtl_pln_str_blk] = ACTIONS(151), + [sym__br_tag] = ACTIONS(371), + [sym__br_acr_bgn] = ACTIONS(373), + [sym__br_als_bgn] = ACTIONS(375), + [sym__bl] = ACTIONS(369), + [sym_comment] = ACTIONS(3), + }, + [STATE(84)] = { + [sym__r_prp_val] = STATE(981), + [sym__br_prp_val] = STATE(984), + [sym__r_prp] = STATE(162), + [sym__br_prp] = STATE(164), + [sym__r_flw_seq_val] = STATE(1031), + [sym__br_flw_seq_val] = STATE(1035), + [sym__r_flw_seq] = STATE(1282), + [sym__br_flw_seq] = STATE(1283), + [sym__r_flw_map_val] = STATE(1031), + [sym__br_flw_map_val] = STATE(1035), + [sym__r_flw_map] = STATE(1302), + [sym__br_flw_map] = STATE(1304), + [sym__r_flw_imp_r_par] = STATE(929), + [sym__r_flw_imp_br_par] = STATE(931), + [sym__br_flw_imp_r_par] = STATE(932), + [sym__br_flw_imp_br_par] = STATE(933), + [sym__r_dqt_str_val] = STATE(1031), + [sym__br_dqt_str_val] = STATE(1035), + [sym__r_dqt_str] = STATE(1306), + [sym__br_dqt_str] = STATE(1307), + [sym__r_sqt_str_val] = STATE(1031), + [sym__br_sqt_str_val] = STATE(1035), + [sym__r_sqt_str] = STATE(1309), + [sym__br_sqt_str] = STATE(1310), + [sym__r_pln_flw_val] = STATE(981), + [sym__br_pln_flw_val] = STATE(984), + [sym__r_sgl_pln_flw] = STATE(1222), + [sym__br_sgl_pln_flw] = STATE(1345), + [sym__r_mtl_pln_flw] = STATE(1222), + [sym__br_mtl_pln_flw] = STATE(1345), + [sym__r_als_val] = STATE(981), + [sym__br_als_val] = STATE(984), + [sym__r_als] = STATE(1246), + [sym__br_als] = STATE(1272), + [sym__r_acr] = STATE(245), + [sym__br_acr] = STATE(248), + [sym__r_flw_seq_bgn] = ACTIONS(577), + [sym__br_flw_seq_bgn] = ACTIONS(387), + [sym__r_flw_map_bgn] = ACTIONS(579), + [sym__br_flw_map_bgn] = ACTIONS(391), + [sym__r_flw_map_end] = ACTIONS(581), + [sym__br_flw_map_end] = ACTIONS(581), + [sym__b_flw_map_end] = ACTIONS(581), + [sym__r_flw_sep_bgn] = ACTIONS(581), + [sym__br_flw_sep_bgn] = ACTIONS(581), + [sym__r_dqt_str_bgn] = ACTIONS(583), + [sym__br_dqt_str_bgn] = ACTIONS(400), + [sym__r_sqt_str_bgn] = ACTIONS(585), + [sym__br_sqt_str_bgn] = ACTIONS(404), + [sym__r_sgl_pln_nul_flw] = ACTIONS(406), + [sym__br_sgl_pln_nul_flw] = ACTIONS(408), + [sym__r_sgl_pln_bol_flw] = ACTIONS(406), + [sym__br_sgl_pln_bol_flw] = ACTIONS(408), + [sym__r_sgl_pln_int_flw] = ACTIONS(406), + [sym__br_sgl_pln_int_flw] = ACTIONS(408), + [sym__r_sgl_pln_flt_flw] = ACTIONS(406), + [sym__br_sgl_pln_flt_flw] = ACTIONS(408), + [sym__r_sgl_pln_tms_flw] = ACTIONS(406), + [sym__br_sgl_pln_tms_flw] = ACTIONS(408), + [sym__r_sgl_pln_str_flw] = ACTIONS(406), + [sym__br_sgl_pln_str_flw] = ACTIONS(408), + [sym__r_mtl_pln_str_flw] = ACTIONS(410), + [sym__br_mtl_pln_str_flw] = ACTIONS(412), + [sym__r_tag] = ACTIONS(587), + [sym__br_tag] = ACTIONS(416), + [sym__r_acr_bgn] = ACTIONS(418), + [sym__br_acr_bgn] = ACTIONS(420), + [sym__r_als_bgn] = ACTIONS(422), + [sym__br_als_bgn] = ACTIONS(424), + [sym_comment] = ACTIONS(3), + }, + [STATE(85)] = { + [sym__r_prp_val] = STATE(980), + [sym__br_prp_val] = STATE(991), + [sym__r_prp] = STATE(162), + [sym__br_prp] = STATE(164), + [sym__r_flw_seq_val] = STATE(1009), + [sym__br_flw_seq_val] = STATE(1018), + [sym__r_flw_seq] = STATE(1282), + [sym__br_flw_seq] = STATE(1283), + [sym__r_flw_map_val] = STATE(1009), + [sym__br_flw_map_val] = STATE(1018), + [sym__r_flw_map] = STATE(1302), + [sym__br_flw_map] = STATE(1304), + [sym__r_flw_imp_r_par] = STATE(948), + [sym__r_flw_imp_br_par] = STATE(953), + [sym__br_flw_imp_r_par] = STATE(960), + [sym__br_flw_imp_br_par] = STATE(804), + [sym__r_dqt_str_val] = STATE(1009), + [sym__br_dqt_str_val] = STATE(1018), + [sym__r_dqt_str] = STATE(1306), + [sym__br_dqt_str] = STATE(1307), + [sym__r_sqt_str_val] = STATE(1009), + [sym__br_sqt_str_val] = STATE(1018), + [sym__r_sqt_str] = STATE(1309), + [sym__br_sqt_str] = STATE(1310), + [sym__r_pln_flw_val] = STATE(980), + [sym__br_pln_flw_val] = STATE(991), + [sym__r_sgl_pln_flw] = STATE(1222), + [sym__br_sgl_pln_flw] = STATE(1345), + [sym__r_mtl_pln_flw] = STATE(1222), + [sym__br_mtl_pln_flw] = STATE(1345), + [sym__r_als_val] = STATE(980), + [sym__br_als_val] = STATE(991), + [sym__r_als] = STATE(1246), + [sym__br_als] = STATE(1272), + [sym__r_acr] = STATE(245), + [sym__br_acr] = STATE(248), + [sym__r_flw_seq_bgn] = ACTIONS(577), + [sym__br_flw_seq_bgn] = ACTIONS(387), + [sym__r_flw_seq_end] = ACTIONS(396), + [sym__br_flw_seq_end] = ACTIONS(396), + [sym__b_flw_seq_end] = ACTIONS(396), + [sym__r_flw_map_bgn] = ACTIONS(579), + [sym__br_flw_map_bgn] = ACTIONS(391), + [sym__r_flw_sep_bgn] = ACTIONS(396), + [sym__br_flw_sep_bgn] = ACTIONS(396), + [sym__r_dqt_str_bgn] = ACTIONS(583), + [sym__br_dqt_str_bgn] = ACTIONS(400), + [sym__r_sqt_str_bgn] = ACTIONS(585), + [sym__br_sqt_str_bgn] = ACTIONS(404), + [sym__r_sgl_pln_nul_flw] = ACTIONS(406), + [sym__br_sgl_pln_nul_flw] = ACTIONS(408), + [sym__r_sgl_pln_bol_flw] = ACTIONS(406), + [sym__br_sgl_pln_bol_flw] = ACTIONS(408), + [sym__r_sgl_pln_int_flw] = ACTIONS(406), + [sym__br_sgl_pln_int_flw] = ACTIONS(408), + [sym__r_sgl_pln_flt_flw] = ACTIONS(406), + [sym__br_sgl_pln_flt_flw] = ACTIONS(408), + [sym__r_sgl_pln_tms_flw] = ACTIONS(406), + [sym__br_sgl_pln_tms_flw] = ACTIONS(408), + [sym__r_sgl_pln_str_flw] = ACTIONS(406), + [sym__br_sgl_pln_str_flw] = ACTIONS(408), + [sym__r_mtl_pln_str_flw] = ACTIONS(410), + [sym__br_mtl_pln_str_flw] = ACTIONS(412), + [sym__r_tag] = ACTIONS(587), + [sym__br_tag] = ACTIONS(416), + [sym__r_acr_bgn] = ACTIONS(418), + [sym__br_acr_bgn] = ACTIONS(420), + [sym__r_als_bgn] = ACTIONS(422), + [sym__br_als_bgn] = ACTIONS(424), + [sym_comment] = ACTIONS(3), + }, + [STATE(86)] = { + [sym__r_prp_val] = STATE(980), + [sym__br_prp_val] = STATE(991), + [sym__r_prp] = STATE(162), + [sym__br_prp] = STATE(164), + [sym__r_flw_seq_val] = STATE(1009), + [sym__br_flw_seq_val] = STATE(1018), + [sym__r_flw_seq] = STATE(1282), + [sym__br_flw_seq] = STATE(1283), + [sym__r_flw_map_val] = STATE(1009), + [sym__br_flw_map_val] = STATE(1018), + [sym__r_flw_map] = STATE(1302), + [sym__br_flw_map] = STATE(1304), + [sym__r_flw_imp_r_par] = STATE(806), + [sym__r_flw_imp_br_par] = STATE(807), + [sym__br_flw_imp_r_par] = STATE(808), + [sym__br_flw_imp_br_par] = STATE(809), + [sym__r_dqt_str_val] = STATE(1009), + [sym__br_dqt_str_val] = STATE(1018), + [sym__r_dqt_str] = STATE(1306), + [sym__br_dqt_str] = STATE(1307), + [sym__r_sqt_str_val] = STATE(1009), + [sym__br_sqt_str_val] = STATE(1018), + [sym__r_sqt_str] = STATE(1309), + [sym__br_sqt_str] = STATE(1310), + [sym__r_pln_flw_val] = STATE(980), + [sym__br_pln_flw_val] = STATE(991), + [sym__r_sgl_pln_flw] = STATE(1222), + [sym__br_sgl_pln_flw] = STATE(1345), + [sym__r_mtl_pln_flw] = STATE(1222), + [sym__br_mtl_pln_flw] = STATE(1345), + [sym__r_als_val] = STATE(980), + [sym__br_als_val] = STATE(991), + [sym__r_als] = STATE(1246), + [sym__br_als] = STATE(1272), + [sym__r_acr] = STATE(245), + [sym__br_acr] = STATE(248), + [sym__r_flw_seq_bgn] = ACTIONS(577), + [sym__br_flw_seq_bgn] = ACTIONS(387), + [sym__r_flw_seq_end] = ACTIONS(581), + [sym__br_flw_seq_end] = ACTIONS(581), + [sym__b_flw_seq_end] = ACTIONS(581), + [sym__r_flw_map_bgn] = ACTIONS(579), + [sym__br_flw_map_bgn] = ACTIONS(391), + [sym__r_flw_sep_bgn] = ACTIONS(581), + [sym__br_flw_sep_bgn] = ACTIONS(581), + [sym__r_dqt_str_bgn] = ACTIONS(583), + [sym__br_dqt_str_bgn] = ACTIONS(400), + [sym__r_sqt_str_bgn] = ACTIONS(585), + [sym__br_sqt_str_bgn] = ACTIONS(404), + [sym__r_sgl_pln_nul_flw] = ACTIONS(406), + [sym__br_sgl_pln_nul_flw] = ACTIONS(408), + [sym__r_sgl_pln_bol_flw] = ACTIONS(406), + [sym__br_sgl_pln_bol_flw] = ACTIONS(408), + [sym__r_sgl_pln_int_flw] = ACTIONS(406), + [sym__br_sgl_pln_int_flw] = ACTIONS(408), + [sym__r_sgl_pln_flt_flw] = ACTIONS(406), + [sym__br_sgl_pln_flt_flw] = ACTIONS(408), + [sym__r_sgl_pln_tms_flw] = ACTIONS(406), + [sym__br_sgl_pln_tms_flw] = ACTIONS(408), + [sym__r_sgl_pln_str_flw] = ACTIONS(406), + [sym__br_sgl_pln_str_flw] = ACTIONS(408), + [sym__r_mtl_pln_str_flw] = ACTIONS(410), + [sym__br_mtl_pln_str_flw] = ACTIONS(412), + [sym__r_tag] = ACTIONS(587), + [sym__br_tag] = ACTIONS(416), + [sym__r_acr_bgn] = ACTIONS(418), + [sym__br_acr_bgn] = ACTIONS(420), + [sym__r_als_bgn] = ACTIONS(422), + [sym__br_als_bgn] = ACTIONS(424), + [sym_comment] = ACTIONS(3), + }, + [STATE(87)] = { + [sym__r_prp_val] = STATE(981), + [sym__br_prp_val] = STATE(984), + [sym__r_prp] = STATE(162), + [sym__br_prp] = STATE(164), + [sym__r_flw_seq_val] = STATE(1031), + [sym__br_flw_seq_val] = STATE(1035), + [sym__r_flw_seq] = STATE(1282), + [sym__br_flw_seq] = STATE(1283), + [sym__r_flw_map_val] = STATE(1031), + [sym__br_flw_map_val] = STATE(1035), + [sym__r_flw_map] = STATE(1302), + [sym__br_flw_map] = STATE(1304), + [sym__r_flw_imp_r_par] = STATE(924), + [sym__r_flw_imp_br_par] = STATE(925), + [sym__br_flw_imp_r_par] = STATE(926), + [sym__br_flw_imp_br_par] = STATE(927), + [sym__r_dqt_str_val] = STATE(1031), + [sym__br_dqt_str_val] = STATE(1035), + [sym__r_dqt_str] = STATE(1306), + [sym__br_dqt_str] = STATE(1307), + [sym__r_sqt_str_val] = STATE(1031), + [sym__br_sqt_str_val] = STATE(1035), + [sym__r_sqt_str] = STATE(1309), + [sym__br_sqt_str] = STATE(1310), + [sym__r_pln_flw_val] = STATE(981), + [sym__br_pln_flw_val] = STATE(984), + [sym__r_sgl_pln_flw] = STATE(1222), + [sym__br_sgl_pln_flw] = STATE(1345), + [sym__r_mtl_pln_flw] = STATE(1222), + [sym__br_mtl_pln_flw] = STATE(1345), + [sym__r_als_val] = STATE(981), + [sym__br_als_val] = STATE(984), + [sym__r_als] = STATE(1246), + [sym__br_als] = STATE(1272), + [sym__r_acr] = STATE(245), + [sym__br_acr] = STATE(248), + [sym__r_flw_seq_bgn] = ACTIONS(577), + [sym__br_flw_seq_bgn] = ACTIONS(387), + [sym__r_flw_map_bgn] = ACTIONS(579), + [sym__br_flw_map_bgn] = ACTIONS(391), + [sym__r_flw_map_end] = ACTIONS(396), + [sym__br_flw_map_end] = ACTIONS(396), + [sym__b_flw_map_end] = ACTIONS(396), + [sym__r_flw_sep_bgn] = ACTIONS(396), + [sym__br_flw_sep_bgn] = ACTIONS(396), + [sym__r_dqt_str_bgn] = ACTIONS(583), + [sym__br_dqt_str_bgn] = ACTIONS(400), + [sym__r_sqt_str_bgn] = ACTIONS(585), + [sym__br_sqt_str_bgn] = ACTIONS(404), + [sym__r_sgl_pln_nul_flw] = ACTIONS(406), + [sym__br_sgl_pln_nul_flw] = ACTIONS(408), + [sym__r_sgl_pln_bol_flw] = ACTIONS(406), + [sym__br_sgl_pln_bol_flw] = ACTIONS(408), + [sym__r_sgl_pln_int_flw] = ACTIONS(406), + [sym__br_sgl_pln_int_flw] = ACTIONS(408), + [sym__r_sgl_pln_flt_flw] = ACTIONS(406), + [sym__br_sgl_pln_flt_flw] = ACTIONS(408), + [sym__r_sgl_pln_tms_flw] = ACTIONS(406), + [sym__br_sgl_pln_tms_flw] = ACTIONS(408), + [sym__r_sgl_pln_str_flw] = ACTIONS(406), + [sym__br_sgl_pln_str_flw] = ACTIONS(408), + [sym__r_mtl_pln_str_flw] = ACTIONS(410), + [sym__br_mtl_pln_str_flw] = ACTIONS(412), + [sym__r_tag] = ACTIONS(587), + [sym__br_tag] = ACTIONS(416), + [sym__r_acr_bgn] = ACTIONS(418), + [sym__br_acr_bgn] = ACTIONS(420), + [sym__r_als_bgn] = ACTIONS(422), + [sym__br_als_bgn] = ACTIONS(424), + [sym_comment] = ACTIONS(3), + }, + [STATE(88)] = { + [sym__r_prp_val] = STATE(934), + [sym__br_prp_val] = STATE(934), + [sym__r_prp] = STATE(119), + [sym__br_prp] = STATE(120), + [sym__r_flw_seq_val] = STATE(934), + [sym__br_flw_seq_val] = STATE(934), + [sym__r_flw_seq] = STATE(865), + [sym__br_flw_seq] = STATE(866), + [sym__r_flw_map_val] = STATE(934), + [sym__br_flw_map_val] = STATE(934), + [sym__r_flw_map] = STATE(867), + [sym__br_flw_map] = STATE(868), + [sym__flw_ann_par_tal] = STATE(934), + [sym__r_dqt_str_val] = STATE(934), + [sym__br_dqt_str_val] = STATE(934), + [sym__r_dqt_str] = STATE(869), + [sym__br_dqt_str] = STATE(870), + [sym__r_sqt_str_val] = STATE(934), + [sym__br_sqt_str_val] = STATE(934), + [sym__r_sqt_str] = STATE(871), + [sym__br_sqt_str] = STATE(872), + [sym__r_pln_flw_val] = STATE(934), + [sym__br_pln_flw_val] = STATE(934), + [sym__r_sgl_pln_flw] = STATE(803), + [sym__br_sgl_pln_flw] = STATE(802), + [sym__r_mtl_pln_flw] = STATE(803), + [sym__br_mtl_pln_flw] = STATE(802), + [sym__r_als_val] = STATE(934), + [sym__br_als_val] = STATE(934), + [sym__r_als] = STATE(913), + [sym__br_als] = STATE(914), + [sym__r_acr] = STATE(213), + [sym__br_acr] = STATE(218), + [sym__r_flw_seq_bgn] = ACTIONS(589), + [sym__br_flw_seq_bgn] = ACTIONS(517), + [sym__r_flw_map_bgn] = ACTIONS(591), + [sym__br_flw_map_bgn] = ACTIONS(521), + [sym__r_flw_map_end] = ACTIONS(457), + [sym__br_flw_map_end] = ACTIONS(457), + [sym__b_flw_map_end] = ACTIONS(457), + [sym__r_flw_sep_bgn] = ACTIONS(457), + [sym__br_flw_sep_bgn] = ACTIONS(457), + [sym__r_dqt_str_bgn] = ACTIONS(593), + [sym__br_dqt_str_bgn] = ACTIONS(525), + [sym__r_sqt_str_bgn] = ACTIONS(595), + [sym__br_sqt_str_bgn] = ACTIONS(529), + [sym__r_sgl_pln_nul_flw] = ACTIONS(531), + [sym__br_sgl_pln_nul_flw] = ACTIONS(533), + [sym__r_sgl_pln_bol_flw] = ACTIONS(531), + [sym__br_sgl_pln_bol_flw] = ACTIONS(533), + [sym__r_sgl_pln_int_flw] = ACTIONS(531), + [sym__br_sgl_pln_int_flw] = ACTIONS(533), + [sym__r_sgl_pln_flt_flw] = ACTIONS(531), + [sym__br_sgl_pln_flt_flw] = ACTIONS(533), + [sym__r_sgl_pln_tms_flw] = ACTIONS(531), + [sym__br_sgl_pln_tms_flw] = ACTIONS(533), + [sym__r_sgl_pln_str_flw] = ACTIONS(531), + [sym__br_sgl_pln_str_flw] = ACTIONS(533), + [sym__r_mtl_pln_str_flw] = ACTIONS(535), + [sym__br_mtl_pln_str_flw] = ACTIONS(537), + [sym__r_tag] = ACTIONS(597), + [sym__br_tag] = ACTIONS(541), + [sym__r_acr_bgn] = ACTIONS(543), + [sym__br_acr_bgn] = ACTIONS(545), + [sym__r_als_bgn] = ACTIONS(547), + [sym__br_als_bgn] = ACTIONS(549), + [sym_comment] = ACTIONS(3), + }, + [STATE(89)] = { + [sym__r_prp_val] = STATE(951), + [sym__br_prp_val] = STATE(951), + [sym__r_prp] = STATE(119), + [sym__br_prp] = STATE(120), + [sym__r_flw_seq_val] = STATE(951), + [sym__br_flw_seq_val] = STATE(951), + [sym__r_flw_seq] = STATE(865), + [sym__br_flw_seq] = STATE(866), + [sym__r_flw_map_val] = STATE(951), + [sym__br_flw_map_val] = STATE(951), + [sym__r_flw_map] = STATE(867), + [sym__br_flw_map] = STATE(868), + [sym__flw_ann_par_tal] = STATE(951), + [sym__r_dqt_str_val] = STATE(951), + [sym__br_dqt_str_val] = STATE(951), + [sym__r_dqt_str] = STATE(869), + [sym__br_dqt_str] = STATE(870), + [sym__r_sqt_str_val] = STATE(951), + [sym__br_sqt_str_val] = STATE(951), + [sym__r_sqt_str] = STATE(871), + [sym__br_sqt_str] = STATE(872), + [sym__r_pln_flw_val] = STATE(951), + [sym__br_pln_flw_val] = STATE(951), + [sym__r_sgl_pln_flw] = STATE(803), + [sym__br_sgl_pln_flw] = STATE(802), + [sym__r_mtl_pln_flw] = STATE(803), + [sym__br_mtl_pln_flw] = STATE(802), + [sym__r_als_val] = STATE(951), + [sym__br_als_val] = STATE(951), + [sym__r_als] = STATE(913), + [sym__br_als] = STATE(914), + [sym__r_acr] = STATE(213), + [sym__br_acr] = STATE(218), + [sym__r_flw_seq_bgn] = ACTIONS(589), + [sym__br_flw_seq_bgn] = ACTIONS(517), + [sym__r_flw_map_bgn] = ACTIONS(591), + [sym__br_flw_map_bgn] = ACTIONS(521), + [sym__r_flw_map_end] = ACTIONS(599), + [sym__br_flw_map_end] = ACTIONS(599), + [sym__b_flw_map_end] = ACTIONS(599), + [sym__r_flw_sep_bgn] = ACTIONS(599), + [sym__br_flw_sep_bgn] = ACTIONS(599), + [sym__r_dqt_str_bgn] = ACTIONS(593), + [sym__br_dqt_str_bgn] = ACTIONS(525), + [sym__r_sqt_str_bgn] = ACTIONS(595), + [sym__br_sqt_str_bgn] = ACTIONS(529), + [sym__r_sgl_pln_nul_flw] = ACTIONS(531), + [sym__br_sgl_pln_nul_flw] = ACTIONS(533), + [sym__r_sgl_pln_bol_flw] = ACTIONS(531), + [sym__br_sgl_pln_bol_flw] = ACTIONS(533), + [sym__r_sgl_pln_int_flw] = ACTIONS(531), + [sym__br_sgl_pln_int_flw] = ACTIONS(533), + [sym__r_sgl_pln_flt_flw] = ACTIONS(531), + [sym__br_sgl_pln_flt_flw] = ACTIONS(533), + [sym__r_sgl_pln_tms_flw] = ACTIONS(531), + [sym__br_sgl_pln_tms_flw] = ACTIONS(533), + [sym__r_sgl_pln_str_flw] = ACTIONS(531), + [sym__br_sgl_pln_str_flw] = ACTIONS(533), + [sym__r_mtl_pln_str_flw] = ACTIONS(535), + [sym__br_mtl_pln_str_flw] = ACTIONS(537), + [sym__r_tag] = ACTIONS(597), + [sym__br_tag] = ACTIONS(541), + [sym__r_acr_bgn] = ACTIONS(543), + [sym__br_acr_bgn] = ACTIONS(545), + [sym__r_als_bgn] = ACTIONS(547), + [sym__br_als_bgn] = ACTIONS(549), + [sym_comment] = ACTIONS(3), + }, + [STATE(90)] = { + [sym__r_prp_val] = STATE(954), + [sym__br_prp_val] = STATE(954), + [sym__r_prp] = STATE(121), + [sym__br_prp] = STATE(117), + [sym__r_flw_seq_val] = STATE(954), + [sym__br_flw_seq_val] = STATE(954), + [sym__r_flw_seq] = STATE(817), + [sym__br_flw_seq] = STATE(818), + [sym__r_flw_map_val] = STATE(954), + [sym__br_flw_map_val] = STATE(954), + [sym__r_flw_map] = STATE(819), + [sym__br_flw_map] = STATE(820), + [sym__flw_ann_par_tal] = STATE(954), + [sym__r_dqt_str_val] = STATE(954), + [sym__br_dqt_str_val] = STATE(954), + [sym__r_dqt_str] = STATE(821), + [sym__br_dqt_str] = STATE(822), + [sym__r_sqt_str_val] = STATE(954), + [sym__br_sqt_str_val] = STATE(954), + [sym__r_sqt_str] = STATE(823), + [sym__br_sqt_str] = STATE(824), + [sym__r_pln_flw_val] = STATE(954), + [sym__br_pln_flw_val] = STATE(954), + [sym__r_sgl_pln_flw] = STATE(792), + [sym__br_sgl_pln_flw] = STATE(786), + [sym__r_mtl_pln_flw] = STATE(792), + [sym__br_mtl_pln_flw] = STATE(786), + [sym__r_als_val] = STATE(954), + [sym__br_als_val] = STATE(954), + [sym__r_als] = STATE(873), + [sym__br_als] = STATE(874), + [sym__r_acr] = STATE(214), + [sym__br_acr] = STATE(224), + [sym__r_flw_seq_bgn] = ACTIONS(601), + [sym__br_flw_seq_bgn] = ACTIONS(452), + [sym__r_flw_seq_end] = ACTIONS(603), + [sym__br_flw_seq_end] = ACTIONS(603), + [sym__b_flw_seq_end] = ACTIONS(603), + [sym__r_flw_map_bgn] = ACTIONS(605), + [sym__br_flw_map_bgn] = ACTIONS(461), + [sym__r_flw_sep_bgn] = ACTIONS(603), + [sym__br_flw_sep_bgn] = ACTIONS(603), + [sym__r_dqt_str_bgn] = ACTIONS(607), + [sym__br_dqt_str_bgn] = ACTIONS(465), + [sym__r_sqt_str_bgn] = ACTIONS(609), + [sym__br_sqt_str_bgn] = ACTIONS(469), + [sym__r_sgl_pln_nul_flw] = ACTIONS(471), + [sym__br_sgl_pln_nul_flw] = ACTIONS(473), + [sym__r_sgl_pln_bol_flw] = ACTIONS(471), + [sym__br_sgl_pln_bol_flw] = ACTIONS(473), + [sym__r_sgl_pln_int_flw] = ACTIONS(471), + [sym__br_sgl_pln_int_flw] = ACTIONS(473), + [sym__r_sgl_pln_flt_flw] = ACTIONS(471), + [sym__br_sgl_pln_flt_flw] = ACTIONS(473), + [sym__r_sgl_pln_tms_flw] = ACTIONS(471), + [sym__br_sgl_pln_tms_flw] = ACTIONS(473), + [sym__r_sgl_pln_str_flw] = ACTIONS(471), + [sym__br_sgl_pln_str_flw] = ACTIONS(473), + [sym__r_mtl_pln_str_flw] = ACTIONS(475), + [sym__br_mtl_pln_str_flw] = ACTIONS(477), + [sym__r_tag] = ACTIONS(611), + [sym__br_tag] = ACTIONS(481), + [sym__r_acr_bgn] = ACTIONS(483), + [sym__br_acr_bgn] = ACTIONS(485), + [sym__r_als_bgn] = ACTIONS(487), + [sym__br_als_bgn] = ACTIONS(489), + [sym_comment] = ACTIONS(3), + }, + [STATE(91)] = { + [sym__r_prp_val] = STATE(810), + [sym__br_prp_val] = STATE(810), + [sym__r_prp] = STATE(121), + [sym__br_prp] = STATE(117), + [sym__r_flw_seq_val] = STATE(810), + [sym__br_flw_seq_val] = STATE(810), + [sym__r_flw_seq] = STATE(817), + [sym__br_flw_seq] = STATE(818), + [sym__r_flw_map_val] = STATE(810), + [sym__br_flw_map_val] = STATE(810), + [sym__r_flw_map] = STATE(819), + [sym__br_flw_map] = STATE(820), + [sym__flw_ann_par_tal] = STATE(810), + [sym__r_dqt_str_val] = STATE(810), + [sym__br_dqt_str_val] = STATE(810), + [sym__r_dqt_str] = STATE(821), + [sym__br_dqt_str] = STATE(822), + [sym__r_sqt_str_val] = STATE(810), + [sym__br_sqt_str_val] = STATE(810), + [sym__r_sqt_str] = STATE(823), + [sym__br_sqt_str] = STATE(824), + [sym__r_pln_flw_val] = STATE(810), + [sym__br_pln_flw_val] = STATE(810), + [sym__r_sgl_pln_flw] = STATE(792), + [sym__br_sgl_pln_flw] = STATE(786), + [sym__r_mtl_pln_flw] = STATE(792), + [sym__br_mtl_pln_flw] = STATE(786), + [sym__r_als_val] = STATE(810), + [sym__br_als_val] = STATE(810), + [sym__r_als] = STATE(873), + [sym__br_als] = STATE(874), + [sym__r_acr] = STATE(214), + [sym__br_acr] = STATE(224), + [sym__r_flw_seq_bgn] = ACTIONS(601), + [sym__br_flw_seq_bgn] = ACTIONS(452), + [sym__r_flw_seq_end] = ACTIONS(457), + [sym__br_flw_seq_end] = ACTIONS(457), + [sym__b_flw_seq_end] = ACTIONS(457), + [sym__r_flw_map_bgn] = ACTIONS(605), + [sym__br_flw_map_bgn] = ACTIONS(461), + [sym__r_flw_sep_bgn] = ACTIONS(457), + [sym__br_flw_sep_bgn] = ACTIONS(457), + [sym__r_dqt_str_bgn] = ACTIONS(607), + [sym__br_dqt_str_bgn] = ACTIONS(465), + [sym__r_sqt_str_bgn] = ACTIONS(609), + [sym__br_sqt_str_bgn] = ACTIONS(469), + [sym__r_sgl_pln_nul_flw] = ACTIONS(471), + [sym__br_sgl_pln_nul_flw] = ACTIONS(473), + [sym__r_sgl_pln_bol_flw] = ACTIONS(471), + [sym__br_sgl_pln_bol_flw] = ACTIONS(473), + [sym__r_sgl_pln_int_flw] = ACTIONS(471), + [sym__br_sgl_pln_int_flw] = ACTIONS(473), + [sym__r_sgl_pln_flt_flw] = ACTIONS(471), + [sym__br_sgl_pln_flt_flw] = ACTIONS(473), + [sym__r_sgl_pln_tms_flw] = ACTIONS(471), + [sym__br_sgl_pln_tms_flw] = ACTIONS(473), + [sym__r_sgl_pln_str_flw] = ACTIONS(471), + [sym__br_sgl_pln_str_flw] = ACTIONS(473), + [sym__r_mtl_pln_str_flw] = ACTIONS(475), + [sym__br_mtl_pln_str_flw] = ACTIONS(477), + [sym__r_tag] = ACTIONS(611), + [sym__br_tag] = ACTIONS(481), + [sym__r_acr_bgn] = ACTIONS(483), + [sym__br_acr_bgn] = ACTIONS(485), + [sym__r_als_bgn] = ACTIONS(487), + [sym__br_als_bgn] = ACTIONS(489), + [sym_comment] = ACTIONS(3), + }, + [STATE(92)] = { + [sym__r_prp_val] = STATE(816), + [sym__br_prp_val] = STATE(816), + [sym__r_prp] = STATE(121), + [sym__br_prp] = STATE(117), + [sym__r_flw_seq_val] = STATE(816), + [sym__br_flw_seq_val] = STATE(816), + [sym__r_flw_seq] = STATE(817), + [sym__br_flw_seq] = STATE(818), + [sym__r_flw_map_val] = STATE(816), + [sym__br_flw_map_val] = STATE(816), + [sym__r_flw_map] = STATE(819), + [sym__br_flw_map] = STATE(820), + [sym__flw_ann_par_tal] = STATE(816), + [sym__r_dqt_str_val] = STATE(816), + [sym__br_dqt_str_val] = STATE(816), + [sym__r_dqt_str] = STATE(821), + [sym__br_dqt_str] = STATE(822), + [sym__r_sqt_str_val] = STATE(816), + [sym__br_sqt_str_val] = STATE(816), + [sym__r_sqt_str] = STATE(823), + [sym__br_sqt_str] = STATE(824), + [sym__r_pln_flw_val] = STATE(816), + [sym__br_pln_flw_val] = STATE(816), + [sym__r_sgl_pln_flw] = STATE(792), + [sym__br_sgl_pln_flw] = STATE(786), + [sym__r_mtl_pln_flw] = STATE(792), + [sym__br_mtl_pln_flw] = STATE(786), + [sym__r_als_val] = STATE(816), + [sym__br_als_val] = STATE(816), + [sym__r_als] = STATE(873), + [sym__br_als] = STATE(874), + [sym__r_acr] = STATE(214), + [sym__br_acr] = STATE(224), + [sym__r_flw_seq_bgn] = ACTIONS(601), + [sym__br_flw_seq_bgn] = ACTIONS(452), + [sym__r_flw_seq_end] = ACTIONS(599), + [sym__br_flw_seq_end] = ACTIONS(599), + [sym__b_flw_seq_end] = ACTIONS(599), + [sym__r_flw_map_bgn] = ACTIONS(605), + [sym__br_flw_map_bgn] = ACTIONS(461), + [sym__r_flw_sep_bgn] = ACTIONS(599), + [sym__br_flw_sep_bgn] = ACTIONS(599), + [sym__r_dqt_str_bgn] = ACTIONS(607), + [sym__br_dqt_str_bgn] = ACTIONS(465), + [sym__r_sqt_str_bgn] = ACTIONS(609), + [sym__br_sqt_str_bgn] = ACTIONS(469), + [sym__r_sgl_pln_nul_flw] = ACTIONS(471), + [sym__br_sgl_pln_nul_flw] = ACTIONS(473), + [sym__r_sgl_pln_bol_flw] = ACTIONS(471), + [sym__br_sgl_pln_bol_flw] = ACTIONS(473), + [sym__r_sgl_pln_int_flw] = ACTIONS(471), + [sym__br_sgl_pln_int_flw] = ACTIONS(473), + [sym__r_sgl_pln_flt_flw] = ACTIONS(471), + [sym__br_sgl_pln_flt_flw] = ACTIONS(473), + [sym__r_sgl_pln_tms_flw] = ACTIONS(471), + [sym__br_sgl_pln_tms_flw] = ACTIONS(473), + [sym__r_sgl_pln_str_flw] = ACTIONS(471), + [sym__br_sgl_pln_str_flw] = ACTIONS(473), + [sym__r_mtl_pln_str_flw] = ACTIONS(475), + [sym__br_mtl_pln_str_flw] = ACTIONS(477), + [sym__r_tag] = ACTIONS(611), + [sym__br_tag] = ACTIONS(481), + [sym__r_acr_bgn] = ACTIONS(483), + [sym__br_acr_bgn] = ACTIONS(485), + [sym__r_als_bgn] = ACTIONS(487), + [sym__br_als_bgn] = ACTIONS(489), + [sym_comment] = ACTIONS(3), + }, + [STATE(93)] = { + [sym__r_prp_val] = STATE(864), + [sym__br_prp_val] = STATE(864), + [sym__r_prp] = STATE(119), + [sym__br_prp] = STATE(120), + [sym__r_flw_seq_val] = STATE(864), + [sym__br_flw_seq_val] = STATE(864), + [sym__r_flw_seq] = STATE(865), + [sym__br_flw_seq] = STATE(866), + [sym__r_flw_map_val] = STATE(864), + [sym__br_flw_map_val] = STATE(864), + [sym__r_flw_map] = STATE(867), + [sym__br_flw_map] = STATE(868), + [sym__flw_ann_par_tal] = STATE(864), + [sym__r_dqt_str_val] = STATE(864), + [sym__br_dqt_str_val] = STATE(864), + [sym__r_dqt_str] = STATE(869), + [sym__br_dqt_str] = STATE(870), + [sym__r_sqt_str_val] = STATE(864), + [sym__br_sqt_str_val] = STATE(864), + [sym__r_sqt_str] = STATE(871), + [sym__br_sqt_str] = STATE(872), + [sym__r_pln_flw_val] = STATE(864), + [sym__br_pln_flw_val] = STATE(864), + [sym__r_sgl_pln_flw] = STATE(803), + [sym__br_sgl_pln_flw] = STATE(802), + [sym__r_mtl_pln_flw] = STATE(803), + [sym__br_mtl_pln_flw] = STATE(802), + [sym__r_als_val] = STATE(864), + [sym__br_als_val] = STATE(864), + [sym__r_als] = STATE(913), + [sym__br_als] = STATE(914), + [sym__r_acr] = STATE(213), + [sym__br_acr] = STATE(218), + [sym__r_flw_seq_bgn] = ACTIONS(589), + [sym__br_flw_seq_bgn] = ACTIONS(517), + [sym__r_flw_map_bgn] = ACTIONS(591), + [sym__br_flw_map_bgn] = ACTIONS(521), + [sym__r_flw_map_end] = ACTIONS(603), + [sym__br_flw_map_end] = ACTIONS(603), + [sym__b_flw_map_end] = ACTIONS(603), + [sym__r_flw_sep_bgn] = ACTIONS(603), + [sym__br_flw_sep_bgn] = ACTIONS(603), + [sym__r_dqt_str_bgn] = ACTIONS(593), + [sym__br_dqt_str_bgn] = ACTIONS(525), + [sym__r_sqt_str_bgn] = ACTIONS(595), + [sym__br_sqt_str_bgn] = ACTIONS(529), + [sym__r_sgl_pln_nul_flw] = ACTIONS(531), + [sym__br_sgl_pln_nul_flw] = ACTIONS(533), + [sym__r_sgl_pln_bol_flw] = ACTIONS(531), + [sym__br_sgl_pln_bol_flw] = ACTIONS(533), + [sym__r_sgl_pln_int_flw] = ACTIONS(531), + [sym__br_sgl_pln_int_flw] = ACTIONS(533), + [sym__r_sgl_pln_flt_flw] = ACTIONS(531), + [sym__br_sgl_pln_flt_flw] = ACTIONS(533), + [sym__r_sgl_pln_tms_flw] = ACTIONS(531), + [sym__br_sgl_pln_tms_flw] = ACTIONS(533), + [sym__r_sgl_pln_str_flw] = ACTIONS(531), + [sym__br_sgl_pln_str_flw] = ACTIONS(533), + [sym__r_mtl_pln_str_flw] = ACTIONS(535), + [sym__br_mtl_pln_str_flw] = ACTIONS(537), + [sym__r_tag] = ACTIONS(597), + [sym__br_tag] = ACTIONS(541), + [sym__r_acr_bgn] = ACTIONS(543), + [sym__br_acr_bgn] = ACTIONS(545), + [sym__r_als_bgn] = ACTIONS(547), + [sym__br_als_bgn] = ACTIONS(549), + [sym_comment] = ACTIONS(3), + }, + [STATE(94)] = { + [sym__r_prp_val] = STATE(936), + [sym__br_prp_val] = STATE(936), + [sym__r_prp] = STATE(119), + [sym__br_prp] = STATE(120), + [sym__r_flw_seq_val] = STATE(936), + [sym__br_flw_seq_val] = STATE(936), + [sym__r_flw_seq] = STATE(865), + [sym__br_flw_seq] = STATE(866), + [sym__r_flw_map_val] = STATE(936), + [sym__br_flw_map_val] = STATE(936), + [sym__r_flw_map] = STATE(867), + [sym__br_flw_map] = STATE(868), + [sym__flw_ann_par_tal] = STATE(936), + [sym__r_dqt_str_val] = STATE(936), + [sym__br_dqt_str_val] = STATE(936), + [sym__r_dqt_str] = STATE(869), + [sym__br_dqt_str] = STATE(870), + [sym__r_sqt_str_val] = STATE(936), + [sym__br_sqt_str_val] = STATE(936), + [sym__r_sqt_str] = STATE(871), + [sym__br_sqt_str] = STATE(872), + [sym__r_pln_flw_val] = STATE(936), + [sym__br_pln_flw_val] = STATE(936), + [sym__r_sgl_pln_flw] = STATE(803), + [sym__br_sgl_pln_flw] = STATE(802), + [sym__r_mtl_pln_flw] = STATE(803), + [sym__br_mtl_pln_flw] = STATE(802), + [sym__r_als_val] = STATE(936), + [sym__br_als_val] = STATE(936), + [sym__r_als] = STATE(913), + [sym__br_als] = STATE(914), + [sym__r_acr] = STATE(213), + [sym__br_acr] = STATE(218), + [sym__r_flw_seq_bgn] = ACTIONS(589), + [sym__br_flw_seq_bgn] = ACTIONS(517), + [sym__r_flw_map_bgn] = ACTIONS(591), + [sym__br_flw_map_bgn] = ACTIONS(521), + [sym__r_flw_map_end] = ACTIONS(613), + [sym__br_flw_map_end] = ACTIONS(613), + [sym__b_flw_map_end] = ACTIONS(613), + [sym__r_flw_sep_bgn] = ACTIONS(613), + [sym__br_flw_sep_bgn] = ACTIONS(613), + [sym__r_dqt_str_bgn] = ACTIONS(593), + [sym__br_dqt_str_bgn] = ACTIONS(525), + [sym__r_sqt_str_bgn] = ACTIONS(595), + [sym__br_sqt_str_bgn] = ACTIONS(529), + [sym__r_sgl_pln_nul_flw] = ACTIONS(531), + [sym__br_sgl_pln_nul_flw] = ACTIONS(533), + [sym__r_sgl_pln_bol_flw] = ACTIONS(531), + [sym__br_sgl_pln_bol_flw] = ACTIONS(533), + [sym__r_sgl_pln_int_flw] = ACTIONS(531), + [sym__br_sgl_pln_int_flw] = ACTIONS(533), + [sym__r_sgl_pln_flt_flw] = ACTIONS(531), + [sym__br_sgl_pln_flt_flw] = ACTIONS(533), + [sym__r_sgl_pln_tms_flw] = ACTIONS(531), + [sym__br_sgl_pln_tms_flw] = ACTIONS(533), + [sym__r_sgl_pln_str_flw] = ACTIONS(531), + [sym__br_sgl_pln_str_flw] = ACTIONS(533), + [sym__r_mtl_pln_str_flw] = ACTIONS(535), + [sym__br_mtl_pln_str_flw] = ACTIONS(537), + [sym__r_tag] = ACTIONS(597), + [sym__br_tag] = ACTIONS(541), + [sym__r_acr_bgn] = ACTIONS(543), + [sym__br_acr_bgn] = ACTIONS(545), + [sym__r_als_bgn] = ACTIONS(547), + [sym__br_als_bgn] = ACTIONS(549), + [sym_comment] = ACTIONS(3), + }, + [STATE(95)] = { + [sym__r_prp_val] = STATE(920), + [sym__br_prp_val] = STATE(920), + [sym__r_prp] = STATE(121), + [sym__br_prp] = STATE(117), + [sym__r_flw_seq_val] = STATE(920), + [sym__br_flw_seq_val] = STATE(920), + [sym__r_flw_seq] = STATE(817), + [sym__br_flw_seq] = STATE(818), + [sym__r_flw_map_val] = STATE(920), + [sym__br_flw_map_val] = STATE(920), + [sym__r_flw_map] = STATE(819), + [sym__br_flw_map] = STATE(820), + [sym__flw_ann_par_tal] = STATE(920), + [sym__r_dqt_str_val] = STATE(920), + [sym__br_dqt_str_val] = STATE(920), + [sym__r_dqt_str] = STATE(821), + [sym__br_dqt_str] = STATE(822), + [sym__r_sqt_str_val] = STATE(920), + [sym__br_sqt_str_val] = STATE(920), + [sym__r_sqt_str] = STATE(823), + [sym__br_sqt_str] = STATE(824), + [sym__r_pln_flw_val] = STATE(920), + [sym__br_pln_flw_val] = STATE(920), + [sym__r_sgl_pln_flw] = STATE(792), + [sym__br_sgl_pln_flw] = STATE(786), + [sym__r_mtl_pln_flw] = STATE(792), + [sym__br_mtl_pln_flw] = STATE(786), + [sym__r_als_val] = STATE(920), + [sym__br_als_val] = STATE(920), + [sym__r_als] = STATE(873), + [sym__br_als] = STATE(874), + [sym__r_acr] = STATE(214), + [sym__br_acr] = STATE(224), + [sym__r_flw_seq_bgn] = ACTIONS(601), + [sym__br_flw_seq_bgn] = ACTIONS(452), + [sym__r_flw_seq_end] = ACTIONS(613), + [sym__br_flw_seq_end] = ACTIONS(613), + [sym__b_flw_seq_end] = ACTIONS(613), + [sym__r_flw_map_bgn] = ACTIONS(605), + [sym__br_flw_map_bgn] = ACTIONS(461), + [sym__r_flw_sep_bgn] = ACTIONS(613), + [sym__br_flw_sep_bgn] = ACTIONS(613), + [sym__r_dqt_str_bgn] = ACTIONS(607), + [sym__br_dqt_str_bgn] = ACTIONS(465), + [sym__r_sqt_str_bgn] = ACTIONS(609), + [sym__br_sqt_str_bgn] = ACTIONS(469), + [sym__r_sgl_pln_nul_flw] = ACTIONS(471), + [sym__br_sgl_pln_nul_flw] = ACTIONS(473), + [sym__r_sgl_pln_bol_flw] = ACTIONS(471), + [sym__br_sgl_pln_bol_flw] = ACTIONS(473), + [sym__r_sgl_pln_int_flw] = ACTIONS(471), + [sym__br_sgl_pln_int_flw] = ACTIONS(473), + [sym__r_sgl_pln_flt_flw] = ACTIONS(471), + [sym__br_sgl_pln_flt_flw] = ACTIONS(473), + [sym__r_sgl_pln_tms_flw] = ACTIONS(471), + [sym__br_sgl_pln_tms_flw] = ACTIONS(473), + [sym__r_sgl_pln_str_flw] = ACTIONS(471), + [sym__br_sgl_pln_str_flw] = ACTIONS(473), + [sym__r_mtl_pln_str_flw] = ACTIONS(475), + [sym__br_mtl_pln_str_flw] = ACTIONS(477), + [sym__r_tag] = ACTIONS(611), + [sym__br_tag] = ACTIONS(481), + [sym__r_acr_bgn] = ACTIONS(483), + [sym__br_acr_bgn] = ACTIONS(485), + [sym__r_als_bgn] = ACTIONS(487), + [sym__br_als_bgn] = ACTIONS(489), + [sym_comment] = ACTIONS(3), + }, +}; + +static const uint16_t ts_small_parse_table[] = { + [0] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(617), 1, + sym__r_blk_imp_bgn, + ACTIONS(622), 1, + sym__r_acr_bgn, + ACTIONS(624), 1, + sym__br_acr_bgn, + STATE(103), 1, + sym__r_acr, + STATE(108), 1, + sym__br_acr, + ACTIONS(619), 10, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + ACTIONS(615), 38, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__b_blk_key_bgn, + sym__br_blk_val_bgn, + sym__b_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__br_flw_seq_bgn, + sym__b_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__b_flw_map_bgn, + sym__br_dqt_str_bgn, + sym__b_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__b_sqt_str_bgn, + sym__br_sgl_pln_nul_blk, + sym__b_sgl_pln_nul_blk, + sym__br_sgl_pln_bol_blk, + sym__b_sgl_pln_bol_blk, + sym__br_sgl_pln_int_blk, + sym__b_sgl_pln_int_blk, + sym__br_sgl_pln_flt_blk, + sym__b_sgl_pln_flt_blk, + sym__br_sgl_pln_tms_blk, + sym__b_sgl_pln_tms_blk, + sym__br_sgl_pln_str_blk, + sym__b_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__b_tag, + sym__b_acr_bgn, + sym__br_als_bgn, + sym__b_als_bgn, + sym__bl, + [71] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(622), 1, + sym__r_acr_bgn, + ACTIONS(629), 1, + sym__r_blk_imp_bgn, + ACTIONS(634), 1, + sym__br_acr_bgn, + STATE(104), 1, + sym__r_acr, + STATE(109), 1, + sym__br_acr, + ACTIONS(631), 10, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + ACTIONS(627), 38, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__b_blk_key_bgn, + sym__br_blk_val_bgn, + sym__b_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__br_flw_seq_bgn, + sym__b_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__b_flw_map_bgn, + sym__br_dqt_str_bgn, + sym__b_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__b_sqt_str_bgn, + sym__br_sgl_pln_nul_blk, + sym__b_sgl_pln_nul_blk, + sym__br_sgl_pln_bol_blk, + sym__b_sgl_pln_bol_blk, + sym__br_sgl_pln_int_blk, + sym__b_sgl_pln_int_blk, + sym__br_sgl_pln_flt_blk, + sym__b_sgl_pln_flt_blk, + sym__br_sgl_pln_tms_blk, + sym__b_sgl_pln_tms_blk, + sym__br_sgl_pln_str_blk, + sym__b_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__b_tag, + sym__b_acr_bgn, + sym__br_als_bgn, + sym__b_als_bgn, + sym__bl, + [142] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(624), 1, + sym__br_acr_bgn, + ACTIONS(637), 1, + sym__r_acr_bgn, + STATE(108), 2, + sym__r_acr, + sym__br_acr, + ACTIONS(615), 48, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__b_blk_key_bgn, + sym__br_blk_val_bgn, + sym__b_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__b_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__b_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__b_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__b_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__b_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__b_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__b_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__b_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__b_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__b_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__b_tag, + sym__b_acr_bgn, + sym__br_als_bgn, + sym__b_als_bgn, + sym__bl, + [206] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(629), 1, + sym__r_blk_imp_bgn, + ACTIONS(639), 1, + sym__r_tag, + ACTIONS(641), 1, + sym__br_tag, + ACTIONS(631), 10, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + ACTIONS(627), 38, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__b_blk_key_bgn, + sym__br_blk_val_bgn, + sym__b_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__br_flw_seq_bgn, + sym__b_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__b_flw_map_bgn, + sym__br_dqt_str_bgn, + sym__b_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__b_sqt_str_bgn, + sym__br_sgl_pln_nul_blk, + sym__b_sgl_pln_nul_blk, + sym__br_sgl_pln_bol_blk, + sym__b_sgl_pln_bol_blk, + sym__br_sgl_pln_int_blk, + sym__b_sgl_pln_int_blk, + sym__br_sgl_pln_flt_blk, + sym__b_sgl_pln_flt_blk, + sym__br_sgl_pln_tms_blk, + sym__b_sgl_pln_tms_blk, + sym__br_sgl_pln_str_blk, + sym__b_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__b_tag, + sym__br_acr_bgn, + sym__b_acr_bgn, + sym__br_als_bgn, + sym__b_als_bgn, + sym__bl, + [271] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(617), 1, + sym__r_blk_imp_bgn, + ACTIONS(644), 1, + sym__r_tag, + ACTIONS(646), 1, + sym__br_tag, + ACTIONS(619), 10, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + ACTIONS(615), 38, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__b_blk_key_bgn, + sym__br_blk_val_bgn, + sym__b_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__br_flw_seq_bgn, + sym__b_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__b_flw_map_bgn, + sym__br_dqt_str_bgn, + sym__b_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__b_sqt_str_bgn, + sym__br_sgl_pln_nul_blk, + sym__b_sgl_pln_nul_blk, + sym__br_sgl_pln_bol_blk, + sym__b_sgl_pln_bol_blk, + sym__br_sgl_pln_int_blk, + sym__b_sgl_pln_int_blk, + sym__br_sgl_pln_flt_blk, + sym__b_sgl_pln_flt_blk, + sym__br_sgl_pln_tms_blk, + sym__b_sgl_pln_tms_blk, + sym__br_sgl_pln_str_blk, + sym__b_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__b_tag, + sym__br_acr_bgn, + sym__b_acr_bgn, + sym__br_als_bgn, + sym__b_als_bgn, + sym__bl, + [336] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 51, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__b_blk_key_bgn, + sym__br_blk_val_bgn, + sym__b_blk_val_bgn, + sym__r_blk_imp_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__b_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__b_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__b_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__b_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__b_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__b_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__b_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__b_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__b_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__b_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__r_tag, + sym__br_tag, + sym__b_tag, + sym__br_acr_bgn, + sym__b_acr_bgn, + sym__br_als_bgn, + sym__b_als_bgn, + sym__bl, + [393] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(651), 51, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__b_blk_key_bgn, + sym__br_blk_val_bgn, + sym__b_blk_val_bgn, + sym__r_blk_imp_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__b_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__b_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__b_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__b_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__b_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__b_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__b_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__b_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__b_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__b_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__r_tag, + sym__br_tag, + sym__b_tag, + sym__br_acr_bgn, + sym__b_acr_bgn, + sym__br_als_bgn, + sym__b_als_bgn, + sym__bl, + [450] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(655), 1, + sym__r_blk_imp_bgn, + ACTIONS(657), 10, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + ACTIONS(653), 39, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__b_blk_key_bgn, + sym__br_blk_val_bgn, + sym__b_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__br_flw_seq_bgn, + sym__b_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__b_flw_map_bgn, + sym__br_dqt_str_bgn, + sym__b_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__b_sqt_str_bgn, + sym__br_sgl_pln_nul_blk, + sym__b_sgl_pln_nul_blk, + sym__br_sgl_pln_bol_blk, + sym__b_sgl_pln_bol_blk, + sym__br_sgl_pln_int_blk, + sym__b_sgl_pln_int_blk, + sym__br_sgl_pln_flt_blk, + sym__b_sgl_pln_flt_blk, + sym__br_sgl_pln_tms_blk, + sym__b_sgl_pln_tms_blk, + sym__br_sgl_pln_str_blk, + sym__b_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__b_tag, + sym__br_acr_bgn, + sym__b_acr_bgn, + sym__br_als_bgn, + sym__b_als_bgn, + sym__bl, + [510] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(662), 1, + sym__r_blk_imp_bgn, + ACTIONS(664), 10, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + ACTIONS(660), 39, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__b_blk_key_bgn, + sym__br_blk_val_bgn, + sym__b_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__br_flw_seq_bgn, + sym__b_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__b_flw_map_bgn, + sym__br_dqt_str_bgn, + sym__b_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__b_sqt_str_bgn, + sym__br_sgl_pln_nul_blk, + sym__b_sgl_pln_nul_blk, + sym__br_sgl_pln_bol_blk, + sym__b_sgl_pln_bol_blk, + sym__br_sgl_pln_int_blk, + sym__b_sgl_pln_int_blk, + sym__br_sgl_pln_flt_blk, + sym__b_sgl_pln_flt_blk, + sym__br_sgl_pln_tms_blk, + sym__b_sgl_pln_tms_blk, + sym__br_sgl_pln_str_blk, + sym__b_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__b_tag, + sym__br_acr_bgn, + sym__b_acr_bgn, + sym__br_als_bgn, + sym__b_als_bgn, + sym__bl, + [570] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(646), 1, + sym__br_tag, + ACTIONS(667), 1, + sym__r_tag, + ACTIONS(615), 48, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__b_blk_key_bgn, + sym__br_blk_val_bgn, + sym__b_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__b_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__b_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__b_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__b_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__b_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__b_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__b_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__b_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__b_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__b_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__b_tag, + sym__br_acr_bgn, + sym__b_acr_bgn, + sym__br_als_bgn, + sym__b_als_bgn, + sym__bl, + [630] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 50, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__b_blk_key_bgn, + sym__br_blk_val_bgn, + sym__b_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__b_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__b_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__b_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__b_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__b_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__b_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__b_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__b_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__b_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__b_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__r_tag, + sym__br_tag, + sym__b_tag, + sym__br_acr_bgn, + sym__b_acr_bgn, + sym__br_als_bgn, + sym__b_als_bgn, + sym__bl, + [686] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 50, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__b_blk_key_bgn, + sym__br_blk_val_bgn, + sym__b_blk_val_bgn, + sym__r_blk_imp_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__b_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__b_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__b_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__b_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__b_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__b_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__b_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__b_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__b_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__b_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__b_tag, + sym__br_acr_bgn, + sym__b_acr_bgn, + sym__br_als_bgn, + sym__b_als_bgn, + sym__bl, + [742] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(653), 49, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__b_blk_key_bgn, + sym__br_blk_val_bgn, + sym__b_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__b_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__b_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__b_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__b_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__b_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__b_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__b_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__b_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__b_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__b_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__b_tag, + sym__br_acr_bgn, + sym__b_acr_bgn, + sym__br_als_bgn, + sym__b_als_bgn, + sym__bl, + [797] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(660), 49, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__b_blk_key_bgn, + sym__br_blk_val_bgn, + sym__b_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__b_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__b_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__b_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__b_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__b_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__b_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__b_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__b_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__b_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__b_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__b_tag, + sym__br_acr_bgn, + sym__b_acr_bgn, + sym__br_als_bgn, + sym__b_als_bgn, + sym__bl, + [852] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(651), 49, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__b_blk_key_bgn, + sym__br_blk_val_bgn, + sym__b_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__b_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__b_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__b_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__b_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__b_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__b_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__b_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__b_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__b_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__b_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__b_tag, + sym__br_acr_bgn, + sym__b_acr_bgn, + sym__br_als_bgn, + sym__b_als_bgn, + sym__bl, + [907] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 49, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__b_blk_key_bgn, + sym__br_blk_val_bgn, + sym__b_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__b_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__b_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__b_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__b_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__b_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__b_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__b_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__b_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__b_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__b_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__b_tag, + sym__br_acr_bgn, + sym__b_acr_bgn, + sym__br_als_bgn, + sym__b_als_bgn, + sym__bl, + [962] = 19, + ACTIONS(3), 1, + sym_comment, + ACTIONS(207), 1, + sym__br_flw_seq_bgn, + ACTIONS(211), 1, + sym__br_flw_map_bgn, + ACTIONS(227), 1, + sym__br_dqt_str_bgn, + ACTIONS(231), 1, + sym__br_sqt_str_bgn, + ACTIONS(237), 1, + sym__r_mtl_pln_str_flw, + ACTIONS(239), 1, + sym__br_mtl_pln_str_flw, + ACTIONS(426), 1, + sym__r_flw_seq_bgn, + ACTIONS(428), 1, + sym__r_flw_map_bgn, + ACTIONS(436), 1, + sym__r_dqt_str_bgn, + ACTIONS(438), 1, + sym__r_sqt_str_bgn, + STATE(598), 2, + sym__r_flw_seq, + sym__br_flw_seq, + STATE(599), 2, + sym__r_flw_map, + sym__br_flw_map, + STATE(600), 2, + sym__r_dqt_str, + sym__br_dqt_str, + STATE(601), 2, + sym__r_sqt_str, + sym__br_sqt_str, + STATE(639), 4, + sym__r_sgl_pln_flw, + sym__br_sgl_pln_flw, + sym__r_mtl_pln_flw, + sym__br_mtl_pln_flw, + ACTIONS(233), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + ACTIONS(235), 6, + sym__br_sgl_pln_nul_flw, + sym__br_sgl_pln_bol_flw, + sym__br_sgl_pln_int_flw, + sym__br_sgl_pln_flt_flw, + sym__br_sgl_pln_tms_flw, + sym__br_sgl_pln_str_flw, + ACTIONS(369), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [1043] = 19, + ACTIONS(3), 1, + sym_comment, + ACTIONS(207), 1, + sym__br_flw_seq_bgn, + ACTIONS(211), 1, + sym__br_flw_map_bgn, + ACTIONS(227), 1, + sym__br_dqt_str_bgn, + ACTIONS(231), 1, + sym__br_sqt_str_bgn, + ACTIONS(237), 1, + sym__r_mtl_pln_str_flw, + ACTIONS(239), 1, + sym__br_mtl_pln_str_flw, + ACTIONS(426), 1, + sym__r_flw_seq_bgn, + ACTIONS(428), 1, + sym__r_flw_map_bgn, + ACTIONS(436), 1, + sym__r_dqt_str_bgn, + ACTIONS(438), 1, + sym__r_sqt_str_bgn, + STATE(594), 2, + sym__r_flw_seq, + sym__br_flw_seq, + STATE(595), 2, + sym__r_flw_map, + sym__br_flw_map, + STATE(596), 2, + sym__r_dqt_str, + sym__br_dqt_str, + STATE(597), 2, + sym__r_sqt_str, + sym__br_sqt_str, + STATE(637), 4, + sym__r_sgl_pln_flw, + sym__br_sgl_pln_flw, + sym__r_mtl_pln_flw, + sym__br_mtl_pln_flw, + ACTIONS(233), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + ACTIONS(235), 6, + sym__br_sgl_pln_nul_flw, + sym__br_sgl_pln_bol_flw, + sym__br_sgl_pln_int_flw, + sym__br_sgl_pln_flt_flw, + sym__br_sgl_pln_tms_flw, + sym__br_sgl_pln_str_flw, + ACTIONS(377), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [1124] = 19, + ACTIONS(3), 1, + sym_comment, + ACTIONS(289), 1, + sym__br_flw_seq_bgn, + ACTIONS(297), 1, + sym__br_flw_map_bgn, + ACTIONS(309), 1, + sym__br_dqt_str_bgn, + ACTIONS(313), 1, + sym__br_sqt_str_bgn, + ACTIONS(319), 1, + sym__r_mtl_pln_str_flw, + ACTIONS(321), 1, + sym__br_mtl_pln_str_flw, + ACTIONS(491), 1, + sym__r_flw_seq_bgn, + ACTIONS(493), 1, + sym__r_flw_map_bgn, + ACTIONS(499), 1, + sym__r_dqt_str_bgn, + ACTIONS(501), 1, + sym__r_sqt_str_bgn, + STATE(728), 2, + sym__r_flw_seq, + sym__br_flw_seq, + STATE(729), 2, + sym__r_flw_map, + sym__br_flw_map, + STATE(730), 2, + sym__r_dqt_str, + sym__br_dqt_str, + STATE(731), 2, + sym__r_sqt_str, + sym__br_sqt_str, + STATE(701), 4, + sym__r_sgl_pln_flw, + sym__br_sgl_pln_flw, + sym__r_mtl_pln_flw, + sym__br_mtl_pln_flw, + ACTIONS(315), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + ACTIONS(317), 6, + sym__br_sgl_pln_nul_flw, + sym__br_sgl_pln_bol_flw, + sym__br_sgl_pln_int_flw, + sym__br_sgl_pln_flt_flw, + sym__br_sgl_pln_tms_flw, + sym__br_sgl_pln_str_flw, + ACTIONS(369), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + [1204] = 19, + ACTIONS(3), 1, + sym_comment, + ACTIONS(289), 1, + sym__br_flw_seq_bgn, + ACTIONS(297), 1, + sym__br_flw_map_bgn, + ACTIONS(309), 1, + sym__br_dqt_str_bgn, + ACTIONS(313), 1, + sym__br_sqt_str_bgn, + ACTIONS(319), 1, + sym__r_mtl_pln_str_flw, + ACTIONS(321), 1, + sym__br_mtl_pln_str_flw, + ACTIONS(491), 1, + sym__r_flw_seq_bgn, + ACTIONS(493), 1, + sym__r_flw_map_bgn, + ACTIONS(499), 1, + sym__r_dqt_str_bgn, + ACTIONS(501), 1, + sym__r_sqt_str_bgn, + STATE(724), 2, + sym__r_flw_seq, + sym__br_flw_seq, + STATE(725), 2, + sym__r_flw_map, + sym__br_flw_map, + STATE(726), 2, + sym__r_dqt_str, + sym__br_dqt_str, + STATE(727), 2, + sym__r_sqt_str, + sym__br_sqt_str, + STATE(700), 4, + sym__r_sgl_pln_flw, + sym__br_sgl_pln_flw, + sym__r_mtl_pln_flw, + sym__br_mtl_pln_flw, + ACTIONS(315), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + ACTIONS(317), 6, + sym__br_sgl_pln_nul_flw, + sym__br_sgl_pln_bol_flw, + sym__br_sgl_pln_int_flw, + sym__br_sgl_pln_flt_flw, + sym__br_sgl_pln_tms_flw, + sym__br_sgl_pln_str_flw, + ACTIONS(377), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + [1284] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(629), 1, + sym__r_blk_imp_bgn, + ACTIONS(669), 1, + sym__r_acr_bgn, + ACTIONS(671), 1, + sym__br_acr_bgn, + STATE(166), 1, + sym__r_acr, + STATE(169), 1, + sym__br_acr, + ACTIONS(631), 10, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + ACTIONS(627), 24, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + sym__br_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_blk, + sym__br_sgl_pln_bol_blk, + sym__br_sgl_pln_int_blk, + sym__br_sgl_pln_flt_blk, + sym__br_sgl_pln_tms_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__br_als_bgn, + [1341] = 19, + ACTIONS(3), 1, + sym_comment, + ACTIONS(452), 1, + sym__br_flw_seq_bgn, + ACTIONS(461), 1, + sym__br_flw_map_bgn, + ACTIONS(465), 1, + sym__br_dqt_str_bgn, + ACTIONS(469), 1, + sym__br_sqt_str_bgn, + ACTIONS(475), 1, + sym__r_mtl_pln_str_flw, + ACTIONS(477), 1, + sym__br_mtl_pln_str_flw, + ACTIONS(601), 1, + sym__r_flw_seq_bgn, + ACTIONS(605), 1, + sym__r_flw_map_bgn, + ACTIONS(607), 1, + sym__r_dqt_str_bgn, + ACTIONS(609), 1, + sym__r_sqt_str_bgn, + STATE(846), 2, + sym__r_flw_seq, + sym__br_flw_seq, + STATE(847), 2, + sym__r_flw_map, + sym__br_flw_map, + STATE(848), 2, + sym__r_dqt_str, + sym__br_dqt_str, + STATE(849), 2, + sym__r_sqt_str, + sym__br_sqt_str, + STATE(942), 4, + sym__r_sgl_pln_flw, + sym__br_sgl_pln_flw, + sym__r_mtl_pln_flw, + sym__br_mtl_pln_flw, + ACTIONS(369), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + ACTIONS(471), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + ACTIONS(473), 6, + sym__br_sgl_pln_nul_flw, + sym__br_sgl_pln_bol_flw, + sym__br_sgl_pln_int_flw, + sym__br_sgl_pln_flt_flw, + sym__br_sgl_pln_tms_flw, + sym__br_sgl_pln_str_flw, + [1420] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(617), 1, + sym__r_blk_imp_bgn, + ACTIONS(669), 1, + sym__r_acr_bgn, + ACTIONS(674), 1, + sym__br_acr_bgn, + STATE(165), 1, + sym__r_acr, + STATE(176), 1, + sym__br_acr, + ACTIONS(619), 10, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + ACTIONS(615), 24, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + sym__br_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_blk, + sym__br_sgl_pln_bol_blk, + sym__br_sgl_pln_int_blk, + sym__br_sgl_pln_flt_blk, + sym__br_sgl_pln_tms_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__br_als_bgn, + [1477] = 19, + ACTIONS(3), 1, + sym_comment, + ACTIONS(517), 1, + sym__br_flw_seq_bgn, + ACTIONS(521), 1, + sym__br_flw_map_bgn, + ACTIONS(525), 1, + sym__br_dqt_str_bgn, + ACTIONS(529), 1, + sym__br_sqt_str_bgn, + ACTIONS(535), 1, + sym__r_mtl_pln_str_flw, + ACTIONS(537), 1, + sym__br_mtl_pln_str_flw, + ACTIONS(589), 1, + sym__r_flw_seq_bgn, + ACTIONS(591), 1, + sym__r_flw_map_bgn, + ACTIONS(593), 1, + sym__r_dqt_str_bgn, + ACTIONS(595), 1, + sym__r_sqt_str_bgn, + STATE(892), 2, + sym__r_flw_seq, + sym__br_flw_seq, + STATE(893), 2, + sym__r_flw_map, + sym__br_flw_map, + STATE(894), 2, + sym__r_dqt_str, + sym__br_dqt_str, + STATE(895), 2, + sym__r_sqt_str, + sym__br_sqt_str, + STATE(811), 4, + sym__r_sgl_pln_flw, + sym__br_sgl_pln_flw, + sym__r_mtl_pln_flw, + sym__br_mtl_pln_flw, + ACTIONS(377), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + ACTIONS(531), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + ACTIONS(533), 6, + sym__br_sgl_pln_nul_flw, + sym__br_sgl_pln_bol_flw, + sym__br_sgl_pln_int_flw, + sym__br_sgl_pln_flt_flw, + sym__br_sgl_pln_tms_flw, + sym__br_sgl_pln_str_flw, + [1556] = 19, + ACTIONS(3), 1, + sym_comment, + ACTIONS(517), 1, + sym__br_flw_seq_bgn, + ACTIONS(521), 1, + sym__br_flw_map_bgn, + ACTIONS(525), 1, + sym__br_dqt_str_bgn, + ACTIONS(529), 1, + sym__br_sqt_str_bgn, + ACTIONS(535), 1, + sym__r_mtl_pln_str_flw, + ACTIONS(537), 1, + sym__br_mtl_pln_str_flw, + ACTIONS(589), 1, + sym__r_flw_seq_bgn, + ACTIONS(591), 1, + sym__r_flw_map_bgn, + ACTIONS(593), 1, + sym__r_dqt_str_bgn, + ACTIONS(595), 1, + sym__r_sqt_str_bgn, + STATE(896), 2, + sym__r_flw_seq, + sym__br_flw_seq, + STATE(897), 2, + sym__r_flw_map, + sym__br_flw_map, + STATE(898), 2, + sym__r_dqt_str, + sym__br_dqt_str, + STATE(899), 2, + sym__r_sqt_str, + sym__br_sqt_str, + STATE(812), 4, + sym__r_sgl_pln_flw, + sym__br_sgl_pln_flw, + sym__r_mtl_pln_flw, + sym__br_mtl_pln_flw, + ACTIONS(369), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + ACTIONS(531), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + ACTIONS(533), 6, + sym__br_sgl_pln_nul_flw, + sym__br_sgl_pln_bol_flw, + sym__br_sgl_pln_int_flw, + sym__br_sgl_pln_flt_flw, + sym__br_sgl_pln_tms_flw, + sym__br_sgl_pln_str_flw, + [1635] = 19, + ACTIONS(3), 1, + sym_comment, + ACTIONS(452), 1, + sym__br_flw_seq_bgn, + ACTIONS(461), 1, + sym__br_flw_map_bgn, + ACTIONS(465), 1, + sym__br_dqt_str_bgn, + ACTIONS(469), 1, + sym__br_sqt_str_bgn, + ACTIONS(475), 1, + sym__r_mtl_pln_str_flw, + ACTIONS(477), 1, + sym__br_mtl_pln_str_flw, + ACTIONS(601), 1, + sym__r_flw_seq_bgn, + ACTIONS(605), 1, + sym__r_flw_map_bgn, + ACTIONS(607), 1, + sym__r_dqt_str_bgn, + ACTIONS(609), 1, + sym__r_sqt_str_bgn, + STATE(842), 2, + sym__r_flw_seq, + sym__br_flw_seq, + STATE(843), 2, + sym__r_flw_map, + sym__br_flw_map, + STATE(844), 2, + sym__r_dqt_str, + sym__br_dqt_str, + STATE(845), 2, + sym__r_sqt_str, + sym__br_sqt_str, + STATE(930), 4, + sym__r_sgl_pln_flw, + sym__br_sgl_pln_flw, + sym__r_mtl_pln_flw, + sym__br_mtl_pln_flw, + ACTIONS(377), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + ACTIONS(471), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + ACTIONS(473), 6, + sym__br_sgl_pln_nul_flw, + sym__br_sgl_pln_bol_flw, + sym__br_sgl_pln_int_flw, + sym__br_sgl_pln_flt_flw, + sym__br_sgl_pln_tms_flw, + sym__br_sgl_pln_str_flw, + [1714] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(617), 1, + sym__r_blk_imp_bgn, + ACTIONS(677), 1, + sym__r_acr_bgn, + ACTIONS(679), 1, + sym__br_acr_bgn, + STATE(168), 1, + sym__r_acr, + STATE(178), 1, + sym__br_acr, + ACTIONS(619), 10, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + ACTIONS(615), 23, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_blk, + sym__br_sgl_pln_bol_blk, + sym__br_sgl_pln_int_blk, + sym__br_sgl_pln_flt_blk, + sym__br_sgl_pln_tms_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__br_als_bgn, + sym__bl, + [1770] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(629), 1, + sym__r_blk_imp_bgn, + ACTIONS(677), 1, + sym__r_acr_bgn, + ACTIONS(682), 1, + sym__br_acr_bgn, + STATE(172), 1, + sym__r_acr, + STATE(179), 1, + sym__br_acr, + ACTIONS(631), 10, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + ACTIONS(627), 23, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_blk, + sym__br_sgl_pln_bol_blk, + sym__br_sgl_pln_int_blk, + sym__br_sgl_pln_flt_blk, + sym__br_sgl_pln_tms_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__br_als_bgn, + sym__bl, + [1826] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(674), 1, + sym__br_acr_bgn, + ACTIONS(685), 1, + sym__r_acr_bgn, + STATE(176), 2, + sym__r_acr, + sym__br_acr, + ACTIONS(615), 34, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + sym__br_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__br_als_bgn, + [1876] = 26, + ACTIONS(3), 1, + sym_comment, + ACTIONS(687), 1, + sym__b_blk_key_bgn, + ACTIONS(689), 1, + sym__b_blk_val_bgn, + ACTIONS(691), 1, + sym__b_flw_seq_bgn, + ACTIONS(693), 1, + sym__b_flw_map_bgn, + ACTIONS(695), 1, + sym__b_dqt_str_bgn, + ACTIONS(697), 1, + sym__b_sqt_str_bgn, + ACTIONS(701), 1, + sym__b_tag, + ACTIONS(703), 1, + sym__b_acr_bgn, + ACTIONS(705), 1, + sym__b_als_bgn, + ACTIONS(707), 1, + sym__bl, + STATE(279), 1, + sym__b_blk_key_itm, + STATE(322), 1, + sym__b_sgl_prp, + STATE(323), 1, + sym__b_blk_exp_itm, + STATE(325), 1, + sym__b_blk_val_itm, + STATE(326), 1, + sym__b_blk_imp_itm, + STATE(420), 1, + sym__b_acr, + STATE(1412), 1, + sym__b_als, + STATE(1464), 1, + sym__b_sgl_dqt_str, + STATE(1493), 1, + sym__b_sgl_flw_seq, + STATE(1502), 1, + sym__b_sgl_flw_map, + STATE(1520), 1, + sym__b_sgl_sqt_str, + STATE(1532), 1, + sym__b_sgl_pln_blk, + STATE(144), 2, + sym__b_blk_map_itm, + aux_sym__r_blk_map_repeat1, + ACTIONS(699), 6, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + STATE(1299), 7, + sym__b_sgl_prp_val, + sym__b_sgl_flw_seq_val, + sym__b_sgl_flw_map_val, + sym__b_sgl_dqt_str_val, + sym__b_sgl_sqt_str_val, + sym__b_sgl_pln_blk_val, + sym__b_als_val, + [1967] = 28, + ACTIONS(3), 1, + sym_comment, + ACTIONS(709), 1, + sym__r_flw_seq_bgn, + ACTIONS(711), 1, + sym__r_flw_map_bgn, + ACTIONS(713), 1, + sym__r_flw_map_end, + ACTIONS(715), 1, + sym__r_flw_key_bgn, + ACTIONS(717), 1, + sym__r_flw_njv_bgn, + ACTIONS(719), 1, + sym__r_dqt_str_bgn, + ACTIONS(721), 1, + sym__r_sqt_str_bgn, + ACTIONS(725), 1, + sym__r_tag, + ACTIONS(727), 1, + sym__r_acr_bgn, + ACTIONS(729), 1, + sym__r_als_bgn, + STATE(265), 1, + sym__r_sgl_prp, + STATE(398), 1, + sym__r_acr, + STATE(964), 1, + sym__r_sgl_flw_col_itm, + STATE(1100), 1, + sym__r_als, + STATE(1187), 1, + sym__r_sgl_pln_flw, + STATE(1209), 1, + sym__r_sgl_flw_seq, + STATE(1210), 1, + sym__r_sgl_flw_map, + STATE(1213), 1, + sym__r_sgl_dqt_str, + STATE(1214), 1, + sym__r_sgl_sqt_str, + STATE(1250), 1, + sym__r_sgl_flw_exp_par, + STATE(1251), 1, + sym__r_sgl_flw_imp_par, + STATE(1252), 1, + sym__r_sgl_flw_njl_ann_par, + STATE(1322), 1, + sym__sgl_flw_map_tal, + STATE(1449), 1, + sym__r_sgl_flw_col_dat, + STATE(1038), 3, + sym__r_sgl_prp_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + STATE(1045), 4, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + ACTIONS(723), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [2062] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 37, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + sym__br_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_imp_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__r_tag, + sym__br_tag, + sym__br_acr_bgn, + sym__br_als_bgn, + [2105] = 26, + ACTIONS(3), 1, + sym_comment, + ACTIONS(731), 1, + sym__b_blk_key_bgn, + ACTIONS(734), 1, + sym__b_blk_val_bgn, + ACTIONS(737), 1, + sym__b_flw_seq_bgn, + ACTIONS(740), 1, + sym__b_flw_map_bgn, + ACTIONS(743), 1, + sym__b_dqt_str_bgn, + ACTIONS(746), 1, + sym__b_sqt_str_bgn, + ACTIONS(752), 1, + sym__b_tag, + ACTIONS(755), 1, + sym__b_acr_bgn, + ACTIONS(758), 1, + sym__b_als_bgn, + ACTIONS(761), 1, + sym__bl, + STATE(279), 1, + sym__b_blk_key_itm, + STATE(322), 1, + sym__b_sgl_prp, + STATE(323), 1, + sym__b_blk_exp_itm, + STATE(325), 1, + sym__b_blk_val_itm, + STATE(326), 1, + sym__b_blk_imp_itm, + STATE(420), 1, + sym__b_acr, + STATE(1412), 1, + sym__b_als, + STATE(1464), 1, + sym__b_sgl_dqt_str, + STATE(1493), 1, + sym__b_sgl_flw_seq, + STATE(1502), 1, + sym__b_sgl_flw_map, + STATE(1520), 1, + sym__b_sgl_sqt_str, + STATE(1532), 1, + sym__b_sgl_pln_blk, + STATE(128), 2, + sym__b_blk_map_itm, + aux_sym__r_blk_map_repeat1, + ACTIONS(749), 6, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + STATE(1299), 7, + sym__b_sgl_prp_val, + sym__b_sgl_flw_seq_val, + sym__b_sgl_flw_map_val, + sym__b_sgl_dqt_str_val, + sym__b_sgl_sqt_str_val, + sym__b_sgl_pln_blk_val, + sym__b_als_val, + [2196] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(651), 37, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + sym__br_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_imp_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__r_tag, + sym__br_tag, + sym__br_acr_bgn, + sym__br_als_bgn, + [2239] = 26, + ACTIONS(3), 1, + sym_comment, + ACTIONS(687), 1, + sym__b_blk_key_bgn, + ACTIONS(689), 1, + sym__b_blk_val_bgn, + ACTIONS(691), 1, + sym__b_flw_seq_bgn, + ACTIONS(693), 1, + sym__b_flw_map_bgn, + ACTIONS(695), 1, + sym__b_dqt_str_bgn, + ACTIONS(697), 1, + sym__b_sqt_str_bgn, + ACTIONS(701), 1, + sym__b_tag, + ACTIONS(703), 1, + sym__b_acr_bgn, + ACTIONS(705), 1, + sym__b_als_bgn, + ACTIONS(763), 1, + sym__bl, + STATE(279), 1, + sym__b_blk_key_itm, + STATE(322), 1, + sym__b_sgl_prp, + STATE(323), 1, + sym__b_blk_exp_itm, + STATE(325), 1, + sym__b_blk_val_itm, + STATE(326), 1, + sym__b_blk_imp_itm, + STATE(420), 1, + sym__b_acr, + STATE(1412), 1, + sym__b_als, + STATE(1464), 1, + sym__b_sgl_dqt_str, + STATE(1493), 1, + sym__b_sgl_flw_seq, + STATE(1502), 1, + sym__b_sgl_flw_map, + STATE(1520), 1, + sym__b_sgl_sqt_str, + STATE(1532), 1, + sym__b_sgl_pln_blk, + STATE(145), 2, + sym__b_blk_map_itm, + aux_sym__r_blk_map_repeat1, + ACTIONS(699), 6, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + STATE(1299), 7, + sym__b_sgl_prp_val, + sym__b_sgl_flw_seq_val, + sym__b_sgl_flw_map_val, + sym__b_sgl_dqt_str_val, + sym__b_sgl_sqt_str_val, + sym__b_sgl_pln_blk_val, + sym__b_als_val, + [2330] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(617), 1, + sym__r_blk_imp_bgn, + ACTIONS(765), 1, + sym__r_tag, + ACTIONS(767), 1, + sym__br_tag, + ACTIONS(619), 10, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + ACTIONS(615), 24, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + sym__br_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_blk, + sym__br_sgl_pln_bol_blk, + sym__br_sgl_pln_int_blk, + sym__br_sgl_pln_flt_blk, + sym__br_sgl_pln_tms_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_acr_bgn, + sym__br_als_bgn, + [2381] = 28, + ACTIONS(3), 1, + sym_comment, + ACTIONS(770), 1, + sym__r_flw_seq_bgn, + ACTIONS(772), 1, + sym__r_flw_seq_end, + ACTIONS(774), 1, + sym__r_flw_map_bgn, + ACTIONS(776), 1, + sym__r_flw_key_bgn, + ACTIONS(778), 1, + sym__r_flw_njv_bgn, + ACTIONS(780), 1, + sym__r_dqt_str_bgn, + ACTIONS(782), 1, + sym__r_sqt_str_bgn, + ACTIONS(786), 1, + sym__r_tag, + ACTIONS(788), 1, + sym__r_acr_bgn, + ACTIONS(790), 1, + sym__r_als_bgn, + STATE(261), 1, + sym__r_sgl_prp, + STATE(395), 1, + sym__r_acr, + STATE(986), 1, + sym__r_sgl_flw_col_itm, + STATE(1097), 1, + sym__r_als, + STATE(1110), 1, + sym__r_sgl_flw_seq, + STATE(1113), 1, + sym__r_sgl_flw_map, + STATE(1114), 1, + sym__r_sgl_dqt_str, + STATE(1116), 1, + sym__r_sgl_sqt_str, + STATE(1132), 1, + sym__r_sgl_pln_flw, + STATE(1225), 1, + sym__r_sgl_flw_exp_par, + STATE(1240), 1, + sym__r_sgl_flw_imp_par, + STATE(1253), 1, + sym__r_sgl_flw_njl_ann_par, + STATE(1423), 1, + sym__sgl_flw_seq_tal, + STATE(1459), 1, + sym__r_sgl_flw_col_dat, + STATE(976), 3, + sym__r_sgl_prp_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + STATE(1025), 4, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + ACTIONS(784), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [2476] = 28, + ACTIONS(3), 1, + sym_comment, + ACTIONS(709), 1, + sym__r_flw_seq_bgn, + ACTIONS(711), 1, + sym__r_flw_map_bgn, + ACTIONS(715), 1, + sym__r_flw_key_bgn, + ACTIONS(717), 1, + sym__r_flw_njv_bgn, + ACTIONS(719), 1, + sym__r_dqt_str_bgn, + ACTIONS(721), 1, + sym__r_sqt_str_bgn, + ACTIONS(725), 1, + sym__r_tag, + ACTIONS(727), 1, + sym__r_acr_bgn, + ACTIONS(729), 1, + sym__r_als_bgn, + ACTIONS(792), 1, + sym__r_flw_map_end, + STATE(265), 1, + sym__r_sgl_prp, + STATE(398), 1, + sym__r_acr, + STATE(964), 1, + sym__r_sgl_flw_col_itm, + STATE(1100), 1, + sym__r_als, + STATE(1187), 1, + sym__r_sgl_pln_flw, + STATE(1209), 1, + sym__r_sgl_flw_seq, + STATE(1210), 1, + sym__r_sgl_flw_map, + STATE(1213), 1, + sym__r_sgl_dqt_str, + STATE(1214), 1, + sym__r_sgl_sqt_str, + STATE(1250), 1, + sym__r_sgl_flw_exp_par, + STATE(1251), 1, + sym__r_sgl_flw_imp_par, + STATE(1252), 1, + sym__r_sgl_flw_njl_ann_par, + STATE(1516), 1, + sym__r_sgl_flw_col_dat, + STATE(1517), 1, + sym__sgl_flw_map_tal, + STATE(1038), 3, + sym__r_sgl_prp_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + STATE(1045), 4, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + ACTIONS(723), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [2571] = 26, + ACTIONS(3), 1, + sym_comment, + ACTIONS(687), 1, + sym__b_blk_key_bgn, + ACTIONS(689), 1, + sym__b_blk_val_bgn, + ACTIONS(691), 1, + sym__b_flw_seq_bgn, + ACTIONS(693), 1, + sym__b_flw_map_bgn, + ACTIONS(695), 1, + sym__b_dqt_str_bgn, + ACTIONS(697), 1, + sym__b_sqt_str_bgn, + ACTIONS(701), 1, + sym__b_tag, + ACTIONS(703), 1, + sym__b_acr_bgn, + ACTIONS(705), 1, + sym__b_als_bgn, + ACTIONS(794), 1, + sym__bl, + STATE(279), 1, + sym__b_blk_key_itm, + STATE(322), 1, + sym__b_sgl_prp, + STATE(323), 1, + sym__b_blk_exp_itm, + STATE(325), 1, + sym__b_blk_val_itm, + STATE(326), 1, + sym__b_blk_imp_itm, + STATE(420), 1, + sym__b_acr, + STATE(1412), 1, + sym__b_als, + STATE(1464), 1, + sym__b_sgl_dqt_str, + STATE(1493), 1, + sym__b_sgl_flw_seq, + STATE(1502), 1, + sym__b_sgl_flw_map, + STATE(1520), 1, + sym__b_sgl_sqt_str, + STATE(1532), 1, + sym__b_sgl_pln_blk, + STATE(138), 2, + sym__b_blk_map_itm, + aux_sym__r_blk_map_repeat1, + ACTIONS(699), 6, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + STATE(1299), 7, + sym__b_sgl_prp_val, + sym__b_sgl_flw_seq_val, + sym__b_sgl_flw_map_val, + sym__b_sgl_dqt_str_val, + sym__b_sgl_sqt_str_val, + sym__b_sgl_pln_blk_val, + sym__b_als_val, + [2662] = 26, + ACTIONS(3), 1, + sym_comment, + ACTIONS(687), 1, + sym__b_blk_key_bgn, + ACTIONS(689), 1, + sym__b_blk_val_bgn, + ACTIONS(691), 1, + sym__b_flw_seq_bgn, + ACTIONS(693), 1, + sym__b_flw_map_bgn, + ACTIONS(695), 1, + sym__b_dqt_str_bgn, + ACTIONS(697), 1, + sym__b_sqt_str_bgn, + ACTIONS(701), 1, + sym__b_tag, + ACTIONS(703), 1, + sym__b_acr_bgn, + ACTIONS(705), 1, + sym__b_als_bgn, + ACTIONS(796), 1, + sym__bl, + STATE(279), 1, + sym__b_blk_key_itm, + STATE(322), 1, + sym__b_sgl_prp, + STATE(323), 1, + sym__b_blk_exp_itm, + STATE(325), 1, + sym__b_blk_val_itm, + STATE(326), 1, + sym__b_blk_imp_itm, + STATE(420), 1, + sym__b_acr, + STATE(1412), 1, + sym__b_als, + STATE(1464), 1, + sym__b_sgl_dqt_str, + STATE(1493), 1, + sym__b_sgl_flw_seq, + STATE(1502), 1, + sym__b_sgl_flw_map, + STATE(1520), 1, + sym__b_sgl_sqt_str, + STATE(1532), 1, + sym__b_sgl_pln_blk, + STATE(139), 2, + sym__b_blk_map_itm, + aux_sym__r_blk_map_repeat1, + ACTIONS(699), 6, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + STATE(1299), 7, + sym__b_sgl_prp_val, + sym__b_sgl_flw_seq_val, + sym__b_sgl_flw_map_val, + sym__b_sgl_dqt_str_val, + sym__b_sgl_sqt_str_val, + sym__b_sgl_pln_blk_val, + sym__b_als_val, + [2753] = 28, + ACTIONS(3), 1, + sym_comment, + ACTIONS(770), 1, + sym__r_flw_seq_bgn, + ACTIONS(774), 1, + sym__r_flw_map_bgn, + ACTIONS(776), 1, + sym__r_flw_key_bgn, + ACTIONS(778), 1, + sym__r_flw_njv_bgn, + ACTIONS(780), 1, + sym__r_dqt_str_bgn, + ACTIONS(782), 1, + sym__r_sqt_str_bgn, + ACTIONS(786), 1, + sym__r_tag, + ACTIONS(788), 1, + sym__r_acr_bgn, + ACTIONS(790), 1, + sym__r_als_bgn, + ACTIONS(798), 1, + sym__r_flw_seq_end, + STATE(261), 1, + sym__r_sgl_prp, + STATE(395), 1, + sym__r_acr, + STATE(986), 1, + sym__r_sgl_flw_col_itm, + STATE(1097), 1, + sym__r_als, + STATE(1110), 1, + sym__r_sgl_flw_seq, + STATE(1113), 1, + sym__r_sgl_flw_map, + STATE(1114), 1, + sym__r_sgl_dqt_str, + STATE(1116), 1, + sym__r_sgl_sqt_str, + STATE(1132), 1, + sym__r_sgl_pln_flw, + STATE(1139), 1, + sym__sgl_flw_seq_tal, + STATE(1225), 1, + sym__r_sgl_flw_exp_par, + STATE(1240), 1, + sym__r_sgl_flw_imp_par, + STATE(1253), 1, + sym__r_sgl_flw_njl_ann_par, + STATE(1468), 1, + sym__r_sgl_flw_col_dat, + STATE(976), 3, + sym__r_sgl_prp_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + STATE(1025), 4, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + ACTIONS(784), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [2848] = 28, + ACTIONS(3), 1, + sym_comment, + ACTIONS(709), 1, + sym__r_flw_seq_bgn, + ACTIONS(711), 1, + sym__r_flw_map_bgn, + ACTIONS(715), 1, + sym__r_flw_key_bgn, + ACTIONS(717), 1, + sym__r_flw_njv_bgn, + ACTIONS(719), 1, + sym__r_dqt_str_bgn, + ACTIONS(721), 1, + sym__r_sqt_str_bgn, + ACTIONS(725), 1, + sym__r_tag, + ACTIONS(727), 1, + sym__r_acr_bgn, + ACTIONS(729), 1, + sym__r_als_bgn, + ACTIONS(800), 1, + sym__r_flw_map_end, + STATE(265), 1, + sym__r_sgl_prp, + STATE(398), 1, + sym__r_acr, + STATE(964), 1, + sym__r_sgl_flw_col_itm, + STATE(1100), 1, + sym__r_als, + STATE(1145), 1, + sym__sgl_flw_map_tal, + STATE(1187), 1, + sym__r_sgl_pln_flw, + STATE(1209), 1, + sym__r_sgl_flw_seq, + STATE(1210), 1, + sym__r_sgl_flw_map, + STATE(1213), 1, + sym__r_sgl_dqt_str, + STATE(1214), 1, + sym__r_sgl_sqt_str, + STATE(1250), 1, + sym__r_sgl_flw_exp_par, + STATE(1251), 1, + sym__r_sgl_flw_imp_par, + STATE(1252), 1, + sym__r_sgl_flw_njl_ann_par, + STATE(1471), 1, + sym__r_sgl_flw_col_dat, + STATE(1038), 3, + sym__r_sgl_prp_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + STATE(1045), 4, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + ACTIONS(723), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [2943] = 26, + ACTIONS(3), 1, + sym_comment, + ACTIONS(687), 1, + sym__b_blk_key_bgn, + ACTIONS(689), 1, + sym__b_blk_val_bgn, + ACTIONS(691), 1, + sym__b_flw_seq_bgn, + ACTIONS(693), 1, + sym__b_flw_map_bgn, + ACTIONS(695), 1, + sym__b_dqt_str_bgn, + ACTIONS(697), 1, + sym__b_sqt_str_bgn, + ACTIONS(701), 1, + sym__b_tag, + ACTIONS(703), 1, + sym__b_acr_bgn, + ACTIONS(705), 1, + sym__b_als_bgn, + ACTIONS(802), 1, + sym__bl, + STATE(279), 1, + sym__b_blk_key_itm, + STATE(322), 1, + sym__b_sgl_prp, + STATE(323), 1, + sym__b_blk_exp_itm, + STATE(325), 1, + sym__b_blk_val_itm, + STATE(326), 1, + sym__b_blk_imp_itm, + STATE(420), 1, + sym__b_acr, + STATE(1412), 1, + sym__b_als, + STATE(1464), 1, + sym__b_sgl_dqt_str, + STATE(1493), 1, + sym__b_sgl_flw_seq, + STATE(1502), 1, + sym__b_sgl_flw_map, + STATE(1520), 1, + sym__b_sgl_sqt_str, + STATE(1532), 1, + sym__b_sgl_pln_blk, + STATE(128), 2, + sym__b_blk_map_itm, + aux_sym__r_blk_map_repeat1, + ACTIONS(699), 6, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + STATE(1299), 7, + sym__b_sgl_prp_val, + sym__b_sgl_flw_seq_val, + sym__b_sgl_flw_map_val, + sym__b_sgl_dqt_str_val, + sym__b_sgl_sqt_str_val, + sym__b_sgl_pln_blk_val, + sym__b_als_val, + [3034] = 26, + ACTIONS(3), 1, + sym_comment, + ACTIONS(687), 1, + sym__b_blk_key_bgn, + ACTIONS(689), 1, + sym__b_blk_val_bgn, + ACTIONS(691), 1, + sym__b_flw_seq_bgn, + ACTIONS(693), 1, + sym__b_flw_map_bgn, + ACTIONS(695), 1, + sym__b_dqt_str_bgn, + ACTIONS(697), 1, + sym__b_sqt_str_bgn, + ACTIONS(701), 1, + sym__b_tag, + ACTIONS(703), 1, + sym__b_acr_bgn, + ACTIONS(705), 1, + sym__b_als_bgn, + ACTIONS(804), 1, + sym__bl, + STATE(279), 1, + sym__b_blk_key_itm, + STATE(322), 1, + sym__b_sgl_prp, + STATE(323), 1, + sym__b_blk_exp_itm, + STATE(325), 1, + sym__b_blk_val_itm, + STATE(326), 1, + sym__b_blk_imp_itm, + STATE(420), 1, + sym__b_acr, + STATE(1412), 1, + sym__b_als, + STATE(1464), 1, + sym__b_sgl_dqt_str, + STATE(1493), 1, + sym__b_sgl_flw_seq, + STATE(1502), 1, + sym__b_sgl_flw_map, + STATE(1520), 1, + sym__b_sgl_sqt_str, + STATE(1532), 1, + sym__b_sgl_pln_blk, + STATE(128), 2, + sym__b_blk_map_itm, + aux_sym__r_blk_map_repeat1, + ACTIONS(699), 6, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + STATE(1299), 7, + sym__b_sgl_prp_val, + sym__b_sgl_flw_seq_val, + sym__b_sgl_flw_map_val, + sym__b_sgl_dqt_str_val, + sym__b_sgl_sqt_str_val, + sym__b_sgl_pln_blk_val, + sym__b_als_val, + [3125] = 28, + ACTIONS(3), 1, + sym_comment, + ACTIONS(770), 1, + sym__r_flw_seq_bgn, + ACTIONS(774), 1, + sym__r_flw_map_bgn, + ACTIONS(776), 1, + sym__r_flw_key_bgn, + ACTIONS(778), 1, + sym__r_flw_njv_bgn, + ACTIONS(780), 1, + sym__r_dqt_str_bgn, + ACTIONS(782), 1, + sym__r_sqt_str_bgn, + ACTIONS(786), 1, + sym__r_tag, + ACTIONS(788), 1, + sym__r_acr_bgn, + ACTIONS(790), 1, + sym__r_als_bgn, + ACTIONS(806), 1, + sym__r_flw_seq_end, + STATE(261), 1, + sym__r_sgl_prp, + STATE(395), 1, + sym__r_acr, + STATE(986), 1, + sym__r_sgl_flw_col_itm, + STATE(1097), 1, + sym__r_als, + STATE(1110), 1, + sym__r_sgl_flw_seq, + STATE(1113), 1, + sym__r_sgl_flw_map, + STATE(1114), 1, + sym__r_sgl_dqt_str, + STATE(1116), 1, + sym__r_sgl_sqt_str, + STATE(1132), 1, + sym__r_sgl_pln_flw, + STATE(1225), 1, + sym__r_sgl_flw_exp_par, + STATE(1240), 1, + sym__r_sgl_flw_imp_par, + STATE(1253), 1, + sym__r_sgl_flw_njl_ann_par, + STATE(1445), 1, + sym__sgl_flw_seq_tal, + STATE(1459), 1, + sym__r_sgl_flw_col_dat, + STATE(976), 3, + sym__r_sgl_prp_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + STATE(1025), 4, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + ACTIONS(784), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [3220] = 28, + ACTIONS(3), 1, + sym_comment, + ACTIONS(709), 1, + sym__r_flw_seq_bgn, + ACTIONS(711), 1, + sym__r_flw_map_bgn, + ACTIONS(715), 1, + sym__r_flw_key_bgn, + ACTIONS(717), 1, + sym__r_flw_njv_bgn, + ACTIONS(719), 1, + sym__r_dqt_str_bgn, + ACTIONS(721), 1, + sym__r_sqt_str_bgn, + ACTIONS(725), 1, + sym__r_tag, + ACTIONS(727), 1, + sym__r_acr_bgn, + ACTIONS(729), 1, + sym__r_als_bgn, + ACTIONS(808), 1, + sym__r_flw_map_end, + STATE(265), 1, + sym__r_sgl_prp, + STATE(398), 1, + sym__r_acr, + STATE(964), 1, + sym__r_sgl_flw_col_itm, + STATE(1100), 1, + sym__r_als, + STATE(1187), 1, + sym__r_sgl_pln_flw, + STATE(1209), 1, + sym__r_sgl_flw_seq, + STATE(1210), 1, + sym__r_sgl_flw_map, + STATE(1213), 1, + sym__r_sgl_dqt_str, + STATE(1214), 1, + sym__r_sgl_sqt_str, + STATE(1250), 1, + sym__r_sgl_flw_exp_par, + STATE(1251), 1, + sym__r_sgl_flw_imp_par, + STATE(1252), 1, + sym__r_sgl_flw_njl_ann_par, + STATE(1496), 1, + sym__sgl_flw_map_tal, + STATE(1516), 1, + sym__r_sgl_flw_col_dat, + STATE(1038), 3, + sym__r_sgl_prp_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + STATE(1045), 4, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + ACTIONS(723), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [3315] = 26, + ACTIONS(3), 1, + sym_comment, + ACTIONS(687), 1, + sym__b_blk_key_bgn, + ACTIONS(689), 1, + sym__b_blk_val_bgn, + ACTIONS(691), 1, + sym__b_flw_seq_bgn, + ACTIONS(693), 1, + sym__b_flw_map_bgn, + ACTIONS(695), 1, + sym__b_dqt_str_bgn, + ACTIONS(697), 1, + sym__b_sqt_str_bgn, + ACTIONS(701), 1, + sym__b_tag, + ACTIONS(703), 1, + sym__b_acr_bgn, + ACTIONS(705), 1, + sym__b_als_bgn, + ACTIONS(810), 1, + sym__bl, + STATE(279), 1, + sym__b_blk_key_itm, + STATE(322), 1, + sym__b_sgl_prp, + STATE(323), 1, + sym__b_blk_exp_itm, + STATE(325), 1, + sym__b_blk_val_itm, + STATE(326), 1, + sym__b_blk_imp_itm, + STATE(420), 1, + sym__b_acr, + STATE(1412), 1, + sym__b_als, + STATE(1464), 1, + sym__b_sgl_dqt_str, + STATE(1493), 1, + sym__b_sgl_flw_seq, + STATE(1502), 1, + sym__b_sgl_flw_map, + STATE(1520), 1, + sym__b_sgl_sqt_str, + STATE(1532), 1, + sym__b_sgl_pln_blk, + STATE(149), 2, + sym__b_blk_map_itm, + aux_sym__r_blk_map_repeat1, + ACTIONS(699), 6, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + STATE(1299), 7, + sym__b_sgl_prp_val, + sym__b_sgl_flw_seq_val, + sym__b_sgl_flw_map_val, + sym__b_sgl_dqt_str_val, + sym__b_sgl_sqt_str_val, + sym__b_sgl_pln_blk_val, + sym__b_als_val, + [3406] = 26, + ACTIONS(3), 1, + sym_comment, + ACTIONS(687), 1, + sym__b_blk_key_bgn, + ACTIONS(689), 1, + sym__b_blk_val_bgn, + ACTIONS(691), 1, + sym__b_flw_seq_bgn, + ACTIONS(693), 1, + sym__b_flw_map_bgn, + ACTIONS(695), 1, + sym__b_dqt_str_bgn, + ACTIONS(697), 1, + sym__b_sqt_str_bgn, + ACTIONS(701), 1, + sym__b_tag, + ACTIONS(703), 1, + sym__b_acr_bgn, + ACTIONS(705), 1, + sym__b_als_bgn, + ACTIONS(812), 1, + sym__bl, + STATE(279), 1, + sym__b_blk_key_itm, + STATE(322), 1, + sym__b_sgl_prp, + STATE(323), 1, + sym__b_blk_exp_itm, + STATE(325), 1, + sym__b_blk_val_itm, + STATE(326), 1, + sym__b_blk_imp_itm, + STATE(420), 1, + sym__b_acr, + STATE(1412), 1, + sym__b_als, + STATE(1464), 1, + sym__b_sgl_dqt_str, + STATE(1493), 1, + sym__b_sgl_flw_seq, + STATE(1502), 1, + sym__b_sgl_flw_map, + STATE(1520), 1, + sym__b_sgl_sqt_str, + STATE(1532), 1, + sym__b_sgl_pln_blk, + STATE(150), 2, + sym__b_blk_map_itm, + aux_sym__r_blk_map_repeat1, + ACTIONS(699), 6, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + STATE(1299), 7, + sym__b_sgl_prp_val, + sym__b_sgl_flw_seq_val, + sym__b_sgl_flw_map_val, + sym__b_sgl_dqt_str_val, + sym__b_sgl_sqt_str_val, + sym__b_sgl_pln_blk_val, + sym__b_als_val, + [3497] = 26, + ACTIONS(3), 1, + sym_comment, + ACTIONS(687), 1, + sym__b_blk_key_bgn, + ACTIONS(689), 1, + sym__b_blk_val_bgn, + ACTIONS(691), 1, + sym__b_flw_seq_bgn, + ACTIONS(693), 1, + sym__b_flw_map_bgn, + ACTIONS(695), 1, + sym__b_dqt_str_bgn, + ACTIONS(697), 1, + sym__b_sqt_str_bgn, + ACTIONS(701), 1, + sym__b_tag, + ACTIONS(703), 1, + sym__b_acr_bgn, + ACTIONS(705), 1, + sym__b_als_bgn, + ACTIONS(814), 1, + sym__bl, + STATE(279), 1, + sym__b_blk_key_itm, + STATE(322), 1, + sym__b_sgl_prp, + STATE(323), 1, + sym__b_blk_exp_itm, + STATE(325), 1, + sym__b_blk_val_itm, + STATE(326), 1, + sym__b_blk_imp_itm, + STATE(420), 1, + sym__b_acr, + STATE(1412), 1, + sym__b_als, + STATE(1464), 1, + sym__b_sgl_dqt_str, + STATE(1493), 1, + sym__b_sgl_flw_seq, + STATE(1502), 1, + sym__b_sgl_flw_map, + STATE(1520), 1, + sym__b_sgl_sqt_str, + STATE(1532), 1, + sym__b_sgl_pln_blk, + STATE(128), 2, + sym__b_blk_map_itm, + aux_sym__r_blk_map_repeat1, + ACTIONS(699), 6, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + STATE(1299), 7, + sym__b_sgl_prp_val, + sym__b_sgl_flw_seq_val, + sym__b_sgl_flw_map_val, + sym__b_sgl_dqt_str_val, + sym__b_sgl_sqt_str_val, + sym__b_sgl_pln_blk_val, + sym__b_als_val, + [3588] = 26, + ACTIONS(3), 1, + sym_comment, + ACTIONS(687), 1, + sym__b_blk_key_bgn, + ACTIONS(689), 1, + sym__b_blk_val_bgn, + ACTIONS(691), 1, + sym__b_flw_seq_bgn, + ACTIONS(693), 1, + sym__b_flw_map_bgn, + ACTIONS(695), 1, + sym__b_dqt_str_bgn, + ACTIONS(697), 1, + sym__b_sqt_str_bgn, + ACTIONS(701), 1, + sym__b_tag, + ACTIONS(703), 1, + sym__b_acr_bgn, + ACTIONS(705), 1, + sym__b_als_bgn, + ACTIONS(816), 1, + sym__bl, + STATE(279), 1, + sym__b_blk_key_itm, + STATE(322), 1, + sym__b_sgl_prp, + STATE(323), 1, + sym__b_blk_exp_itm, + STATE(325), 1, + sym__b_blk_val_itm, + STATE(326), 1, + sym__b_blk_imp_itm, + STATE(420), 1, + sym__b_acr, + STATE(1412), 1, + sym__b_als, + STATE(1464), 1, + sym__b_sgl_dqt_str, + STATE(1493), 1, + sym__b_sgl_flw_seq, + STATE(1502), 1, + sym__b_sgl_flw_map, + STATE(1520), 1, + sym__b_sgl_sqt_str, + STATE(1532), 1, + sym__b_sgl_pln_blk, + STATE(128), 2, + sym__b_blk_map_itm, + aux_sym__r_blk_map_repeat1, + ACTIONS(699), 6, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + STATE(1299), 7, + sym__b_sgl_prp_val, + sym__b_sgl_flw_seq_val, + sym__b_sgl_flw_map_val, + sym__b_sgl_dqt_str_val, + sym__b_sgl_sqt_str_val, + sym__b_sgl_pln_blk_val, + sym__b_als_val, + [3679] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(629), 1, + sym__r_blk_imp_bgn, + ACTIONS(818), 1, + sym__r_tag, + ACTIONS(820), 1, + sym__br_tag, + ACTIONS(631), 10, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + ACTIONS(627), 24, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + sym__br_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_blk, + sym__br_sgl_pln_bol_blk, + sym__br_sgl_pln_int_blk, + sym__br_sgl_pln_flt_blk, + sym__br_sgl_pln_tms_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_acr_bgn, + sym__br_als_bgn, + [3730] = 28, + ACTIONS(3), 1, + sym_comment, + ACTIONS(770), 1, + sym__r_flw_seq_bgn, + ACTIONS(774), 1, + sym__r_flw_map_bgn, + ACTIONS(776), 1, + sym__r_flw_key_bgn, + ACTIONS(778), 1, + sym__r_flw_njv_bgn, + ACTIONS(780), 1, + sym__r_dqt_str_bgn, + ACTIONS(782), 1, + sym__r_sqt_str_bgn, + ACTIONS(786), 1, + sym__r_tag, + ACTIONS(788), 1, + sym__r_acr_bgn, + ACTIONS(790), 1, + sym__r_als_bgn, + ACTIONS(823), 1, + sym__r_flw_seq_end, + STATE(261), 1, + sym__r_sgl_prp, + STATE(395), 1, + sym__r_acr, + STATE(986), 1, + sym__r_sgl_flw_col_itm, + STATE(1050), 1, + sym__sgl_flw_seq_tal, + STATE(1097), 1, + sym__r_als, + STATE(1110), 1, + sym__r_sgl_flw_seq, + STATE(1113), 1, + sym__r_sgl_flw_map, + STATE(1114), 1, + sym__r_sgl_dqt_str, + STATE(1116), 1, + sym__r_sgl_sqt_str, + STATE(1132), 1, + sym__r_sgl_pln_flw, + STATE(1225), 1, + sym__r_sgl_flw_exp_par, + STATE(1240), 1, + sym__r_sgl_flw_imp_par, + STATE(1253), 1, + sym__r_sgl_flw_njl_ann_par, + STATE(1473), 1, + sym__r_sgl_flw_col_dat, + STATE(976), 3, + sym__r_sgl_prp_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + STATE(1025), 4, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + ACTIONS(784), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [3825] = 28, + ACTIONS(3), 1, + sym_comment, + ACTIONS(709), 1, + sym__r_flw_seq_bgn, + ACTIONS(711), 1, + sym__r_flw_map_bgn, + ACTIONS(715), 1, + sym__r_flw_key_bgn, + ACTIONS(717), 1, + sym__r_flw_njv_bgn, + ACTIONS(719), 1, + sym__r_dqt_str_bgn, + ACTIONS(721), 1, + sym__r_sqt_str_bgn, + ACTIONS(725), 1, + sym__r_tag, + ACTIONS(727), 1, + sym__r_acr_bgn, + ACTIONS(729), 1, + sym__r_als_bgn, + ACTIONS(825), 1, + sym__r_flw_map_end, + STATE(265), 1, + sym__r_sgl_prp, + STATE(398), 1, + sym__r_acr, + STATE(964), 1, + sym__r_sgl_flw_col_itm, + STATE(1064), 1, + sym__sgl_flw_map_tal, + STATE(1100), 1, + sym__r_als, + STATE(1187), 1, + sym__r_sgl_pln_flw, + STATE(1209), 1, + sym__r_sgl_flw_seq, + STATE(1210), 1, + sym__r_sgl_flw_map, + STATE(1213), 1, + sym__r_sgl_dqt_str, + STATE(1214), 1, + sym__r_sgl_sqt_str, + STATE(1250), 1, + sym__r_sgl_flw_exp_par, + STATE(1251), 1, + sym__r_sgl_flw_imp_par, + STATE(1252), 1, + sym__r_sgl_flw_njl_ann_par, + STATE(1476), 1, + sym__r_sgl_flw_col_dat, + STATE(1038), 3, + sym__r_sgl_prp_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + STATE(1045), 4, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + ACTIONS(723), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [3920] = 26, + ACTIONS(3), 1, + sym_comment, + ACTIONS(687), 1, + sym__b_blk_key_bgn, + ACTIONS(689), 1, + sym__b_blk_val_bgn, + ACTIONS(691), 1, + sym__b_flw_seq_bgn, + ACTIONS(693), 1, + sym__b_flw_map_bgn, + ACTIONS(695), 1, + sym__b_dqt_str_bgn, + ACTIONS(697), 1, + sym__b_sqt_str_bgn, + ACTIONS(701), 1, + sym__b_tag, + ACTIONS(703), 1, + sym__b_acr_bgn, + ACTIONS(705), 1, + sym__b_als_bgn, + ACTIONS(827), 1, + sym__bl, + STATE(279), 1, + sym__b_blk_key_itm, + STATE(322), 1, + sym__b_sgl_prp, + STATE(323), 1, + sym__b_blk_exp_itm, + STATE(325), 1, + sym__b_blk_val_itm, + STATE(326), 1, + sym__b_blk_imp_itm, + STATE(420), 1, + sym__b_acr, + STATE(1412), 1, + sym__b_als, + STATE(1464), 1, + sym__b_sgl_dqt_str, + STATE(1493), 1, + sym__b_sgl_flw_seq, + STATE(1502), 1, + sym__b_sgl_flw_map, + STATE(1520), 1, + sym__b_sgl_sqt_str, + STATE(1532), 1, + sym__b_sgl_pln_blk, + STATE(128), 2, + sym__b_blk_map_itm, + aux_sym__r_blk_map_repeat1, + ACTIONS(699), 6, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + STATE(1299), 7, + sym__b_sgl_prp_val, + sym__b_sgl_flw_seq_val, + sym__b_sgl_flw_map_val, + sym__b_sgl_dqt_str_val, + sym__b_sgl_sqt_str_val, + sym__b_sgl_pln_blk_val, + sym__b_als_val, + [4011] = 26, + ACTIONS(3), 1, + sym_comment, + ACTIONS(687), 1, + sym__b_blk_key_bgn, + ACTIONS(689), 1, + sym__b_blk_val_bgn, + ACTIONS(691), 1, + sym__b_flw_seq_bgn, + ACTIONS(693), 1, + sym__b_flw_map_bgn, + ACTIONS(695), 1, + sym__b_dqt_str_bgn, + ACTIONS(697), 1, + sym__b_sqt_str_bgn, + ACTIONS(701), 1, + sym__b_tag, + ACTIONS(703), 1, + sym__b_acr_bgn, + ACTIONS(705), 1, + sym__b_als_bgn, + ACTIONS(829), 1, + sym__bl, + STATE(279), 1, + sym__b_blk_key_itm, + STATE(322), 1, + sym__b_sgl_prp, + STATE(323), 1, + sym__b_blk_exp_itm, + STATE(325), 1, + sym__b_blk_val_itm, + STATE(326), 1, + sym__b_blk_imp_itm, + STATE(420), 1, + sym__b_acr, + STATE(1412), 1, + sym__b_als, + STATE(1464), 1, + sym__b_sgl_dqt_str, + STATE(1493), 1, + sym__b_sgl_flw_seq, + STATE(1502), 1, + sym__b_sgl_flw_map, + STATE(1520), 1, + sym__b_sgl_sqt_str, + STATE(1532), 1, + sym__b_sgl_pln_blk, + STATE(128), 2, + sym__b_blk_map_itm, + aux_sym__r_blk_map_repeat1, + ACTIONS(699), 6, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + STATE(1299), 7, + sym__b_sgl_prp_val, + sym__b_sgl_flw_seq_val, + sym__b_sgl_flw_map_val, + sym__b_sgl_dqt_str_val, + sym__b_sgl_sqt_str_val, + sym__b_sgl_pln_blk_val, + sym__b_als_val, + [4102] = 28, + ACTIONS(3), 1, + sym_comment, + ACTIONS(770), 1, + sym__r_flw_seq_bgn, + ACTIONS(774), 1, + sym__r_flw_map_bgn, + ACTIONS(776), 1, + sym__r_flw_key_bgn, + ACTIONS(778), 1, + sym__r_flw_njv_bgn, + ACTIONS(780), 1, + sym__r_dqt_str_bgn, + ACTIONS(782), 1, + sym__r_sqt_str_bgn, + ACTIONS(786), 1, + sym__r_tag, + ACTIONS(788), 1, + sym__r_acr_bgn, + ACTIONS(790), 1, + sym__r_als_bgn, + ACTIONS(831), 1, + sym__r_flw_seq_end, + STATE(261), 1, + sym__r_sgl_prp, + STATE(395), 1, + sym__r_acr, + STATE(986), 1, + sym__r_sgl_flw_col_itm, + STATE(1097), 1, + sym__r_als, + STATE(1110), 1, + sym__r_sgl_flw_seq, + STATE(1113), 1, + sym__r_sgl_flw_map, + STATE(1114), 1, + sym__r_sgl_dqt_str, + STATE(1116), 1, + sym__r_sgl_sqt_str, + STATE(1132), 1, + sym__r_sgl_pln_flw, + STATE(1225), 1, + sym__r_sgl_flw_exp_par, + STATE(1240), 1, + sym__r_sgl_flw_imp_par, + STATE(1253), 1, + sym__r_sgl_flw_njl_ann_par, + STATE(1457), 1, + sym__r_sgl_flw_col_dat, + STATE(1509), 1, + sym__sgl_flw_seq_tal, + STATE(976), 3, + sym__r_sgl_prp_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + STATE(1025), 4, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + ACTIONS(784), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [4197] = 28, + ACTIONS(3), 1, + sym_comment, + ACTIONS(709), 1, + sym__r_flw_seq_bgn, + ACTIONS(711), 1, + sym__r_flw_map_bgn, + ACTIONS(715), 1, + sym__r_flw_key_bgn, + ACTIONS(717), 1, + sym__r_flw_njv_bgn, + ACTIONS(719), 1, + sym__r_dqt_str_bgn, + ACTIONS(721), 1, + sym__r_sqt_str_bgn, + ACTIONS(725), 1, + sym__r_tag, + ACTIONS(727), 1, + sym__r_acr_bgn, + ACTIONS(729), 1, + sym__r_als_bgn, + ACTIONS(833), 1, + sym__r_flw_map_end, + STATE(265), 1, + sym__r_sgl_prp, + STATE(398), 1, + sym__r_acr, + STATE(964), 1, + sym__r_sgl_flw_col_itm, + STATE(1100), 1, + sym__r_als, + STATE(1187), 1, + sym__r_sgl_pln_flw, + STATE(1209), 1, + sym__r_sgl_flw_seq, + STATE(1210), 1, + sym__r_sgl_flw_map, + STATE(1213), 1, + sym__r_sgl_dqt_str, + STATE(1214), 1, + sym__r_sgl_sqt_str, + STATE(1250), 1, + sym__r_sgl_flw_exp_par, + STATE(1251), 1, + sym__r_sgl_flw_imp_par, + STATE(1252), 1, + sym__r_sgl_flw_njl_ann_par, + STATE(1422), 1, + sym__sgl_flw_map_tal, + STATE(1460), 1, + sym__r_sgl_flw_col_dat, + STATE(1038), 3, + sym__r_sgl_prp_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + STATE(1045), 4, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + ACTIONS(723), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [4292] = 28, + ACTIONS(3), 1, + sym_comment, + ACTIONS(770), 1, + sym__r_flw_seq_bgn, + ACTIONS(774), 1, + sym__r_flw_map_bgn, + ACTIONS(776), 1, + sym__r_flw_key_bgn, + ACTIONS(778), 1, + sym__r_flw_njv_bgn, + ACTIONS(780), 1, + sym__r_dqt_str_bgn, + ACTIONS(782), 1, + sym__r_sqt_str_bgn, + ACTIONS(786), 1, + sym__r_tag, + ACTIONS(788), 1, + sym__r_acr_bgn, + ACTIONS(790), 1, + sym__r_als_bgn, + ACTIONS(835), 1, + sym__r_flw_seq_end, + STATE(261), 1, + sym__r_sgl_prp, + STATE(395), 1, + sym__r_acr, + STATE(986), 1, + sym__r_sgl_flw_col_itm, + STATE(1097), 1, + sym__r_als, + STATE(1110), 1, + sym__r_sgl_flw_seq, + STATE(1113), 1, + sym__r_sgl_flw_map, + STATE(1114), 1, + sym__r_sgl_dqt_str, + STATE(1116), 1, + sym__r_sgl_sqt_str, + STATE(1132), 1, + sym__r_sgl_pln_flw, + STATE(1225), 1, + sym__r_sgl_flw_exp_par, + STATE(1240), 1, + sym__r_sgl_flw_imp_par, + STATE(1253), 1, + sym__r_sgl_flw_njl_ann_par, + STATE(1257), 1, + sym__sgl_flw_seq_tal, + STATE(1525), 1, + sym__r_sgl_flw_col_dat, + STATE(976), 3, + sym__r_sgl_prp_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + STATE(1025), 4, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + ACTIONS(784), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [4387] = 28, + ACTIONS(3), 1, + sym_comment, + ACTIONS(709), 1, + sym__r_flw_seq_bgn, + ACTIONS(711), 1, + sym__r_flw_map_bgn, + ACTIONS(715), 1, + sym__r_flw_key_bgn, + ACTIONS(717), 1, + sym__r_flw_njv_bgn, + ACTIONS(719), 1, + sym__r_dqt_str_bgn, + ACTIONS(721), 1, + sym__r_sqt_str_bgn, + ACTIONS(725), 1, + sym__r_tag, + ACTIONS(727), 1, + sym__r_acr_bgn, + ACTIONS(729), 1, + sym__r_als_bgn, + ACTIONS(837), 1, + sym__r_flw_map_end, + STATE(265), 1, + sym__r_sgl_prp, + STATE(398), 1, + sym__r_acr, + STATE(964), 1, + sym__r_sgl_flw_col_itm, + STATE(1100), 1, + sym__r_als, + STATE(1187), 1, + sym__r_sgl_pln_flw, + STATE(1209), 1, + sym__r_sgl_flw_seq, + STATE(1210), 1, + sym__r_sgl_flw_map, + STATE(1213), 1, + sym__r_sgl_dqt_str, + STATE(1214), 1, + sym__r_sgl_sqt_str, + STATE(1250), 1, + sym__r_sgl_flw_exp_par, + STATE(1251), 1, + sym__r_sgl_flw_imp_par, + STATE(1252), 1, + sym__r_sgl_flw_njl_ann_par, + STATE(1264), 1, + sym__sgl_flw_map_tal, + STATE(1527), 1, + sym__r_sgl_flw_col_dat, + STATE(1038), 3, + sym__r_sgl_prp_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + STATE(1045), 4, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + ACTIONS(723), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [4482] = 28, + ACTIONS(3), 1, + sym_comment, + ACTIONS(770), 1, + sym__r_flw_seq_bgn, + ACTIONS(774), 1, + sym__r_flw_map_bgn, + ACTIONS(776), 1, + sym__r_flw_key_bgn, + ACTIONS(778), 1, + sym__r_flw_njv_bgn, + ACTIONS(780), 1, + sym__r_dqt_str_bgn, + ACTIONS(782), 1, + sym__r_sqt_str_bgn, + ACTIONS(786), 1, + sym__r_tag, + ACTIONS(788), 1, + sym__r_acr_bgn, + ACTIONS(790), 1, + sym__r_als_bgn, + ACTIONS(839), 1, + sym__r_flw_seq_end, + STATE(261), 1, + sym__r_sgl_prp, + STATE(395), 1, + sym__r_acr, + STATE(986), 1, + sym__r_sgl_flw_col_itm, + STATE(1097), 1, + sym__r_als, + STATE(1110), 1, + sym__r_sgl_flw_seq, + STATE(1113), 1, + sym__r_sgl_flw_map, + STATE(1114), 1, + sym__r_sgl_dqt_str, + STATE(1116), 1, + sym__r_sgl_sqt_str, + STATE(1132), 1, + sym__r_sgl_pln_flw, + STATE(1225), 1, + sym__r_sgl_flw_exp_par, + STATE(1240), 1, + sym__r_sgl_flw_imp_par, + STATE(1253), 1, + sym__r_sgl_flw_njl_ann_par, + STATE(1317), 1, + sym__sgl_flw_seq_tal, + STATE(1447), 1, + sym__r_sgl_flw_col_dat, + STATE(976), 3, + sym__r_sgl_prp_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + STATE(1025), 4, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + ACTIONS(784), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [4577] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(651), 36, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_imp_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__r_tag, + sym__br_tag, + sym__br_acr_bgn, + sym__br_als_bgn, + sym__bl, + [4619] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(617), 1, + sym__r_blk_imp_bgn, + ACTIONS(841), 1, + sym__r_tag, + ACTIONS(843), 1, + sym__br_tag, + ACTIONS(619), 10, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + ACTIONS(615), 23, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_blk, + sym__br_sgl_pln_bol_blk, + sym__br_sgl_pln_int_blk, + sym__br_sgl_pln_flt_blk, + sym__br_sgl_pln_tms_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_acr_bgn, + sym__br_als_bgn, + sym__bl, + [4669] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(629), 1, + sym__r_blk_imp_bgn, + ACTIONS(846), 1, + sym__r_tag, + ACTIONS(848), 1, + sym__br_tag, + ACTIONS(631), 10, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + ACTIONS(627), 23, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_blk, + sym__br_sgl_pln_bol_blk, + sym__br_sgl_pln_int_blk, + sym__br_sgl_pln_flt_blk, + sym__br_sgl_pln_tms_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_acr_bgn, + sym__br_als_bgn, + sym__bl, + [4719] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 36, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + sym__br_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_imp_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__br_acr_bgn, + sym__br_als_bgn, + [4761] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(767), 1, + sym__br_tag, + ACTIONS(851), 1, + sym__r_tag, + ACTIONS(615), 34, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + sym__br_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_acr_bgn, + sym__br_als_bgn, + [4807] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 36, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + sym__br_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__r_tag, + sym__br_tag, + sym__br_acr_bgn, + sym__br_als_bgn, + [4849] = 19, + ACTIONS(3), 1, + sym_comment, + ACTIONS(387), 1, + sym__br_flw_seq_bgn, + ACTIONS(391), 1, + sym__br_flw_map_bgn, + ACTIONS(400), 1, + sym__br_dqt_str_bgn, + ACTIONS(404), 1, + sym__br_sqt_str_bgn, + ACTIONS(410), 1, + sym__r_mtl_pln_str_flw, + ACTIONS(412), 1, + sym__br_mtl_pln_str_flw, + ACTIONS(577), 1, + sym__r_flw_seq_bgn, + ACTIONS(579), 1, + sym__r_flw_map_bgn, + ACTIONS(583), 1, + sym__r_dqt_str_bgn, + ACTIONS(585), 1, + sym__r_sqt_str_bgn, + ACTIONS(377), 2, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + STATE(1338), 2, + sym__r_flw_seq, + sym__br_flw_seq, + STATE(1339), 2, + sym__r_flw_map, + sym__br_flw_map, + STATE(1340), 2, + sym__r_dqt_str, + sym__br_dqt_str, + STATE(1341), 2, + sym__r_sqt_str, + sym__br_sqt_str, + STATE(1398), 4, + sym__r_sgl_pln_flw, + sym__br_sgl_pln_flw, + sym__r_mtl_pln_flw, + sym__br_mtl_pln_flw, + ACTIONS(406), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + ACTIONS(408), 6, + sym__br_sgl_pln_nul_flw, + sym__br_sgl_pln_bol_flw, + sym__br_sgl_pln_int_flw, + sym__br_sgl_pln_flt_flw, + sym__br_sgl_pln_tms_flw, + sym__br_sgl_pln_str_flw, + [4925] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 36, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_imp_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__r_tag, + sym__br_tag, + sym__br_acr_bgn, + sym__br_als_bgn, + sym__bl, + [4967] = 19, + ACTIONS(3), 1, + sym_comment, + ACTIONS(387), 1, + sym__br_flw_seq_bgn, + ACTIONS(391), 1, + sym__br_flw_map_bgn, + ACTIONS(400), 1, + sym__br_dqt_str_bgn, + ACTIONS(404), 1, + sym__br_sqt_str_bgn, + ACTIONS(410), 1, + sym__r_mtl_pln_str_flw, + ACTIONS(412), 1, + sym__br_mtl_pln_str_flw, + ACTIONS(577), 1, + sym__r_flw_seq_bgn, + ACTIONS(579), 1, + sym__r_flw_map_bgn, + ACTIONS(583), 1, + sym__r_dqt_str_bgn, + ACTIONS(585), 1, + sym__r_sqt_str_bgn, + ACTIONS(369), 2, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + STATE(1342), 2, + sym__r_flw_seq, + sym__br_flw_seq, + STATE(1343), 2, + sym__r_flw_map, + sym__br_flw_map, + STATE(1346), 2, + sym__r_dqt_str, + sym__br_dqt_str, + STATE(1349), 2, + sym__r_sqt_str, + sym__br_sqt_str, + STATE(1400), 4, + sym__r_sgl_pln_flw, + sym__br_sgl_pln_flw, + sym__r_mtl_pln_flw, + sym__br_mtl_pln_flw, + ACTIONS(406), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + ACTIONS(408), 6, + sym__br_sgl_pln_nul_flw, + sym__br_sgl_pln_bol_flw, + sym__br_sgl_pln_int_flw, + sym__br_sgl_pln_flt_flw, + sym__br_sgl_pln_tms_flw, + sym__br_sgl_pln_str_flw, + [5043] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(655), 1, + sym__r_blk_imp_bgn, + ACTIONS(657), 10, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + ACTIONS(653), 25, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + sym__br_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_blk, + sym__br_sgl_pln_bol_blk, + sym__br_sgl_pln_int_blk, + sym__br_sgl_pln_flt_blk, + sym__br_sgl_pln_tms_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__br_acr_bgn, + sym__br_als_bgn, + [5089] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(662), 1, + sym__r_blk_imp_bgn, + ACTIONS(664), 10, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + ACTIONS(660), 25, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + sym__br_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_blk, + sym__br_sgl_pln_bol_blk, + sym__br_sgl_pln_int_blk, + sym__br_sgl_pln_flt_blk, + sym__br_sgl_pln_tms_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__br_acr_bgn, + sym__br_als_bgn, + [5135] = 26, + ACTIONS(3), 1, + sym_comment, + ACTIONS(770), 1, + sym__r_flw_seq_bgn, + ACTIONS(774), 1, + sym__r_flw_map_bgn, + ACTIONS(776), 1, + sym__r_flw_key_bgn, + ACTIONS(778), 1, + sym__r_flw_njv_bgn, + ACTIONS(780), 1, + sym__r_dqt_str_bgn, + ACTIONS(782), 1, + sym__r_sqt_str_bgn, + ACTIONS(786), 1, + sym__r_tag, + ACTIONS(788), 1, + sym__r_acr_bgn, + ACTIONS(790), 1, + sym__r_als_bgn, + ACTIONS(853), 1, + sym__r_flw_seq_end, + STATE(261), 1, + sym__r_sgl_prp, + STATE(395), 1, + sym__r_acr, + STATE(1097), 1, + sym__r_als, + STATE(1110), 1, + sym__r_sgl_flw_seq, + STATE(1113), 1, + sym__r_sgl_flw_map, + STATE(1114), 1, + sym__r_sgl_dqt_str, + STATE(1116), 1, + sym__r_sgl_sqt_str, + STATE(1132), 1, + sym__r_sgl_pln_flw, + STATE(1225), 1, + sym__r_sgl_flw_exp_par, + STATE(1240), 1, + sym__r_sgl_flw_imp_par, + STATE(1245), 1, + sym__r_sgl_flw_col_itm, + STATE(1253), 1, + sym__r_sgl_flw_njl_ann_par, + STATE(976), 3, + sym__r_sgl_prp_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + STATE(1025), 4, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + ACTIONS(784), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [5224] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(655), 1, + sym__r_blk_imp_bgn, + ACTIONS(657), 10, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + ACTIONS(653), 24, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_blk, + sym__br_sgl_pln_bol_blk, + sym__br_sgl_pln_int_blk, + sym__br_sgl_pln_flt_blk, + sym__br_sgl_pln_tms_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__br_acr_bgn, + sym__br_als_bgn, + sym__bl, + [5269] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(660), 35, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + sym__br_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__br_acr_bgn, + sym__br_als_bgn, + [5310] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 35, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + sym__br_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__br_acr_bgn, + sym__br_als_bgn, + [5351] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(651), 35, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + sym__br_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__br_acr_bgn, + sym__br_als_bgn, + [5392] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(662), 1, + sym__r_blk_imp_bgn, + ACTIONS(664), 10, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + ACTIONS(660), 24, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_blk, + sym__br_sgl_pln_bol_blk, + sym__br_sgl_pln_int_blk, + sym__br_sgl_pln_flt_blk, + sym__br_sgl_pln_tms_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__br_acr_bgn, + sym__br_als_bgn, + sym__bl, + [5437] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 35, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_imp_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__br_acr_bgn, + sym__br_als_bgn, + sym__bl, + [5478] = 26, + ACTIONS(3), 1, + sym_comment, + ACTIONS(709), 1, + sym__r_flw_seq_bgn, + ACTIONS(711), 1, + sym__r_flw_map_bgn, + ACTIONS(715), 1, + sym__r_flw_key_bgn, + ACTIONS(717), 1, + sym__r_flw_njv_bgn, + ACTIONS(719), 1, + sym__r_dqt_str_bgn, + ACTIONS(721), 1, + sym__r_sqt_str_bgn, + ACTIONS(725), 1, + sym__r_tag, + ACTIONS(727), 1, + sym__r_acr_bgn, + ACTIONS(729), 1, + sym__r_als_bgn, + ACTIONS(853), 1, + sym__r_flw_map_end, + STATE(265), 1, + sym__r_sgl_prp, + STATE(398), 1, + sym__r_acr, + STATE(1100), 1, + sym__r_als, + STATE(1187), 1, + sym__r_sgl_pln_flw, + STATE(1209), 1, + sym__r_sgl_flw_seq, + STATE(1210), 1, + sym__r_sgl_flw_map, + STATE(1213), 1, + sym__r_sgl_dqt_str, + STATE(1214), 1, + sym__r_sgl_sqt_str, + STATE(1250), 1, + sym__r_sgl_flw_exp_par, + STATE(1251), 1, + sym__r_sgl_flw_imp_par, + STATE(1252), 1, + sym__r_sgl_flw_njl_ann_par, + STATE(1372), 1, + sym__r_sgl_flw_col_itm, + STATE(1038), 3, + sym__r_sgl_prp_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + STATE(1045), 4, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + ACTIONS(723), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [5567] = 26, + ACTIONS(3), 1, + sym_comment, + ACTIONS(709), 1, + sym__r_flw_seq_bgn, + ACTIONS(711), 1, + sym__r_flw_map_bgn, + ACTIONS(715), 1, + sym__r_flw_key_bgn, + ACTIONS(717), 1, + sym__r_flw_njv_bgn, + ACTIONS(719), 1, + sym__r_dqt_str_bgn, + ACTIONS(721), 1, + sym__r_sqt_str_bgn, + ACTIONS(725), 1, + sym__r_tag, + ACTIONS(727), 1, + sym__r_acr_bgn, + ACTIONS(729), 1, + sym__r_als_bgn, + ACTIONS(855), 1, + sym__r_flw_map_end, + STATE(265), 1, + sym__r_sgl_prp, + STATE(398), 1, + sym__r_acr, + STATE(1100), 1, + sym__r_als, + STATE(1187), 1, + sym__r_sgl_pln_flw, + STATE(1209), 1, + sym__r_sgl_flw_seq, + STATE(1210), 1, + sym__r_sgl_flw_map, + STATE(1213), 1, + sym__r_sgl_dqt_str, + STATE(1214), 1, + sym__r_sgl_sqt_str, + STATE(1250), 1, + sym__r_sgl_flw_exp_par, + STATE(1251), 1, + sym__r_sgl_flw_imp_par, + STATE(1252), 1, + sym__r_sgl_flw_njl_ann_par, + STATE(1372), 1, + sym__r_sgl_flw_col_itm, + STATE(1038), 3, + sym__r_sgl_prp_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + STATE(1045), 4, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + ACTIONS(723), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [5656] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(653), 35, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + sym__br_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__br_acr_bgn, + sym__br_als_bgn, + [5697] = 26, + ACTIONS(3), 1, + sym_comment, + ACTIONS(770), 1, + sym__r_flw_seq_bgn, + ACTIONS(774), 1, + sym__r_flw_map_bgn, + ACTIONS(776), 1, + sym__r_flw_key_bgn, + ACTIONS(778), 1, + sym__r_flw_njv_bgn, + ACTIONS(780), 1, + sym__r_dqt_str_bgn, + ACTIONS(782), 1, + sym__r_sqt_str_bgn, + ACTIONS(786), 1, + sym__r_tag, + ACTIONS(788), 1, + sym__r_acr_bgn, + ACTIONS(790), 1, + sym__r_als_bgn, + ACTIONS(855), 1, + sym__r_flw_seq_end, + STATE(261), 1, + sym__r_sgl_prp, + STATE(395), 1, + sym__r_acr, + STATE(1097), 1, + sym__r_als, + STATE(1110), 1, + sym__r_sgl_flw_seq, + STATE(1113), 1, + sym__r_sgl_flw_map, + STATE(1114), 1, + sym__r_sgl_dqt_str, + STATE(1116), 1, + sym__r_sgl_sqt_str, + STATE(1132), 1, + sym__r_sgl_pln_flw, + STATE(1225), 1, + sym__r_sgl_flw_exp_par, + STATE(1240), 1, + sym__r_sgl_flw_imp_par, + STATE(1245), 1, + sym__r_sgl_flw_col_itm, + STATE(1253), 1, + sym__r_sgl_flw_njl_ann_par, + STATE(976), 3, + sym__r_sgl_prp_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + STATE(1025), 4, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + ACTIONS(784), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [5786] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(653), 34, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__br_acr_bgn, + sym__br_als_bgn, + sym__bl, + [5826] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(660), 34, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__br_acr_bgn, + sym__br_als_bgn, + sym__bl, + [5866] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(651), 34, + sym__br_blk_seq_bgn, + sym__b_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__r_blk_lit_bgn, + sym__br_blk_lit_bgn, + sym__r_blk_fld_bgn, + sym__br_blk_fld_bgn, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__br_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__br_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__br_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__br_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__br_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__br_sgl_pln_str_blk, + sym__r_mtl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__br_acr_bgn, + sym__br_als_bgn, + sym__bl, + [5906] = 25, + ACTIONS(3), 1, + sym_comment, + ACTIONS(770), 1, + sym__r_flw_seq_bgn, + ACTIONS(774), 1, + sym__r_flw_map_bgn, + ACTIONS(776), 1, + sym__r_flw_key_bgn, + ACTIONS(778), 1, + sym__r_flw_njv_bgn, + ACTIONS(780), 1, + sym__r_dqt_str_bgn, + ACTIONS(782), 1, + sym__r_sqt_str_bgn, + ACTIONS(786), 1, + sym__r_tag, + ACTIONS(788), 1, + sym__r_acr_bgn, + ACTIONS(790), 1, + sym__r_als_bgn, + STATE(261), 1, + sym__r_sgl_prp, + STATE(395), 1, + sym__r_acr, + STATE(1097), 1, + sym__r_als, + STATE(1110), 1, + sym__r_sgl_flw_seq, + STATE(1113), 1, + sym__r_sgl_flw_map, + STATE(1114), 1, + sym__r_sgl_dqt_str, + STATE(1116), 1, + sym__r_sgl_sqt_str, + STATE(1132), 1, + sym__r_sgl_pln_flw, + STATE(1225), 1, + sym__r_sgl_flw_exp_par, + STATE(1240), 1, + sym__r_sgl_flw_imp_par, + STATE(1245), 1, + sym__r_sgl_flw_col_itm, + STATE(1253), 1, + sym__r_sgl_flw_njl_ann_par, + STATE(976), 3, + sym__r_sgl_prp_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + STATE(1025), 4, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + ACTIONS(784), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [5992] = 25, + ACTIONS(3), 1, + sym_comment, + ACTIONS(709), 1, + sym__r_flw_seq_bgn, + ACTIONS(711), 1, + sym__r_flw_map_bgn, + ACTIONS(715), 1, + sym__r_flw_key_bgn, + ACTIONS(717), 1, + sym__r_flw_njv_bgn, + ACTIONS(719), 1, + sym__r_dqt_str_bgn, + ACTIONS(721), 1, + sym__r_sqt_str_bgn, + ACTIONS(725), 1, + sym__r_tag, + ACTIONS(727), 1, + sym__r_acr_bgn, + ACTIONS(729), 1, + sym__r_als_bgn, + STATE(265), 1, + sym__r_sgl_prp, + STATE(398), 1, + sym__r_acr, + STATE(1100), 1, + sym__r_als, + STATE(1187), 1, + sym__r_sgl_pln_flw, + STATE(1209), 1, + sym__r_sgl_flw_seq, + STATE(1210), 1, + sym__r_sgl_flw_map, + STATE(1213), 1, + sym__r_sgl_dqt_str, + STATE(1214), 1, + sym__r_sgl_sqt_str, + STATE(1250), 1, + sym__r_sgl_flw_exp_par, + STATE(1251), 1, + sym__r_sgl_flw_imp_par, + STATE(1252), 1, + sym__r_sgl_flw_njl_ann_par, + STATE(1372), 1, + sym__r_sgl_flw_col_itm, + STATE(1038), 3, + sym__r_sgl_prp_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + STATE(1045), 4, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + ACTIONS(723), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [6078] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(857), 1, + sym__r_acr_bgn, + ACTIONS(859), 1, + sym__br_acr_bgn, + STATE(219), 1, + sym__r_acr, + STATE(221), 1, + sym__br_acr, + ACTIONS(619), 13, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + ACTIONS(615), 16, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__br_flw_sep_bgn, + sym__br_flw_njv_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_flw, + sym__br_sgl_pln_bol_flw, + sym__br_sgl_pln_int_flw, + sym__br_sgl_pln_flt_flw, + sym__br_sgl_pln_tms_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [6127] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(857), 1, + sym__r_acr_bgn, + ACTIONS(859), 1, + sym__br_acr_bgn, + STATE(222), 2, + sym__r_acr, + sym__br_acr, + ACTIONS(627), 29, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [6172] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(857), 1, + sym__r_acr_bgn, + ACTIONS(859), 1, + sym__br_acr_bgn, + STATE(221), 2, + sym__r_acr, + sym__br_acr, + ACTIONS(615), 29, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [6217] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(861), 1, + sym__r_acr_bgn, + ACTIONS(863), 1, + sym__br_acr_bgn, + STATE(232), 2, + sym__r_acr, + sym__br_acr, + ACTIONS(627), 28, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [6261] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(861), 1, + sym__r_acr_bgn, + ACTIONS(863), 1, + sym__br_acr_bgn, + STATE(231), 2, + sym__r_acr, + sym__br_acr, + ACTIONS(615), 28, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [6305] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(861), 1, + sym__r_acr_bgn, + ACTIONS(863), 1, + sym__br_acr_bgn, + STATE(230), 1, + sym__r_acr, + STATE(231), 1, + sym__br_acr, + ACTIONS(619), 13, + sym__r_flw_seq_bgn, + sym__r_flw_seq_end, + sym__r_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + ACTIONS(615), 15, + sym__br_flw_seq_bgn, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__br_flw_map_bgn, + sym__br_flw_sep_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_flw, + sym__br_sgl_pln_bol_flw, + sym__br_sgl_pln_int_flw, + sym__br_sgl_pln_flt_flw, + sym__br_sgl_pln_tms_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [6353] = 21, + ACTIONS(3), 1, + sym_comment, + ACTIONS(865), 1, + sym__r_flw_seq_bgn, + ACTIONS(867), 1, + sym__r_flw_map_bgn, + ACTIONS(871), 1, + sym__r_dqt_str_bgn, + ACTIONS(873), 1, + sym__r_sqt_str_bgn, + ACTIONS(877), 1, + sym__r_tag, + ACTIONS(879), 1, + sym__r_acr_bgn, + ACTIONS(881), 1, + sym__r_als_bgn, + STATE(365), 1, + sym__r_sgl_prp, + STATE(413), 1, + sym__r_acr, + STATE(1312), 1, + sym__r_sgl_flw_imp_par, + STATE(1455), 1, + sym__r_als, + STATE(1463), 1, + sym__r_sgl_dqt_str, + STATE(1467), 1, + sym__r_sgl_sqt_str, + STATE(1506), 1, + sym__r_sgl_flw_seq, + STATE(1518), 1, + sym__r_sgl_pln_flw, + STATE(1534), 1, + sym__r_sgl_flw_map, + ACTIONS(869), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + STATE(1239), 3, + sym__r_sgl_prp_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + STATE(1242), 4, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + ACTIONS(875), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [6428] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(883), 2, + sym__r_tag, + sym__br_tag, + ACTIONS(615), 29, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [6467] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(883), 1, + sym__br_tag, + ACTIONS(885), 1, + sym__r_tag, + ACTIONS(619), 13, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + ACTIONS(615), 16, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__br_flw_sep_bgn, + sym__br_flw_njv_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_flw, + sym__br_sgl_pln_bol_flw, + sym__br_sgl_pln_int_flw, + sym__br_sgl_pln_flt_flw, + sym__br_sgl_pln_tms_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [6510] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(887), 1, + sym__r_acr_bgn, + ACTIONS(889), 1, + sym__br_acr_bgn, + STATE(236), 2, + sym__r_acr, + sym__br_acr, + ACTIONS(615), 27, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [6553] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(891), 1, + sym__r_acr_bgn, + ACTIONS(893), 1, + sym__br_acr_bgn, + STATE(243), 2, + sym__r_acr, + sym__br_acr, + ACTIONS(627), 27, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [6596] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(651), 31, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + sym__r_tag, + sym__br_tag, + [6633] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(891), 1, + sym__r_acr_bgn, + ACTIONS(893), 1, + sym__br_acr_bgn, + STATE(240), 2, + sym__r_acr, + sym__br_acr, + ACTIONS(615), 27, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [6676] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 31, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + sym__r_tag, + sym__br_tag, + [6713] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(895), 2, + sym__r_tag, + sym__br_tag, + ACTIONS(627), 29, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [6752] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(887), 1, + sym__r_acr_bgn, + ACTIONS(889), 1, + sym__br_acr_bgn, + STATE(236), 1, + sym__br_acr, + STATE(238), 1, + sym__r_acr, + ACTIONS(619), 12, + sym__r_flw_seq_bgn, + sym__r_flw_seq_end, + sym__r_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + ACTIONS(615), 15, + sym__br_flw_seq_bgn, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__br_flw_map_bgn, + sym__br_flw_sep_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_flw, + sym__br_sgl_pln_bol_flw, + sym__br_sgl_pln_int_flw, + sym__br_sgl_pln_flt_flw, + sym__br_sgl_pln_tms_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [6799] = 19, + ACTIONS(3), 1, + sym_comment, + ACTIONS(897), 1, + sym__r_flw_seq_bgn, + ACTIONS(901), 1, + sym__r_flw_map_bgn, + ACTIONS(903), 1, + sym__r_dqt_str_bgn, + ACTIONS(905), 1, + sym__r_sqt_str_bgn, + ACTIONS(909), 1, + sym__r_tag, + ACTIONS(911), 1, + sym__r_acr_bgn, + ACTIONS(913), 1, + sym__r_als_bgn, + STATE(274), 1, + sym__r_sgl_prp, + STATE(401), 1, + sym__r_acr, + STATE(1219), 1, + sym__r_sgl_flw_seq, + STATE(1223), 1, + sym__r_sgl_flw_map, + STATE(1224), 1, + sym__r_sgl_dqt_str, + STATE(1228), 1, + sym__r_sgl_sqt_str, + STATE(1326), 1, + sym__r_sgl_pln_flw, + STATE(1348), 1, + sym__r_als, + ACTIONS(899), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + ACTIONS(907), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + STATE(1379), 8, + sym__r_sgl_prp_val, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__sgl_flw_ann_par_tal, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + [6870] = 19, + ACTIONS(3), 1, + sym_comment, + ACTIONS(915), 1, + sym__r_flw_seq_bgn, + ACTIONS(917), 1, + sym__r_flw_map_bgn, + ACTIONS(919), 1, + sym__r_dqt_str_bgn, + ACTIONS(921), 1, + sym__r_sqt_str_bgn, + ACTIONS(925), 1, + sym__r_tag, + ACTIONS(927), 1, + sym__r_acr_bgn, + ACTIONS(929), 1, + sym__r_als_bgn, + STATE(276), 1, + sym__r_sgl_prp, + STATE(404), 1, + sym__r_acr, + STATE(1301), 1, + sym__r_sgl_flw_seq, + STATE(1305), 1, + sym__r_sgl_flw_map, + STATE(1308), 1, + sym__r_sgl_dqt_str, + STATE(1311), 1, + sym__r_sgl_sqt_str, + STATE(1336), 1, + sym__r_sgl_pln_flw, + STATE(1353), 1, + sym__r_als, + ACTIONS(899), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + ACTIONS(923), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + STATE(1319), 8, + sym__r_sgl_prp_val, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__sgl_flw_ann_par_tal, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + [6941] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(891), 1, + sym__r_acr_bgn, + ACTIONS(893), 1, + sym__br_acr_bgn, + STATE(240), 1, + sym__br_acr, + STATE(242), 1, + sym__r_acr, + ACTIONS(619), 12, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + ACTIONS(615), 15, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__br_flw_sep_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_flw, + sym__br_sgl_pln_bol_flw, + sym__br_sgl_pln_int_flw, + sym__br_sgl_pln_flt_flw, + sym__br_sgl_pln_tms_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [6988] = 19, + ACTIONS(3), 1, + sym_comment, + ACTIONS(915), 1, + sym__r_flw_seq_bgn, + ACTIONS(917), 1, + sym__r_flw_map_bgn, + ACTIONS(919), 1, + sym__r_dqt_str_bgn, + ACTIONS(921), 1, + sym__r_sqt_str_bgn, + ACTIONS(925), 1, + sym__r_tag, + ACTIONS(927), 1, + sym__r_acr_bgn, + ACTIONS(929), 1, + sym__r_als_bgn, + STATE(276), 1, + sym__r_sgl_prp, + STATE(404), 1, + sym__r_acr, + STATE(1301), 1, + sym__r_sgl_flw_seq, + STATE(1305), 1, + sym__r_sgl_flw_map, + STATE(1308), 1, + sym__r_sgl_dqt_str, + STATE(1311), 1, + sym__r_sgl_sqt_str, + STATE(1336), 1, + sym__r_sgl_pln_flw, + STATE(1353), 1, + sym__r_als, + ACTIONS(931), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + ACTIONS(923), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + STATE(1371), 8, + sym__r_sgl_prp_val, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__sgl_flw_ann_par_tal, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + [7059] = 19, + ACTIONS(3), 1, + sym_comment, + ACTIONS(897), 1, + sym__r_flw_seq_bgn, + ACTIONS(901), 1, + sym__r_flw_map_bgn, + ACTIONS(903), 1, + sym__r_dqt_str_bgn, + ACTIONS(905), 1, + sym__r_sqt_str_bgn, + ACTIONS(909), 1, + sym__r_tag, + ACTIONS(911), 1, + sym__r_acr_bgn, + ACTIONS(913), 1, + sym__r_als_bgn, + STATE(274), 1, + sym__r_sgl_prp, + STATE(401), 1, + sym__r_acr, + STATE(1219), 1, + sym__r_sgl_flw_seq, + STATE(1223), 1, + sym__r_sgl_flw_map, + STATE(1224), 1, + sym__r_sgl_dqt_str, + STATE(1228), 1, + sym__r_sgl_sqt_str, + STATE(1326), 1, + sym__r_sgl_pln_flw, + STATE(1348), 1, + sym__r_als, + ACTIONS(931), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + ACTIONS(907), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + STATE(1327), 8, + sym__r_sgl_prp_val, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__sgl_flw_ann_par_tal, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + [7130] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(887), 1, + sym__r_acr_bgn, + ACTIONS(889), 1, + sym__br_acr_bgn, + STATE(234), 2, + sym__r_acr, + sym__br_acr, + ACTIONS(627), 27, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [7173] = 21, + ACTIONS(3), 1, + sym_comment, + ACTIONS(865), 1, + sym__r_flw_seq_bgn, + ACTIONS(867), 1, + sym__r_flw_map_bgn, + ACTIONS(871), 1, + sym__r_dqt_str_bgn, + ACTIONS(873), 1, + sym__r_sqt_str_bgn, + ACTIONS(877), 1, + sym__r_tag, + ACTIONS(879), 1, + sym__r_acr_bgn, + ACTIONS(881), 1, + sym__r_als_bgn, + STATE(365), 1, + sym__r_sgl_prp, + STATE(413), 1, + sym__r_acr, + STATE(1292), 1, + sym__r_sgl_flw_imp_par, + STATE(1455), 1, + sym__r_als, + STATE(1463), 1, + sym__r_sgl_dqt_str, + STATE(1467), 1, + sym__r_sgl_sqt_str, + STATE(1506), 1, + sym__r_sgl_flw_seq, + STATE(1518), 1, + sym__r_sgl_pln_flw, + STATE(1534), 1, + sym__r_sgl_flw_map, + ACTIONS(869), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + STATE(1359), 3, + sym__r_sgl_prp_val, + sym__r_sgl_pln_flw_val, + sym__r_als_val, + STATE(1244), 4, + sym__r_sgl_flw_seq_val, + sym__r_sgl_flw_map_val, + sym__r_sgl_dqt_str_val, + sym__r_sgl_sqt_str_val, + ACTIONS(875), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [7248] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 30, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + sym__r_tag, + sym__br_tag, + [7284] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(933), 1, + sym__r_tag, + ACTIONS(935), 1, + sym__br_tag, + ACTIONS(619), 13, + sym__r_flw_seq_bgn, + sym__r_flw_seq_end, + sym__r_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + ACTIONS(615), 15, + sym__br_flw_seq_bgn, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__br_flw_map_bgn, + sym__br_flw_sep_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_flw, + sym__br_sgl_pln_bol_flw, + sym__br_sgl_pln_int_flw, + sym__br_sgl_pln_flt_flw, + sym__br_sgl_pln_tms_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [7326] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(651), 30, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + sym__r_tag, + sym__br_tag, + [7362] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(935), 2, + sym__r_tag, + sym__br_tag, + ACTIONS(615), 28, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [7400] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(937), 2, + sym__r_tag, + sym__br_tag, + ACTIONS(627), 28, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [7438] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 29, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + sym__r_tag, + sym__br_tag, + [7473] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(651), 29, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + sym__r_tag, + sym__br_tag, + [7508] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(939), 2, + sym__r_tag, + sym__br_tag, + ACTIONS(615), 27, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [7545] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(941), 2, + sym__r_tag, + sym__br_tag, + ACTIONS(615), 27, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [7582] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(941), 1, + sym__br_tag, + ACTIONS(943), 1, + sym__r_tag, + ACTIONS(619), 12, + sym__r_flw_seq_bgn, + sym__r_flw_seq_end, + sym__r_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + ACTIONS(615), 15, + sym__br_flw_seq_bgn, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__br_flw_map_bgn, + sym__br_flw_sep_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_flw, + sym__br_sgl_pln_bol_flw, + sym__br_sgl_pln_int_flw, + sym__br_sgl_pln_flt_flw, + sym__br_sgl_pln_tms_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [7623] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(651), 29, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [7658] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 29, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [7693] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(945), 2, + sym__r_tag, + sym__br_tag, + ACTIONS(627), 27, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [7730] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(657), 13, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + ACTIONS(653), 16, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__br_flw_sep_bgn, + sym__br_flw_njv_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_flw, + sym__br_sgl_pln_bol_flw, + sym__br_sgl_pln_int_flw, + sym__br_sgl_pln_flt_flw, + sym__br_sgl_pln_tms_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [7767] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(939), 1, + sym__br_tag, + ACTIONS(947), 1, + sym__r_tag, + ACTIONS(619), 12, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + ACTIONS(615), 15, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__br_flw_sep_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_flw, + sym__br_sgl_pln_bol_flw, + sym__br_sgl_pln_int_flw, + sym__br_sgl_pln_flt_flw, + sym__br_sgl_pln_tms_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [7808] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(653), 29, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [7843] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(660), 29, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [7878] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 29, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + sym__r_tag, + sym__br_tag, + [7913] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(949), 2, + sym__r_tag, + sym__br_tag, + ACTIONS(627), 27, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [7950] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(651), 29, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + sym__r_tag, + sym__br_tag, + [7985] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(951), 1, + sym__r_acr_bgn, + ACTIONS(953), 1, + sym__br_acr_bgn, + STATE(257), 1, + sym__r_acr, + STATE(258), 1, + sym__br_acr, + ACTIONS(619), 11, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + ACTIONS(615), 13, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_flw_njv_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_flw, + sym__br_sgl_pln_bol_flw, + sym__br_sgl_pln_int_flw, + sym__br_sgl_pln_flt_flw, + sym__br_sgl_pln_tms_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [8029] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 28, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [8063] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(651), 28, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [8097] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(951), 1, + sym__r_acr_bgn, + ACTIONS(953), 1, + sym__br_acr_bgn, + STATE(258), 2, + sym__r_acr, + sym__br_acr, + ACTIONS(615), 24, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [8137] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(657), 13, + sym__r_flw_seq_bgn, + sym__r_flw_seq_end, + sym__r_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + ACTIONS(653), 15, + sym__br_flw_seq_bgn, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__br_flw_map_bgn, + sym__br_flw_sep_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_flw, + sym__br_sgl_pln_bol_flw, + sym__br_sgl_pln_int_flw, + sym__br_sgl_pln_flt_flw, + sym__br_sgl_pln_tms_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [8173] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(653), 28, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [8207] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(660), 28, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [8241] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(951), 1, + sym__r_acr_bgn, + ACTIONS(953), 1, + sym__br_acr_bgn, + STATE(260), 2, + sym__r_acr, + sym__br_acr, + ACTIONS(627), 24, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [8281] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(660), 27, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [8314] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(651), 27, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [8347] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(653), 27, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [8380] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(651), 27, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [8413] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(657), 12, + sym__r_flw_seq_bgn, + sym__r_flw_seq_end, + sym__r_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + ACTIONS(653), 15, + sym__br_flw_seq_bgn, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__br_flw_map_bgn, + sym__br_flw_sep_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_flw, + sym__br_sgl_pln_bol_flw, + sym__br_sgl_pln_int_flw, + sym__br_sgl_pln_flt_flw, + sym__br_sgl_pln_tms_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [8448] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 27, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [8481] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(653), 27, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [8514] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 27, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [8547] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(657), 12, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + ACTIONS(653), 15, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__br_flw_sep_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_flw, + sym__br_sgl_pln_bol_flw, + sym__br_sgl_pln_int_flw, + sym__br_sgl_pln_flt_flw, + sym__br_sgl_pln_tms_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [8582] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(660), 27, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [8615] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(955), 1, + sym__r_tag, + ACTIONS(957), 1, + sym__br_tag, + ACTIONS(619), 11, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + ACTIONS(615), 13, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_flw_njv_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_flw, + sym__br_sgl_pln_bol_flw, + sym__br_sgl_pln_int_flw, + sym__br_sgl_pln_flt_flw, + sym__br_sgl_pln_tms_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [8653] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(957), 2, + sym__r_tag, + sym__br_tag, + ACTIONS(615), 24, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [8687] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 26, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + sym__r_tag, + sym__br_tag, + [8719] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(651), 26, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + sym__r_tag, + sym__br_tag, + [8751] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(959), 2, + sym__r_tag, + sym__br_tag, + ACTIONS(627), 24, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [8785] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(961), 25, + sym__eof, + sym__s_dir_yml_bgn, + sym__s_dir_tag_bgn, + sym__s_dir_rsv_bgn, + sym__s_drs_end, + sym__s_doc_end, + sym__br_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__br_blk_lit_bgn, + sym__br_blk_fld_bgn, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_blk, + sym__br_sgl_pln_bol_blk, + sym__br_sgl_pln_int_blk, + sym__br_sgl_pln_flt_blk, + sym__br_sgl_pln_tms_blk, + sym__br_sgl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__br_acr_bgn, + sym__br_als_bgn, + [8816] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(963), 25, + sym__eof, + sym__s_dir_yml_bgn, + sym__s_dir_tag_bgn, + sym__s_dir_rsv_bgn, + sym__s_drs_end, + sym__s_doc_end, + sym__br_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__br_blk_lit_bgn, + sym__br_blk_fld_bgn, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_blk, + sym__br_sgl_pln_bol_blk, + sym__br_sgl_pln_int_blk, + sym__br_sgl_pln_flt_blk, + sym__br_sgl_pln_tms_blk, + sym__br_sgl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__br_acr_bgn, + sym__br_als_bgn, + [8847] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(961), 25, + sym__eof, + sym__s_dir_yml_bgn, + sym__s_dir_tag_bgn, + sym__s_dir_rsv_bgn, + sym__s_drs_end, + sym__s_doc_end, + sym__br_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__br_blk_lit_bgn, + sym__br_blk_fld_bgn, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_blk, + sym__br_sgl_pln_bol_blk, + sym__br_sgl_pln_int_blk, + sym__br_sgl_pln_flt_blk, + sym__br_sgl_pln_tms_blk, + sym__br_sgl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__br_acr_bgn, + sym__br_als_bgn, + [8878] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(965), 25, + sym__eof, + sym__s_dir_yml_bgn, + sym__s_dir_tag_bgn, + sym__s_dir_rsv_bgn, + sym__s_drs_end, + sym__s_doc_end, + sym__br_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__br_blk_lit_bgn, + sym__br_blk_fld_bgn, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_blk, + sym__br_sgl_pln_bol_blk, + sym__br_sgl_pln_int_blk, + sym__br_sgl_pln_flt_blk, + sym__br_sgl_pln_tms_blk, + sym__br_sgl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__br_acr_bgn, + sym__br_als_bgn, + [8909] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(967), 25, + sym__eof, + sym__s_dir_yml_bgn, + sym__s_dir_tag_bgn, + sym__s_dir_rsv_bgn, + sym__s_drs_end, + sym__s_doc_end, + sym__br_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__br_blk_lit_bgn, + sym__br_blk_fld_bgn, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_blk, + sym__br_sgl_pln_bol_blk, + sym__br_sgl_pln_int_blk, + sym__br_sgl_pln_flt_blk, + sym__br_sgl_pln_tms_blk, + sym__br_sgl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__br_acr_bgn, + sym__br_als_bgn, + [8940] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(967), 25, + sym__eof, + sym__s_dir_yml_bgn, + sym__s_dir_tag_bgn, + sym__s_dir_rsv_bgn, + sym__s_drs_end, + sym__s_doc_end, + sym__br_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__br_blk_lit_bgn, + sym__br_blk_fld_bgn, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_blk, + sym__br_sgl_pln_bol_blk, + sym__br_sgl_pln_int_blk, + sym__br_sgl_pln_flt_blk, + sym__br_sgl_pln_tms_blk, + sym__br_sgl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__br_acr_bgn, + sym__br_als_bgn, + [8971] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(969), 25, + sym__eof, + sym__s_dir_yml_bgn, + sym__s_dir_tag_bgn, + sym__s_dir_rsv_bgn, + sym__s_drs_end, + sym__s_doc_end, + sym__br_blk_seq_bgn, + sym__br_blk_key_bgn, + sym__br_blk_val_bgn, + sym__br_blk_lit_bgn, + sym__br_blk_fld_bgn, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_blk, + sym__br_sgl_pln_bol_blk, + sym__br_sgl_pln_int_blk, + sym__br_sgl_pln_flt_blk, + sym__br_sgl_pln_tms_blk, + sym__br_sgl_pln_str_blk, + sym__br_mtl_pln_str_blk, + sym__br_tag, + sym__br_acr_bgn, + sym__br_als_bgn, + [9002] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 24, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [9032] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(657), 11, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + ACTIONS(653), 13, + sym__br_flw_seq_bgn, + sym__br_flw_map_bgn, + sym__br_flw_njv_bgn, + sym__br_dqt_str_bgn, + sym__br_sqt_str_bgn, + sym__br_sgl_pln_nul_flw, + sym__br_sgl_pln_bol_flw, + sym__br_sgl_pln_int_flw, + sym__br_sgl_pln_flt_flw, + sym__br_sgl_pln_tms_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [9064] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(653), 24, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [9094] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(651), 24, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [9124] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(660), 24, + sym__r_flw_seq_bgn, + sym__br_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__br_flw_map_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__br_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__br_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__br_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__br_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__br_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__br_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__br_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__br_sgl_pln_str_flw, + sym__r_mtl_pln_str_flw, + sym__br_mtl_pln_str_flw, + [9154] = 12, + ACTIONS(3), 1, + sym_comment, + ACTIONS(770), 1, + sym__r_flw_seq_bgn, + ACTIONS(774), 1, + sym__r_flw_map_bgn, + ACTIONS(780), 1, + sym__r_dqt_str_bgn, + ACTIONS(782), 1, + sym__r_sqt_str_bgn, + STATE(1084), 1, + sym__r_sgl_pln_flw, + STATE(1161), 1, + sym__r_sgl_flw_seq, + STATE(1162), 1, + sym__r_sgl_flw_map, + STATE(1163), 1, + sym__r_sgl_dqt_str, + STATE(1164), 1, + sym__r_sgl_sqt_str, + ACTIONS(971), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + ACTIONS(784), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [9198] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(975), 1, + sym__r_blk_imp_bgn, + STATE(332), 1, + sym__blk_imp_itm_tal, + ACTIONS(973), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9226] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(975), 1, + sym__r_blk_imp_bgn, + STATE(334), 1, + sym__blk_imp_itm_tal, + ACTIONS(977), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9254] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(975), 1, + sym__r_blk_imp_bgn, + STATE(334), 1, + sym__blk_imp_itm_tal, + ACTIONS(973), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9282] = 12, + ACTIONS(3), 1, + sym_comment, + ACTIONS(709), 1, + sym__r_flw_seq_bgn, + ACTIONS(711), 1, + sym__r_flw_map_bgn, + ACTIONS(719), 1, + sym__r_dqt_str_bgn, + ACTIONS(721), 1, + sym__r_sqt_str_bgn, + STATE(1051), 1, + sym__r_sgl_flw_seq, + STATE(1052), 1, + sym__r_sgl_flw_map, + STATE(1053), 1, + sym__r_sgl_dqt_str, + STATE(1054), 1, + sym__r_sgl_sqt_str, + STATE(1171), 1, + sym__r_sgl_pln_flw, + ACTIONS(971), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + ACTIONS(723), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [9326] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(979), 17, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__r_blk_imp_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9349] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(983), 1, + sym__r_blk_imp_bgn, + ACTIONS(981), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9374] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(983), 1, + sym__r_blk_imp_bgn, + ACTIONS(985), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9399] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(989), 1, + sym__r_blk_imp_bgn, + ACTIONS(987), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9424] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(993), 1, + sym__r_blk_imp_bgn, + ACTIONS(991), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9449] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(997), 1, + sym__r_blk_imp_bgn, + ACTIONS(995), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9474] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1001), 1, + sym__r_blk_imp_bgn, + ACTIONS(999), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9499] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1003), 17, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__r_blk_imp_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9522] = 12, + ACTIONS(3), 1, + sym_comment, + ACTIONS(897), 1, + sym__r_flw_seq_bgn, + ACTIONS(901), 1, + sym__r_flw_map_bgn, + ACTIONS(903), 1, + sym__r_dqt_str_bgn, + ACTIONS(905), 1, + sym__r_sqt_str_bgn, + STATE(1231), 1, + sym__r_sgl_flw_seq, + STATE(1232), 1, + sym__r_sgl_flw_map, + STATE(1233), 1, + sym__r_sgl_dqt_str, + STATE(1234), 1, + sym__r_sgl_sqt_str, + STATE(1269), 1, + sym__r_sgl_pln_flw, + ACTIONS(971), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + ACTIONS(907), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [9565] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1005), 17, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__r_blk_imp_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9588] = 12, + ACTIONS(3), 1, + sym_comment, + ACTIONS(915), 1, + sym__r_flw_seq_bgn, + ACTIONS(917), 1, + sym__r_flw_map_bgn, + ACTIONS(919), 1, + sym__r_dqt_str_bgn, + ACTIONS(921), 1, + sym__r_sqt_str_bgn, + STATE(1236), 1, + sym__r_sgl_pln_flw, + STATE(1354), 1, + sym__r_sgl_flw_seq, + STATE(1357), 1, + sym__r_sgl_flw_map, + STATE(1358), 1, + sym__r_sgl_dqt_str, + STATE(1360), 1, + sym__r_sgl_sqt_str, + ACTIONS(971), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + ACTIONS(923), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [9631] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(689), 1, + sym__b_blk_val_bgn, + STATE(329), 1, + sym__b_blk_val_itm, + ACTIONS(1007), 15, + sym__b_blk_key_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9658] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(689), 1, + sym__b_blk_val_bgn, + STATE(331), 1, + sym__b_blk_val_itm, + ACTIONS(1009), 15, + sym__b_blk_key_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9685] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(689), 1, + sym__b_blk_val_bgn, + STATE(306), 1, + sym__b_blk_val_itm, + ACTIONS(1011), 15, + sym__b_blk_key_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9712] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1013), 17, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__r_blk_imp_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9735] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1017), 1, + sym__r_blk_imp_bgn, + ACTIONS(1015), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9760] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(983), 1, + sym__r_blk_imp_bgn, + ACTIONS(1019), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9785] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1021), 17, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__r_blk_imp_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9808] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1025), 1, + sym__r_blk_imp_bgn, + ACTIONS(1023), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9833] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1029), 1, + sym__r_blk_imp_bgn, + ACTIONS(1027), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9858] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1033), 1, + sym__r_blk_imp_bgn, + ACTIONS(1031), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9883] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1037), 1, + sym__r_blk_imp_bgn, + ACTIONS(1035), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9908] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1041), 1, + sym__r_blk_imp_bgn, + ACTIONS(1039), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9933] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1045), 1, + sym__r_blk_imp_bgn, + ACTIONS(1043), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9958] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1047), 17, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__r_blk_imp_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [9981] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1049), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10003] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1051), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10025] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1053), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10047] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1055), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10069] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1057), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10091] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1059), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10113] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1061), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10135] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1063), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10157] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1065), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10179] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(977), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10201] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1067), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10223] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1069), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10245] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1071), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10267] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1073), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10289] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1075), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10311] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1077), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10333] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1079), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10355] = 12, + ACTIONS(3), 1, + sym_comment, + ACTIONS(971), 1, + sym__r_blk_imp_bgn, + ACTIONS(1081), 1, + sym__r_flw_seq_bgn, + ACTIONS(1083), 1, + sym__r_flw_map_bgn, + ACTIONS(1085), 1, + sym__r_dqt_str_bgn, + ACTIONS(1087), 1, + sym__r_sqt_str_bgn, + STATE(1521), 1, + sym__r_sgl_flw_seq, + STATE(1523), 1, + sym__r_sgl_flw_map, + STATE(1524), 1, + sym__r_sgl_dqt_str, + STATE(1528), 1, + sym__r_sgl_sqt_str, + STATE(1529), 1, + sym__r_sgl_pln_blk, + ACTIONS(1089), 6, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + [10397] = 12, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1081), 1, + sym__r_flw_seq_bgn, + ACTIONS(1083), 1, + sym__r_flw_map_bgn, + ACTIONS(1085), 1, + sym__r_dqt_str_bgn, + ACTIONS(1087), 1, + sym__r_sqt_str_bgn, + ACTIONS(1091), 1, + sym__r_blk_imp_bgn, + STATE(1530), 1, + sym__r_sgl_flw_seq, + STATE(1531), 1, + sym__r_sgl_flw_map, + STATE(1533), 1, + sym__r_sgl_dqt_str, + STATE(1536), 1, + sym__r_sgl_sqt_str, + STATE(1537), 1, + sym__r_sgl_pln_blk, + ACTIONS(1089), 6, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + [10439] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1093), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10461] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1095), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10483] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1097), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10505] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1099), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10527] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1101), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10549] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1003), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10571] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1103), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10593] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1105), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10615] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1107), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10637] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1109), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10659] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1111), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10681] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1113), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10703] = 12, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1081), 1, + sym__r_flw_seq_bgn, + ACTIONS(1083), 1, + sym__r_flw_map_bgn, + ACTIONS(1085), 1, + sym__r_dqt_str_bgn, + ACTIONS(1087), 1, + sym__r_sqt_str_bgn, + ACTIONS(1115), 1, + sym__r_blk_imp_bgn, + STATE(1415), 1, + sym__r_sgl_dqt_str, + STATE(1418), 1, + sym__r_sgl_sqt_str, + STATE(1419), 1, + sym__r_sgl_pln_blk, + STATE(1491), 1, + sym__r_sgl_flw_seq, + STATE(1492), 1, + sym__r_sgl_flw_map, + ACTIONS(1089), 6, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + [10745] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1117), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10767] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(987), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10789] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1119), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10811] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1117), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10833] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1121), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10855] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1123), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10877] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1125), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10899] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(979), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10921] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1127), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10943] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1099), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10965] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1005), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [10987] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1101), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11009] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(985), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11031] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1129), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11053] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1131), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11075] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1133), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11097] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1135), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11119] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1137), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11141] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1139), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11163] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1141), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11185] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1143), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11207] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1145), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11229] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1147), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11251] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1149), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11273] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1151), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11295] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1153), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11317] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1155), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11339] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1157), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11361] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1159), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11383] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1161), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11405] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1163), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11427] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(991), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11449] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1165), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11471] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1015), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11493] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1019), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11515] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1167), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11537] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1169), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11559] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1107), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11581] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1171), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11603] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1173), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11625] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(995), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11647] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1109), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11669] = 12, + ACTIONS(3), 1, + sym_comment, + ACTIONS(865), 1, + sym__r_flw_seq_bgn, + ACTIONS(867), 1, + sym__r_flw_map_bgn, + ACTIONS(871), 1, + sym__r_dqt_str_bgn, + ACTIONS(873), 1, + sym__r_sqt_str_bgn, + ACTIONS(971), 1, + sym__r_flw_njv_bgn, + STATE(1466), 1, + sym__r_sgl_flw_map, + STATE(1469), 1, + sym__r_sgl_dqt_str, + STATE(1470), 1, + sym__r_sgl_pln_flw, + STATE(1482), 1, + sym__r_sgl_sqt_str, + STATE(1535), 1, + sym__r_sgl_flw_seq, + ACTIONS(875), 6, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [11711] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1175), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11733] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1177), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11755] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1179), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11777] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1181), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11799] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1183), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11821] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(999), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11843] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1031), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11865] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1035), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11887] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1039), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11909] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1185), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11931] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1043), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11953] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1187), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11975] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1189), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [11997] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1191), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [12019] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1193), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [12041] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1195), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [12063] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1197), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [12085] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1199), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [12107] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1201), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [12129] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1203), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [12151] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(981), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [12173] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1205), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [12195] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1207), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [12217] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1209), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [12239] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1211), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [12261] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1213), 16, + sym__b_blk_key_bgn, + sym__b_blk_val_bgn, + sym__b_flw_seq_bgn, + sym__b_flw_map_bgn, + sym__b_dqt_str_bgn, + sym__b_sqt_str_bgn, + sym__b_sgl_pln_nul_blk, + sym__b_sgl_pln_bol_blk, + sym__b_sgl_pln_int_blk, + sym__b_sgl_pln_flt_blk, + sym__b_sgl_pln_tms_blk, + sym__b_sgl_pln_str_blk, + sym__b_tag, + sym__b_acr_bgn, + sym__b_als_bgn, + sym__bl, + [12283] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1215), 1, + sym__r_acr_bgn, + STATE(406), 1, + sym__r_acr, + ACTIONS(617), 13, + sym__r_flw_seq_bgn, + sym__r_flw_seq_end, + sym__r_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [12308] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1217), 1, + sym__r_acr_bgn, + STATE(408), 1, + sym__r_acr, + ACTIONS(617), 13, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [12333] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1219), 1, + sym__r_acr_bgn, + STATE(419), 1, + sym__r_acr, + ACTIONS(617), 12, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [12357] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1221), 1, + sym__r_tag, + ACTIONS(617), 13, + sym__r_flw_seq_bgn, + sym__r_flw_seq_end, + sym__r_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [12379] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1223), 1, + sym__r_acr_bgn, + STATE(417), 1, + sym__r_acr, + ACTIONS(617), 12, + sym__r_flw_seq_bgn, + sym__r_flw_seq_end, + sym__r_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [12403] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 14, + sym__r_flw_seq_bgn, + sym__r_flw_seq_end, + sym__r_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__r_tag, + [12423] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1225), 1, + sym__r_tag, + ACTIONS(617), 13, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [12445] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 14, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__r_tag, + [12465] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 13, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [12484] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1227), 1, + sym__r_tag, + ACTIONS(617), 12, + sym__r_flw_seq_bgn, + sym__r_flw_seq_end, + sym__r_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [12505] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 13, + sym__r_flw_seq_bgn, + sym__r_flw_seq_end, + sym__r_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [12524] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1229), 1, + sym__r_acr_bgn, + STATE(445), 1, + sym__r_acr, + ACTIONS(617), 11, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [12547] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1231), 1, + sym__r_tag, + ACTIONS(617), 12, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [12568] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1235), 1, + sym__r_acr_bgn, + STATE(425), 1, + sym__r_acr, + ACTIONS(1233), 11, + sym__r_blk_imp_bgn, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + [12591] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(655), 13, + sym__r_flw_seq_bgn, + sym__r_flw_seq_end, + sym__r_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [12610] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 13, + sym__r_flw_seq_bgn, + sym__r_flw_seq_end, + sym__r_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__r_tag, + [12629] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(655), 13, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [12648] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1235), 1, + sym__r_acr_bgn, + STATE(469), 1, + sym__r_acr, + ACTIONS(629), 11, + sym__r_blk_imp_bgn, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + [12671] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 13, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__r_tag, + [12690] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 12, + sym__r_flw_seq_bgn, + sym__r_flw_seq_end, + sym__r_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [12708] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 12, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + sym__r_tag, + [12726] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1237), 1, + sym__r_tag, + ACTIONS(617), 11, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [12746] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 12, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [12764] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1239), 1, + sym__r_tag, + ACTIONS(629), 11, + sym__r_blk_imp_bgn, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + [12784] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1241), 12, + sym__r_blk_imp_bgn, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__r_tag, + [12802] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(655), 12, + sym__r_flw_seq_bgn, + sym__r_flw_seq_end, + sym__r_flw_map_bgn, + sym__r_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [12820] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(651), 12, + sym__r_blk_imp_bgn, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + sym__r_tag, + [12838] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(655), 12, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [12856] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1243), 1, + sym__r_tag, + ACTIONS(1233), 11, + sym__r_blk_imp_bgn, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + [12876] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1249), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1251), 1, + sym__br_dqt_esc_nwl, + STATE(458), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1245), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1253), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(633), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [12905] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1257), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1259), 1, + sym__br_dqt_esc_nwl, + STATE(502), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1255), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1261), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(587), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [12934] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1263), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1265), 1, + sym__br_dqt_esc_nwl, + STATE(502), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1255), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1267), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(619), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [12963] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 11, + sym__r_blk_imp_bgn, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + [12980] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1269), 11, + sym__r_blk_imp_bgn, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + [12997] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1271), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1273), 1, + sym__br_dqt_esc_nwl, + STATE(502), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1255), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1275), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(589), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13026] = 9, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1279), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1281), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1283), 1, + sym__r_dqt_str_end, + ACTIONS(1285), 1, + sym__br_dqt_str_end, + STATE(432), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1277), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(543), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13057] = 9, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1289), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1291), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1293), 1, + sym__r_dqt_str_end, + ACTIONS(1295), 1, + sym__br_dqt_str_end, + STATE(433), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1287), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(546), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13088] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1299), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1301), 1, + sym__br_dqt_esc_nwl, + STATE(435), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1297), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1303), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(607), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13117] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1307), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1309), 1, + sym__br_dqt_esc_nwl, + STATE(455), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1305), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1311), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(629), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13146] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1315), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1317), 1, + sym__br_dqt_esc_nwl, + STATE(436), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1313), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1319), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(635), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13175] = 9, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1321), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1323), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1325), 1, + sym__r_dqt_str_end, + ACTIONS(1327), 1, + sym__br_dqt_str_end, + STATE(502), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1255), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(557), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13206] = 9, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1329), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1331), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1333), 1, + sym__r_dqt_str_end, + ACTIONS(1335), 1, + sym__br_dqt_str_end, + STATE(502), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1255), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(559), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13237] = 9, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1337), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1339), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1341), 1, + sym__r_dqt_str_end, + ACTIONS(1343), 1, + sym__br_dqt_str_end, + STATE(502), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1255), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(582), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13268] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1345), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1347), 1, + sym__br_dqt_esc_nwl, + STATE(502), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1255), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1349), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(617), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13297] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1351), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1353), 1, + sym__br_dqt_esc_nwl, + STATE(502), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1255), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1355), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(643), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13326] = 9, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1359), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1361), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1363), 1, + sym__r_dqt_str_end, + ACTIONS(1365), 1, + sym__br_dqt_str_end, + STATE(442), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1357), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(577), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13357] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(649), 11, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [13374] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1369), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1371), 1, + sym__br_dqt_esc_nwl, + STATE(444), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1367), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1373), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(627), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13403] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1377), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1379), 1, + sym__br_dqt_esc_nwl, + STATE(426), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1375), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1381), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(579), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13432] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1385), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1387), 1, + sym__br_dqt_esc_nwl, + STATE(473), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1383), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1389), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(659), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13461] = 9, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1257), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1259), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1261), 1, + sym__br_dqt_str_end, + ACTIONS(1391), 1, + sym__r_dqt_str_end, + STATE(502), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1255), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(587), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13492] = 9, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1307), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1309), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1311), 1, + sym__br_dqt_str_end, + ACTIONS(1395), 1, + sym__r_dqt_str_end, + STATE(460), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1393), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(629), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13523] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1397), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1399), 1, + sym__br_dqt_esc_nwl, + STATE(502), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1255), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1401), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(650), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13552] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(655), 11, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_flw_njv_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_flw, + sym__r_sgl_pln_bol_flw, + sym__r_sgl_pln_int_flw, + sym__r_sgl_pln_flt_flw, + sym__r_sgl_pln_tms_flw, + sym__r_sgl_pln_str_flw, + [13569] = 9, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1369), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1371), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1373), 1, + sym__br_dqt_str_end, + ACTIONS(1405), 1, + sym__r_dqt_str_end, + STATE(465), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1403), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(627), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13600] = 9, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1409), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1411), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1413), 1, + sym__r_dqt_str_end, + ACTIONS(1415), 1, + sym__br_dqt_str_end, + STATE(467), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1407), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(630), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13631] = 9, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1299), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1301), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1303), 1, + sym__br_dqt_str_end, + ACTIONS(1419), 1, + sym__r_dqt_str_end, + STATE(451), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1417), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(607), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13662] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1279), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1281), 1, + sym__br_dqt_esc_nwl, + STATE(452), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1285), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + ACTIONS(1421), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(543), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13691] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1425), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1427), 1, + sym__br_dqt_esc_nwl, + STATE(453), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1423), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1429), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(682), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13720] = 9, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1345), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1347), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1349), 1, + sym__br_dqt_str_end, + ACTIONS(1431), 1, + sym__r_dqt_str_end, + STATE(502), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1255), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(617), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13751] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1321), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1323), 1, + sym__br_dqt_esc_nwl, + STATE(502), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1255), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1327), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(557), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13780] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1433), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1435), 1, + sym__br_dqt_esc_nwl, + STATE(502), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1255), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1437), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(688), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13809] = 9, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1249), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1251), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1253), 1, + sym__br_dqt_str_end, + ACTIONS(1441), 1, + sym__r_dqt_str_end, + STATE(456), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1439), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(633), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13840] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1443), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1445), 1, + sym__br_dqt_esc_nwl, + STATE(502), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1255), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1447), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(685), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13869] = 9, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1449), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1451), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1453), 1, + sym__r_dqt_str_end, + ACTIONS(1455), 1, + sym__br_dqt_str_end, + STATE(502), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1255), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(641), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13900] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1359), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1361), 1, + sym__br_dqt_esc_nwl, + STATE(422), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1365), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + ACTIONS(1457), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(577), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13929] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1449), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1451), 1, + sym__br_dqt_esc_nwl, + STATE(502), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1255), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1455), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(641), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13958] = 9, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1461), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1463), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1465), 1, + sym__r_dqt_str_end, + ACTIONS(1467), 1, + sym__br_dqt_str_end, + STATE(434), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1459), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(647), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [13989] = 9, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1443), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1445), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1447), 1, + sym__br_dqt_str_end, + ACTIONS(1469), 1, + sym__r_dqt_str_end, + STATE(502), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1255), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(685), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [14020] = 9, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1473), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1475), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1477), 1, + sym__r_dqt_str_end, + ACTIONS(1479), 1, + sym__br_dqt_str_end, + STATE(464), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1471), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(657), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [14051] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1483), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1485), 1, + sym__br_dqt_esc_nwl, + STATE(423), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1481), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1487), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(609), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [14080] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1473), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1475), 1, + sym__br_dqt_esc_nwl, + STATE(466), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1479), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + ACTIONS(1489), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(657), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [14109] = 9, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1491), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1493), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1495), 1, + sym__r_dqt_str_end, + ACTIONS(1497), 1, + sym__br_dqt_str_end, + STATE(502), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1255), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(664), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [14140] = 9, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1397), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1399), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1401), 1, + sym__br_dqt_str_end, + ACTIONS(1499), 1, + sym__r_dqt_str_end, + STATE(502), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1255), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(650), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [14171] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1491), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1493), 1, + sym__br_dqt_esc_nwl, + STATE(502), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1255), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1497), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(664), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [14200] = 9, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1501), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1503), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1505), 1, + sym__r_dqt_str_end, + ACTIONS(1507), 1, + sym__br_dqt_str_end, + STATE(502), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1255), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(652), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [14231] = 9, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1511), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1513), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1515), 1, + sym__r_dqt_str_end, + ACTIONS(1517), 1, + sym__br_dqt_str_end, + STATE(471), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1509), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(680), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [14262] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(662), 11, + sym__r_blk_imp_bgn, + sym__r_flw_seq_bgn, + sym__r_flw_map_bgn, + sym__r_dqt_str_bgn, + sym__r_sqt_str_bgn, + sym__r_sgl_pln_nul_blk, + sym__r_sgl_pln_bol_blk, + sym__r_sgl_pln_int_blk, + sym__r_sgl_pln_flt_blk, + sym__r_sgl_pln_tms_blk, + sym__r_sgl_pln_str_blk, + [14279] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1511), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1513), 1, + sym__br_dqt_esc_nwl, + STATE(472), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1517), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + ACTIONS(1519), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(680), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [14308] = 9, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1521), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1523), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1525), 1, + sym__r_dqt_str_end, + ACTIONS(1527), 1, + sym__br_dqt_str_end, + STATE(502), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1255), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + STATE(686), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [14339] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1521), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1523), 1, + sym__br_dqt_esc_nwl, + STATE(502), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1255), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1527), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(686), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [14368] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1529), 1, + sym__r_dqt_esc_nwl, + ACTIONS(1531), 1, + sym__br_dqt_esc_nwl, + STATE(502), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1255), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1533), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(666), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [14397] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(13), 1, + sym__s_drs_end, + ACTIONS(379), 1, + sym__eof, + ACTIONS(1535), 1, + sym__s_doc_end, + STATE(476), 1, + sym__doc_w_bgn_wo_end, + STATE(1155), 1, + sym__exp_doc, + STATE(1428), 2, + sym__doc_w_bgn_w_end_seq, + sym__doc_w_bgn_wo_end_seq, + STATE(38), 3, + sym__doc_w_bgn_w_end, + sym__exp_doc_end, + sym__doc_end, + [14425] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(221), 1, + sym__r_flw_njv_bgn, + ACTIONS(223), 1, + sym__br_flw_njv_bgn, + STATE(793), 1, + sym__br_flw_njl_ann_par, + STATE(943), 1, + sym__r_flw_njl_ann_par, + STATE(1337), 1, + sym__r_sgl_flw_njl_ann_par, + ACTIONS(1537), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + ACTIONS(1540), 3, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__br_flw_sep_bgn, + [14453] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(13), 1, + sym__s_drs_end, + ACTIONS(15), 1, + sym__s_doc_end, + ACTIONS(1542), 1, + sym__eof, + STATE(476), 1, + sym__doc_w_bgn_wo_end, + STATE(1155), 1, + sym__exp_doc, + STATE(1526), 2, + sym__doc_w_bgn_w_end_seq, + sym__doc_w_bgn_wo_end_seq, + STATE(38), 3, + sym__doc_w_bgn_w_end, + sym__exp_doc_end, + sym__doc_end, + [14481] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(13), 1, + sym__s_drs_end, + ACTIONS(379), 1, + sym__eof, + ACTIONS(1544), 1, + sym__s_doc_end, + STATE(476), 1, + sym__doc_w_bgn_wo_end, + STATE(1155), 1, + sym__exp_doc, + STATE(1428), 2, + sym__doc_w_bgn_w_end_seq, + sym__doc_w_bgn_wo_end_seq, + STATE(38), 3, + sym__doc_w_bgn_w_end, + sym__exp_doc_end, + sym__doc_end, + [14509] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(7), 1, + sym__s_dir_yml_bgn, + ACTIONS(9), 1, + sym__s_dir_tag_bgn, + ACTIONS(11), 1, + sym__s_dir_rsv_bgn, + ACTIONS(13), 1, + sym__s_drs_end, + STATE(1085), 1, + sym__exp_doc, + STATE(522), 5, + sym__s_dir, + sym__s_dir_yml, + sym__s_dir_tag, + sym__s_dir_rsv, + aux_sym__drs_doc_repeat1, + [14535] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(13), 1, + sym__s_drs_end, + ACTIONS(379), 1, + sym__eof, + ACTIONS(1546), 1, + sym__s_doc_end, + STATE(476), 1, + sym__doc_w_bgn_wo_end, + STATE(1155), 1, + sym__exp_doc, + STATE(1428), 2, + sym__doc_w_bgn_w_end_seq, + sym__doc_w_bgn_wo_end_seq, + STATE(38), 3, + sym__doc_w_bgn_w_end, + sym__exp_doc_end, + sym__doc_end, + [14563] = 8, + ACTIONS(3), 1, + sym_comment, + ACTIONS(13), 1, + sym__s_drs_end, + ACTIONS(15), 1, + sym__s_doc_end, + ACTIONS(1548), 1, + sym__eof, + STATE(476), 1, + sym__doc_w_bgn_wo_end, + STATE(1155), 1, + sym__exp_doc, + STATE(1490), 2, + sym__doc_w_bgn_w_end_seq, + sym__doc_w_bgn_wo_end_seq, + STATE(38), 3, + sym__doc_w_bgn_w_end, + sym__exp_doc_end, + sym__doc_end, + [14591] = 4, + ACTIONS(3), 1, + sym_comment, + STATE(481), 1, + aux_sym__br_mtl_dqt_ctn_repeat1, + ACTIONS(1550), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1553), 6, + sym__br_dqt_str_ctn, + sym__r_dqt_esc_nwl, + sym__br_dqt_esc_nwl, + sym__br_dqt_esc_seq, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + [14610] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1559), 1, + sym__r_sqt_str_end, + ACTIONS(1561), 1, + sym__br_sqt_str_end, + STATE(526), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1555), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + STATE(755), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [14635] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1565), 1, + sym__r_sqt_str_end, + ACTIONS(1567), 1, + sym__br_sqt_str_end, + STATE(529), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1563), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(756), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [14660] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(615), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1569), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1571), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(779), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [14683] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(495), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1573), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1575), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(761), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [14706] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1581), 1, + sym__r_dqt_esc_nwl, + STATE(499), 1, + aux_sym__br_mtl_dqt_ctn_repeat1, + ACTIONS(1577), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1579), 5, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_nwl, + sym__br_dqt_esc_seq, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + [14727] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1575), 1, + sym__br_sqt_str_end, + ACTIONS(1585), 1, + sym__r_sqt_str_end, + STATE(488), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1583), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(761), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [14752] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1587), 1, + sym__r_sqt_str_end, + ACTIONS(1589), 1, + sym__br_sqt_str_end, + STATE(615), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1569), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(763), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [14777] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(497), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1591), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1593), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(781), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [14800] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(508), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1595), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1597), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(754), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [14823] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1599), 1, + sym__r_sqt_str_end, + ACTIONS(1601), 1, + sym__br_sqt_str_end, + STATE(615), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1569), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(771), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [14848] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(223), 1, + sym__br_flw_njv_bgn, + ACTIONS(434), 1, + sym__r_flw_njv_bgn, + STATE(937), 1, + sym__r_flw_njl_ann_par, + STATE(956), 1, + sym__br_flw_njl_ann_par, + ACTIONS(1540), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [14871] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(223), 1, + sym__br_flw_njv_bgn, + ACTIONS(434), 1, + sym__r_flw_njv_bgn, + STATE(938), 1, + sym__r_flw_njl_ann_par, + STATE(961), 1, + sym__br_flw_njl_ann_par, + ACTIONS(1603), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [14894] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1607), 1, + sym__r_sqt_str_end, + ACTIONS(1609), 1, + sym__br_sqt_str_end, + STATE(503), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1605), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(762), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [14919] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(615), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1569), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1589), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(763), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [14942] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(615), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1569), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1611), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(768), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [14965] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(615), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1569), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1613), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(741), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [14988] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1615), 1, + sym__r_flw_jsv_bgn, + ACTIONS(1617), 1, + sym__br_flw_jsv_bgn, + STATE(787), 1, + sym__br_flw_jsl_ann_par, + STATE(940), 1, + sym__r_flw_jsl_ann_par, + ACTIONS(1540), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [15011] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1623), 1, + sym__r_dqt_esc_nwl, + STATE(481), 1, + aux_sym__br_mtl_dqt_ctn_repeat1, + ACTIONS(1619), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1621), 5, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_nwl, + sym__br_dqt_esc_seq, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + [15032] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(615), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1569), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1601), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(771), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15055] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1627), 1, + sym__r_sqt_str_end, + ACTIONS(1629), 1, + sym__br_sqt_str_end, + STATE(507), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1625), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(773), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15080] = 4, + ACTIONS(3), 1, + sym_comment, + STATE(502), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(1631), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + ACTIONS(1634), 6, + sym__br_dqt_str_ctn, + sym__r_dqt_esc_nwl, + sym__br_dqt_esc_nwl, + sym__br_dqt_esc_seq, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + [15099] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1636), 1, + sym__r_sqt_str_end, + ACTIONS(1638), 1, + sym__br_sqt_str_end, + STATE(615), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1569), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(764), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15124] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1615), 1, + sym__r_flw_jsv_bgn, + ACTIONS(1617), 1, + sym__br_flw_jsv_bgn, + STATE(788), 1, + sym__br_flw_jsl_ann_par, + STATE(941), 1, + sym__r_flw_jsl_ann_par, + ACTIONS(1603), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [15147] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(510), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1629), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + ACTIONS(1640), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(773), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15170] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(615), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1569), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1642), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(776), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15193] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1644), 1, + sym__r_sqt_str_end, + ACTIONS(1646), 1, + sym__br_sqt_str_end, + STATE(615), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1569), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(775), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15218] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(615), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1569), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1648), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(750), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15241] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(506), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1650), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1652), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(774), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15264] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(615), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1569), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1646), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(775), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15287] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(535), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1654), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1656), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(765), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15310] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1658), 1, + sym__r_sqt_str_end, + ACTIONS(1660), 1, + sym__br_sqt_str_end, + STATE(615), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1569), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(752), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15335] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1656), 1, + sym__br_sqt_str_end, + ACTIONS(1664), 1, + sym__r_sqt_str_end, + STATE(531), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1662), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(765), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15360] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1668), 1, + sym__r_sqt_str_end, + ACTIONS(1670), 1, + sym__br_sqt_str_end, + STATE(491), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1666), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(769), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15385] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1674), 1, + sym__r_sqt_str_end, + ACTIONS(1676), 1, + sym__br_sqt_str_end, + STATE(521), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1672), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(777), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15410] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1597), 1, + sym__br_sqt_str_end, + ACTIONS(1680), 1, + sym__r_sqt_str_end, + STATE(518), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1678), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(754), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15435] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(530), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1682), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1684), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(770), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15458] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1648), 1, + sym__br_sqt_str_end, + ACTIONS(1686), 1, + sym__r_sqt_str_end, + STATE(615), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1569), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(750), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15483] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(524), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1676), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + ACTIONS(1688), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(777), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15506] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(537), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1561), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + ACTIONS(1690), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(755), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15529] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1692), 1, + sym__r_sqt_str_end, + ACTIONS(1694), 1, + sym__br_sqt_str_end, + STATE(615), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1569), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(778), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15554] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1696), 1, + sym__s_dir_yml_bgn, + ACTIONS(1699), 1, + sym__s_dir_tag_bgn, + ACTIONS(1702), 1, + sym__s_dir_rsv_bgn, + ACTIONS(1705), 1, + sym__s_drs_end, + STATE(522), 5, + sym__s_dir, + sym__s_dir_yml, + sym__s_dir_tag, + sym__s_dir_rsv, + aux_sym__drs_doc_repeat1, + [15577] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(500), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1670), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + ACTIONS(1707), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(769), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15600] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(615), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1569), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1694), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(778), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15623] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1711), 1, + sym__r_sqt_str_end, + ACTIONS(1713), 1, + sym__br_sqt_str_end, + STATE(512), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1709), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(757), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15648] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1715), 1, + sym__r_sqt_str_end, + ACTIONS(1717), 1, + sym__br_sqt_str_end, + STATE(615), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1569), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(759), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15673] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(484), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1719), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1721), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(693), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15696] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1725), 1, + sym__r_sqt_str_end, + ACTIONS(1727), 1, + sym__br_sqt_str_end, + STATE(534), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1723), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(780), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15721] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1729), 1, + sym__r_sqt_str_end, + ACTIONS(1731), 1, + sym__br_sqt_str_end, + STATE(615), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1569), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(760), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15746] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(615), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1569), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1733), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(772), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15769] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1735), 1, + sym__r_sqt_str_end, + ACTIONS(1737), 1, + sym__br_sqt_str_end, + STATE(615), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1569), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(767), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15794] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(536), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1727), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + ACTIONS(1739), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(780), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15817] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(496), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1741), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1743), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(766), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15840] = 7, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1745), 1, + sym__r_sqt_str_end, + ACTIONS(1747), 1, + sym__br_sqt_str_end, + STATE(615), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1569), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + STATE(782), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15865] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(615), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1569), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1737), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(767), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15888] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(615), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1569), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1747), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(782), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15911] = 6, + ACTIONS(3), 1, + sym_comment, + STATE(615), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1569), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1717), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(759), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [15934] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(303), 1, + sym__r_flw_njv_bgn, + STATE(922), 1, + sym__r_flw_njl_ann_par, + STATE(1335), 1, + sym__r_sgl_flw_njl_ann_par, + ACTIONS(1749), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + ACTIONS(1752), 3, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__br_flw_sep_bgn, + [15956] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1756), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [15975] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1151), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [15988] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1323), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1327), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(557), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16007] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1153), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [16020] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1327), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16039] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1331), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1335), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(559), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16058] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1155), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [16071] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1335), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16090] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1157), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [16103] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1159), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [16116] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1161), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [16129] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1163), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [16142] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1021), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [16155] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1760), 2, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + STATE(552), 2, + sym__flw_seq_dat_rpt, + aux_sym__r_flw_seq_dat_repeat1, + ACTIONS(1758), 3, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + [16172] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1763), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1765), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(584), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16191] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1767), 1, + sym__r_flw_jsv_bgn, + STATE(950), 1, + sym__r_flw_jsl_ann_par, + ACTIONS(1752), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [16208] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1769), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + ACTIONS(1023), 4, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__br_flw_sep_bgn, + sym__br_flw_jsv_bgn, + [16223] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1772), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + ACTIONS(1775), 4, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__br_flw_sep_bgn, + sym__br_flw_njv_bgn, + [16238] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1777), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16257] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1779), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1777), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(561), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16276] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1781), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16295] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1783), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1781), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(562), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16314] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1785), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16333] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1787), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16352] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1789), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [16365] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1775), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [16378] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1794), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1791), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1797), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16397] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1175), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [16410] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1801), 2, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + STATE(567), 2, + sym__flw_map_dat_rpt, + aux_sym__r_flw_map_dat_repeat1, + ACTIONS(1799), 3, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + [16427] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1177), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [16440] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1804), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + ACTIONS(1027), 4, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__br_flw_sep_bgn, + sym__br_flw_jsv_bgn, + [16455] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1181), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [16468] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1183), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [16481] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1807), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + ACTIONS(1031), 4, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__br_flw_sep_bgn, + sym__br_flw_jsv_bgn, + [16496] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1031), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [16509] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1035), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [16522] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1259), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1261), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(587), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16541] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1810), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + ACTIONS(1039), 4, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__br_flw_sep_bgn, + sym__br_flw_jsv_bgn, + [16556] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1261), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16575] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1273), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1275), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(589), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16594] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1275), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16613] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1039), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [16626] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1043), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [16639] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1813), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16658] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1815), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1813), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(585), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16677] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1817), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16696] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1819), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16715] = 4, + ACTIONS(3), 1, + sym_comment, + STATE(586), 1, + aux_sym__br_mtl_sqt_ctn_repeat1, + ACTIONS(1821), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1824), 4, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + [16732] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1826), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16751] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1828), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1826), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(591), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16770] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1830), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16789] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1832), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1830), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(592), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16808] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1834), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16827] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1836), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [16846] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1047), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [16859] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1197), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [16872] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1199), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [16885] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1201), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [16898] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1203), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [16911] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1189), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [16924] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1121), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [16937] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1063), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [16950] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1165), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [16963] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1111), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [16976] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1113), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [16989] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(987), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [17002] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1347), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1349), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(617), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17021] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1838), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + ACTIONS(987), 4, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__br_flw_sep_bgn, + sym__br_flw_jsv_bgn, + [17036] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1349), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17055] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1265), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1267), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(619), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17074] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1267), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17093] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(991), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [17106] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1841), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + ACTIONS(995), 4, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__br_flw_sep_bgn, + sym__br_flw_jsv_bgn, + [17121] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(995), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [17134] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(999), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [17147] = 4, + ACTIONS(3), 1, + sym_comment, + STATE(586), 1, + aux_sym__br_mtl_sqt_ctn_repeat1, + ACTIONS(1844), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1846), 4, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + [17164] = 4, + ACTIONS(3), 1, + sym_comment, + STATE(615), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(1848), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1851), 4, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + [17181] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1053), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [17194] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1853), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17213] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1855), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1853), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(621), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17232] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1857), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17251] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1859), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1857), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(622), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17270] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1861), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17289] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1863), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17308] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1149), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [17321] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1057), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [17334] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1399), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1401), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(650), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17353] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1059), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [17366] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1401), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17385] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1503), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1507), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(652), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17404] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1447), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17423] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1507), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17442] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1451), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1455), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(641), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17461] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1061), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [17474] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1455), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17493] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1353), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1355), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(643), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17512] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1355), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17531] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1213), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [17544] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1865), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [17557] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(979), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [17570] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1867), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [17583] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1339), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1343), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(582), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17602] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1869), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17621] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1871), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1869), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(539), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17640] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1873), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17659] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1875), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1873), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(646), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17678] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1767), 1, + sym__r_flw_jsv_bgn, + STATE(952), 1, + sym__r_flw_jsl_ann_par, + ACTIONS(1877), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [17695] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1879), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17714] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1343), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17733] = 4, + ACTIONS(3), 1, + sym_comment, + STATE(614), 1, + aux_sym__br_mtl_sqt_ctn_repeat1, + ACTIONS(1881), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + ACTIONS(1883), 4, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + [17750] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1887), 2, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + STATE(660), 2, + sym__flw_seq_dat_rpt, + aux_sym__r_flw_seq_dat_repeat1, + ACTIONS(1885), 3, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + [17767] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1889), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17786] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1891), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1889), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(654), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17805] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1893), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17824] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1895), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1893), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(656), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17843] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1897), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17862] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1493), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1497), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(664), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17881] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1899), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17900] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1497), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17919] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1531), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1533), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(666), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17938] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1533), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [17957] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1901), 2, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + STATE(552), 2, + sym__flw_seq_dat_rpt, + aux_sym__r_flw_seq_dat_repeat1, + ACTIONS(559), 3, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + [17974] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1905), 2, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + STATE(663), 2, + sym__flw_seq_dat_rpt, + aux_sym__r_flw_seq_dat_repeat1, + ACTIONS(1903), 3, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + [17991] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1005), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [18004] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1907), 2, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + STATE(552), 2, + sym__flw_seq_dat_rpt, + aux_sym__r_flw_seq_dat_repeat1, + ACTIONS(561), 3, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + [18021] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1909), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [18040] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1911), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1909), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(668), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [18059] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1913), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [18078] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1915), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1913), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(669), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [18097] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1917), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [18116] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1919), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [18135] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1923), 2, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + STATE(673), 2, + sym__flw_map_dat_rpt, + aux_sym__r_flw_map_dat_repeat1, + ACTIONS(1921), 3, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + [18152] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1927), 2, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + STATE(675), 2, + sym__flw_map_dat_rpt, + aux_sym__r_flw_map_dat_repeat1, + ACTIONS(1925), 3, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + [18169] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(497), 1, + sym__r_flw_njv_bgn, + STATE(923), 1, + sym__r_flw_njl_ann_par, + ACTIONS(1877), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [18186] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1929), 2, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + STATE(567), 2, + sym__flw_map_dat_rpt, + aux_sym__r_flw_map_dat_repeat1, + ACTIONS(553), 3, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + [18203] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(497), 1, + sym__r_flw_njv_bgn, + STATE(921), 1, + sym__r_flw_njl_ann_par, + ACTIONS(1752), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [18220] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1931), 2, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + STATE(567), 2, + sym__flw_map_dat_rpt, + aux_sym__r_flw_map_dat_repeat1, + ACTIONS(551), 3, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + [18237] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1445), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1447), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(685), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [18256] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1933), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [18269] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1523), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1527), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(686), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [18288] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1935), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [18301] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1527), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [18320] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1435), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1437), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(688), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [18339] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1437), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [18358] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1937), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [18371] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1939), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [18384] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1765), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [18403] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1941), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [18422] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1943), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1941), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(690), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [18441] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1945), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [18460] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1947), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1945), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(691), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [18479] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1949), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [18498] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1754), 1, + sym__br_dqt_esc_nwl, + ACTIONS(1247), 2, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_seq, + ACTIONS(1951), 2, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + STATE(565), 2, + sym__br_mtl_dqt_ctn, + aux_sym__r_dqt_str_repeat1, + [18517] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1055), 7, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [18530] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1571), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [18546] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1955), 1, + sym__r_dir_rsv_prm, + STATE(758), 1, + aux_sym__s_dir_rsv_repeat1, + ACTIONS(1953), 4, + sym__s_dir_yml_bgn, + sym__s_dir_tag_bgn, + sym__s_dir_rsv_bgn, + sym__s_drs_end, + [18562] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1933), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + [18574] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1935), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + [18586] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1937), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + [18598] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1959), 1, + sym__r_dir_rsv_prm, + STATE(698), 1, + aux_sym__s_dir_rsv_repeat1, + ACTIONS(1957), 4, + sym__s_dir_yml_bgn, + sym__s_dir_tag_bgn, + sym__s_dir_rsv_bgn, + sym__s_drs_end, + [18614] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1939), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + [18626] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1865), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + [18638] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1867), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + [18650] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1149), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18662] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1151), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18674] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1153), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18686] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1155), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18698] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1157), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18710] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1159), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18722] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1161), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18734] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1163), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18746] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1021), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + [18758] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1023), 3, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__br_flw_sep_bgn, + ACTIONS(1769), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18772] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1175), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18784] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1177), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18796] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1027), 3, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__br_flw_sep_bgn, + ACTIONS(1804), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18810] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1181), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18822] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1183), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18834] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1031), 3, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__br_flw_sep_bgn, + ACTIONS(1807), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18848] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1031), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18860] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1035), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18872] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1039), 3, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__br_flw_sep_bgn, + ACTIONS(1810), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18886] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1039), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18898] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1043), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18910] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1047), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + [18922] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1197), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18934] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1199), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18946] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1201), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18958] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1203), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18970] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1189), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18982] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1121), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [18994] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1063), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [19006] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1165), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [19018] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1111), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [19030] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1113), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [19042] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(987), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [19054] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(987), 3, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__br_flw_sep_bgn, + ACTIONS(1838), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [19068] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(991), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [19080] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(995), 3, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__br_flw_sep_bgn, + ACTIONS(1841), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [19094] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(995), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [19106] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(999), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [19118] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1053), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [19130] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1962), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19146] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1057), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [19158] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1059), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [19170] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1061), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [19182] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1213), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [19194] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(979), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + [19206] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1772), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + ACTIONS(1775), 3, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__br_flw_sep_bgn, + [19220] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1789), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + [19232] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1775), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + [19244] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1964), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19260] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1966), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1969), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19276] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1971), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19292] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1005), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_njv_bgn, + [19304] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1648), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19320] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1717), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19336] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1731), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19352] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1660), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19368] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1975), 1, + sym__r_dir_rsv_prm, + STATE(698), 1, + aux_sym__s_dir_rsv_repeat1, + ACTIONS(1973), 4, + sym__s_dir_yml_bgn, + sym__s_dir_tag_bgn, + sym__s_dir_rsv_bgn, + sym__s_drs_end, + [19384] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1977), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19400] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1979), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19416] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1589), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19432] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1638), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19448] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1981), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19464] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1983), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19480] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1737), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19496] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1611), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19512] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1985), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19528] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1987), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19544] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1601), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19560] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1733), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19576] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1989), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19592] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1991), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19608] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1646), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19624] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1642), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19640] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1993), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19656] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1995), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19672] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1694), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19688] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1997), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19704] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1999), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19720] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1747), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19736] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(1613), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19752] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1557), 2, + sym__br_sqt_str_ctn, + sym__br_sqt_esc_sqt, + ACTIONS(2001), 2, + sym__r_sqt_str_end, + sym__br_sqt_str_end, + STATE(751), 2, + sym__br_mtl_sqt_ctn, + aux_sym__r_sqt_str_repeat1, + [19768] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1055), 6, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [19780] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1175), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [19791] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1772), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + ACTIONS(1775), 3, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__br_flw_sep_bgn, + [19804] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1789), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [19815] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2003), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [19826] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2005), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [19837] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2007), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [19848] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2009), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [19859] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2007), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [19870] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1775), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [19881] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2003), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [19892] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1621), 5, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_nwl, + sym__br_dqt_esc_seq, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + [19903] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2009), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [19914] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1935), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [19925] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1937), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [19936] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1939), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [19947] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2011), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [19958] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2013), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [19969] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1772), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + ACTIONS(1775), 3, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__br_flw_sep_bgn, + [19982] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1789), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [19993] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1775), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20004] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2015), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20015] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(303), 1, + sym__r_flw_njv_bgn, + ACTIONS(305), 1, + sym__br_flw_njv_bgn, + STATE(922), 1, + sym__r_flw_njl_ann_par, + STATE(949), 1, + sym__br_flw_njl_ann_par, + STATE(1335), 1, + sym__r_sgl_flw_njl_ann_par, + [20034] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2017), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20045] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2017), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20056] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2017), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20067] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2017), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20078] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2019), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20089] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1865), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20100] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1867), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20111] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1933), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20122] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2021), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20133] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2023), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20144] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2025), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20155] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1149), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20166] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1151), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20177] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1153), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20188] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1155), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20199] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1157), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20210] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1159), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20221] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1161), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20232] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1163), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20243] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2027), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20254] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2021), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20265] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1769), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + ACTIONS(1023), 3, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__br_flw_sep_bgn, + [20278] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1175), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20289] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1177), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20300] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1804), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + ACTIONS(1027), 3, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__br_flw_sep_bgn, + [20313] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1181), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20324] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1183), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20335] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1807), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + ACTIONS(1031), 3, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__br_flw_sep_bgn, + [20348] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1031), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20359] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1035), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20370] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1810), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + ACTIONS(1039), 3, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__br_flw_sep_bgn, + [20383] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1039), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20394] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1043), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20405] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2021), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20416] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2023), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20427] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2023), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20438] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1197), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20449] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1199), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20460] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1201), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20471] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1203), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20482] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1189), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20493] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1121), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20504] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1063), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20515] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1165), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20526] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1111), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20537] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1113), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20548] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(987), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20559] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1838), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + ACTIONS(987), 3, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__br_flw_sep_bgn, + [20572] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(991), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20583] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1841), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + ACTIONS(995), 3, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__br_flw_sep_bgn, + [20596] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(995), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20607] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(999), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20618] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1053), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20629] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1055), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20640] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1057), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20651] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1059), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20662] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1061), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20673] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1213), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20684] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2029), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20695] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1149), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20706] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1151), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20717] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1153), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20728] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1155), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20739] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1157), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20750] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1159), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20761] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1161), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20772] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1163), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20783] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(979), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20794] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1021), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20805] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2031), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20816] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1769), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + ACTIONS(1023), 3, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__br_flw_sep_bgn, + [20829] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1177), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20840] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1804), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + ACTIONS(1027), 3, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__br_flw_sep_bgn, + [20853] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1181), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20864] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1183), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20875] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1807), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + ACTIONS(1031), 3, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__br_flw_sep_bgn, + [20888] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1031), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20899] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1035), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20910] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1810), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + ACTIONS(1039), 3, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__br_flw_sep_bgn, + [20923] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1039), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20934] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1043), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20945] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2033), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20956] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2035), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20967] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2037), 5, + sym__br_dqt_str_ctn, + sym__br_dqt_esc_nwl, + sym__br_dqt_esc_seq, + sym__r_dqt_str_end, + sym__br_dqt_str_end, + [20978] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1005), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [20989] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1047), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21000] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1197), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21011] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1199), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21022] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1201), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21033] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1203), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21044] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1189), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21055] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1121), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21066] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1063), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21077] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1165), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21088] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1111), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21099] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1113), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21110] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1838), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + ACTIONS(987), 3, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__br_flw_sep_bgn, + [21123] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(991), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21134] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1841), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + ACTIONS(995), 3, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__br_flw_sep_bgn, + [21147] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(995), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21158] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(999), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21169] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1053), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21180] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1055), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21191] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1057), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21202] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1059), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21213] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1061), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21224] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1213), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21235] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(979), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21246] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1021), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21257] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1005), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21268] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1047), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21279] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(975), 1, + sym__r_blk_imp_bgn, + STATE(332), 1, + sym__blk_imp_itm_tal, + ACTIONS(2039), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [21294] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(975), 1, + sym__r_blk_imp_bgn, + STATE(334), 1, + sym__blk_imp_itm_tal, + ACTIONS(2039), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [21309] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2041), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + ACTIONS(2044), 3, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__br_flw_sep_bgn, + [21322] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2046), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21333] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2048), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21344] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2048), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21355] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2050), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21366] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2015), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21377] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2015), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21388] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2015), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21399] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2015), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21410] = 6, + ACTIONS(3), 1, + sym_comment, + ACTIONS(221), 1, + sym__r_flw_njv_bgn, + ACTIONS(223), 1, + sym__br_flw_njv_bgn, + STATE(793), 1, + sym__br_flw_njl_ann_par, + STATE(943), 1, + sym__r_flw_njl_ann_par, + STATE(1337), 1, + sym__r_sgl_flw_njl_ann_par, + [21429] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2017), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21440] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1865), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21451] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2017), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21462] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2017), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21473] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2017), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21484] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2019), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21495] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2041), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + ACTIONS(2044), 3, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__br_flw_sep_bgn, + [21508] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2046), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21519] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2048), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21530] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2050), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21541] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(975), 1, + sym__r_blk_imp_bgn, + STATE(334), 1, + sym__blk_imp_itm_tal, + ACTIONS(2052), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [21556] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2048), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21567] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2050), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21578] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1867), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21589] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2048), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21600] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2003), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21611] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2005), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21622] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2003), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21633] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2005), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21644] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2015), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21655] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2003), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21666] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2048), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21677] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2025), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21688] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2050), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21699] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2015), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21710] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2029), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21721] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1933), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21732] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2003), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21743] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1935), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21754] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1937), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21765] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1939), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21776] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2015), 5, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21787] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2005), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21798] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(987), 5, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + sym__r_flw_sep_bgn, + sym__br_flw_sep_bgn, + [21809] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2054), 1, + sym__r_flw_seq_end, + ACTIONS(2056), 1, + sym__r_flw_sep_bgn, + STATE(963), 2, + sym__sgl_flw_col_dat_rpt, + aux_sym__r_sgl_flw_col_dat_repeat1, + [21823] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2059), 1, + sym__r_flw_map_end, + ACTIONS(2061), 1, + sym__r_flw_sep_bgn, + STATE(1012), 2, + sym__sgl_flw_col_dat_rpt, + aux_sym__r_sgl_flw_col_dat_repeat1, + [21837] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(69), 1, + sym__b_blk_seq_bgn, + ACTIONS(2063), 1, + sym__bl, + STATE(973), 2, + sym__b_blk_seq_itm, + aux_sym__r_blk_seq_repeat1, + [21851] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(69), 1, + sym__b_blk_seq_bgn, + ACTIONS(2065), 1, + sym__bl, + STATE(974), 2, + sym__b_blk_seq_itm, + aux_sym__r_blk_seq_repeat1, + [21865] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(975), 1, + sym__r_blk_imp_bgn, + STATE(332), 1, + sym__blk_imp_itm_tal, + ACTIONS(973), 2, + sym__b_blk_seq_bgn, + sym__bl, + [21879] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2067), 4, + sym__s_dir_yml_bgn, + sym__s_dir_tag_bgn, + sym__s_dir_rsv_bgn, + sym__s_drs_end, + [21889] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(975), 1, + sym__r_blk_imp_bgn, + STATE(334), 1, + sym__blk_imp_itm_tal, + ACTIONS(973), 2, + sym__b_blk_seq_bgn, + sym__bl, + [21903] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2071), 1, + sym__r_dqt_str_end, + STATE(1014), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(2069), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + [21917] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2075), 1, + sym__r_dqt_str_end, + STATE(977), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(2073), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + [21931] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2079), 1, + sym__r_sqt_str_end, + STATE(978), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(2077), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + [21945] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(69), 1, + sym__b_blk_seq_bgn, + ACTIONS(2081), 1, + sym__bl, + STATE(979), 2, + sym__b_blk_seq_itm, + aux_sym__r_blk_seq_repeat1, + [21959] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(69), 1, + sym__b_blk_seq_bgn, + ACTIONS(2083), 1, + sym__bl, + STATE(979), 2, + sym__b_blk_seq_itm, + aux_sym__r_blk_seq_repeat1, + [21973] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2087), 1, + sym__r_sqt_str_end, + STATE(1029), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(2085), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + [21987] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(778), 1, + sym__r_flw_njv_bgn, + STATE(1226), 1, + sym__r_sgl_flw_njl_ann_par, + ACTIONS(2089), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [22001] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2093), 1, + sym__r_dqt_str_end, + STATE(1023), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(2091), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + [22015] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2097), 1, + sym__r_sqt_str_end, + STATE(1024), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(2095), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + [22029] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2099), 1, + sym__b_blk_seq_bgn, + ACTIONS(2102), 1, + sym__bl, + STATE(979), 2, + sym__b_blk_seq_itm, + aux_sym__r_blk_seq_repeat1, + [22043] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(305), 1, + sym__br_flw_njv_bgn, + ACTIONS(497), 1, + sym__r_flw_njv_bgn, + STATE(921), 1, + sym__r_flw_njl_ann_par, + STATE(944), 1, + sym__br_flw_njl_ann_par, + [22059] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(223), 1, + sym__br_flw_njv_bgn, + ACTIONS(434), 1, + sym__r_flw_njv_bgn, + STATE(937), 1, + sym__r_flw_njl_ann_par, + STATE(956), 1, + sym__br_flw_njl_ann_par, + [22075] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2106), 1, + sym__r_dqt_str_end, + STATE(993), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(2104), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + [22089] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2110), 1, + sym__r_sqt_str_end, + STATE(994), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(2108), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + [22103] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(223), 1, + sym__br_flw_njv_bgn, + ACTIONS(434), 1, + sym__r_flw_njv_bgn, + STATE(938), 1, + sym__r_flw_njl_ann_par, + STATE(961), 1, + sym__br_flw_njl_ann_par, + [22119] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1001), 1, + sym__r_blk_imp_bgn, + ACTIONS(999), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [22131] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2059), 1, + sym__r_flw_seq_end, + ACTIONS(2112), 1, + sym__r_flw_sep_bgn, + STATE(1016), 2, + sym__sgl_flw_col_dat_rpt, + aux_sym__r_sgl_flw_col_dat_repeat1, + [22145] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(997), 1, + sym__r_blk_imp_bgn, + ACTIONS(995), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [22157] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1029), 1, + sym__r_blk_imp_bgn, + ACTIONS(1027), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [22169] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(989), 1, + sym__r_blk_imp_bgn, + ACTIONS(987), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [22181] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(993), 1, + sym__r_blk_imp_bgn, + ACTIONS(991), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [22193] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(305), 1, + sym__br_flw_njv_bgn, + ACTIONS(497), 1, + sym__r_flw_njv_bgn, + STATE(923), 1, + sym__r_flw_njl_ann_par, + STATE(945), 1, + sym__br_flw_njl_ann_par, + [22209] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2114), 1, + sym__r_dqt_str_end, + STATE(1023), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(2091), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + [22223] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2116), 1, + sym__r_dqt_str_end, + STATE(1023), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(2091), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + [22237] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2118), 1, + sym__r_sqt_str_end, + STATE(1024), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(2095), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + [22251] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(69), 1, + sym__b_blk_seq_bgn, + ACTIONS(2120), 1, + sym__bl, + STATE(979), 2, + sym__b_blk_seq_itm, + aux_sym__r_blk_seq_repeat1, + [22265] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1033), 1, + sym__r_blk_imp_bgn, + ACTIONS(1031), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [22277] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(983), 1, + sym__r_blk_imp_bgn, + ACTIONS(1019), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [22289] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(69), 1, + sym__b_blk_seq_bgn, + ACTIONS(2122), 1, + sym__bl, + STATE(979), 2, + sym__b_blk_seq_itm, + aux_sym__r_blk_seq_repeat1, + [22303] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(979), 4, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + sym__r_blk_imp_bgn, + [22313] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1037), 1, + sym__r_blk_imp_bgn, + ACTIONS(1035), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [22325] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1021), 4, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + sym__r_blk_imp_bgn, + [22335] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(69), 1, + sym__b_blk_seq_bgn, + ACTIONS(2124), 1, + sym__bl, + STATE(1022), 2, + sym__b_blk_seq_itm, + aux_sym__r_blk_seq_repeat1, + [22349] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(69), 1, + sym__b_blk_seq_bgn, + ACTIONS(2126), 1, + sym__bl, + STATE(1026), 2, + sym__b_blk_seq_itm, + aux_sym__r_blk_seq_repeat1, + [22363] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(69), 1, + sym__b_blk_seq_bgn, + ACTIONS(2128), 1, + sym__bl, + STATE(998), 2, + sym__b_blk_seq_itm, + aux_sym__r_blk_seq_repeat1, + [22377] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1041), 1, + sym__r_blk_imp_bgn, + ACTIONS(1039), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [22389] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2130), 1, + sym__r_dqt_str_end, + STATE(1023), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(2091), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + [22403] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2132), 1, + sym__r_sqt_str_end, + STATE(1024), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(2095), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + [22417] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1045), 1, + sym__r_blk_imp_bgn, + ACTIONS(1043), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [22429] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1767), 1, + sym__r_flw_jsv_bgn, + ACTIONS(2134), 1, + sym__br_flw_jsv_bgn, + STATE(946), 1, + sym__br_flw_jsl_ann_par, + STATE(950), 1, + sym__r_flw_jsl_ann_par, + [22445] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2138), 1, + sym__r_dqt_str_end, + STATE(1020), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(2136), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + [22459] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2142), 1, + sym__r_sqt_str_end, + STATE(1021), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(2140), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + [22473] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(855), 1, + sym__r_flw_map_end, + ACTIONS(2144), 1, + sym__r_flw_sep_bgn, + STATE(1034), 2, + sym__sgl_flw_col_dat_rpt, + aux_sym__r_sgl_flw_col_dat_repeat1, + [22487] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2146), 1, + sym__r_sqt_str_end, + STATE(1024), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(2095), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + [22501] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2148), 1, + sym__r_dqt_str_end, + STATE(1023), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(2091), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + [22515] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2150), 4, + sym__s_dir_yml_bgn, + sym__s_dir_tag_bgn, + sym__s_dir_rsv_bgn, + sym__s_drs_end, + [22525] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(855), 1, + sym__r_flw_seq_end, + ACTIONS(2152), 1, + sym__r_flw_sep_bgn, + STATE(963), 2, + sym__sgl_flw_col_dat_rpt, + aux_sym__r_sgl_flw_col_dat_repeat1, + [22539] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2156), 1, + sym__r_dqt_str_end, + STATE(1006), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(2154), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + [22553] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1767), 1, + sym__r_flw_jsv_bgn, + ACTIONS(2134), 1, + sym__br_flw_jsv_bgn, + STATE(947), 1, + sym__br_flw_jsl_ann_par, + STATE(952), 1, + sym__r_flw_jsl_ann_par, + [22569] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2160), 1, + sym__r_sqt_str_end, + STATE(1007), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(2158), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + [22583] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2162), 1, + sym__r_dqt_str_end, + STATE(1023), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(2091), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + [22597] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2164), 1, + sym__r_sqt_str_end, + STATE(1024), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(2095), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + [22611] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(69), 1, + sym__b_blk_seq_bgn, + ACTIONS(2166), 1, + sym__bl, + STATE(979), 2, + sym__b_blk_seq_itm, + aux_sym__r_blk_seq_repeat1, + [22625] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1634), 1, + sym__r_dqt_str_end, + STATE(1023), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(2168), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + [22639] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1851), 1, + sym__r_sqt_str_end, + STATE(1024), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(2171), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + [22653] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2174), 1, + sym__r_flw_jsv_bgn, + STATE(1235), 1, + sym__r_sgl_flw_jsl_ann_par, + ACTIONS(2089), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [22667] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(69), 1, + sym__b_blk_seq_bgn, + ACTIONS(2176), 1, + sym__bl, + STATE(979), 2, + sym__b_blk_seq_itm, + aux_sym__r_blk_seq_repeat1, + [22681] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2180), 1, + sym__r_dqt_str_end, + STATE(1032), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(2178), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + [22695] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2184), 1, + sym__r_sqt_str_end, + STATE(1033), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(2182), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + [22709] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2186), 1, + sym__r_sqt_str_end, + STATE(1024), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(2095), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + [22723] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1003), 4, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + sym__r_blk_imp_bgn, + [22733] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1615), 1, + sym__r_flw_jsv_bgn, + ACTIONS(1617), 1, + sym__br_flw_jsv_bgn, + STATE(787), 1, + sym__br_flw_jsl_ann_par, + STATE(940), 1, + sym__r_flw_jsl_ann_par, + [22749] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2188), 1, + sym__r_dqt_str_end, + STATE(1023), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(2091), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + [22763] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2190), 1, + sym__r_sqt_str_end, + STATE(1024), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(2095), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + [22777] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2054), 1, + sym__r_flw_map_end, + ACTIONS(2192), 1, + sym__r_flw_sep_bgn, + STATE(1034), 2, + sym__sgl_flw_col_dat_rpt, + aux_sym__r_sgl_flw_col_dat_repeat1, + [22791] = 5, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1615), 1, + sym__r_flw_jsv_bgn, + ACTIONS(1617), 1, + sym__br_flw_jsv_bgn, + STATE(788), 1, + sym__br_flw_jsl_ann_par, + STATE(941), 1, + sym__r_flw_jsl_ann_par, + [22807] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1013), 4, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + sym__r_blk_imp_bgn, + [22817] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(983), 1, + sym__r_blk_imp_bgn, + ACTIONS(981), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [22829] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(717), 1, + sym__r_flw_njv_bgn, + STATE(1409), 1, + sym__r_sgl_flw_njl_ann_par, + ACTIONS(2089), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [22843] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1005), 4, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + sym__r_blk_imp_bgn, + [22853] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(983), 1, + sym__r_blk_imp_bgn, + ACTIONS(985), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [22865] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(69), 1, + sym__b_blk_seq_bgn, + ACTIONS(2195), 1, + sym__bl, + STATE(979), 2, + sym__b_blk_seq_itm, + aux_sym__r_blk_seq_repeat1, + [22879] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2199), 1, + sym__r_dqt_str_end, + STATE(992), 1, + aux_sym__r_sgl_dqt_ctn, + ACTIONS(2197), 2, + sym__r_dqt_str_ctn, + sym__r_dqt_esc_seq, + [22893] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2203), 1, + sym__r_sqt_str_end, + STATE(1013), 1, + aux_sym__r_sgl_sqt_ctn, + ACTIONS(2201), 2, + sym__r_sqt_str_ctn, + sym__r_sqt_esc_sqt, + [22907] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1047), 4, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + sym__r_blk_imp_bgn, + [22917] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2205), 1, + sym__r_flw_jsv_bgn, + STATE(1332), 1, + sym__r_sgl_flw_jsl_ann_par, + ACTIONS(2089), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [22931] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1017), 1, + sym__r_blk_imp_bgn, + ACTIONS(1015), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [22943] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1025), 1, + sym__r_blk_imp_bgn, + ACTIONS(1023), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [22955] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(69), 1, + sym__b_blk_seq_bgn, + ACTIONS(2207), 1, + sym__bl, + STATE(995), 2, + sym__b_blk_seq_itm, + aux_sym__r_blk_seq_repeat1, + [22969] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(979), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [22978] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2209), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [22987] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2211), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [22996] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2213), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [23005] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2215), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [23014] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2217), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [23023] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1075), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23032] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2219), 1, + sym__br_blk_str_ctn, + ACTIONS(2222), 1, + sym__bl, + STATE(1056), 1, + aux_sym__r_blk_str_repeat1, + [23045] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1079), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23054] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2224), 3, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + [23063] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1933), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + [23072] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1157), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23081] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2226), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [23090] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2228), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [23099] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1173), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23108] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2230), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [23117] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1065), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23126] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2232), 1, + sym__br_blk_str_ctn, + ACTIONS(2234), 1, + sym__bl, + STATE(1056), 1, + aux_sym__r_blk_str_repeat1, + [23139] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1033), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [23148] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1041), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [23157] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1051), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23166] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1153), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23175] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1155), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23184] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(989), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [23193] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1113), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23202] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(997), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [23211] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(987), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23220] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1183), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23229] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1933), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + [23238] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2236), 1, + sym__br_blk_str_ctn, + ACTIONS(2238), 1, + sym__bl, + STATE(1089), 1, + aux_sym__r_blk_str_repeat1, + [23251] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1005), 3, + sym__b_blk_seq_bgn, + sym__r_blk_imp_bgn, + sym__bl, + [23260] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1067), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23269] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2240), 1, + sym__br_blk_str_ctn, + ACTIONS(2242), 1, + sym__bl, + STATE(1066), 1, + aux_sym__r_blk_str_repeat1, + [23282] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(991), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23291] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1145), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23300] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2244), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + [23309] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2246), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23318] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(995), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23327] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1159), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23336] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1171), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23345] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2232), 1, + sym__br_blk_str_ctn, + ACTIONS(2248), 1, + sym__bl, + STATE(1056), 1, + aux_sym__r_blk_str_repeat1, + [23358] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(999), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23367] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1179), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23376] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1053), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23385] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1055), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23394] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1015), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23403] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1019), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23412] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1057), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23421] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(979), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + [23430] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1059), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23439] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1005), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + [23448] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(979), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + [23457] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1005), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + [23466] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1031), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23475] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1147), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23484] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1061), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23493] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1213), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23502] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1003), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23511] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1013), 3, + sym__b_blk_seq_bgn, + sym__r_blk_imp_bgn, + sym__bl, + [23520] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1035), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23529] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1177), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23538] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2250), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [23547] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2252), 1, + sym__br_blk_str_ctn, + ACTIONS(2254), 1, + sym__bl, + STATE(1120), 1, + aux_sym__r_blk_str_repeat1, + [23560] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2256), 1, + sym__br_blk_str_ctn, + ACTIONS(2258), 1, + sym__bl, + STATE(1121), 1, + aux_sym__r_blk_str_repeat1, + [23573] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2260), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [23582] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2262), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [23591] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1149), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23600] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2264), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [23609] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1017), 1, + sym__r_blk_imp_bgn, + ACTIONS(1015), 2, + sym__b_blk_seq_bgn, + sym__bl, + [23620] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(983), 1, + sym__r_blk_imp_bgn, + ACTIONS(1019), 2, + sym__b_blk_seq_bgn, + sym__bl, + [23631] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1167), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23640] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2232), 1, + sym__br_blk_str_ctn, + ACTIONS(2266), 1, + sym__bl, + STATE(1056), 1, + aux_sym__r_blk_str_repeat1, + [23653] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2232), 1, + sym__br_blk_str_ctn, + ACTIONS(2268), 1, + sym__bl, + STATE(1056), 1, + aux_sym__r_blk_str_repeat1, + [23666] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1021), 3, + sym__b_blk_seq_bgn, + sym__r_blk_imp_bgn, + sym__bl, + [23675] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2270), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23684] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2272), 3, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + [23693] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2274), 3, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + [23702] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1039), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23711] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1161), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23720] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1025), 1, + sym__r_blk_imp_bgn, + ACTIONS(1023), 2, + sym__b_blk_seq_bgn, + sym__bl, + [23731] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1163), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23740] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1043), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23749] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1175), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23758] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2276), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + [23767] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1181), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23776] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1111), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23785] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1129), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23794] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1185), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23803] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(979), 3, + sym__b_blk_seq_bgn, + sym__r_blk_imp_bgn, + sym__bl, + [23812] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2278), 3, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + [23821] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2209), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [23830] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2280), 1, + sym__br_blk_str_ctn, + ACTIONS(2282), 1, + sym__bl, + STATE(1147), 1, + aux_sym__r_blk_str_repeat1, + [23843] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2284), 1, + sym__br_blk_str_ctn, + ACTIONS(2286), 1, + sym__bl, + STATE(1148), 1, + aux_sym__r_blk_str_repeat1, + [23856] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1131), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23865] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2288), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23874] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1029), 1, + sym__r_blk_imp_bgn, + ACTIONS(1027), 2, + sym__b_blk_seq_bgn, + sym__bl, + [23885] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2230), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [23894] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1033), 1, + sym__r_blk_imp_bgn, + ACTIONS(1031), 2, + sym__b_blk_seq_bgn, + sym__bl, + [23905] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2232), 1, + sym__br_blk_str_ctn, + ACTIONS(2290), 1, + sym__bl, + STATE(1056), 1, + aux_sym__r_blk_str_repeat1, + [23918] = 4, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2232), 1, + sym__br_blk_str_ctn, + ACTIONS(2292), 1, + sym__bl, + STATE(1056), 1, + aux_sym__r_blk_str_repeat1, + [23931] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1037), 1, + sym__r_blk_imp_bgn, + ACTIONS(1035), 2, + sym__b_blk_seq_bgn, + sym__bl, + [23942] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1041), 1, + sym__r_blk_imp_bgn, + ACTIONS(1039), 2, + sym__b_blk_seq_bgn, + sym__bl, + [23953] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2294), 3, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + [23962] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2296), 3, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + [23971] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1045), 1, + sym__r_blk_imp_bgn, + ACTIONS(1043), 2, + sym__b_blk_seq_bgn, + sym__bl, + [23982] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1137), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [23991] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2300), 1, + sym__s_doc_end, + ACTIONS(2298), 2, + sym__eof, + sym__s_drs_end, + [24002] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1151), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [24011] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1005), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [24020] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1047), 3, + sym__b_blk_seq_bgn, + sym__r_blk_imp_bgn, + sym__bl, + [24029] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(983), 1, + sym__r_blk_imp_bgn, + ACTIONS(981), 2, + sym__b_blk_seq_bgn, + sym__bl, + [24040] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(983), 1, + sym__r_blk_imp_bgn, + ACTIONS(985), 2, + sym__b_blk_seq_bgn, + sym__bl, + [24051] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2211), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [24060] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2213), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [24069] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2215), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [24078] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2217), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [24087] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2302), 3, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + [24096] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2304), 3, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + [24105] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2308), 1, + sym__s_doc_end, + ACTIONS(2306), 2, + sym__eof, + sym__s_drs_end, + [24116] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2310), 1, + sym__s_doc_end, + ACTIONS(2306), 2, + sym__eof, + sym__s_drs_end, + [24127] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2052), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [24136] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1139), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [24145] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2244), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + [24154] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2312), 3, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + [24163] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2314), 3, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + [24172] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2226), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [24181] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1141), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [24190] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1205), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [24199] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1191), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [24208] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2228), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [24217] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(989), 1, + sym__r_blk_imp_bgn, + ACTIONS(987), 2, + sym__b_blk_seq_bgn, + sym__bl, + [24228] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(993), 1, + sym__r_blk_imp_bgn, + ACTIONS(991), 2, + sym__b_blk_seq_bgn, + sym__bl, + [24239] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(997), 1, + sym__r_blk_imp_bgn, + ACTIONS(995), 2, + sym__b_blk_seq_bgn, + sym__bl, + [24250] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2316), 3, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + [24259] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2318), 3, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + [24268] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1001), 1, + sym__r_blk_imp_bgn, + ACTIONS(999), 2, + sym__b_blk_seq_bgn, + sym__bl, + [24279] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1193), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [24288] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1195), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [24297] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2276), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_njv_bgn, + [24306] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1197), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [24315] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1033), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [24324] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1041), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [24333] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1199), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [24342] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1201), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [24351] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2320), 3, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + [24360] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2322), 3, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + [24369] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(989), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [24378] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(997), 3, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [24387] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1203), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [24396] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1003), 3, + sym__b_blk_seq_bgn, + sym__r_blk_imp_bgn, + sym__bl, + [24405] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(981), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [24414] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1143), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [24423] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1207), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [24432] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1209), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [24441] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1211), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [24450] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1189), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [24459] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1121), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [24468] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1063), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [24477] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1165), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [24486] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(985), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [24495] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2250), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [24504] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2260), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [24513] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2324), 3, + sym__r_flw_seq_end, + sym__br_flw_seq_end, + sym__b_flw_seq_end, + [24522] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2326), 3, + sym__r_flw_map_end, + sym__br_flw_map_end, + sym__b_flw_map_end, + [24531] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2262), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [24540] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2264), 3, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + sym__r_flw_jsv_bgn, + [24549] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1187), 3, + sym__eof, + sym__s_drs_end, + sym__s_doc_end, + [24558] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1935), 2, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [24566] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1161), 2, + sym__b_blk_seq_bgn, + sym__bl, + [24574] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1163), 2, + sym__b_blk_seq_bgn, + sym__bl, + [24582] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2250), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [24590] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1015), 2, + sym__b_blk_seq_bgn, + sym__bl, + [24598] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1019), 2, + sym__b_blk_seq_bgn, + sym__bl, + [24606] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1775), 2, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [24614] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2260), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [24622] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2262), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [24630] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2328), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [24638] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2330), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [24646] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(975), 1, + sym__r_blk_imp_bgn, + STATE(313), 1, + sym__blk_imp_itm_tal, + [24656] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2264), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [24664] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1171), 2, + sym__b_blk_seq_bgn, + sym__bl, + [24672] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1173), 2, + sym__b_blk_seq_bgn, + sym__bl, + [24680] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2211), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [24688] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2213), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [24696] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2215), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [24704] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2217), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [24712] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2330), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [24720] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2244), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [24728] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(975), 1, + sym__r_blk_imp_bgn, + STATE(314), 1, + sym__blk_imp_itm_tal, + [24738] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2226), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [24746] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(717), 1, + sym__r_flw_njv_bgn, + STATE(1409), 1, + sym__r_sgl_flw_njl_ann_par, + [24756] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2328), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [24764] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2228), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [24772] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2205), 1, + sym__r_flw_jsv_bgn, + STATE(1332), 1, + sym__r_sgl_flw_jsl_ann_par, + [24782] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1772), 1, + sym__r_flw_njv_bgn, + ACTIONS(1775), 1, + sym__br_flw_njv_bgn, + [24792] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2174), 1, + sym__r_flw_jsv_bgn, + STATE(1235), 1, + sym__r_sgl_flw_jsl_ann_par, + [24802] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2332), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [24810] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(979), 2, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [24818] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1175), 2, + sym__b_blk_seq_bgn, + sym__bl, + [24826] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1005), 2, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [24834] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1033), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [24842] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2328), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [24850] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2328), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [24858] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2334), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [24866] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2334), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [24874] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1047), 2, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [24882] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1041), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [24890] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1177), 2, + sym__b_blk_seq_bgn, + sym__bl, + [24898] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2209), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [24906] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1181), 2, + sym__b_blk_seq_bgn, + sym__bl, + [24914] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1183), 2, + sym__b_blk_seq_bgn, + sym__bl, + [24922] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1031), 2, + sym__b_blk_seq_bgn, + sym__bl, + [24930] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1035), 2, + sym__b_blk_seq_bgn, + sym__bl, + [24938] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1937), 2, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [24946] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1939), 2, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [24954] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2230), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [24962] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1039), 2, + sym__b_blk_seq_bgn, + sym__bl, + [24970] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1043), 2, + sym__b_blk_seq_bgn, + sym__bl, + [24978] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2336), 2, + sym__b_blk_seq_bgn, + sym__bl, + [24986] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2338), 2, + sym__b_blk_seq_bgn, + sym__bl, + [24994] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2244), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [25002] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(989), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [25010] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(997), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [25018] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1021), 2, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [25026] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1191), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25034] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1193), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25042] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1195), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25050] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1197), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25058] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1199), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25066] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1201), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25074] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1203), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25082] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(981), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25090] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1003), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25098] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1149), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25106] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1151), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25114] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1207), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25122] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1209), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25130] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1211), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25138] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1189), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25146] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1121), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25154] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1063), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25162] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1165), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25170] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(985), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25178] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2340), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [25186] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1933), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [25194] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1167), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25202] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1179), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25210] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1065), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25218] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1067), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25226] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1933), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [25234] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(975), 1, + sym__r_blk_imp_bgn, + STATE(304), 1, + sym__blk_imp_itm_tal, + [25244] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1075), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25252] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2250), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [25260] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1153), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25268] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1079), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25276] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1155), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25284] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2260), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [25292] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1157), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25300] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1159), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25308] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2262), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [25316] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1161), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25324] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1163), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25332] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2264), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [25340] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2340), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [25348] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2342), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25356] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1023), 1, + sym__br_flw_jsv_bgn, + ACTIONS(1769), 1, + sym__r_flw_jsv_bgn, + [25366] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1933), 2, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [25374] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1175), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25382] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2209), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [25390] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1177), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25398] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2344), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [25406] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1027), 1, + sym__br_flw_jsv_bgn, + ACTIONS(1804), 1, + sym__r_flw_jsv_bgn, + [25416] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1181), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25424] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2230), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [25432] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1183), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25440] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1213), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25448] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1031), 1, + sym__br_flw_jsv_bgn, + ACTIONS(1807), 1, + sym__r_flw_jsv_bgn, + [25458] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2276), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [25466] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2346), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [25474] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1031), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25482] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1035), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25490] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1039), 1, + sym__br_flw_jsv_bgn, + ACTIONS(1810), 1, + sym__r_flw_jsv_bgn, + [25500] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1039), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25508] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2330), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [25516] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1111), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25524] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1043), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25532] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2330), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [25540] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2276), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [25548] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2330), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [25556] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1197), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25564] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1199), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25572] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1201), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25580] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1203), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25588] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1189), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25596] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1121), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25604] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1113), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25612] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1789), 2, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [25620] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1063), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25628] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(987), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25636] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(979), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [25644] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1165), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25652] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(991), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25660] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(995), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25668] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1005), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [25676] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(979), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [25684] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2211), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [25692] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(999), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25700] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1005), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [25708] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2213), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [25716] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2215), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [25724] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(778), 1, + sym__r_flw_njv_bgn, + STATE(1226), 1, + sym__r_sgl_flw_njl_ann_par, + [25734] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2217), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [25742] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1111), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25750] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1185), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25758] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1187), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25766] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1205), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25774] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1051), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25782] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2226), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [25790] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1113), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25798] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2228), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [25806] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(987), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25814] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(987), 1, + sym__br_flw_jsv_bgn, + ACTIONS(1838), 1, + sym__r_flw_jsv_bgn, + [25824] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2346), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [25832] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2332), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [25840] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(991), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25848] = 3, + ACTIONS(3), 1, + sym_comment, + ACTIONS(995), 1, + sym__br_flw_jsv_bgn, + ACTIONS(1841), 1, + sym__r_flw_jsv_bgn, + [25858] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1053), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25866] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1055), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25874] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1057), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25882] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1059), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25890] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2344), 2, + sym__r_flw_seq_end, + sym__r_flw_sep_bgn, + [25898] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1129), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25906] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1131), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25914] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1061), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25922] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1213), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25930] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(995), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25938] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(999), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [25946] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1137), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25954] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1139), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25962] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1141), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25970] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1143), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25978] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1145), 2, + sym__b_blk_seq_bgn, + sym__bl, + [25986] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1033), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [25994] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1041), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [26002] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1147), 2, + sym__b_blk_seq_bgn, + sym__bl, + [26010] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1149), 2, + sym__b_blk_seq_bgn, + sym__bl, + [26018] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1151), 2, + sym__b_blk_seq_bgn, + sym__bl, + [26026] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1053), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [26034] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1055), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [26042] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1865), 2, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [26050] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1057), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [26058] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1867), 2, + sym__r_flw_njv_bgn, + sym__br_flw_njv_bgn, + [26066] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1153), 2, + sym__b_blk_seq_bgn, + sym__bl, + [26074] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1155), 2, + sym__b_blk_seq_bgn, + sym__bl, + [26082] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1059), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [26090] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1157), 2, + sym__b_blk_seq_bgn, + sym__bl, + [26098] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(989), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [26106] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(997), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [26114] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1159), 2, + sym__b_blk_seq_bgn, + sym__bl, + [26122] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1061), 2, + sym__r_flw_jsv_bgn, + sym__br_flw_jsv_bgn, + [26130] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2330), 2, + sym__r_flw_map_end, + sym__r_flw_sep_bgn, + [26138] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2348), 1, + sym__r_acr_ctn, + [26145] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2264), 1, + sym__r_blk_imp_bgn, + [26152] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2350), 1, + sym__r_blk_imp_bgn, + [26159] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2228), 1, + sym__r_blk_imp_bgn, + [26166] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2226), 1, + sym__r_flw_jsv_bgn, + [26173] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2352), 1, + sym__r_blk_imp_bgn, + [26180] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2354), 1, + sym__r_blk_imp_bgn, + [26187] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2356), 1, + sym__r_blk_imp_bgn, + [26194] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2358), 1, + sym__r_blk_imp_bgn, + [26201] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2360), 1, + sym__r_blk_imp_bgn, + [26208] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2250), 1, + sym__r_blk_imp_bgn, + [26215] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(989), 1, + sym__r_blk_imp_bgn, + [26222] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2230), 1, + sym__r_flw_jsv_bgn, + [26229] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2209), 1, + sym__r_blk_imp_bgn, + [26236] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1047), 1, + sym__r_blk_imp_bgn, + [26243] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(997), 1, + sym__r_blk_imp_bgn, + [26250] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2362), 1, + ts_builtin_sym_end, + [26257] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2364), 1, + sym__r_dir_yml_ver, + [26264] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2366), 1, + sym__eof, + [26271] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2368), 1, + ts_builtin_sym_end, + [26278] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2370), 1, + sym__r_acr_ctn, + [26285] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2372), 1, + sym__r_acr_ctn, + [26292] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2374), 1, + sym__r_als_ctn, + [26299] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2376), 1, + sym__r_acr_ctn, + [26306] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2378), 1, + sym__r_acr_ctn, + [26313] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2380), 1, + sym__r_als_ctn, + [26320] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2382), 1, + sym__r_als_ctn, + [26327] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2384), 1, + sym__r_als_ctn, + [26334] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2386), 1, + sym__r_acr_ctn, + [26341] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2388), 1, + sym__r_acr_ctn, + [26348] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2390), 1, + sym__r_als_ctn, + [26355] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2392), 1, + sym__r_als_ctn, + [26362] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2260), 1, + sym__r_blk_imp_bgn, + [26369] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2394), 1, + sym__r_blk_imp_bgn, + [26376] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2396), 1, + sym__r_blk_imp_bgn, + [26383] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2398), 1, + sym__r_blk_imp_bgn, + [26390] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2400), 1, + sym__r_blk_imp_bgn, + [26397] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2402), 1, + sym__r_flw_seq_end, + [26404] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2228), 1, + sym__r_flw_jsv_bgn, + [26411] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2404), 1, + sym__r_flw_map_end, + [26418] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2406), 1, + sym__r_blk_imp_bgn, + [26425] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1033), 1, + sym__r_flw_jsv_bgn, + [26432] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2408), 1, + ts_builtin_sym_end, + [26439] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2262), 1, + sym__r_blk_imp_bgn, + [26446] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2410), 1, + sym__r_dir_tag_pfx, + [26453] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(979), 1, + sym__r_flw_njv_bgn, + [26460] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2412), 1, + sym__eof, + [26467] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2414), 1, + sym__r_flw_seq_end, + [26474] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1041), 1, + sym__r_flw_jsv_bgn, + [26481] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2416), 1, + sym__r_flw_seq_end, + [26488] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2418), 1, + sym__r_flw_map_end, + [26495] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2420), 1, + sym__r_blk_imp_bgn, + [26502] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1005), 1, + sym__r_flw_njv_bgn, + [26509] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2262), 1, + sym__r_flw_jsv_bgn, + [26516] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2422), 1, + sym__r_blk_imp_bgn, + [26523] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2424), 1, + ts_builtin_sym_end, + [26530] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2213), 1, + sym__r_flw_jsv_bgn, + [26537] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2264), 1, + sym__r_flw_jsv_bgn, + [26544] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2426), 1, + sym__r_flw_seq_end, + [26551] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2215), 1, + sym__r_flw_jsv_bgn, + [26558] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2244), 1, + sym__r_flw_njv_bgn, + [26565] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2428), 1, + sym__r_flw_map_end, + [26572] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2430), 1, + sym__r_acr_ctn, + [26579] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2432), 1, + sym__r_flw_seq_end, + [26586] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2434), 1, + sym__r_als_ctn, + [26593] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1933), 1, + sym__r_flw_njv_bgn, + [26600] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2436), 1, + sym__r_flw_map_end, + [26607] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1033), 1, + sym__r_blk_imp_bgn, + [26614] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2438), 1, + sym__r_acr_ctn, + [26621] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2440), 1, + sym__r_acr_ctn, + [26628] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2442), 1, + sym__r_als_ctn, + [26635] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2444), 1, + sym__r_als_ctn, + [26642] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2217), 1, + sym__r_flw_jsv_bgn, + [26649] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2446), 1, + sym__r_acr_ctn, + [26656] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2448), 1, + sym__r_acr_ctn, + [26663] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2450), 1, + sym__r_blk_imp_bgn, + [26670] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2452), 1, + sym__r_als_ctn, + [26677] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1021), 1, + sym__r_blk_imp_bgn, + [26684] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2454), 1, + sym__r_als_ctn, + [26691] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2456), 1, + sym__eof, + [26698] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2458), 1, + sym__eof, + [26705] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2460), 1, + sym__r_blk_imp_bgn, + [26712] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2462), 1, + sym__r_blk_imp_bgn, + [26719] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2464), 1, + sym__r_blk_imp_bgn, + [26726] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2466), 1, + sym__r_als_ctn, + [26733] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(989), 1, + sym__r_flw_jsv_bgn, + [26740] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2468), 1, + sym__r_blk_imp_bgn, + [26747] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2470), 1, + sym__r_blk_imp_bgn, + [26754] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2472), 1, + sym__r_acr_ctn, + [26761] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2474), 1, + sym__r_blk_imp_bgn, + [26768] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1041), 1, + sym__r_blk_imp_bgn, + [26775] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2226), 1, + sym__r_blk_imp_bgn, + [26782] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2476), 1, + sym__r_blk_imp_bgn, + [26789] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2478), 1, + sym__r_acr_ctn, + [26796] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2480), 1, + sym__r_als_ctn, + [26803] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2482), 1, + sym__r_als_ctn, + [26810] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2250), 1, + sym__r_flw_jsv_bgn, + [26817] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(997), 1, + sym__r_flw_jsv_bgn, + [26824] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2484), 1, + sym__r_als_ctn, + [26831] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2209), 1, + sym__r_flw_jsv_bgn, + [26838] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2486), 1, + sym__r_acr_ctn, + [26845] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2488), 1, + sym__r_acr_ctn, + [26852] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2490), 1, + sym__r_als_ctn, + [26859] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2492), 1, + sym__r_als_ctn, + [26866] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2494), 1, + sym__r_blk_imp_bgn, + [26873] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2496), 1, + sym__r_dir_tag_hdl, + [26880] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2498), 1, + sym__r_flw_map_end, + [26887] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2230), 1, + sym__r_blk_imp_bgn, + [26894] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2276), 1, + sym__r_flw_njv_bgn, + [26901] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2500), 1, + sym__r_acr_ctn, + [26908] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2502), 1, + sym__r_blk_imp_bgn, + [26915] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2211), 1, + sym__r_blk_imp_bgn, + [26922] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(1003), 1, + sym__r_blk_imp_bgn, + [26929] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2213), 1, + sym__r_blk_imp_bgn, + [26936] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2215), 1, + sym__r_blk_imp_bgn, + [26943] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2504), 1, + sym__r_flw_seq_end, + [26950] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2506), 1, + sym__eof, + [26957] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2508), 1, + sym__r_flw_map_end, + [26964] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2217), 1, + sym__r_blk_imp_bgn, + [26971] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2510), 1, + sym__r_blk_imp_bgn, + [26978] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2512), 1, + sym__r_blk_imp_bgn, + [26985] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2514), 1, + sym__r_blk_imp_bgn, + [26992] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2516), 1, + sym__r_blk_imp_bgn, + [26999] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2518), 1, + sym__r_blk_imp_bgn, + [27006] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2260), 1, + sym__r_flw_jsv_bgn, + [27013] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2211), 1, + sym__r_flw_jsv_bgn, + [27020] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2520), 1, + sym__r_blk_imp_bgn, + [27027] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2522), 1, + sym__r_blk_imp_bgn, + [27034] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2524), 1, + sym__r_acr_ctn, + [27041] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2526), 1, + sym__r_acr_ctn, + [27048] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2528), 1, + sym__r_als_ctn, + [27055] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2530), 1, + sym__r_als_ctn, + [27062] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2532), 1, + sym__r_acr_ctn, + [27069] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2534), 1, + sym__r_acr_ctn, + [27076] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2536), 1, + sym__r_als_ctn, + [27083] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2538), 1, + sym__r_acr_ctn, + [27090] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2540), 1, + sym__r_acr_ctn, + [27097] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2542), 1, + sym__r_als_ctn, + [27104] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2544), 1, + sym__r_acr_ctn, + [27111] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2546), 1, + sym__r_acr_ctn, + [27118] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2548), 1, + sym__r_als_ctn, + [27125] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2550), 1, + sym__r_blk_imp_bgn, + [27132] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2552), 1, + sym__r_acr_ctn, + [27139] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2554), 1, + sym__r_als_ctn, + [27146] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2556), 1, + sym__r_acr_ctn, + [27153] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2558), 1, + sym__r_acr_ctn, + [27160] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2560), 1, + sym__r_als_ctn, + [27167] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2562), 1, + sym__r_acr_ctn, + [27174] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2564), 1, + sym__r_acr_ctn, + [27181] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2566), 1, + sym__r_als_ctn, + [27188] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2568), 1, + sym__r_acr_ctn, + [27195] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2570), 1, + sym__r_acr_ctn, + [27202] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2572), 1, + sym__r_acr_ctn, + [27209] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2574), 1, + sym__r_acr_ctn, + [27216] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2576), 1, + sym__r_acr_ctn, + [27223] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2578), 1, + sym__r_acr_ctn, + [27230] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2580), 1, + sym__r_acr_ctn, + [27237] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2582), 1, + sym__r_acr_ctn, + [27244] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2584), 1, + sym__r_acr_ctn, + [27251] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2586), 1, + sym__r_acr_ctn, + [27258] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2588), 1, + sym__r_acr_ctn, + [27265] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2590), 1, + sym__r_acr_ctn, + [27272] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2592), 1, + sym__r_acr_ctn, + [27279] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2594), 1, + sym__r_acr_ctn, + [27286] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2596), 1, + sym__r_acr_ctn, + [27293] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2598), 1, + sym__r_acr_ctn, + [27300] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2600), 1, + sym__r_acr_ctn, + [27307] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2602), 1, + sym__r_acr_ctn, + [27314] = 2, + ACTIONS(3), 1, + sym_comment, + ACTIONS(2604), 1, + sym__r_acr_ctn, +}; + +static const uint32_t ts_small_parse_table_map[] = { + [SMALL_STATE(96)] = 0, + [SMALL_STATE(97)] = 71, + [SMALL_STATE(98)] = 142, + [SMALL_STATE(99)] = 206, + [SMALL_STATE(100)] = 271, + [SMALL_STATE(101)] = 336, + [SMALL_STATE(102)] = 393, + [SMALL_STATE(103)] = 450, + [SMALL_STATE(104)] = 510, + [SMALL_STATE(105)] = 570, + [SMALL_STATE(106)] = 630, + [SMALL_STATE(107)] = 686, + [SMALL_STATE(108)] = 742, + [SMALL_STATE(109)] = 797, + [SMALL_STATE(110)] = 852, + [SMALL_STATE(111)] = 907, + [SMALL_STATE(112)] = 962, + [SMALL_STATE(113)] = 1043, + [SMALL_STATE(114)] = 1124, + [SMALL_STATE(115)] = 1204, + [SMALL_STATE(116)] = 1284, + [SMALL_STATE(117)] = 1341, + [SMALL_STATE(118)] = 1420, + [SMALL_STATE(119)] = 1477, + [SMALL_STATE(120)] = 1556, + [SMALL_STATE(121)] = 1635, + [SMALL_STATE(122)] = 1714, + [SMALL_STATE(123)] = 1770, + [SMALL_STATE(124)] = 1826, + [SMALL_STATE(125)] = 1876, + [SMALL_STATE(126)] = 1967, + [SMALL_STATE(127)] = 2062, + [SMALL_STATE(128)] = 2105, + [SMALL_STATE(129)] = 2196, + [SMALL_STATE(130)] = 2239, + [SMALL_STATE(131)] = 2330, + [SMALL_STATE(132)] = 2381, + [SMALL_STATE(133)] = 2476, + [SMALL_STATE(134)] = 2571, + [SMALL_STATE(135)] = 2662, + [SMALL_STATE(136)] = 2753, + [SMALL_STATE(137)] = 2848, + [SMALL_STATE(138)] = 2943, + [SMALL_STATE(139)] = 3034, + [SMALL_STATE(140)] = 3125, + [SMALL_STATE(141)] = 3220, + [SMALL_STATE(142)] = 3315, + [SMALL_STATE(143)] = 3406, + [SMALL_STATE(144)] = 3497, + [SMALL_STATE(145)] = 3588, + [SMALL_STATE(146)] = 3679, + [SMALL_STATE(147)] = 3730, + [SMALL_STATE(148)] = 3825, + [SMALL_STATE(149)] = 3920, + [SMALL_STATE(150)] = 4011, + [SMALL_STATE(151)] = 4102, + [SMALL_STATE(152)] = 4197, + [SMALL_STATE(153)] = 4292, + [SMALL_STATE(154)] = 4387, + [SMALL_STATE(155)] = 4482, + [SMALL_STATE(156)] = 4577, + [SMALL_STATE(157)] = 4619, + [SMALL_STATE(158)] = 4669, + [SMALL_STATE(159)] = 4719, + [SMALL_STATE(160)] = 4761, + [SMALL_STATE(161)] = 4807, + [SMALL_STATE(162)] = 4849, + [SMALL_STATE(163)] = 4925, + [SMALL_STATE(164)] = 4967, + [SMALL_STATE(165)] = 5043, + [SMALL_STATE(166)] = 5089, + [SMALL_STATE(167)] = 5135, + [SMALL_STATE(168)] = 5224, + [SMALL_STATE(169)] = 5269, + [SMALL_STATE(170)] = 5310, + [SMALL_STATE(171)] = 5351, + [SMALL_STATE(172)] = 5392, + [SMALL_STATE(173)] = 5437, + [SMALL_STATE(174)] = 5478, + [SMALL_STATE(175)] = 5567, + [SMALL_STATE(176)] = 5656, + [SMALL_STATE(177)] = 5697, + [SMALL_STATE(178)] = 5786, + [SMALL_STATE(179)] = 5826, + [SMALL_STATE(180)] = 5866, + [SMALL_STATE(181)] = 5906, + [SMALL_STATE(182)] = 5992, + [SMALL_STATE(183)] = 6078, + [SMALL_STATE(184)] = 6127, + [SMALL_STATE(185)] = 6172, + [SMALL_STATE(186)] = 6217, + [SMALL_STATE(187)] = 6261, + [SMALL_STATE(188)] = 6305, + [SMALL_STATE(189)] = 6353, + [SMALL_STATE(190)] = 6428, + [SMALL_STATE(191)] = 6467, + [SMALL_STATE(192)] = 6510, + [SMALL_STATE(193)] = 6553, + [SMALL_STATE(194)] = 6596, + [SMALL_STATE(195)] = 6633, + [SMALL_STATE(196)] = 6676, + [SMALL_STATE(197)] = 6713, + [SMALL_STATE(198)] = 6752, + [SMALL_STATE(199)] = 6799, + [SMALL_STATE(200)] = 6870, + [SMALL_STATE(201)] = 6941, + [SMALL_STATE(202)] = 6988, + [SMALL_STATE(203)] = 7059, + [SMALL_STATE(204)] = 7130, + [SMALL_STATE(205)] = 7173, + [SMALL_STATE(206)] = 7248, + [SMALL_STATE(207)] = 7284, + [SMALL_STATE(208)] = 7326, + [SMALL_STATE(209)] = 7362, + [SMALL_STATE(210)] = 7400, + [SMALL_STATE(211)] = 7438, + [SMALL_STATE(212)] = 7473, + [SMALL_STATE(213)] = 7508, + [SMALL_STATE(214)] = 7545, + [SMALL_STATE(215)] = 7582, + [SMALL_STATE(216)] = 7623, + [SMALL_STATE(217)] = 7658, + [SMALL_STATE(218)] = 7693, + [SMALL_STATE(219)] = 7730, + [SMALL_STATE(220)] = 7767, + [SMALL_STATE(221)] = 7808, + [SMALL_STATE(222)] = 7843, + [SMALL_STATE(223)] = 7878, + [SMALL_STATE(224)] = 7913, + [SMALL_STATE(225)] = 7950, + [SMALL_STATE(226)] = 7985, + [SMALL_STATE(227)] = 8029, + [SMALL_STATE(228)] = 8063, + [SMALL_STATE(229)] = 8097, + [SMALL_STATE(230)] = 8137, + [SMALL_STATE(231)] = 8173, + [SMALL_STATE(232)] = 8207, + [SMALL_STATE(233)] = 8241, + [SMALL_STATE(234)] = 8281, + [SMALL_STATE(235)] = 8314, + [SMALL_STATE(236)] = 8347, + [SMALL_STATE(237)] = 8380, + [SMALL_STATE(238)] = 8413, + [SMALL_STATE(239)] = 8448, + [SMALL_STATE(240)] = 8481, + [SMALL_STATE(241)] = 8514, + [SMALL_STATE(242)] = 8547, + [SMALL_STATE(243)] = 8582, + [SMALL_STATE(244)] = 8615, + [SMALL_STATE(245)] = 8653, + [SMALL_STATE(246)] = 8687, + [SMALL_STATE(247)] = 8719, + [SMALL_STATE(248)] = 8751, + [SMALL_STATE(249)] = 8785, + [SMALL_STATE(250)] = 8816, + [SMALL_STATE(251)] = 8847, + [SMALL_STATE(252)] = 8878, + [SMALL_STATE(253)] = 8909, + [SMALL_STATE(254)] = 8940, + [SMALL_STATE(255)] = 8971, + [SMALL_STATE(256)] = 9002, + [SMALL_STATE(257)] = 9032, + [SMALL_STATE(258)] = 9064, + [SMALL_STATE(259)] = 9094, + [SMALL_STATE(260)] = 9124, + [SMALL_STATE(261)] = 9154, + [SMALL_STATE(262)] = 9198, + [SMALL_STATE(263)] = 9226, + [SMALL_STATE(264)] = 9254, + [SMALL_STATE(265)] = 9282, + [SMALL_STATE(266)] = 9326, + [SMALL_STATE(267)] = 9349, + [SMALL_STATE(268)] = 9374, + [SMALL_STATE(269)] = 9399, + [SMALL_STATE(270)] = 9424, + [SMALL_STATE(271)] = 9449, + [SMALL_STATE(272)] = 9474, + [SMALL_STATE(273)] = 9499, + [SMALL_STATE(274)] = 9522, + [SMALL_STATE(275)] = 9565, + [SMALL_STATE(276)] = 9588, + [SMALL_STATE(277)] = 9631, + [SMALL_STATE(278)] = 9658, + [SMALL_STATE(279)] = 9685, + [SMALL_STATE(280)] = 9712, + [SMALL_STATE(281)] = 9735, + [SMALL_STATE(282)] = 9760, + [SMALL_STATE(283)] = 9785, + [SMALL_STATE(284)] = 9808, + [SMALL_STATE(285)] = 9833, + [SMALL_STATE(286)] = 9858, + [SMALL_STATE(287)] = 9883, + [SMALL_STATE(288)] = 9908, + [SMALL_STATE(289)] = 9933, + [SMALL_STATE(290)] = 9958, + [SMALL_STATE(291)] = 9981, + [SMALL_STATE(292)] = 10003, + [SMALL_STATE(293)] = 10025, + [SMALL_STATE(294)] = 10047, + [SMALL_STATE(295)] = 10069, + [SMALL_STATE(296)] = 10091, + [SMALL_STATE(297)] = 10113, + [SMALL_STATE(298)] = 10135, + [SMALL_STATE(299)] = 10157, + [SMALL_STATE(300)] = 10179, + [SMALL_STATE(301)] = 10201, + [SMALL_STATE(302)] = 10223, + [SMALL_STATE(303)] = 10245, + [SMALL_STATE(304)] = 10267, + [SMALL_STATE(305)] = 10289, + [SMALL_STATE(306)] = 10311, + [SMALL_STATE(307)] = 10333, + [SMALL_STATE(308)] = 10355, + [SMALL_STATE(309)] = 10397, + [SMALL_STATE(310)] = 10439, + [SMALL_STATE(311)] = 10461, + [SMALL_STATE(312)] = 10483, + [SMALL_STATE(313)] = 10505, + [SMALL_STATE(314)] = 10527, + [SMALL_STATE(315)] = 10549, + [SMALL_STATE(316)] = 10571, + [SMALL_STATE(317)] = 10593, + [SMALL_STATE(318)] = 10615, + [SMALL_STATE(319)] = 10637, + [SMALL_STATE(320)] = 10659, + [SMALL_STATE(321)] = 10681, + [SMALL_STATE(322)] = 10703, + [SMALL_STATE(323)] = 10745, + [SMALL_STATE(324)] = 10767, + [SMALL_STATE(325)] = 10789, + [SMALL_STATE(326)] = 10811, + [SMALL_STATE(327)] = 10833, + [SMALL_STATE(328)] = 10855, + [SMALL_STATE(329)] = 10877, + [SMALL_STATE(330)] = 10899, + [SMALL_STATE(331)] = 10921, + [SMALL_STATE(332)] = 10943, + [SMALL_STATE(333)] = 10965, + [SMALL_STATE(334)] = 10987, + [SMALL_STATE(335)] = 11009, + [SMALL_STATE(336)] = 11031, + [SMALL_STATE(337)] = 11053, + [SMALL_STATE(338)] = 11075, + [SMALL_STATE(339)] = 11097, + [SMALL_STATE(340)] = 11119, + [SMALL_STATE(341)] = 11141, + [SMALL_STATE(342)] = 11163, + [SMALL_STATE(343)] = 11185, + [SMALL_STATE(344)] = 11207, + [SMALL_STATE(345)] = 11229, + [SMALL_STATE(346)] = 11251, + [SMALL_STATE(347)] = 11273, + [SMALL_STATE(348)] = 11295, + [SMALL_STATE(349)] = 11317, + [SMALL_STATE(350)] = 11339, + [SMALL_STATE(351)] = 11361, + [SMALL_STATE(352)] = 11383, + [SMALL_STATE(353)] = 11405, + [SMALL_STATE(354)] = 11427, + [SMALL_STATE(355)] = 11449, + [SMALL_STATE(356)] = 11471, + [SMALL_STATE(357)] = 11493, + [SMALL_STATE(358)] = 11515, + [SMALL_STATE(359)] = 11537, + [SMALL_STATE(360)] = 11559, + [SMALL_STATE(361)] = 11581, + [SMALL_STATE(362)] = 11603, + [SMALL_STATE(363)] = 11625, + [SMALL_STATE(364)] = 11647, + [SMALL_STATE(365)] = 11669, + [SMALL_STATE(366)] = 11711, + [SMALL_STATE(367)] = 11733, + [SMALL_STATE(368)] = 11755, + [SMALL_STATE(369)] = 11777, + [SMALL_STATE(370)] = 11799, + [SMALL_STATE(371)] = 11821, + [SMALL_STATE(372)] = 11843, + [SMALL_STATE(373)] = 11865, + [SMALL_STATE(374)] = 11887, + [SMALL_STATE(375)] = 11909, + [SMALL_STATE(376)] = 11931, + [SMALL_STATE(377)] = 11953, + [SMALL_STATE(378)] = 11975, + [SMALL_STATE(379)] = 11997, + [SMALL_STATE(380)] = 12019, + [SMALL_STATE(381)] = 12041, + [SMALL_STATE(382)] = 12063, + [SMALL_STATE(383)] = 12085, + [SMALL_STATE(384)] = 12107, + [SMALL_STATE(385)] = 12129, + [SMALL_STATE(386)] = 12151, + [SMALL_STATE(387)] = 12173, + [SMALL_STATE(388)] = 12195, + [SMALL_STATE(389)] = 12217, + [SMALL_STATE(390)] = 12239, + [SMALL_STATE(391)] = 12261, + [SMALL_STATE(392)] = 12283, + [SMALL_STATE(393)] = 12308, + [SMALL_STATE(394)] = 12333, + [SMALL_STATE(395)] = 12357, + [SMALL_STATE(396)] = 12379, + [SMALL_STATE(397)] = 12403, + [SMALL_STATE(398)] = 12423, + [SMALL_STATE(399)] = 12445, + [SMALL_STATE(400)] = 12465, + [SMALL_STATE(401)] = 12484, + [SMALL_STATE(402)] = 12505, + [SMALL_STATE(403)] = 12524, + [SMALL_STATE(404)] = 12547, + [SMALL_STATE(405)] = 12568, + [SMALL_STATE(406)] = 12591, + [SMALL_STATE(407)] = 12610, + [SMALL_STATE(408)] = 12629, + [SMALL_STATE(409)] = 12648, + [SMALL_STATE(410)] = 12671, + [SMALL_STATE(411)] = 12690, + [SMALL_STATE(412)] = 12708, + [SMALL_STATE(413)] = 12726, + [SMALL_STATE(414)] = 12746, + [SMALL_STATE(415)] = 12764, + [SMALL_STATE(416)] = 12784, + [SMALL_STATE(417)] = 12802, + [SMALL_STATE(418)] = 12820, + [SMALL_STATE(419)] = 12838, + [SMALL_STATE(420)] = 12856, + [SMALL_STATE(421)] = 12876, + [SMALL_STATE(422)] = 12905, + [SMALL_STATE(423)] = 12934, + [SMALL_STATE(424)] = 12963, + [SMALL_STATE(425)] = 12980, + [SMALL_STATE(426)] = 12997, + [SMALL_STATE(427)] = 13026, + [SMALL_STATE(428)] = 13057, + [SMALL_STATE(429)] = 13088, + [SMALL_STATE(430)] = 13117, + [SMALL_STATE(431)] = 13146, + [SMALL_STATE(432)] = 13175, + [SMALL_STATE(433)] = 13206, + [SMALL_STATE(434)] = 13237, + [SMALL_STATE(435)] = 13268, + [SMALL_STATE(436)] = 13297, + [SMALL_STATE(437)] = 13326, + [SMALL_STATE(438)] = 13357, + [SMALL_STATE(439)] = 13374, + [SMALL_STATE(440)] = 13403, + [SMALL_STATE(441)] = 13432, + [SMALL_STATE(442)] = 13461, + [SMALL_STATE(443)] = 13492, + [SMALL_STATE(444)] = 13523, + [SMALL_STATE(445)] = 13552, + [SMALL_STATE(446)] = 13569, + [SMALL_STATE(447)] = 13600, + [SMALL_STATE(448)] = 13631, + [SMALL_STATE(449)] = 13662, + [SMALL_STATE(450)] = 13691, + [SMALL_STATE(451)] = 13720, + [SMALL_STATE(452)] = 13751, + [SMALL_STATE(453)] = 13780, + [SMALL_STATE(454)] = 13809, + [SMALL_STATE(455)] = 13840, + [SMALL_STATE(456)] = 13869, + [SMALL_STATE(457)] = 13900, + [SMALL_STATE(458)] = 13929, + [SMALL_STATE(459)] = 13958, + [SMALL_STATE(460)] = 13989, + [SMALL_STATE(461)] = 14020, + [SMALL_STATE(462)] = 14051, + [SMALL_STATE(463)] = 14080, + [SMALL_STATE(464)] = 14109, + [SMALL_STATE(465)] = 14140, + [SMALL_STATE(466)] = 14171, + [SMALL_STATE(467)] = 14200, + [SMALL_STATE(468)] = 14231, + [SMALL_STATE(469)] = 14262, + [SMALL_STATE(470)] = 14279, + [SMALL_STATE(471)] = 14308, + [SMALL_STATE(472)] = 14339, + [SMALL_STATE(473)] = 14368, + [SMALL_STATE(474)] = 14397, + [SMALL_STATE(475)] = 14425, + [SMALL_STATE(476)] = 14453, + [SMALL_STATE(477)] = 14481, + [SMALL_STATE(478)] = 14509, + [SMALL_STATE(479)] = 14535, + [SMALL_STATE(480)] = 14563, + [SMALL_STATE(481)] = 14591, + [SMALL_STATE(482)] = 14610, + [SMALL_STATE(483)] = 14635, + [SMALL_STATE(484)] = 14660, + [SMALL_STATE(485)] = 14683, + [SMALL_STATE(486)] = 14706, + [SMALL_STATE(487)] = 14727, + [SMALL_STATE(488)] = 14752, + [SMALL_STATE(489)] = 14777, + [SMALL_STATE(490)] = 14800, + [SMALL_STATE(491)] = 14823, + [SMALL_STATE(492)] = 14848, + [SMALL_STATE(493)] = 14871, + [SMALL_STATE(494)] = 14894, + [SMALL_STATE(495)] = 14919, + [SMALL_STATE(496)] = 14942, + [SMALL_STATE(497)] = 14965, + [SMALL_STATE(498)] = 14988, + [SMALL_STATE(499)] = 15011, + [SMALL_STATE(500)] = 15032, + [SMALL_STATE(501)] = 15055, + [SMALL_STATE(502)] = 15080, + [SMALL_STATE(503)] = 15099, + [SMALL_STATE(504)] = 15124, + [SMALL_STATE(505)] = 15147, + [SMALL_STATE(506)] = 15170, + [SMALL_STATE(507)] = 15193, + [SMALL_STATE(508)] = 15218, + [SMALL_STATE(509)] = 15241, + [SMALL_STATE(510)] = 15264, + [SMALL_STATE(511)] = 15287, + [SMALL_STATE(512)] = 15310, + [SMALL_STATE(513)] = 15335, + [SMALL_STATE(514)] = 15360, + [SMALL_STATE(515)] = 15385, + [SMALL_STATE(516)] = 15410, + [SMALL_STATE(517)] = 15435, + [SMALL_STATE(518)] = 15458, + [SMALL_STATE(519)] = 15483, + [SMALL_STATE(520)] = 15506, + [SMALL_STATE(521)] = 15529, + [SMALL_STATE(522)] = 15554, + [SMALL_STATE(523)] = 15577, + [SMALL_STATE(524)] = 15600, + [SMALL_STATE(525)] = 15623, + [SMALL_STATE(526)] = 15648, + [SMALL_STATE(527)] = 15673, + [SMALL_STATE(528)] = 15696, + [SMALL_STATE(529)] = 15721, + [SMALL_STATE(530)] = 15746, + [SMALL_STATE(531)] = 15769, + [SMALL_STATE(532)] = 15794, + [SMALL_STATE(533)] = 15817, + [SMALL_STATE(534)] = 15840, + [SMALL_STATE(535)] = 15865, + [SMALL_STATE(536)] = 15888, + [SMALL_STATE(537)] = 15911, + [SMALL_STATE(538)] = 15934, + [SMALL_STATE(539)] = 15956, + [SMALL_STATE(540)] = 15975, + [SMALL_STATE(541)] = 15988, + [SMALL_STATE(542)] = 16007, + [SMALL_STATE(543)] = 16020, + [SMALL_STATE(544)] = 16039, + [SMALL_STATE(545)] = 16058, + [SMALL_STATE(546)] = 16071, + [SMALL_STATE(547)] = 16090, + [SMALL_STATE(548)] = 16103, + [SMALL_STATE(549)] = 16116, + [SMALL_STATE(550)] = 16129, + [SMALL_STATE(551)] = 16142, + [SMALL_STATE(552)] = 16155, + [SMALL_STATE(553)] = 16172, + [SMALL_STATE(554)] = 16191, + [SMALL_STATE(555)] = 16208, + [SMALL_STATE(556)] = 16223, + [SMALL_STATE(557)] = 16238, + [SMALL_STATE(558)] = 16257, + [SMALL_STATE(559)] = 16276, + [SMALL_STATE(560)] = 16295, + [SMALL_STATE(561)] = 16314, + [SMALL_STATE(562)] = 16333, + [SMALL_STATE(563)] = 16352, + [SMALL_STATE(564)] = 16365, + [SMALL_STATE(565)] = 16378, + [SMALL_STATE(566)] = 16397, + [SMALL_STATE(567)] = 16410, + [SMALL_STATE(568)] = 16427, + [SMALL_STATE(569)] = 16440, + [SMALL_STATE(570)] = 16455, + [SMALL_STATE(571)] = 16468, + [SMALL_STATE(572)] = 16481, + [SMALL_STATE(573)] = 16496, + [SMALL_STATE(574)] = 16509, + [SMALL_STATE(575)] = 16522, + [SMALL_STATE(576)] = 16541, + [SMALL_STATE(577)] = 16556, + [SMALL_STATE(578)] = 16575, + [SMALL_STATE(579)] = 16594, + [SMALL_STATE(580)] = 16613, + [SMALL_STATE(581)] = 16626, + [SMALL_STATE(582)] = 16639, + [SMALL_STATE(583)] = 16658, + [SMALL_STATE(584)] = 16677, + [SMALL_STATE(585)] = 16696, + [SMALL_STATE(586)] = 16715, + [SMALL_STATE(587)] = 16732, + [SMALL_STATE(588)] = 16751, + [SMALL_STATE(589)] = 16770, + [SMALL_STATE(590)] = 16789, + [SMALL_STATE(591)] = 16808, + [SMALL_STATE(592)] = 16827, + [SMALL_STATE(593)] = 16846, + [SMALL_STATE(594)] = 16859, + [SMALL_STATE(595)] = 16872, + [SMALL_STATE(596)] = 16885, + [SMALL_STATE(597)] = 16898, + [SMALL_STATE(598)] = 16911, + [SMALL_STATE(599)] = 16924, + [SMALL_STATE(600)] = 16937, + [SMALL_STATE(601)] = 16950, + [SMALL_STATE(602)] = 16963, + [SMALL_STATE(603)] = 16976, + [SMALL_STATE(604)] = 16989, + [SMALL_STATE(605)] = 17002, + [SMALL_STATE(606)] = 17021, + [SMALL_STATE(607)] = 17036, + [SMALL_STATE(608)] = 17055, + [SMALL_STATE(609)] = 17074, + [SMALL_STATE(610)] = 17093, + [SMALL_STATE(611)] = 17106, + [SMALL_STATE(612)] = 17121, + [SMALL_STATE(613)] = 17134, + [SMALL_STATE(614)] = 17147, + [SMALL_STATE(615)] = 17164, + [SMALL_STATE(616)] = 17181, + [SMALL_STATE(617)] = 17194, + [SMALL_STATE(618)] = 17213, + [SMALL_STATE(619)] = 17232, + [SMALL_STATE(620)] = 17251, + [SMALL_STATE(621)] = 17270, + [SMALL_STATE(622)] = 17289, + [SMALL_STATE(623)] = 17308, + [SMALL_STATE(624)] = 17321, + [SMALL_STATE(625)] = 17334, + [SMALL_STATE(626)] = 17353, + [SMALL_STATE(627)] = 17366, + [SMALL_STATE(628)] = 17385, + [SMALL_STATE(629)] = 17404, + [SMALL_STATE(630)] = 17423, + [SMALL_STATE(631)] = 17442, + [SMALL_STATE(632)] = 17461, + [SMALL_STATE(633)] = 17474, + [SMALL_STATE(634)] = 17493, + [SMALL_STATE(635)] = 17512, + [SMALL_STATE(636)] = 17531, + [SMALL_STATE(637)] = 17544, + [SMALL_STATE(638)] = 17557, + [SMALL_STATE(639)] = 17570, + [SMALL_STATE(640)] = 17583, + [SMALL_STATE(641)] = 17602, + [SMALL_STATE(642)] = 17621, + [SMALL_STATE(643)] = 17640, + [SMALL_STATE(644)] = 17659, + [SMALL_STATE(645)] = 17678, + [SMALL_STATE(646)] = 17695, + [SMALL_STATE(647)] = 17714, + [SMALL_STATE(648)] = 17733, + [SMALL_STATE(649)] = 17750, + [SMALL_STATE(650)] = 17767, + [SMALL_STATE(651)] = 17786, + [SMALL_STATE(652)] = 17805, + [SMALL_STATE(653)] = 17824, + [SMALL_STATE(654)] = 17843, + [SMALL_STATE(655)] = 17862, + [SMALL_STATE(656)] = 17881, + [SMALL_STATE(657)] = 17900, + [SMALL_STATE(658)] = 17919, + [SMALL_STATE(659)] = 17938, + [SMALL_STATE(660)] = 17957, + [SMALL_STATE(661)] = 17974, + [SMALL_STATE(662)] = 17991, + [SMALL_STATE(663)] = 18004, + [SMALL_STATE(664)] = 18021, + [SMALL_STATE(665)] = 18040, + [SMALL_STATE(666)] = 18059, + [SMALL_STATE(667)] = 18078, + [SMALL_STATE(668)] = 18097, + [SMALL_STATE(669)] = 18116, + [SMALL_STATE(670)] = 18135, + [SMALL_STATE(671)] = 18152, + [SMALL_STATE(672)] = 18169, + [SMALL_STATE(673)] = 18186, + [SMALL_STATE(674)] = 18203, + [SMALL_STATE(675)] = 18220, + [SMALL_STATE(676)] = 18237, + [SMALL_STATE(677)] = 18256, + [SMALL_STATE(678)] = 18269, + [SMALL_STATE(679)] = 18288, + [SMALL_STATE(680)] = 18301, + [SMALL_STATE(681)] = 18320, + [SMALL_STATE(682)] = 18339, + [SMALL_STATE(683)] = 18358, + [SMALL_STATE(684)] = 18371, + [SMALL_STATE(685)] = 18384, + [SMALL_STATE(686)] = 18403, + [SMALL_STATE(687)] = 18422, + [SMALL_STATE(688)] = 18441, + [SMALL_STATE(689)] = 18460, + [SMALL_STATE(690)] = 18479, + [SMALL_STATE(691)] = 18498, + [SMALL_STATE(692)] = 18517, + [SMALL_STATE(693)] = 18530, + [SMALL_STATE(694)] = 18546, + [SMALL_STATE(695)] = 18562, + [SMALL_STATE(696)] = 18574, + [SMALL_STATE(697)] = 18586, + [SMALL_STATE(698)] = 18598, + [SMALL_STATE(699)] = 18614, + [SMALL_STATE(700)] = 18626, + [SMALL_STATE(701)] = 18638, + [SMALL_STATE(702)] = 18650, + [SMALL_STATE(703)] = 18662, + [SMALL_STATE(704)] = 18674, + [SMALL_STATE(705)] = 18686, + [SMALL_STATE(706)] = 18698, + [SMALL_STATE(707)] = 18710, + [SMALL_STATE(708)] = 18722, + [SMALL_STATE(709)] = 18734, + [SMALL_STATE(710)] = 18746, + [SMALL_STATE(711)] = 18758, + [SMALL_STATE(712)] = 18772, + [SMALL_STATE(713)] = 18784, + [SMALL_STATE(714)] = 18796, + [SMALL_STATE(715)] = 18810, + [SMALL_STATE(716)] = 18822, + [SMALL_STATE(717)] = 18834, + [SMALL_STATE(718)] = 18848, + [SMALL_STATE(719)] = 18860, + [SMALL_STATE(720)] = 18872, + [SMALL_STATE(721)] = 18886, + [SMALL_STATE(722)] = 18898, + [SMALL_STATE(723)] = 18910, + [SMALL_STATE(724)] = 18922, + [SMALL_STATE(725)] = 18934, + [SMALL_STATE(726)] = 18946, + [SMALL_STATE(727)] = 18958, + [SMALL_STATE(728)] = 18970, + [SMALL_STATE(729)] = 18982, + [SMALL_STATE(730)] = 18994, + [SMALL_STATE(731)] = 19006, + [SMALL_STATE(732)] = 19018, + [SMALL_STATE(733)] = 19030, + [SMALL_STATE(734)] = 19042, + [SMALL_STATE(735)] = 19054, + [SMALL_STATE(736)] = 19068, + [SMALL_STATE(737)] = 19080, + [SMALL_STATE(738)] = 19094, + [SMALL_STATE(739)] = 19106, + [SMALL_STATE(740)] = 19118, + [SMALL_STATE(741)] = 19130, + [SMALL_STATE(742)] = 19146, + [SMALL_STATE(743)] = 19158, + [SMALL_STATE(744)] = 19170, + [SMALL_STATE(745)] = 19182, + [SMALL_STATE(746)] = 19194, + [SMALL_STATE(747)] = 19206, + [SMALL_STATE(748)] = 19220, + [SMALL_STATE(749)] = 19232, + [SMALL_STATE(750)] = 19244, + [SMALL_STATE(751)] = 19260, + [SMALL_STATE(752)] = 19276, + [SMALL_STATE(753)] = 19292, + [SMALL_STATE(754)] = 19304, + [SMALL_STATE(755)] = 19320, + [SMALL_STATE(756)] = 19336, + [SMALL_STATE(757)] = 19352, + [SMALL_STATE(758)] = 19368, + [SMALL_STATE(759)] = 19384, + [SMALL_STATE(760)] = 19400, + [SMALL_STATE(761)] = 19416, + [SMALL_STATE(762)] = 19432, + [SMALL_STATE(763)] = 19448, + [SMALL_STATE(764)] = 19464, + [SMALL_STATE(765)] = 19480, + [SMALL_STATE(766)] = 19496, + [SMALL_STATE(767)] = 19512, + [SMALL_STATE(768)] = 19528, + [SMALL_STATE(769)] = 19544, + [SMALL_STATE(770)] = 19560, + [SMALL_STATE(771)] = 19576, + [SMALL_STATE(772)] = 19592, + [SMALL_STATE(773)] = 19608, + [SMALL_STATE(774)] = 19624, + [SMALL_STATE(775)] = 19640, + [SMALL_STATE(776)] = 19656, + [SMALL_STATE(777)] = 19672, + [SMALL_STATE(778)] = 19688, + [SMALL_STATE(779)] = 19704, + [SMALL_STATE(780)] = 19720, + [SMALL_STATE(781)] = 19736, + [SMALL_STATE(782)] = 19752, + [SMALL_STATE(783)] = 19768, + [SMALL_STATE(784)] = 19780, + [SMALL_STATE(785)] = 19791, + [SMALL_STATE(786)] = 19804, + [SMALL_STATE(787)] = 19815, + [SMALL_STATE(788)] = 19826, + [SMALL_STATE(789)] = 19837, + [SMALL_STATE(790)] = 19848, + [SMALL_STATE(791)] = 19859, + [SMALL_STATE(792)] = 19870, + [SMALL_STATE(793)] = 19881, + [SMALL_STATE(794)] = 19892, + [SMALL_STATE(795)] = 19903, + [SMALL_STATE(796)] = 19914, + [SMALL_STATE(797)] = 19925, + [SMALL_STATE(798)] = 19936, + [SMALL_STATE(799)] = 19947, + [SMALL_STATE(800)] = 19958, + [SMALL_STATE(801)] = 19969, + [SMALL_STATE(802)] = 19982, + [SMALL_STATE(803)] = 19993, + [SMALL_STATE(804)] = 20004, + [SMALL_STATE(805)] = 20015, + [SMALL_STATE(806)] = 20034, + [SMALL_STATE(807)] = 20045, + [SMALL_STATE(808)] = 20056, + [SMALL_STATE(809)] = 20067, + [SMALL_STATE(810)] = 20078, + [SMALL_STATE(811)] = 20089, + [SMALL_STATE(812)] = 20100, + [SMALL_STATE(813)] = 20111, + [SMALL_STATE(814)] = 20122, + [SMALL_STATE(815)] = 20133, + [SMALL_STATE(816)] = 20144, + [SMALL_STATE(817)] = 20155, + [SMALL_STATE(818)] = 20166, + [SMALL_STATE(819)] = 20177, + [SMALL_STATE(820)] = 20188, + [SMALL_STATE(821)] = 20199, + [SMALL_STATE(822)] = 20210, + [SMALL_STATE(823)] = 20221, + [SMALL_STATE(824)] = 20232, + [SMALL_STATE(825)] = 20243, + [SMALL_STATE(826)] = 20254, + [SMALL_STATE(827)] = 20265, + [SMALL_STATE(828)] = 20278, + [SMALL_STATE(829)] = 20289, + [SMALL_STATE(830)] = 20300, + [SMALL_STATE(831)] = 20313, + [SMALL_STATE(832)] = 20324, + [SMALL_STATE(833)] = 20335, + [SMALL_STATE(834)] = 20348, + [SMALL_STATE(835)] = 20359, + [SMALL_STATE(836)] = 20370, + [SMALL_STATE(837)] = 20383, + [SMALL_STATE(838)] = 20394, + [SMALL_STATE(839)] = 20405, + [SMALL_STATE(840)] = 20416, + [SMALL_STATE(841)] = 20427, + [SMALL_STATE(842)] = 20438, + [SMALL_STATE(843)] = 20449, + [SMALL_STATE(844)] = 20460, + [SMALL_STATE(845)] = 20471, + [SMALL_STATE(846)] = 20482, + [SMALL_STATE(847)] = 20493, + [SMALL_STATE(848)] = 20504, + [SMALL_STATE(849)] = 20515, + [SMALL_STATE(850)] = 20526, + [SMALL_STATE(851)] = 20537, + [SMALL_STATE(852)] = 20548, + [SMALL_STATE(853)] = 20559, + [SMALL_STATE(854)] = 20572, + [SMALL_STATE(855)] = 20583, + [SMALL_STATE(856)] = 20596, + [SMALL_STATE(857)] = 20607, + [SMALL_STATE(858)] = 20618, + [SMALL_STATE(859)] = 20629, + [SMALL_STATE(860)] = 20640, + [SMALL_STATE(861)] = 20651, + [SMALL_STATE(862)] = 20662, + [SMALL_STATE(863)] = 20673, + [SMALL_STATE(864)] = 20684, + [SMALL_STATE(865)] = 20695, + [SMALL_STATE(866)] = 20706, + [SMALL_STATE(867)] = 20717, + [SMALL_STATE(868)] = 20728, + [SMALL_STATE(869)] = 20739, + [SMALL_STATE(870)] = 20750, + [SMALL_STATE(871)] = 20761, + [SMALL_STATE(872)] = 20772, + [SMALL_STATE(873)] = 20783, + [SMALL_STATE(874)] = 20794, + [SMALL_STATE(875)] = 20805, + [SMALL_STATE(876)] = 20816, + [SMALL_STATE(877)] = 20829, + [SMALL_STATE(878)] = 20840, + [SMALL_STATE(879)] = 20853, + [SMALL_STATE(880)] = 20864, + [SMALL_STATE(881)] = 20875, + [SMALL_STATE(882)] = 20888, + [SMALL_STATE(883)] = 20899, + [SMALL_STATE(884)] = 20910, + [SMALL_STATE(885)] = 20923, + [SMALL_STATE(886)] = 20934, + [SMALL_STATE(887)] = 20945, + [SMALL_STATE(888)] = 20956, + [SMALL_STATE(889)] = 20967, + [SMALL_STATE(890)] = 20978, + [SMALL_STATE(891)] = 20989, + [SMALL_STATE(892)] = 21000, + [SMALL_STATE(893)] = 21011, + [SMALL_STATE(894)] = 21022, + [SMALL_STATE(895)] = 21033, + [SMALL_STATE(896)] = 21044, + [SMALL_STATE(897)] = 21055, + [SMALL_STATE(898)] = 21066, + [SMALL_STATE(899)] = 21077, + [SMALL_STATE(900)] = 21088, + [SMALL_STATE(901)] = 21099, + [SMALL_STATE(902)] = 21110, + [SMALL_STATE(903)] = 21123, + [SMALL_STATE(904)] = 21134, + [SMALL_STATE(905)] = 21147, + [SMALL_STATE(906)] = 21158, + [SMALL_STATE(907)] = 21169, + [SMALL_STATE(908)] = 21180, + [SMALL_STATE(909)] = 21191, + [SMALL_STATE(910)] = 21202, + [SMALL_STATE(911)] = 21213, + [SMALL_STATE(912)] = 21224, + [SMALL_STATE(913)] = 21235, + [SMALL_STATE(914)] = 21246, + [SMALL_STATE(915)] = 21257, + [SMALL_STATE(916)] = 21268, + [SMALL_STATE(917)] = 21279, + [SMALL_STATE(918)] = 21294, + [SMALL_STATE(919)] = 21309, + [SMALL_STATE(920)] = 21322, + [SMALL_STATE(921)] = 21333, + [SMALL_STATE(922)] = 21344, + [SMALL_STATE(923)] = 21355, + [SMALL_STATE(924)] = 21366, + [SMALL_STATE(925)] = 21377, + [SMALL_STATE(926)] = 21388, + [SMALL_STATE(927)] = 21399, + [SMALL_STATE(928)] = 21410, + [SMALL_STATE(929)] = 21429, + [SMALL_STATE(930)] = 21440, + [SMALL_STATE(931)] = 21451, + [SMALL_STATE(932)] = 21462, + [SMALL_STATE(933)] = 21473, + [SMALL_STATE(934)] = 21484, + [SMALL_STATE(935)] = 21495, + [SMALL_STATE(936)] = 21508, + [SMALL_STATE(937)] = 21519, + [SMALL_STATE(938)] = 21530, + [SMALL_STATE(939)] = 21541, + [SMALL_STATE(940)] = 21556, + [SMALL_STATE(941)] = 21567, + [SMALL_STATE(942)] = 21578, + [SMALL_STATE(943)] = 21589, + [SMALL_STATE(944)] = 21600, + [SMALL_STATE(945)] = 21611, + [SMALL_STATE(946)] = 21622, + [SMALL_STATE(947)] = 21633, + [SMALL_STATE(948)] = 21644, + [SMALL_STATE(949)] = 21655, + [SMALL_STATE(950)] = 21666, + [SMALL_STATE(951)] = 21677, + [SMALL_STATE(952)] = 21688, + [SMALL_STATE(953)] = 21699, + [SMALL_STATE(954)] = 21710, + [SMALL_STATE(955)] = 21721, + [SMALL_STATE(956)] = 21732, + [SMALL_STATE(957)] = 21743, + [SMALL_STATE(958)] = 21754, + [SMALL_STATE(959)] = 21765, + [SMALL_STATE(960)] = 21776, + [SMALL_STATE(961)] = 21787, + [SMALL_STATE(962)] = 21798, + [SMALL_STATE(963)] = 21809, + [SMALL_STATE(964)] = 21823, + [SMALL_STATE(965)] = 21837, + [SMALL_STATE(966)] = 21851, + [SMALL_STATE(967)] = 21865, + [SMALL_STATE(968)] = 21879, + [SMALL_STATE(969)] = 21889, + [SMALL_STATE(970)] = 21903, + [SMALL_STATE(971)] = 21917, + [SMALL_STATE(972)] = 21931, + [SMALL_STATE(973)] = 21945, + [SMALL_STATE(974)] = 21959, + [SMALL_STATE(975)] = 21973, + [SMALL_STATE(976)] = 21987, + [SMALL_STATE(977)] = 22001, + [SMALL_STATE(978)] = 22015, + [SMALL_STATE(979)] = 22029, + [SMALL_STATE(980)] = 22043, + [SMALL_STATE(981)] = 22059, + [SMALL_STATE(982)] = 22075, + [SMALL_STATE(983)] = 22089, + [SMALL_STATE(984)] = 22103, + [SMALL_STATE(985)] = 22119, + [SMALL_STATE(986)] = 22131, + [SMALL_STATE(987)] = 22145, + [SMALL_STATE(988)] = 22157, + [SMALL_STATE(989)] = 22169, + [SMALL_STATE(990)] = 22181, + [SMALL_STATE(991)] = 22193, + [SMALL_STATE(992)] = 22209, + [SMALL_STATE(993)] = 22223, + [SMALL_STATE(994)] = 22237, + [SMALL_STATE(995)] = 22251, + [SMALL_STATE(996)] = 22265, + [SMALL_STATE(997)] = 22277, + [SMALL_STATE(998)] = 22289, + [SMALL_STATE(999)] = 22303, + [SMALL_STATE(1000)] = 22313, + [SMALL_STATE(1001)] = 22325, + [SMALL_STATE(1002)] = 22335, + [SMALL_STATE(1003)] = 22349, + [SMALL_STATE(1004)] = 22363, + [SMALL_STATE(1005)] = 22377, + [SMALL_STATE(1006)] = 22389, + [SMALL_STATE(1007)] = 22403, + [SMALL_STATE(1008)] = 22417, + [SMALL_STATE(1009)] = 22429, + [SMALL_STATE(1010)] = 22445, + [SMALL_STATE(1011)] = 22459, + [SMALL_STATE(1012)] = 22473, + [SMALL_STATE(1013)] = 22487, + [SMALL_STATE(1014)] = 22501, + [SMALL_STATE(1015)] = 22515, + [SMALL_STATE(1016)] = 22525, + [SMALL_STATE(1017)] = 22539, + [SMALL_STATE(1018)] = 22553, + [SMALL_STATE(1019)] = 22569, + [SMALL_STATE(1020)] = 22583, + [SMALL_STATE(1021)] = 22597, + [SMALL_STATE(1022)] = 22611, + [SMALL_STATE(1023)] = 22625, + [SMALL_STATE(1024)] = 22639, + [SMALL_STATE(1025)] = 22653, + [SMALL_STATE(1026)] = 22667, + [SMALL_STATE(1027)] = 22681, + [SMALL_STATE(1028)] = 22695, + [SMALL_STATE(1029)] = 22709, + [SMALL_STATE(1030)] = 22723, + [SMALL_STATE(1031)] = 22733, + [SMALL_STATE(1032)] = 22749, + [SMALL_STATE(1033)] = 22763, + [SMALL_STATE(1034)] = 22777, + [SMALL_STATE(1035)] = 22791, + [SMALL_STATE(1036)] = 22807, + [SMALL_STATE(1037)] = 22817, + [SMALL_STATE(1038)] = 22829, + [SMALL_STATE(1039)] = 22843, + [SMALL_STATE(1040)] = 22853, + [SMALL_STATE(1041)] = 22865, + [SMALL_STATE(1042)] = 22879, + [SMALL_STATE(1043)] = 22893, + [SMALL_STATE(1044)] = 22907, + [SMALL_STATE(1045)] = 22917, + [SMALL_STATE(1046)] = 22931, + [SMALL_STATE(1047)] = 22943, + [SMALL_STATE(1048)] = 22955, + [SMALL_STATE(1049)] = 22969, + [SMALL_STATE(1050)] = 22978, + [SMALL_STATE(1051)] = 22987, + [SMALL_STATE(1052)] = 22996, + [SMALL_STATE(1053)] = 23005, + [SMALL_STATE(1054)] = 23014, + [SMALL_STATE(1055)] = 23023, + [SMALL_STATE(1056)] = 23032, + [SMALL_STATE(1057)] = 23045, + [SMALL_STATE(1058)] = 23054, + [SMALL_STATE(1059)] = 23063, + [SMALL_STATE(1060)] = 23072, + [SMALL_STATE(1061)] = 23081, + [SMALL_STATE(1062)] = 23090, + [SMALL_STATE(1063)] = 23099, + [SMALL_STATE(1064)] = 23108, + [SMALL_STATE(1065)] = 23117, + [SMALL_STATE(1066)] = 23126, + [SMALL_STATE(1067)] = 23139, + [SMALL_STATE(1068)] = 23148, + [SMALL_STATE(1069)] = 23157, + [SMALL_STATE(1070)] = 23166, + [SMALL_STATE(1071)] = 23175, + [SMALL_STATE(1072)] = 23184, + [SMALL_STATE(1073)] = 23193, + [SMALL_STATE(1074)] = 23202, + [SMALL_STATE(1075)] = 23211, + [SMALL_STATE(1076)] = 23220, + [SMALL_STATE(1077)] = 23229, + [SMALL_STATE(1078)] = 23238, + [SMALL_STATE(1079)] = 23251, + [SMALL_STATE(1080)] = 23260, + [SMALL_STATE(1081)] = 23269, + [SMALL_STATE(1082)] = 23282, + [SMALL_STATE(1083)] = 23291, + [SMALL_STATE(1084)] = 23300, + [SMALL_STATE(1085)] = 23309, + [SMALL_STATE(1086)] = 23318, + [SMALL_STATE(1087)] = 23327, + [SMALL_STATE(1088)] = 23336, + [SMALL_STATE(1089)] = 23345, + [SMALL_STATE(1090)] = 23358, + [SMALL_STATE(1091)] = 23367, + [SMALL_STATE(1092)] = 23376, + [SMALL_STATE(1093)] = 23385, + [SMALL_STATE(1094)] = 23394, + [SMALL_STATE(1095)] = 23403, + [SMALL_STATE(1096)] = 23412, + [SMALL_STATE(1097)] = 23421, + [SMALL_STATE(1098)] = 23430, + [SMALL_STATE(1099)] = 23439, + [SMALL_STATE(1100)] = 23448, + [SMALL_STATE(1101)] = 23457, + [SMALL_STATE(1102)] = 23466, + [SMALL_STATE(1103)] = 23475, + [SMALL_STATE(1104)] = 23484, + [SMALL_STATE(1105)] = 23493, + [SMALL_STATE(1106)] = 23502, + [SMALL_STATE(1107)] = 23511, + [SMALL_STATE(1108)] = 23520, + [SMALL_STATE(1109)] = 23529, + [SMALL_STATE(1110)] = 23538, + [SMALL_STATE(1111)] = 23547, + [SMALL_STATE(1112)] = 23560, + [SMALL_STATE(1113)] = 23573, + [SMALL_STATE(1114)] = 23582, + [SMALL_STATE(1115)] = 23591, + [SMALL_STATE(1116)] = 23600, + [SMALL_STATE(1117)] = 23609, + [SMALL_STATE(1118)] = 23620, + [SMALL_STATE(1119)] = 23631, + [SMALL_STATE(1120)] = 23640, + [SMALL_STATE(1121)] = 23653, + [SMALL_STATE(1122)] = 23666, + [SMALL_STATE(1123)] = 23675, + [SMALL_STATE(1124)] = 23684, + [SMALL_STATE(1125)] = 23693, + [SMALL_STATE(1126)] = 23702, + [SMALL_STATE(1127)] = 23711, + [SMALL_STATE(1128)] = 23720, + [SMALL_STATE(1129)] = 23731, + [SMALL_STATE(1130)] = 23740, + [SMALL_STATE(1131)] = 23749, + [SMALL_STATE(1132)] = 23758, + [SMALL_STATE(1133)] = 23767, + [SMALL_STATE(1134)] = 23776, + [SMALL_STATE(1135)] = 23785, + [SMALL_STATE(1136)] = 23794, + [SMALL_STATE(1137)] = 23803, + [SMALL_STATE(1138)] = 23812, + [SMALL_STATE(1139)] = 23821, + [SMALL_STATE(1140)] = 23830, + [SMALL_STATE(1141)] = 23843, + [SMALL_STATE(1142)] = 23856, + [SMALL_STATE(1143)] = 23865, + [SMALL_STATE(1144)] = 23874, + [SMALL_STATE(1145)] = 23885, + [SMALL_STATE(1146)] = 23894, + [SMALL_STATE(1147)] = 23905, + [SMALL_STATE(1148)] = 23918, + [SMALL_STATE(1149)] = 23931, + [SMALL_STATE(1150)] = 23942, + [SMALL_STATE(1151)] = 23953, + [SMALL_STATE(1152)] = 23962, + [SMALL_STATE(1153)] = 23971, + [SMALL_STATE(1154)] = 23982, + [SMALL_STATE(1155)] = 23991, + [SMALL_STATE(1156)] = 24002, + [SMALL_STATE(1157)] = 24011, + [SMALL_STATE(1158)] = 24020, + [SMALL_STATE(1159)] = 24029, + [SMALL_STATE(1160)] = 24040, + [SMALL_STATE(1161)] = 24051, + [SMALL_STATE(1162)] = 24060, + [SMALL_STATE(1163)] = 24069, + [SMALL_STATE(1164)] = 24078, + [SMALL_STATE(1165)] = 24087, + [SMALL_STATE(1166)] = 24096, + [SMALL_STATE(1167)] = 24105, + [SMALL_STATE(1168)] = 24116, + [SMALL_STATE(1169)] = 24127, + [SMALL_STATE(1170)] = 24136, + [SMALL_STATE(1171)] = 24145, + [SMALL_STATE(1172)] = 24154, + [SMALL_STATE(1173)] = 24163, + [SMALL_STATE(1174)] = 24172, + [SMALL_STATE(1175)] = 24181, + [SMALL_STATE(1176)] = 24190, + [SMALL_STATE(1177)] = 24199, + [SMALL_STATE(1178)] = 24208, + [SMALL_STATE(1179)] = 24217, + [SMALL_STATE(1180)] = 24228, + [SMALL_STATE(1181)] = 24239, + [SMALL_STATE(1182)] = 24250, + [SMALL_STATE(1183)] = 24259, + [SMALL_STATE(1184)] = 24268, + [SMALL_STATE(1185)] = 24279, + [SMALL_STATE(1186)] = 24288, + [SMALL_STATE(1187)] = 24297, + [SMALL_STATE(1188)] = 24306, + [SMALL_STATE(1189)] = 24315, + [SMALL_STATE(1190)] = 24324, + [SMALL_STATE(1191)] = 24333, + [SMALL_STATE(1192)] = 24342, + [SMALL_STATE(1193)] = 24351, + [SMALL_STATE(1194)] = 24360, + [SMALL_STATE(1195)] = 24369, + [SMALL_STATE(1196)] = 24378, + [SMALL_STATE(1197)] = 24387, + [SMALL_STATE(1198)] = 24396, + [SMALL_STATE(1199)] = 24405, + [SMALL_STATE(1200)] = 24414, + [SMALL_STATE(1201)] = 24423, + [SMALL_STATE(1202)] = 24432, + [SMALL_STATE(1203)] = 24441, + [SMALL_STATE(1204)] = 24450, + [SMALL_STATE(1205)] = 24459, + [SMALL_STATE(1206)] = 24468, + [SMALL_STATE(1207)] = 24477, + [SMALL_STATE(1208)] = 24486, + [SMALL_STATE(1209)] = 24495, + [SMALL_STATE(1210)] = 24504, + [SMALL_STATE(1211)] = 24513, + [SMALL_STATE(1212)] = 24522, + [SMALL_STATE(1213)] = 24531, + [SMALL_STATE(1214)] = 24540, + [SMALL_STATE(1215)] = 24549, + [SMALL_STATE(1216)] = 24558, + [SMALL_STATE(1217)] = 24566, + [SMALL_STATE(1218)] = 24574, + [SMALL_STATE(1219)] = 24582, + [SMALL_STATE(1220)] = 24590, + [SMALL_STATE(1221)] = 24598, + [SMALL_STATE(1222)] = 24606, + [SMALL_STATE(1223)] = 24614, + [SMALL_STATE(1224)] = 24622, + [SMALL_STATE(1225)] = 24630, + [SMALL_STATE(1226)] = 24638, + [SMALL_STATE(1227)] = 24646, + [SMALL_STATE(1228)] = 24656, + [SMALL_STATE(1229)] = 24664, + [SMALL_STATE(1230)] = 24672, + [SMALL_STATE(1231)] = 24680, + [SMALL_STATE(1232)] = 24688, + [SMALL_STATE(1233)] = 24696, + [SMALL_STATE(1234)] = 24704, + [SMALL_STATE(1235)] = 24712, + [SMALL_STATE(1236)] = 24720, + [SMALL_STATE(1237)] = 24728, + [SMALL_STATE(1238)] = 24738, + [SMALL_STATE(1239)] = 24746, + [SMALL_STATE(1240)] = 24756, + [SMALL_STATE(1241)] = 24764, + [SMALL_STATE(1242)] = 24772, + [SMALL_STATE(1243)] = 24782, + [SMALL_STATE(1244)] = 24792, + [SMALL_STATE(1245)] = 24802, + [SMALL_STATE(1246)] = 24810, + [SMALL_STATE(1247)] = 24818, + [SMALL_STATE(1248)] = 24826, + [SMALL_STATE(1249)] = 24834, + [SMALL_STATE(1250)] = 24842, + [SMALL_STATE(1251)] = 24850, + [SMALL_STATE(1252)] = 24858, + [SMALL_STATE(1253)] = 24866, + [SMALL_STATE(1254)] = 24874, + [SMALL_STATE(1255)] = 24882, + [SMALL_STATE(1256)] = 24890, + [SMALL_STATE(1257)] = 24898, + [SMALL_STATE(1258)] = 24906, + [SMALL_STATE(1259)] = 24914, + [SMALL_STATE(1260)] = 24922, + [SMALL_STATE(1261)] = 24930, + [SMALL_STATE(1262)] = 24938, + [SMALL_STATE(1263)] = 24946, + [SMALL_STATE(1264)] = 24954, + [SMALL_STATE(1265)] = 24962, + [SMALL_STATE(1266)] = 24970, + [SMALL_STATE(1267)] = 24978, + [SMALL_STATE(1268)] = 24986, + [SMALL_STATE(1269)] = 24994, + [SMALL_STATE(1270)] = 25002, + [SMALL_STATE(1271)] = 25010, + [SMALL_STATE(1272)] = 25018, + [SMALL_STATE(1273)] = 25026, + [SMALL_STATE(1274)] = 25034, + [SMALL_STATE(1275)] = 25042, + [SMALL_STATE(1276)] = 25050, + [SMALL_STATE(1277)] = 25058, + [SMALL_STATE(1278)] = 25066, + [SMALL_STATE(1279)] = 25074, + [SMALL_STATE(1280)] = 25082, + [SMALL_STATE(1281)] = 25090, + [SMALL_STATE(1282)] = 25098, + [SMALL_STATE(1283)] = 25106, + [SMALL_STATE(1284)] = 25114, + [SMALL_STATE(1285)] = 25122, + [SMALL_STATE(1286)] = 25130, + [SMALL_STATE(1287)] = 25138, + [SMALL_STATE(1288)] = 25146, + [SMALL_STATE(1289)] = 25154, + [SMALL_STATE(1290)] = 25162, + [SMALL_STATE(1291)] = 25170, + [SMALL_STATE(1292)] = 25178, + [SMALL_STATE(1293)] = 25186, + [SMALL_STATE(1294)] = 25194, + [SMALL_STATE(1295)] = 25202, + [SMALL_STATE(1296)] = 25210, + [SMALL_STATE(1297)] = 25218, + [SMALL_STATE(1298)] = 25226, + [SMALL_STATE(1299)] = 25234, + [SMALL_STATE(1300)] = 25244, + [SMALL_STATE(1301)] = 25252, + [SMALL_STATE(1302)] = 25260, + [SMALL_STATE(1303)] = 25268, + [SMALL_STATE(1304)] = 25276, + [SMALL_STATE(1305)] = 25284, + [SMALL_STATE(1306)] = 25292, + [SMALL_STATE(1307)] = 25300, + [SMALL_STATE(1308)] = 25308, + [SMALL_STATE(1309)] = 25316, + [SMALL_STATE(1310)] = 25324, + [SMALL_STATE(1311)] = 25332, + [SMALL_STATE(1312)] = 25340, + [SMALL_STATE(1313)] = 25348, + [SMALL_STATE(1314)] = 25356, + [SMALL_STATE(1315)] = 25366, + [SMALL_STATE(1316)] = 25374, + [SMALL_STATE(1317)] = 25382, + [SMALL_STATE(1318)] = 25390, + [SMALL_STATE(1319)] = 25398, + [SMALL_STATE(1320)] = 25406, + [SMALL_STATE(1321)] = 25416, + [SMALL_STATE(1322)] = 25424, + [SMALL_STATE(1323)] = 25432, + [SMALL_STATE(1324)] = 25440, + [SMALL_STATE(1325)] = 25448, + [SMALL_STATE(1326)] = 25458, + [SMALL_STATE(1327)] = 25466, + [SMALL_STATE(1328)] = 25474, + [SMALL_STATE(1329)] = 25482, + [SMALL_STATE(1330)] = 25490, + [SMALL_STATE(1331)] = 25500, + [SMALL_STATE(1332)] = 25508, + [SMALL_STATE(1333)] = 25516, + [SMALL_STATE(1334)] = 25524, + [SMALL_STATE(1335)] = 25532, + [SMALL_STATE(1336)] = 25540, + [SMALL_STATE(1337)] = 25548, + [SMALL_STATE(1338)] = 25556, + [SMALL_STATE(1339)] = 25564, + [SMALL_STATE(1340)] = 25572, + [SMALL_STATE(1341)] = 25580, + [SMALL_STATE(1342)] = 25588, + [SMALL_STATE(1343)] = 25596, + [SMALL_STATE(1344)] = 25604, + [SMALL_STATE(1345)] = 25612, + [SMALL_STATE(1346)] = 25620, + [SMALL_STATE(1347)] = 25628, + [SMALL_STATE(1348)] = 25636, + [SMALL_STATE(1349)] = 25644, + [SMALL_STATE(1350)] = 25652, + [SMALL_STATE(1351)] = 25660, + [SMALL_STATE(1352)] = 25668, + [SMALL_STATE(1353)] = 25676, + [SMALL_STATE(1354)] = 25684, + [SMALL_STATE(1355)] = 25692, + [SMALL_STATE(1356)] = 25700, + [SMALL_STATE(1357)] = 25708, + [SMALL_STATE(1358)] = 25716, + [SMALL_STATE(1359)] = 25724, + [SMALL_STATE(1360)] = 25734, + [SMALL_STATE(1361)] = 25742, + [SMALL_STATE(1362)] = 25750, + [SMALL_STATE(1363)] = 25758, + [SMALL_STATE(1364)] = 25766, + [SMALL_STATE(1365)] = 25774, + [SMALL_STATE(1366)] = 25782, + [SMALL_STATE(1367)] = 25790, + [SMALL_STATE(1368)] = 25798, + [SMALL_STATE(1369)] = 25806, + [SMALL_STATE(1370)] = 25814, + [SMALL_STATE(1371)] = 25824, + [SMALL_STATE(1372)] = 25832, + [SMALL_STATE(1373)] = 25840, + [SMALL_STATE(1374)] = 25848, + [SMALL_STATE(1375)] = 25858, + [SMALL_STATE(1376)] = 25866, + [SMALL_STATE(1377)] = 25874, + [SMALL_STATE(1378)] = 25882, + [SMALL_STATE(1379)] = 25890, + [SMALL_STATE(1380)] = 25898, + [SMALL_STATE(1381)] = 25906, + [SMALL_STATE(1382)] = 25914, + [SMALL_STATE(1383)] = 25922, + [SMALL_STATE(1384)] = 25930, + [SMALL_STATE(1385)] = 25938, + [SMALL_STATE(1386)] = 25946, + [SMALL_STATE(1387)] = 25954, + [SMALL_STATE(1388)] = 25962, + [SMALL_STATE(1389)] = 25970, + [SMALL_STATE(1390)] = 25978, + [SMALL_STATE(1391)] = 25986, + [SMALL_STATE(1392)] = 25994, + [SMALL_STATE(1393)] = 26002, + [SMALL_STATE(1394)] = 26010, + [SMALL_STATE(1395)] = 26018, + [SMALL_STATE(1396)] = 26026, + [SMALL_STATE(1397)] = 26034, + [SMALL_STATE(1398)] = 26042, + [SMALL_STATE(1399)] = 26050, + [SMALL_STATE(1400)] = 26058, + [SMALL_STATE(1401)] = 26066, + [SMALL_STATE(1402)] = 26074, + [SMALL_STATE(1403)] = 26082, + [SMALL_STATE(1404)] = 26090, + [SMALL_STATE(1405)] = 26098, + [SMALL_STATE(1406)] = 26106, + [SMALL_STATE(1407)] = 26114, + [SMALL_STATE(1408)] = 26122, + [SMALL_STATE(1409)] = 26130, + [SMALL_STATE(1410)] = 26138, + [SMALL_STATE(1411)] = 26145, + [SMALL_STATE(1412)] = 26152, + [SMALL_STATE(1413)] = 26159, + [SMALL_STATE(1414)] = 26166, + [SMALL_STATE(1415)] = 26173, + [SMALL_STATE(1416)] = 26180, + [SMALL_STATE(1417)] = 26187, + [SMALL_STATE(1418)] = 26194, + [SMALL_STATE(1419)] = 26201, + [SMALL_STATE(1420)] = 26208, + [SMALL_STATE(1421)] = 26215, + [SMALL_STATE(1422)] = 26222, + [SMALL_STATE(1423)] = 26229, + [SMALL_STATE(1424)] = 26236, + [SMALL_STATE(1425)] = 26243, + [SMALL_STATE(1426)] = 26250, + [SMALL_STATE(1427)] = 26257, + [SMALL_STATE(1428)] = 26264, + [SMALL_STATE(1429)] = 26271, + [SMALL_STATE(1430)] = 26278, + [SMALL_STATE(1431)] = 26285, + [SMALL_STATE(1432)] = 26292, + [SMALL_STATE(1433)] = 26299, + [SMALL_STATE(1434)] = 26306, + [SMALL_STATE(1435)] = 26313, + [SMALL_STATE(1436)] = 26320, + [SMALL_STATE(1437)] = 26327, + [SMALL_STATE(1438)] = 26334, + [SMALL_STATE(1439)] = 26341, + [SMALL_STATE(1440)] = 26348, + [SMALL_STATE(1441)] = 26355, + [SMALL_STATE(1442)] = 26362, + [SMALL_STATE(1443)] = 26369, + [SMALL_STATE(1444)] = 26376, + [SMALL_STATE(1445)] = 26383, + [SMALL_STATE(1446)] = 26390, + [SMALL_STATE(1447)] = 26397, + [SMALL_STATE(1448)] = 26404, + [SMALL_STATE(1449)] = 26411, + [SMALL_STATE(1450)] = 26418, + [SMALL_STATE(1451)] = 26425, + [SMALL_STATE(1452)] = 26432, + [SMALL_STATE(1453)] = 26439, + [SMALL_STATE(1454)] = 26446, + [SMALL_STATE(1455)] = 26453, + [SMALL_STATE(1456)] = 26460, + [SMALL_STATE(1457)] = 26467, + [SMALL_STATE(1458)] = 26474, + [SMALL_STATE(1459)] = 26481, + [SMALL_STATE(1460)] = 26488, + [SMALL_STATE(1461)] = 26495, + [SMALL_STATE(1462)] = 26502, + [SMALL_STATE(1463)] = 26509, + [SMALL_STATE(1464)] = 26516, + [SMALL_STATE(1465)] = 26523, + [SMALL_STATE(1466)] = 26530, + [SMALL_STATE(1467)] = 26537, + [SMALL_STATE(1468)] = 26544, + [SMALL_STATE(1469)] = 26551, + [SMALL_STATE(1470)] = 26558, + [SMALL_STATE(1471)] = 26565, + [SMALL_STATE(1472)] = 26572, + [SMALL_STATE(1473)] = 26579, + [SMALL_STATE(1474)] = 26586, + [SMALL_STATE(1475)] = 26593, + [SMALL_STATE(1476)] = 26600, + [SMALL_STATE(1477)] = 26607, + [SMALL_STATE(1478)] = 26614, + [SMALL_STATE(1479)] = 26621, + [SMALL_STATE(1480)] = 26628, + [SMALL_STATE(1481)] = 26635, + [SMALL_STATE(1482)] = 26642, + [SMALL_STATE(1483)] = 26649, + [SMALL_STATE(1484)] = 26656, + [SMALL_STATE(1485)] = 26663, + [SMALL_STATE(1486)] = 26670, + [SMALL_STATE(1487)] = 26677, + [SMALL_STATE(1488)] = 26684, + [SMALL_STATE(1489)] = 26691, + [SMALL_STATE(1490)] = 26698, + [SMALL_STATE(1491)] = 26705, + [SMALL_STATE(1492)] = 26712, + [SMALL_STATE(1493)] = 26719, + [SMALL_STATE(1494)] = 26726, + [SMALL_STATE(1495)] = 26733, + [SMALL_STATE(1496)] = 26740, + [SMALL_STATE(1497)] = 26747, + [SMALL_STATE(1498)] = 26754, + [SMALL_STATE(1499)] = 26761, + [SMALL_STATE(1500)] = 26768, + [SMALL_STATE(1501)] = 26775, + [SMALL_STATE(1502)] = 26782, + [SMALL_STATE(1503)] = 26789, + [SMALL_STATE(1504)] = 26796, + [SMALL_STATE(1505)] = 26803, + [SMALL_STATE(1506)] = 26810, + [SMALL_STATE(1507)] = 26817, + [SMALL_STATE(1508)] = 26824, + [SMALL_STATE(1509)] = 26831, + [SMALL_STATE(1510)] = 26838, + [SMALL_STATE(1511)] = 26845, + [SMALL_STATE(1512)] = 26852, + [SMALL_STATE(1513)] = 26859, + [SMALL_STATE(1514)] = 26866, + [SMALL_STATE(1515)] = 26873, + [SMALL_STATE(1516)] = 26880, + [SMALL_STATE(1517)] = 26887, + [SMALL_STATE(1518)] = 26894, + [SMALL_STATE(1519)] = 26901, + [SMALL_STATE(1520)] = 26908, + [SMALL_STATE(1521)] = 26915, + [SMALL_STATE(1522)] = 26922, + [SMALL_STATE(1523)] = 26929, + [SMALL_STATE(1524)] = 26936, + [SMALL_STATE(1525)] = 26943, + [SMALL_STATE(1526)] = 26950, + [SMALL_STATE(1527)] = 26957, + [SMALL_STATE(1528)] = 26964, + [SMALL_STATE(1529)] = 26971, + [SMALL_STATE(1530)] = 26978, + [SMALL_STATE(1531)] = 26985, + [SMALL_STATE(1532)] = 26992, + [SMALL_STATE(1533)] = 26999, + [SMALL_STATE(1534)] = 27006, + [SMALL_STATE(1535)] = 27013, + [SMALL_STATE(1536)] = 27020, + [SMALL_STATE(1537)] = 27027, + [SMALL_STATE(1538)] = 27034, + [SMALL_STATE(1539)] = 27041, + [SMALL_STATE(1540)] = 27048, + [SMALL_STATE(1541)] = 27055, + [SMALL_STATE(1542)] = 27062, + [SMALL_STATE(1543)] = 27069, + [SMALL_STATE(1544)] = 27076, + [SMALL_STATE(1545)] = 27083, + [SMALL_STATE(1546)] = 27090, + [SMALL_STATE(1547)] = 27097, + [SMALL_STATE(1548)] = 27104, + [SMALL_STATE(1549)] = 27111, + [SMALL_STATE(1550)] = 27118, + [SMALL_STATE(1551)] = 27125, + [SMALL_STATE(1552)] = 27132, + [SMALL_STATE(1553)] = 27139, + [SMALL_STATE(1554)] = 27146, + [SMALL_STATE(1555)] = 27153, + [SMALL_STATE(1556)] = 27160, + [SMALL_STATE(1557)] = 27167, + [SMALL_STATE(1558)] = 27174, + [SMALL_STATE(1559)] = 27181, + [SMALL_STATE(1560)] = 27188, + [SMALL_STATE(1561)] = 27195, + [SMALL_STATE(1562)] = 27202, + [SMALL_STATE(1563)] = 27209, + [SMALL_STATE(1564)] = 27216, + [SMALL_STATE(1565)] = 27223, + [SMALL_STATE(1566)] = 27230, + [SMALL_STATE(1567)] = 27237, + [SMALL_STATE(1568)] = 27244, + [SMALL_STATE(1569)] = 27251, + [SMALL_STATE(1570)] = 27258, + [SMALL_STATE(1571)] = 27265, + [SMALL_STATE(1572)] = 27272, + [SMALL_STATE(1573)] = 27279, + [SMALL_STATE(1574)] = 27286, + [SMALL_STATE(1575)] = 27293, + [SMALL_STATE(1576)] = 27300, + [SMALL_STATE(1577)] = 27307, + [SMALL_STATE(1578)] = 27314, +}; + +static const TSParseActionEntry ts_parse_actions[] = { + [0] = {.entry = {.count = 0, .reusable = false}}, + [1] = {.entry = {.count = 1, .reusable = false}}, RECOVER(), + [3] = {.entry = {.count = 1, .reusable = true}}, SHIFT_EXTRA(), + [5] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1465), + [7] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1427), + [9] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1515), + [11] = {.entry = {.count = 1, .reusable = true}}, SHIFT(694), + [13] = {.entry = {.count = 1, .reusable = true}}, SHIFT(12), + [15] = {.entry = {.count = 1, .reusable = true}}, SHIFT(250), + [17] = {.entry = {.count = 1, .reusable = true}}, SHIFT(10), + [19] = {.entry = {.count = 1, .reusable = true}}, SHIFT(8), + [21] = {.entry = {.count = 1, .reusable = true}}, SHIFT(3), + [23] = {.entry = {.count = 1, .reusable = true}}, SHIFT(4), + [25] = {.entry = {.count = 1, .reusable = true}}, SHIFT(2), + [27] = {.entry = {.count = 1, .reusable = true}}, SHIFT(5), + [29] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1078), + [31] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1081), + [33] = {.entry = {.count = 1, .reusable = true}}, SHIFT(32), + [35] = {.entry = {.count = 1, .reusable = true}}, SHIFT(27), + [37] = {.entry = {.count = 1, .reusable = true}}, SHIFT(13), + [39] = {.entry = {.count = 1, .reusable = true}}, SHIFT(14), + [41] = {.entry = {.count = 1, .reusable = true}}, SHIFT(443), + [43] = {.entry = {.count = 1, .reusable = true}}, SHIFT(459), + [45] = {.entry = {.count = 1, .reusable = true}}, SHIFT(516), + [47] = {.entry = {.count = 1, .reusable = true}}, SHIFT(525), + [49] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1030), + [51] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1036), + [53] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1135), + [55] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1142), + [57] = {.entry = {.count = 1, .reusable = true}}, SHIFT(118), + [59] = {.entry = {.count = 1, .reusable = true}}, SHIFT(116), + [61] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1498), + [63] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1519), + [65] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1474), + [67] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1486), + [69] = {.entry = {.count = 1, .reusable = true}}, SHIFT(9), + [71] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_blk_val_itm, 1, 0, 0), + [73] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1140), + [75] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1141), + [77] = {.entry = {.count = 1, .reusable = true}}, SHIFT(26), + [79] = {.entry = {.count = 1, .reusable = true}}, SHIFT(25), + [81] = {.entry = {.count = 1, .reusable = true}}, SHIFT(18), + [83] = {.entry = {.count = 1, .reusable = true}}, SHIFT(16), + [85] = {.entry = {.count = 1, .reusable = true}}, SHIFT(427), + [87] = {.entry = {.count = 1, .reusable = true}}, SHIFT(428), + [89] = {.entry = {.count = 1, .reusable = true}}, SHIFT(487), + [91] = {.entry = {.count = 1, .reusable = true}}, SHIFT(494), + [93] = {.entry = {.count = 1, .reusable = true}}, SHIFT(273), + [95] = {.entry = {.count = 1, .reusable = true}}, SHIFT(280), + [97] = {.entry = {.count = 1, .reusable = true}}, SHIFT(336), + [99] = {.entry = {.count = 1, .reusable = true}}, SHIFT(337), + [101] = {.entry = {.count = 1, .reusable = true}}, SHIFT(96), + [103] = {.entry = {.count = 1, .reusable = true}}, SHIFT(97), + [105] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1433), + [107] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1431), + [109] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1435), + [111] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1437), + [113] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_blk_key_itm, 1, 0, 0), + [115] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_blk_key_itm, 1, 0, 0), + [117] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_blk_val_itm, 1, 0, 0), + [119] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_blk_key_itm, 1, 0, 0), + [121] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_blk_val_itm, 1, 0, 0), + [123] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_blk_seq_itm, 1, 0, 0), + [125] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1111), + [127] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1112), + [129] = {.entry = {.count = 1, .reusable = true}}, SHIFT(28), + [131] = {.entry = {.count = 1, .reusable = true}}, SHIFT(29), + [133] = {.entry = {.count = 1, .reusable = true}}, SHIFT(15), + [135] = {.entry = {.count = 1, .reusable = true}}, SHIFT(17), + [137] = {.entry = {.count = 1, .reusable = true}}, SHIFT(446), + [139] = {.entry = {.count = 1, .reusable = true}}, SHIFT(447), + [141] = {.entry = {.count = 1, .reusable = true}}, SHIFT(482), + [143] = {.entry = {.count = 1, .reusable = true}}, SHIFT(483), + [145] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1198), + [147] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1107), + [149] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1380), + [151] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1381), + [153] = {.entry = {.count = 1, .reusable = true}}, SHIFT(122), + [155] = {.entry = {.count = 1, .reusable = true}}, SHIFT(123), + [157] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1430), + [159] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1483), + [161] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1432), + [163] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1508), + [165] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_blk_seq_itm, 1, 0, 0), + [167] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_blk_seq_itm, 1, 0, 0), + [169] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__blk_imp_itm_tal, 1, 0, 0), + [171] = {.entry = {.count = 1, .reusable = true}}, SHIFT(65), + [173] = {.entry = {.count = 1, .reusable = true}}, SHIFT(49), + [175] = {.entry = {.count = 1, .reusable = true}}, SHIFT(449), + [177] = {.entry = {.count = 1, .reusable = true}}, SHIFT(485), + [179] = {.entry = {.count = 1, .reusable = true}}, SHIFT(315), + [181] = {.entry = {.count = 1, .reusable = true}}, SHIFT(98), + [183] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1560), + [185] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1544), + [187] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__exp_doc, 1, 0, 0), + [189] = {.entry = {.count = 1, .reusable = true}}, SHIFT(57), + [191] = {.entry = {.count = 1, .reusable = true}}, SHIFT(45), + [193] = {.entry = {.count = 1, .reusable = true}}, SHIFT(430), + [195] = {.entry = {.count = 1, .reusable = true}}, SHIFT(490), + [197] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1106), + [199] = {.entry = {.count = 1, .reusable = true}}, SHIFT(124), + [201] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1472), + [203] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1494), + [205] = {.entry = {.count = 1, .reusable = true}}, SHIFT(24), + [207] = {.entry = {.count = 1, .reusable = true}}, SHIFT(60), + [209] = {.entry = {.count = 1, .reusable = true}}, SHIFT(19), + [211] = {.entry = {.count = 1, .reusable = true}}, SHIFT(42), + [213] = {.entry = {.count = 1, .reusable = true}}, SHIFT(988), + [215] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1133), + [217] = {.entry = {.count = 1, .reusable = true}}, SHIFT(40), + [219] = {.entry = {.count = 1, .reusable = true}}, SHIFT(84), + [221] = {.entry = {.count = 1, .reusable = true}}, SHIFT(69), + [223] = {.entry = {.count = 1, .reusable = true}}, SHIFT(94), + [225] = {.entry = {.count = 1, .reusable = true}}, SHIFT(448), + [227] = {.entry = {.count = 1, .reusable = true}}, SHIFT(462), + [229] = {.entry = {.count = 1, .reusable = true}}, SHIFT(514), + [231] = {.entry = {.count = 1, .reusable = true}}, SHIFT(517), + [233] = {.entry = {.count = 1, .reusable = true}}, SHIFT(677), + [235] = {.entry = {.count = 1, .reusable = true}}, SHIFT(679), + [237] = {.entry = {.count = 1, .reusable = true}}, SHIFT(683), + [239] = {.entry = {.count = 1, .reusable = true}}, SHIFT(684), + [241] = {.entry = {.count = 1, .reusable = true}}, SHIFT(183), + [243] = {.entry = {.count = 1, .reusable = true}}, SHIFT(184), + [245] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1438), + [247] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1503), + [249] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1440), + [251] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1505), + [253] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1076), + [255] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1144), + [257] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1258), + [259] = {.entry = {.count = 1, .reusable = true}}, SHIFT(285), + [261] = {.entry = {.count = 1, .reusable = true}}, SHIFT(370), + [263] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1259), + [265] = {.entry = {.count = 1, .reusable = true}}, SHIFT(369), + [267] = {.entry = {.count = 1, .reusable = true}}, SHIFT(569), + [269] = {.entry = {.count = 1, .reusable = true}}, SHIFT(570), + [271] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1320), + [273] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1321), + [275] = {.entry = {.count = 1, .reusable = true}}, SHIFT(714), + [277] = {.entry = {.count = 1, .reusable = true}}, SHIFT(715), + [279] = {.entry = {.count = 1, .reusable = true}}, SHIFT(830), + [281] = {.entry = {.count = 1, .reusable = true}}, SHIFT(831), + [283] = {.entry = {.count = 1, .reusable = true}}, SHIFT(878), + [285] = {.entry = {.count = 1, .reusable = true}}, SHIFT(879), + [287] = {.entry = {.count = 1, .reusable = true}}, SHIFT(30), + [289] = {.entry = {.count = 1, .reusable = true}}, SHIFT(64), + [291] = {.entry = {.count = 1, .reusable = true}}, SHIFT(555), + [293] = {.entry = {.count = 1, .reusable = true}}, SHIFT(566), + [295] = {.entry = {.count = 1, .reusable = true}}, SHIFT(21), + [297] = {.entry = {.count = 1, .reusable = true}}, SHIFT(53), + [299] = {.entry = {.count = 1, .reusable = true}}, SHIFT(41), + [301] = {.entry = {.count = 1, .reusable = true}}, SHIFT(86), + [303] = {.entry = {.count = 1, .reusable = true}}, SHIFT(55), + [305] = {.entry = {.count = 1, .reusable = true}}, SHIFT(95), + [307] = {.entry = {.count = 1, .reusable = true}}, SHIFT(437), + [309] = {.entry = {.count = 1, .reusable = true}}, SHIFT(440), + [311] = {.entry = {.count = 1, .reusable = true}}, SHIFT(513), + [313] = {.entry = {.count = 1, .reusable = true}}, SHIFT(533), + [315] = {.entry = {.count = 1, .reusable = true}}, SHIFT(695), + [317] = {.entry = {.count = 1, .reusable = true}}, SHIFT(696), + [319] = {.entry = {.count = 1, .reusable = true}}, SHIFT(697), + [321] = {.entry = {.count = 1, .reusable = true}}, SHIFT(699), + [323] = {.entry = {.count = 1, .reusable = true}}, SHIFT(188), + [325] = {.entry = {.count = 1, .reusable = true}}, SHIFT(186), + [327] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1578), + [329] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1434), + [331] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1504), + [333] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1436), + [335] = {.entry = {.count = 1, .reusable = true}}, SHIFT(284), + [337] = {.entry = {.count = 1, .reusable = true}}, SHIFT(367), + [339] = {.entry = {.count = 1, .reusable = true}}, SHIFT(366), + [341] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1047), + [343] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1109), + [345] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1128), + [347] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1247), + [349] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1256), + [351] = {.entry = {.count = 1, .reusable = true}}, SHIFT(711), + [353] = {.entry = {.count = 1, .reusable = true}}, SHIFT(712), + [355] = {.entry = {.count = 1, .reusable = true}}, SHIFT(827), + [357] = {.entry = {.count = 1, .reusable = true}}, SHIFT(828), + [359] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1131), + [361] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1314), + [363] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1316), + [365] = {.entry = {.count = 1, .reusable = true}}, SHIFT(876), + [367] = {.entry = {.count = 1, .reusable = true}}, SHIFT(784), + [369] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_prp_val, 1, 0, 0), + [371] = {.entry = {.count = 1, .reusable = true}}, SHIFT(409), + [373] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1479), + [375] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1441), + [377] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_prp_val, 1, 0, 0), + [379] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1426), + [381] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__doc_w_bgn_w_end_seq, 1, 0, 0), + [383] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__doc_wo_bgn_w_end_seq, 1, 0, 0), + [385] = {.entry = {.count = 1, .reusable = true}}, SHIFT(33), + [387] = {.entry = {.count = 1, .reusable = true}}, SHIFT(58), + [389] = {.entry = {.count = 1, .reusable = true}}, SHIFT(20), + [391] = {.entry = {.count = 1, .reusable = true}}, SHIFT(47), + [393] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__r_flw_exp_par, 1, 0, 0), REDUCE(sym__r_sgl_flw_exp_par, 1, 0, 0), + [396] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_exp_par, 1, 0, 0), + [398] = {.entry = {.count = 1, .reusable = true}}, SHIFT(454), + [400] = {.entry = {.count = 1, .reusable = true}}, SHIFT(431), + [402] = {.entry = {.count = 1, .reusable = true}}, SHIFT(501), + [404] = {.entry = {.count = 1, .reusable = true}}, SHIFT(509), + [406] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1315), + [408] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1216), + [410] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1262), + [412] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1263), + [414] = {.entry = {.count = 1, .reusable = true}}, SHIFT(226), + [416] = {.entry = {.count = 1, .reusable = true}}, SHIFT(233), + [418] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1545), + [420] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1543), + [422] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1480), + [424] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1481), + [426] = {.entry = {.count = 1, .reusable = true}}, SHIFT(61), + [428] = {.entry = {.count = 1, .reusable = true}}, SHIFT(46), + [430] = {.entry = {.count = 1, .reusable = true}}, SHIFT(571), + [432] = {.entry = {.count = 1, .reusable = true}}, SHIFT(87), + [434] = {.entry = {.count = 1, .reusable = true}}, SHIFT(88), + [436] = {.entry = {.count = 1, .reusable = true}}, SHIFT(429), + [438] = {.entry = {.count = 1, .reusable = true}}, SHIFT(523), + [440] = {.entry = {.count = 1, .reusable = true}}, SHIFT(185), + [442] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1323), + [444] = {.entry = {.count = 1, .reusable = true}}, SHIFT(832), + [446] = {.entry = {.count = 1, .reusable = true}}, SHIFT(880), + [448] = {.entry = {.count = 1, .reusable = true}}, SHIFT(716), + [450] = {.entry = {.count = 1, .reusable = true}}, SHIFT(31), + [452] = {.entry = {.count = 1, .reusable = true}}, SHIFT(63), + [454] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__r_flw_njl_ann_par, 1, 0, 0), REDUCE(sym__r_sgl_flw_njl_ann_par, 1, 0, 0), + [457] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_njl_ann_par, 1, 0, 0), + [459] = {.entry = {.count = 1, .reusable = true}}, SHIFT(22), + [461] = {.entry = {.count = 1, .reusable = true}}, SHIFT(48), + [463] = {.entry = {.count = 1, .reusable = true}}, SHIFT(461), + [465] = {.entry = {.count = 1, .reusable = true}}, SHIFT(441), + [467] = {.entry = {.count = 1, .reusable = true}}, SHIFT(515), + [469] = {.entry = {.count = 1, .reusable = true}}, SHIFT(527), + [471] = {.entry = {.count = 1, .reusable = true}}, SHIFT(955), + [473] = {.entry = {.count = 1, .reusable = true}}, SHIFT(957), + [475] = {.entry = {.count = 1, .reusable = true}}, SHIFT(958), + [477] = {.entry = {.count = 1, .reusable = true}}, SHIFT(959), + [479] = {.entry = {.count = 1, .reusable = true}}, SHIFT(198), + [481] = {.entry = {.count = 1, .reusable = true}}, SHIFT(204), + [483] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1548), + [485] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1546), + [487] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1512), + [489] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1513), + [491] = {.entry = {.count = 1, .reusable = true}}, SHIFT(59), + [493] = {.entry = {.count = 1, .reusable = true}}, SHIFT(43), + [495] = {.entry = {.count = 1, .reusable = true}}, SHIFT(85), + [497] = {.entry = {.count = 1, .reusable = true}}, SHIFT(91), + [499] = {.entry = {.count = 1, .reusable = true}}, SHIFT(457), + [501] = {.entry = {.count = 1, .reusable = true}}, SHIFT(511), + [503] = {.entry = {.count = 1, .reusable = true}}, SHIFT(187), + [505] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1318), + [507] = {.entry = {.count = 1, .reusable = true}}, SHIFT(568), + [509] = {.entry = {.count = 1, .reusable = true}}, SHIFT(829), + [511] = {.entry = {.count = 1, .reusable = true}}, SHIFT(713), + [513] = {.entry = {.count = 1, .reusable = true}}, SHIFT(877), + [515] = {.entry = {.count = 1, .reusable = true}}, SHIFT(34), + [517] = {.entry = {.count = 1, .reusable = true}}, SHIFT(66), + [519] = {.entry = {.count = 1, .reusable = true}}, SHIFT(23), + [521] = {.entry = {.count = 1, .reusable = true}}, SHIFT(50), + [523] = {.entry = {.count = 1, .reusable = true}}, SHIFT(468), + [525] = {.entry = {.count = 1, .reusable = true}}, SHIFT(450), + [527] = {.entry = {.count = 1, .reusable = true}}, SHIFT(528), + [529] = {.entry = {.count = 1, .reusable = true}}, SHIFT(489), + [531] = {.entry = {.count = 1, .reusable = true}}, SHIFT(813), + [533] = {.entry = {.count = 1, .reusable = true}}, SHIFT(796), + [535] = {.entry = {.count = 1, .reusable = true}}, SHIFT(797), + [537] = {.entry = {.count = 1, .reusable = true}}, SHIFT(798), + [539] = {.entry = {.count = 1, .reusable = true}}, SHIFT(201), + [541] = {.entry = {.count = 1, .reusable = true}}, SHIFT(193), + [543] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1554), + [545] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1552), + [547] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1540), + [549] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1541), + [551] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_map_dat, 2, 0, 0), + [553] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_map_dat, 2, 0, 0), + [555] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_map_dat, 3, 0, 0), + [557] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_map_dat, 3, 0, 0), + [559] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_seq_dat, 2, 0, 0), + [561] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_seq_dat, 2, 0, 0), + [563] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_seq_dat, 3, 0, 0), + [565] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_seq_dat, 3, 0, 0), + [567] = {.entry = {.count = 1, .reusable = true}}, SHIFT(62), + [569] = {.entry = {.count = 1, .reusable = true}}, SHIFT(52), + [571] = {.entry = {.count = 1, .reusable = true}}, SHIFT(439), + [573] = {.entry = {.count = 1, .reusable = true}}, SHIFT(520), + [575] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1281), + [577] = {.entry = {.count = 1, .reusable = true}}, SHIFT(67), + [579] = {.entry = {.count = 1, .reusable = true}}, SHIFT(51), + [581] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_exp_par, 1, 0, 0), + [583] = {.entry = {.count = 1, .reusable = true}}, SHIFT(421), + [585] = {.entry = {.count = 1, .reusable = true}}, SHIFT(505), + [587] = {.entry = {.count = 1, .reusable = true}}, SHIFT(229), + [589] = {.entry = {.count = 1, .reusable = true}}, SHIFT(56), + [591] = {.entry = {.count = 1, .reusable = true}}, SHIFT(44), + [593] = {.entry = {.count = 1, .reusable = true}}, SHIFT(470), + [595] = {.entry = {.count = 1, .reusable = true}}, SHIFT(532), + [597] = {.entry = {.count = 1, .reusable = true}}, SHIFT(195), + [599] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_jsl_ann_par, 1, 0, 0), + [601] = {.entry = {.count = 1, .reusable = true}}, SHIFT(68), + [603] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_jsl_ann_par, 1, 0, 0), + [605] = {.entry = {.count = 1, .reusable = true}}, SHIFT(54), + [607] = {.entry = {.count = 1, .reusable = true}}, SHIFT(463), + [609] = {.entry = {.count = 1, .reusable = true}}, SHIFT(519), + [611] = {.entry = {.count = 1, .reusable = true}}, SHIFT(192), + [613] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_njl_ann_par, 1, 0, 0), + [615] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_prp, 1, 0, 0), + [617] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_prp, 1, 0, 0), + [619] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__r_prp, 1, 0, 0), REDUCE(sym__r_sgl_prp, 1, 0, 0), + [622] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1542), + [624] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__r_prp, 1, 0, 0), SHIFT(1539), + [627] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_prp, 1, 0, 0), + [629] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sgl_prp, 1, 0, 0), + [631] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__br_prp, 1, 0, 0), REDUCE(sym__br_sgl_prp, 1, 0, 0), + [634] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__br_prp, 1, 0, 0), SHIFT(1539), + [637] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1571), + [639] = {.entry = {.count = 1, .reusable = true}}, SHIFT(104), + [641] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__br_prp, 1, 0, 0), SHIFT(109), + [644] = {.entry = {.count = 1, .reusable = true}}, SHIFT(103), + [646] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__r_prp, 1, 0, 0), SHIFT(108), + [649] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_acr, 2, 0, 0), + [651] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_acr, 2, 0, 0), + [653] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_prp, 2, 0, 0), + [655] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_prp, 2, 0, 0), + [657] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__r_prp, 2, 0, 0), REDUCE(sym__r_sgl_prp, 2, 0, 0), + [660] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_prp, 2, 0, 0), + [662] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sgl_prp, 2, 0, 0), + [664] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__br_prp, 2, 0, 0), REDUCE(sym__br_sgl_prp, 2, 0, 0), + [667] = {.entry = {.count = 1, .reusable = true}}, SHIFT(108), + [669] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1478), + [671] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__br_prp, 1, 0, 0), SHIFT(1439), + [674] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__r_prp, 1, 0, 0), SHIFT(1439), + [677] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1538), + [679] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__r_prp, 1, 0, 0), SHIFT(1511), + [682] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__br_prp, 1, 0, 0), SHIFT(1511), + [685] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1510), + [687] = {.entry = {.count = 1, .reusable = true}}, SHIFT(6), + [689] = {.entry = {.count = 1, .reusable = true}}, SHIFT(7), + [691] = {.entry = {.count = 1, .reusable = true}}, SHIFT(140), + [693] = {.entry = {.count = 1, .reusable = true}}, SHIFT(141), + [695] = {.entry = {.count = 1, .reusable = true}}, SHIFT(970), + [697] = {.entry = {.count = 1, .reusable = true}}, SHIFT(975), + [699] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1461), + [701] = {.entry = {.count = 1, .reusable = true}}, SHIFT(405), + [703] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1484), + [705] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1488), + [707] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1065), + [709] = {.entry = {.count = 1, .reusable = true}}, SHIFT(147), + [711] = {.entry = {.count = 1, .reusable = true}}, SHIFT(148), + [713] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1322), + [715] = {.entry = {.count = 1, .reusable = true}}, SHIFT(189), + [717] = {.entry = {.count = 1, .reusable = true}}, SHIFT(200), + [719] = {.entry = {.count = 1, .reusable = true}}, SHIFT(971), + [721] = {.entry = {.count = 1, .reusable = true}}, SHIFT(972), + [723] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1059), + [725] = {.entry = {.count = 1, .reusable = true}}, SHIFT(393), + [727] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1565), + [729] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1550), + [731] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__r_blk_map_repeat1, 2, 0, 0), SHIFT_REPEAT(6), + [734] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__r_blk_map_repeat1, 2, 0, 0), SHIFT_REPEAT(7), + [737] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__r_blk_map_repeat1, 2, 0, 0), SHIFT_REPEAT(140), + [740] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__r_blk_map_repeat1, 2, 0, 0), SHIFT_REPEAT(141), + [743] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__r_blk_map_repeat1, 2, 0, 0), SHIFT_REPEAT(970), + [746] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__r_blk_map_repeat1, 2, 0, 0), SHIFT_REPEAT(975), + [749] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__r_blk_map_repeat1, 2, 0, 0), SHIFT_REPEAT(1461), + [752] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__r_blk_map_repeat1, 2, 0, 0), SHIFT_REPEAT(405), + [755] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__r_blk_map_repeat1, 2, 0, 0), SHIFT_REPEAT(1484), + [758] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__r_blk_map_repeat1, 2, 0, 0), SHIFT_REPEAT(1488), + [761] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym__r_blk_map_repeat1, 2, 0, 0), + [763] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1080), + [765] = {.entry = {.count = 1, .reusable = true}}, SHIFT(165), + [767] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__r_prp, 1, 0, 0), SHIFT(176), + [770] = {.entry = {.count = 1, .reusable = true}}, SHIFT(136), + [772] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1423), + [774] = {.entry = {.count = 1, .reusable = true}}, SHIFT(137), + [776] = {.entry = {.count = 1, .reusable = true}}, SHIFT(205), + [778] = {.entry = {.count = 1, .reusable = true}}, SHIFT(199), + [780] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1017), + [782] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1019), + [784] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1077), + [786] = {.entry = {.count = 1, .reusable = true}}, SHIFT(392), + [788] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1564), + [790] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1547), + [792] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1517), + [794] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1296), + [796] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1297), + [798] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1139), + [800] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1145), + [802] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1364), + [804] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1365), + [806] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1445), + [808] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1496), + [810] = {.entry = {.count = 1, .reusable = true}}, SHIFT(299), + [812] = {.entry = {.count = 1, .reusable = true}}, SHIFT(301), + [814] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1176), + [816] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1069), + [818] = {.entry = {.count = 1, .reusable = true}}, SHIFT(166), + [820] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__br_prp, 1, 0, 0), SHIFT(169), + [823] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1050), + [825] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1064), + [827] = {.entry = {.count = 1, .reusable = true}}, SHIFT(387), + [829] = {.entry = {.count = 1, .reusable = true}}, SHIFT(292), + [831] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1509), + [833] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1422), + [835] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1257), + [837] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1264), + [839] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1317), + [841] = {.entry = {.count = 1, .reusable = true}}, SHIFT(168), + [843] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__r_prp, 1, 0, 0), SHIFT(178), + [846] = {.entry = {.count = 1, .reusable = true}}, SHIFT(172), + [848] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__br_prp, 1, 0, 0), SHIFT(179), + [851] = {.entry = {.count = 1, .reusable = true}}, SHIFT(176), + [853] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_flw_col_dat, 3, 0, 0), + [855] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_flw_col_dat, 2, 0, 0), + [857] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1557), + [859] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1555), + [861] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1410), + [863] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1549), + [865] = {.entry = {.count = 1, .reusable = true}}, SHIFT(151), + [867] = {.entry = {.count = 1, .reusable = true}}, SHIFT(152), + [869] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_flw_exp_par, 1, 0, 0), + [871] = {.entry = {.count = 1, .reusable = true}}, SHIFT(982), + [873] = {.entry = {.count = 1, .reusable = true}}, SHIFT(983), + [875] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1475), + [877] = {.entry = {.count = 1, .reusable = true}}, SHIFT(403), + [879] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1572), + [881] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1559), + [883] = {.entry = {.count = 1, .reusable = true}}, SHIFT(221), + [885] = {.entry = {.count = 1, .reusable = true}}, SHIFT(219), + [887] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1567), + [889] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1561), + [891] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1569), + [893] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1563), + [895] = {.entry = {.count = 1, .reusable = true}}, SHIFT(222), + [897] = {.entry = {.count = 1, .reusable = true}}, SHIFT(153), + [899] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_flw_njl_ann_par, 1, 0, 0), + [901] = {.entry = {.count = 1, .reusable = true}}, SHIFT(154), + [903] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1010), + [905] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1011), + [907] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1293), + [909] = {.entry = {.count = 1, .reusable = true}}, SHIFT(396), + [911] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1568), + [913] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1553), + [915] = {.entry = {.count = 1, .reusable = true}}, SHIFT(155), + [917] = {.entry = {.count = 1, .reusable = true}}, SHIFT(126), + [919] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1027), + [921] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1028), + [923] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1298), + [925] = {.entry = {.count = 1, .reusable = true}}, SHIFT(394), + [927] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1570), + [929] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1556), + [931] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_flw_jsl_ann_par, 1, 0, 0), + [933] = {.entry = {.count = 1, .reusable = true}}, SHIFT(230), + [935] = {.entry = {.count = 1, .reusable = true}}, SHIFT(231), + [937] = {.entry = {.count = 1, .reusable = true}}, SHIFT(232), + [939] = {.entry = {.count = 1, .reusable = true}}, SHIFT(240), + [941] = {.entry = {.count = 1, .reusable = true}}, SHIFT(236), + [943] = {.entry = {.count = 1, .reusable = true}}, SHIFT(238), + [945] = {.entry = {.count = 1, .reusable = true}}, SHIFT(243), + [947] = {.entry = {.count = 1, .reusable = true}}, SHIFT(242), + [949] = {.entry = {.count = 1, .reusable = true}}, SHIFT(234), + [951] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1566), + [953] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1558), + [955] = {.entry = {.count = 1, .reusable = true}}, SHIFT(257), + [957] = {.entry = {.count = 1, .reusable = true}}, SHIFT(258), + [959] = {.entry = {.count = 1, .reusable = true}}, SHIFT(260), + [961] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__drs_doc_end, 2, 0, 0), + [963] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__doc_end, 1, 0, 0), + [965] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__bgn_imp_doc_end, 2, 0, 0), + [967] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__exp_doc_end, 2, 0, 0), + [969] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__imp_doc_end, 2, 0, 0), + [971] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_prp_val, 1, 0, 0), + [973] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__blk_seq_itm_tal, 1, 0, 0), + [975] = {.entry = {.count = 1, .reusable = true}}, SHIFT(11), + [977] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__blk_imp_itm_tal, 2, 0, 5), + [979] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_als_val, 1, 0, 0), + [981] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_pln_blk_val, 2, 0, 0), + [983] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sgl_pln_blk_val, 1, 0, 0), + [985] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_pln_blk_val, 2, 0, 0), + [987] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_dqt_str, 3, 0, 0), + [989] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_dqt_str, 3, 0, 0), + [991] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_dqt_str, 3, 0, 0), + [993] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sgl_dqt_str, 3, 0, 0), + [995] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sqt_str, 3, 0, 0), + [997] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_sqt_str, 3, 0, 0), + [999] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sqt_str, 3, 0, 0), + [1001] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sgl_sqt_str, 3, 0, 0), + [1003] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_pln_blk, 1, 0, 0), + [1005] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_als, 2, 0, 0), + [1007] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_blk_exp_itm, 1, 0, 2), + [1009] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_blk_exp_itm, 1, 0, 2), + [1011] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_blk_exp_itm, 1, 0, 2), + [1013] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sgl_pln_blk, 1, 0, 0), + [1015] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_pln_blk_val, 1, 0, 0), + [1017] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_pln_blk_val, 1, 0, 0), + [1019] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_pln_blk_val, 1, 0, 0), + [1021] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_als_val, 1, 0, 0), + [1023] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__flw_seq_tal, 1, 0, 0), + [1025] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__sgl_flw_seq_tal, 1, 0, 0), + [1027] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__flw_map_tal, 1, 0, 0), + [1029] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__sgl_flw_map_tal, 1, 0, 0), + [1031] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_dqt_str, 2, 0, 0), + [1033] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_dqt_str, 2, 0, 0), + [1035] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_dqt_str, 2, 0, 0), + [1037] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sgl_dqt_str, 2, 0, 0), + [1039] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sqt_str, 2, 0, 0), + [1041] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_sqt_str, 2, 0, 0), + [1043] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sqt_str, 2, 0, 0), + [1045] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sgl_sqt_str, 2, 0, 0), + [1047] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_als, 2, 0, 0), + [1049] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_blk_exp_itm, 1, 0, 3), + [1051] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_blk_map, 3, 0, 0), + [1053] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_dqt_str, 4, 0, 0), + [1055] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_dqt_str, 4, 0, 0), + [1057] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sqt_str, 4, 0, 0), + [1059] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sqt_str, 4, 0, 0), + [1061] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_dqt_str, 5, 0, 0), + [1063] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_dqt_str_val, 2, 0, 0), + [1065] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_blk_map, 2, 0, 0), + [1067] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_blk_map, 2, 0, 0), + [1069] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_blk_key_itm, 2, 0, 4), + [1071] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_blk_val_itm, 2, 0, 5), + [1073] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_blk_imp_itm, 2, 0, 9), + [1075] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_blk_str, 3, 0, 0), + [1077] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_blk_exp_itm, 2, 0, 10), + [1079] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_blk_str, 3, 0, 0), + [1081] = {.entry = {.count = 1, .reusable = true}}, SHIFT(132), + [1083] = {.entry = {.count = 1, .reusable = true}}, SHIFT(133), + [1085] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1042), + [1087] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1043), + [1089] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1522), + [1091] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sgl_prp_val, 1, 0, 0), + [1093] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_blk_seq_spc_val, 1, 0, 0), + [1095] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_blk_key_itm, 2, 0, 4), + [1097] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_blk_key_itm, 2, 0, 4), + [1099] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_blk_imp_itm, 2, 0, 9), + [1101] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_blk_imp_itm, 2, 0, 9), + [1103] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_blk_val_itm, 2, 0, 5), + [1105] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_blk_val_itm, 2, 0, 5), + [1107] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_blk_map_itm, 1, 0, 1), + [1109] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_blk_map_itm, 1, 0, 1), + [1111] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__flw_seq_tal, 2, 0, 0), + [1113] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__flw_map_tal, 2, 0, 0), + [1115] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_sgl_prp_val, 1, 0, 0), + [1117] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_blk_map_itm, 1, 0, 1), + [1119] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_blk_exp_itm, 1, 0, 3), + [1121] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_map_val, 2, 0, 0), + [1123] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_blk_exp_itm, 1, 0, 3), + [1125] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_blk_exp_itm, 2, 0, 10), + [1127] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_blk_exp_itm, 2, 0, 10), + [1129] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_mtl_pln_blk, 1, 0, 0), + [1131] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_mtl_pln_blk, 1, 0, 0), + [1133] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_blk_seq_spc_val, 2, 0, 0), + [1135] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_blk_seq_spc_val, 2, 0, 0), + [1137] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_blk_seq_r_val, 1, 0, 0), + [1139] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_blk_seq_val, 1, 0, 0), + [1141] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_blk_map_r_val, 1, 0, 0), + [1143] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_blk_map_val, 1, 0, 0), + [1145] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_blk_str_val, 1, 0, 0), + [1147] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_blk_str_val, 1, 0, 0), + [1149] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_seq_val, 1, 0, 0), + [1151] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_seq_val, 1, 0, 0), + [1153] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_map_val, 1, 0, 0), + [1155] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_map_val, 1, 0, 0), + [1157] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_dqt_str_val, 1, 0, 0), + [1159] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_dqt_str_val, 1, 0, 0), + [1161] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sqt_str_val, 1, 0, 0), + [1163] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sqt_str_val, 1, 0, 0), + [1165] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sqt_str_val, 2, 0, 0), + [1167] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_blk_seq, 2, 0, 0), + [1169] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_blk_seq_spc, 2, 0, 0), + [1171] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_blk_str, 2, 0, 0), + [1173] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_blk_str, 2, 0, 0), + [1175] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_seq, 2, 0, 0), + [1177] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_seq, 2, 0, 0), + [1179] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_blk_seq, 2, 0, 0), + [1181] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_map, 2, 0, 0), + [1183] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_map, 2, 0, 0), + [1185] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_blk_seq, 3, 0, 0), + [1187] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_blk_seq, 3, 0, 0), + [1189] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_seq_val, 2, 0, 0), + [1191] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_blk_seq_br_val, 2, 0, 0), + [1193] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_blk_map_br_val, 2, 0, 0), + [1195] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_blk_str_val, 2, 0, 0), + [1197] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_seq_val, 2, 0, 0), + [1199] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_map_val, 2, 0, 0), + [1201] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_dqt_str_val, 2, 0, 0), + [1203] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sqt_str_val, 2, 0, 0), + [1205] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_blk_map, 3, 0, 0), + [1207] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_blk_seq_val, 2, 0, 0), + [1209] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_blk_map_val, 2, 0, 0), + [1211] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_blk_str_val, 2, 0, 0), + [1213] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_dqt_str, 5, 0, 0), + [1215] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1573), + [1217] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1574), + [1219] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1576), + [1221] = {.entry = {.count = 1, .reusable = true}}, SHIFT(406), + [1223] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1575), + [1225] = {.entry = {.count = 1, .reusable = true}}, SHIFT(408), + [1227] = {.entry = {.count = 1, .reusable = true}}, SHIFT(417), + [1229] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1577), + [1231] = {.entry = {.count = 1, .reusable = true}}, SHIFT(419), + [1233] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_sgl_prp, 1, 0, 0), + [1235] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1562), + [1237] = {.entry = {.count = 1, .reusable = true}}, SHIFT(445), + [1239] = {.entry = {.count = 1, .reusable = true}}, SHIFT(469), + [1241] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_acr, 2, 0, 0), + [1243] = {.entry = {.count = 1, .reusable = true}}, SHIFT(425), + [1245] = {.entry = {.count = 1, .reusable = true}}, SHIFT(458), + [1247] = {.entry = {.count = 1, .reusable = true}}, SHIFT(486), + [1249] = {.entry = {.count = 1, .reusable = true}}, SHIFT(631), + [1251] = {.entry = {.count = 1, .reusable = true}}, SHIFT(633), + [1253] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1328), + [1255] = {.entry = {.count = 1, .reusable = true}}, SHIFT(502), + [1257] = {.entry = {.count = 1, .reusable = true}}, SHIFT(588), + [1259] = {.entry = {.count = 1, .reusable = true}}, SHIFT(587), + [1261] = {.entry = {.count = 1, .reusable = true}}, SHIFT(734), + [1263] = {.entry = {.count = 1, .reusable = true}}, SHIFT(620), + [1265] = {.entry = {.count = 1, .reusable = true}}, SHIFT(619), + [1267] = {.entry = {.count = 1, .reusable = true}}, SHIFT(610), + [1269] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_sgl_prp, 2, 0, 0), + [1271] = {.entry = {.count = 1, .reusable = true}}, SHIFT(590), + [1273] = {.entry = {.count = 1, .reusable = true}}, SHIFT(589), + [1275] = {.entry = {.count = 1, .reusable = true}}, SHIFT(736), + [1277] = {.entry = {.count = 1, .reusable = true}}, SHIFT(432), + [1279] = {.entry = {.count = 1, .reusable = true}}, SHIFT(541), + [1281] = {.entry = {.count = 1, .reusable = true}}, SHIFT(543), + [1283] = {.entry = {.count = 1, .reusable = true}}, SHIFT(286), + [1285] = {.entry = {.count = 1, .reusable = true}}, SHIFT(372), + [1287] = {.entry = {.count = 1, .reusable = true}}, SHIFT(433), + [1289] = {.entry = {.count = 1, .reusable = true}}, SHIFT(544), + [1291] = {.entry = {.count = 1, .reusable = true}}, SHIFT(546), + [1293] = {.entry = {.count = 1, .reusable = true}}, SHIFT(287), + [1295] = {.entry = {.count = 1, .reusable = true}}, SHIFT(373), + [1297] = {.entry = {.count = 1, .reusable = true}}, SHIFT(435), + [1299] = {.entry = {.count = 1, .reusable = true}}, SHIFT(605), + [1301] = {.entry = {.count = 1, .reusable = true}}, SHIFT(607), + [1303] = {.entry = {.count = 1, .reusable = true}}, SHIFT(573), + [1305] = {.entry = {.count = 1, .reusable = true}}, SHIFT(455), + [1307] = {.entry = {.count = 1, .reusable = true}}, SHIFT(676), + [1309] = {.entry = {.count = 1, .reusable = true}}, SHIFT(629), + [1311] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1102), + [1313] = {.entry = {.count = 1, .reusable = true}}, SHIFT(436), + [1315] = {.entry = {.count = 1, .reusable = true}}, SHIFT(634), + [1317] = {.entry = {.count = 1, .reusable = true}}, SHIFT(635), + [1319] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1329), + [1321] = {.entry = {.count = 1, .reusable = true}}, SHIFT(558), + [1323] = {.entry = {.count = 1, .reusable = true}}, SHIFT(557), + [1325] = {.entry = {.count = 1, .reusable = true}}, SHIFT(269), + [1327] = {.entry = {.count = 1, .reusable = true}}, SHIFT(324), + [1329] = {.entry = {.count = 1, .reusable = true}}, SHIFT(560), + [1331] = {.entry = {.count = 1, .reusable = true}}, SHIFT(559), + [1333] = {.entry = {.count = 1, .reusable = true}}, SHIFT(270), + [1335] = {.entry = {.count = 1, .reusable = true}}, SHIFT(354), + [1337] = {.entry = {.count = 1, .reusable = true}}, SHIFT(583), + [1339] = {.entry = {.count = 1, .reusable = true}}, SHIFT(582), + [1341] = {.entry = {.count = 1, .reusable = true}}, SHIFT(990), + [1343] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1082), + [1345] = {.entry = {.count = 1, .reusable = true}}, SHIFT(618), + [1347] = {.entry = {.count = 1, .reusable = true}}, SHIFT(617), + [1349] = {.entry = {.count = 1, .reusable = true}}, SHIFT(604), + [1351] = {.entry = {.count = 1, .reusable = true}}, SHIFT(644), + [1353] = {.entry = {.count = 1, .reusable = true}}, SHIFT(643), + [1355] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1373), + [1357] = {.entry = {.count = 1, .reusable = true}}, SHIFT(442), + [1359] = {.entry = {.count = 1, .reusable = true}}, SHIFT(575), + [1361] = {.entry = {.count = 1, .reusable = true}}, SHIFT(577), + [1363] = {.entry = {.count = 1, .reusable = true}}, SHIFT(717), + [1365] = {.entry = {.count = 1, .reusable = true}}, SHIFT(718), + [1367] = {.entry = {.count = 1, .reusable = true}}, SHIFT(444), + [1369] = {.entry = {.count = 1, .reusable = true}}, SHIFT(625), + [1371] = {.entry = {.count = 1, .reusable = true}}, SHIFT(627), + [1373] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1260), + [1375] = {.entry = {.count = 1, .reusable = true}}, SHIFT(426), + [1377] = {.entry = {.count = 1, .reusable = true}}, SHIFT(578), + [1379] = {.entry = {.count = 1, .reusable = true}}, SHIFT(579), + [1381] = {.entry = {.count = 1, .reusable = true}}, SHIFT(719), + [1383] = {.entry = {.count = 1, .reusable = true}}, SHIFT(473), + [1385] = {.entry = {.count = 1, .reusable = true}}, SHIFT(658), + [1387] = {.entry = {.count = 1, .reusable = true}}, SHIFT(659), + [1389] = {.entry = {.count = 1, .reusable = true}}, SHIFT(835), + [1391] = {.entry = {.count = 1, .reusable = true}}, SHIFT(735), + [1393] = {.entry = {.count = 1, .reusable = true}}, SHIFT(460), + [1395] = {.entry = {.count = 1, .reusable = true}}, SHIFT(996), + [1397] = {.entry = {.count = 1, .reusable = true}}, SHIFT(651), + [1399] = {.entry = {.count = 1, .reusable = true}}, SHIFT(650), + [1401] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1347), + [1403] = {.entry = {.count = 1, .reusable = true}}, SHIFT(465), + [1405] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1146), + [1407] = {.entry = {.count = 1, .reusable = true}}, SHIFT(467), + [1409] = {.entry = {.count = 1, .reusable = true}}, SHIFT(628), + [1411] = {.entry = {.count = 1, .reusable = true}}, SHIFT(630), + [1413] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1149), + [1415] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1261), + [1417] = {.entry = {.count = 1, .reusable = true}}, SHIFT(451), + [1419] = {.entry = {.count = 1, .reusable = true}}, SHIFT(572), + [1421] = {.entry = {.count = 1, .reusable = true}}, SHIFT(452), + [1423] = {.entry = {.count = 1, .reusable = true}}, SHIFT(453), + [1425] = {.entry = {.count = 1, .reusable = true}}, SHIFT(681), + [1427] = {.entry = {.count = 1, .reusable = true}}, SHIFT(682), + [1429] = {.entry = {.count = 1, .reusable = true}}, SHIFT(883), + [1431] = {.entry = {.count = 1, .reusable = true}}, SHIFT(606), + [1433] = {.entry = {.count = 1, .reusable = true}}, SHIFT(689), + [1435] = {.entry = {.count = 1, .reusable = true}}, SHIFT(688), + [1437] = {.entry = {.count = 1, .reusable = true}}, SHIFT(903), + [1439] = {.entry = {.count = 1, .reusable = true}}, SHIFT(456), + [1441] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1325), + [1443] = {.entry = {.count = 1, .reusable = true}}, SHIFT(553), + [1445] = {.entry = {.count = 1, .reusable = true}}, SHIFT(685), + [1447] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1075), + [1449] = {.entry = {.count = 1, .reusable = true}}, SHIFT(642), + [1451] = {.entry = {.count = 1, .reusable = true}}, SHIFT(641), + [1453] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1370), + [1455] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1369), + [1457] = {.entry = {.count = 1, .reusable = true}}, SHIFT(422), + [1459] = {.entry = {.count = 1, .reusable = true}}, SHIFT(434), + [1461] = {.entry = {.count = 1, .reusable = true}}, SHIFT(640), + [1463] = {.entry = {.count = 1, .reusable = true}}, SHIFT(647), + [1465] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1000), + [1467] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1108), + [1469] = {.entry = {.count = 1, .reusable = true}}, SHIFT(989), + [1471] = {.entry = {.count = 1, .reusable = true}}, SHIFT(464), + [1473] = {.entry = {.count = 1, .reusable = true}}, SHIFT(655), + [1475] = {.entry = {.count = 1, .reusable = true}}, SHIFT(657), + [1477] = {.entry = {.count = 1, .reusable = true}}, SHIFT(833), + [1479] = {.entry = {.count = 1, .reusable = true}}, SHIFT(834), + [1481] = {.entry = {.count = 1, .reusable = true}}, SHIFT(423), + [1483] = {.entry = {.count = 1, .reusable = true}}, SHIFT(608), + [1485] = {.entry = {.count = 1, .reusable = true}}, SHIFT(609), + [1487] = {.entry = {.count = 1, .reusable = true}}, SHIFT(574), + [1489] = {.entry = {.count = 1, .reusable = true}}, SHIFT(466), + [1491] = {.entry = {.count = 1, .reusable = true}}, SHIFT(665), + [1493] = {.entry = {.count = 1, .reusable = true}}, SHIFT(664), + [1495] = {.entry = {.count = 1, .reusable = true}}, SHIFT(853), + [1497] = {.entry = {.count = 1, .reusable = true}}, SHIFT(852), + [1499] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1179), + [1501] = {.entry = {.count = 1, .reusable = true}}, SHIFT(653), + [1503] = {.entry = {.count = 1, .reusable = true}}, SHIFT(652), + [1505] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1180), + [1507] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1350), + [1509] = {.entry = {.count = 1, .reusable = true}}, SHIFT(471), + [1511] = {.entry = {.count = 1, .reusable = true}}, SHIFT(678), + [1513] = {.entry = {.count = 1, .reusable = true}}, SHIFT(680), + [1515] = {.entry = {.count = 1, .reusable = true}}, SHIFT(881), + [1517] = {.entry = {.count = 1, .reusable = true}}, SHIFT(882), + [1519] = {.entry = {.count = 1, .reusable = true}}, SHIFT(472), + [1521] = {.entry = {.count = 1, .reusable = true}}, SHIFT(687), + [1523] = {.entry = {.count = 1, .reusable = true}}, SHIFT(686), + [1525] = {.entry = {.count = 1, .reusable = true}}, SHIFT(902), + [1527] = {.entry = {.count = 1, .reusable = true}}, SHIFT(962), + [1529] = {.entry = {.count = 1, .reusable = true}}, SHIFT(667), + [1531] = {.entry = {.count = 1, .reusable = true}}, SHIFT(666), + [1533] = {.entry = {.count = 1, .reusable = true}}, SHIFT(854), + [1535] = {.entry = {.count = 1, .reusable = true}}, SHIFT(252), + [1537] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__r_flw_map_itm, 1, 0, 0), REDUCE(sym__r_sgl_flw_col_itm, 1, 0, 0), + [1540] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_map_itm, 1, 0, 0), + [1542] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__doc_w_bgn_wo_end_seq, 1, 0, 0), + [1544] = {.entry = {.count = 1, .reusable = true}}, SHIFT(251), + [1546] = {.entry = {.count = 1, .reusable = true}}, SHIFT(253), + [1548] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__doc_wo_bgn_wo_end_seq, 1, 0, 0), + [1550] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__br_mtl_dqt_ctn_repeat1, 2, 0, 0), SHIFT_REPEAT(481), + [1553] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym__br_mtl_dqt_ctn_repeat1, 2, 0, 0), + [1555] = {.entry = {.count = 1, .reusable = true}}, SHIFT(526), + [1557] = {.entry = {.count = 1, .reusable = true}}, SHIFT(648), + [1559] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1150), + [1561] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1265), + [1563] = {.entry = {.count = 1, .reusable = true}}, SHIFT(529), + [1565] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1153), + [1567] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1266), + [1569] = {.entry = {.count = 1, .reusable = true}}, SHIFT(615), + [1571] = {.entry = {.count = 1, .reusable = true}}, SHIFT(857), + [1573] = {.entry = {.count = 1, .reusable = true}}, SHIFT(495), + [1575] = {.entry = {.count = 1, .reusable = true}}, SHIFT(374), + [1577] = {.entry = {.count = 1, .reusable = true}}, SHIFT(499), + [1579] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_mtl_dqt_ctn, 1, 0, 0), + [1581] = {.entry = {.count = 1, .reusable = true}}, SHIFT(794), + [1583] = {.entry = {.count = 1, .reusable = true}}, SHIFT(488), + [1585] = {.entry = {.count = 1, .reusable = true}}, SHIFT(288), + [1587] = {.entry = {.count = 1, .reusable = true}}, SHIFT(271), + [1589] = {.entry = {.count = 1, .reusable = true}}, SHIFT(363), + [1591] = {.entry = {.count = 1, .reusable = true}}, SHIFT(497), + [1593] = {.entry = {.count = 1, .reusable = true}}, SHIFT(886), + [1595] = {.entry = {.count = 1, .reusable = true}}, SHIFT(508), + [1597] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1126), + [1599] = {.entry = {.count = 1, .reusable = true}}, SHIFT(611), + [1601] = {.entry = {.count = 1, .reusable = true}}, SHIFT(612), + [1603] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_map_itm, 1, 0, 0), + [1605] = {.entry = {.count = 1, .reusable = true}}, SHIFT(503), + [1607] = {.entry = {.count = 1, .reusable = true}}, SHIFT(289), + [1609] = {.entry = {.count = 1, .reusable = true}}, SHIFT(376), + [1611] = {.entry = {.count = 1, .reusable = true}}, SHIFT(739), + [1613] = {.entry = {.count = 1, .reusable = true}}, SHIFT(906), + [1615] = {.entry = {.count = 1, .reusable = true}}, SHIFT(89), + [1617] = {.entry = {.count = 1, .reusable = true}}, SHIFT(93), + [1619] = {.entry = {.count = 1, .reusable = true}}, SHIFT(481), + [1621] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_mtl_dqt_ctn, 2, 0, 0), + [1623] = {.entry = {.count = 1, .reusable = true}}, SHIFT(889), + [1625] = {.entry = {.count = 1, .reusable = true}}, SHIFT(507), + [1627] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1330), + [1629] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1331), + [1631] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__r_sgl_dqt_ctn, 2, 0, 0), SHIFT_REPEAT(502), + [1634] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym__r_sgl_dqt_ctn, 2, 0, 0), + [1636] = {.entry = {.count = 1, .reusable = true}}, SHIFT(272), + [1638] = {.entry = {.count = 1, .reusable = true}}, SHIFT(371), + [1640] = {.entry = {.count = 1, .reusable = true}}, SHIFT(510), + [1642] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1385), + [1644] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1374), + [1646] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1384), + [1648] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1086), + [1650] = {.entry = {.count = 1, .reusable = true}}, SHIFT(506), + [1652] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1334), + [1654] = {.entry = {.count = 1, .reusable = true}}, SHIFT(535), + [1656] = {.entry = {.count = 1, .reusable = true}}, SHIFT(721), + [1658] = {.entry = {.count = 1, .reusable = true}}, SHIFT(985), + [1660] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1090), + [1662] = {.entry = {.count = 1, .reusable = true}}, SHIFT(531), + [1664] = {.entry = {.count = 1, .reusable = true}}, SHIFT(720), + [1666] = {.entry = {.count = 1, .reusable = true}}, SHIFT(491), + [1668] = {.entry = {.count = 1, .reusable = true}}, SHIFT(576), + [1670] = {.entry = {.count = 1, .reusable = true}}, SHIFT(580), + [1672] = {.entry = {.count = 1, .reusable = true}}, SHIFT(521), + [1674] = {.entry = {.count = 1, .reusable = true}}, SHIFT(836), + [1676] = {.entry = {.count = 1, .reusable = true}}, SHIFT(837), + [1678] = {.entry = {.count = 1, .reusable = true}}, SHIFT(518), + [1680] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1005), + [1682] = {.entry = {.count = 1, .reusable = true}}, SHIFT(530), + [1684] = {.entry = {.count = 1, .reusable = true}}, SHIFT(581), + [1686] = {.entry = {.count = 1, .reusable = true}}, SHIFT(987), + [1688] = {.entry = {.count = 1, .reusable = true}}, SHIFT(524), + [1690] = {.entry = {.count = 1, .reusable = true}}, SHIFT(537), + [1692] = {.entry = {.count = 1, .reusable = true}}, SHIFT(855), + [1694] = {.entry = {.count = 1, .reusable = true}}, SHIFT(856), + [1696] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__drs_doc_repeat1, 2, 0, 0), SHIFT_REPEAT(1427), + [1699] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__drs_doc_repeat1, 2, 0, 0), SHIFT_REPEAT(1515), + [1702] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__drs_doc_repeat1, 2, 0, 0), SHIFT_REPEAT(694), + [1705] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym__drs_doc_repeat1, 2, 0, 0), + [1707] = {.entry = {.count = 1, .reusable = true}}, SHIFT(500), + [1709] = {.entry = {.count = 1, .reusable = true}}, SHIFT(512), + [1711] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1008), + [1713] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1130), + [1715] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1181), + [1717] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1351), + [1719] = {.entry = {.count = 1, .reusable = true}}, SHIFT(484), + [1721] = {.entry = {.count = 1, .reusable = true}}, SHIFT(838), + [1723] = {.entry = {.count = 1, .reusable = true}}, SHIFT(534), + [1725] = {.entry = {.count = 1, .reusable = true}}, SHIFT(884), + [1727] = {.entry = {.count = 1, .reusable = true}}, SHIFT(885), + [1729] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1184), + [1731] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1355), + [1733] = {.entry = {.count = 1, .reusable = true}}, SHIFT(613), + [1735] = {.entry = {.count = 1, .reusable = true}}, SHIFT(737), + [1737] = {.entry = {.count = 1, .reusable = true}}, SHIFT(738), + [1739] = {.entry = {.count = 1, .reusable = true}}, SHIFT(536), + [1741] = {.entry = {.count = 1, .reusable = true}}, SHIFT(496), + [1743] = {.entry = {.count = 1, .reusable = true}}, SHIFT(722), + [1745] = {.entry = {.count = 1, .reusable = true}}, SHIFT(904), + [1747] = {.entry = {.count = 1, .reusable = true}}, SHIFT(905), + [1749] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__r_flw_seq_itm, 1, 0, 0), REDUCE(sym__r_sgl_flw_col_itm, 1, 0, 0), + [1752] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_seq_itm, 1, 0, 0), + [1754] = {.entry = {.count = 1, .reusable = true}}, SHIFT(565), + [1756] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1408), + [1758] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym__r_flw_seq_dat_repeat1, 2, 0, 0), + [1760] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__r_flw_seq_dat_repeat1, 2, 0, 0), SHIFT_REPEAT(79), + [1763] = {.entry = {.count = 1, .reusable = true}}, SHIFT(584), + [1765] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1092), + [1767] = {.entry = {.count = 1, .reusable = true}}, SHIFT(92), + [1769] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__flw_seq_tal, 1, 0, 0), REDUCE(sym__sgl_flw_seq_tal, 1, 0, 0), + [1772] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__r_pln_flw_val, 1, 0, 0), REDUCE(sym__r_sgl_pln_flw_val, 1, 0, 0), + [1775] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_pln_flw_val, 1, 0, 0), + [1777] = {.entry = {.count = 1, .reusable = true}}, SHIFT(293), + [1779] = {.entry = {.count = 1, .reusable = true}}, SHIFT(561), + [1781] = {.entry = {.count = 1, .reusable = true}}, SHIFT(294), + [1783] = {.entry = {.count = 1, .reusable = true}}, SHIFT(562), + [1785] = {.entry = {.count = 1, .reusable = true}}, SHIFT(297), + [1787] = {.entry = {.count = 1, .reusable = true}}, SHIFT(391), + [1789] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_pln_flw_val, 1, 0, 0), + [1791] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__r_dqt_str_repeat1, 2, 0, 0), SHIFT_REPEAT(486), + [1794] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__r_dqt_str_repeat1, 2, 0, 0), SHIFT_REPEAT(565), + [1797] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym__r_dqt_str_repeat1, 2, 0, 0), + [1799] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym__r_flw_map_dat_repeat1, 2, 0, 0), + [1801] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__r_flw_map_dat_repeat1, 2, 0, 0), SHIFT_REPEAT(78), + [1804] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__flw_map_tal, 1, 0, 0), REDUCE(sym__sgl_flw_map_tal, 1, 0, 0), + [1807] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__r_dqt_str, 2, 0, 0), REDUCE(sym__r_sgl_dqt_str, 2, 0, 0), + [1810] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__r_sqt_str, 2, 0, 0), REDUCE(sym__r_sgl_sqt_str, 2, 0, 0), + [1813] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1093), + [1815] = {.entry = {.count = 1, .reusable = true}}, SHIFT(585), + [1817] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1104), + [1819] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1105), + [1821] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__br_mtl_sqt_ctn_repeat1, 2, 0, 0), SHIFT_REPEAT(586), + [1824] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym__br_mtl_sqt_ctn_repeat1, 2, 0, 0), + [1826] = {.entry = {.count = 1, .reusable = true}}, SHIFT(740), + [1828] = {.entry = {.count = 1, .reusable = true}}, SHIFT(591), + [1830] = {.entry = {.count = 1, .reusable = true}}, SHIFT(783), + [1832] = {.entry = {.count = 1, .reusable = true}}, SHIFT(592), + [1834] = {.entry = {.count = 1, .reusable = true}}, SHIFT(744), + [1836] = {.entry = {.count = 1, .reusable = true}}, SHIFT(745), + [1838] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__r_dqt_str, 3, 0, 0), REDUCE(sym__r_sgl_dqt_str, 3, 0, 0), + [1841] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__r_sqt_str, 3, 0, 0), REDUCE(sym__r_sgl_sqt_str, 3, 0, 0), + [1844] = {.entry = {.count = 1, .reusable = true}}, SHIFT(586), + [1846] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_mtl_sqt_ctn, 2, 0, 0), + [1848] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__r_sgl_sqt_ctn, 2, 0, 0), SHIFT_REPEAT(615), + [1851] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym__r_sgl_sqt_ctn, 2, 0, 0), + [1853] = {.entry = {.count = 1, .reusable = true}}, SHIFT(616), + [1855] = {.entry = {.count = 1, .reusable = true}}, SHIFT(621), + [1857] = {.entry = {.count = 1, .reusable = true}}, SHIFT(692), + [1859] = {.entry = {.count = 1, .reusable = true}}, SHIFT(622), + [1861] = {.entry = {.count = 1, .reusable = true}}, SHIFT(632), + [1863] = {.entry = {.count = 1, .reusable = true}}, SHIFT(636), + [1865] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_pln_flw_val, 2, 0, 0), + [1867] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_pln_flw_val, 2, 0, 0), + [1869] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1396), + [1871] = {.entry = {.count = 1, .reusable = true}}, SHIFT(539), + [1873] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1397), + [1875] = {.entry = {.count = 1, .reusable = true}}, SHIFT(646), + [1877] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_seq_itm, 1, 0, 0), + [1879] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1324), + [1881] = {.entry = {.count = 1, .reusable = true}}, SHIFT(614), + [1883] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_mtl_sqt_ctn, 1, 0, 0), + [1885] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_seq_dat, 1, 0, 0), + [1887] = {.entry = {.count = 1, .reusable = true}}, SHIFT(74), + [1889] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1375), + [1891] = {.entry = {.count = 1, .reusable = true}}, SHIFT(654), + [1893] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1376), + [1895] = {.entry = {.count = 1, .reusable = true}}, SHIFT(656), + [1897] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1382), + [1899] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1383), + [1901] = {.entry = {.count = 1, .reusable = true}}, SHIFT(76), + [1903] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_seq_dat, 1, 0, 0), + [1905] = {.entry = {.count = 1, .reusable = true}}, SHIFT(75), + [1907] = {.entry = {.count = 1, .reusable = true}}, SHIFT(77), + [1909] = {.entry = {.count = 1, .reusable = true}}, SHIFT(858), + [1911] = {.entry = {.count = 1, .reusable = true}}, SHIFT(668), + [1913] = {.entry = {.count = 1, .reusable = true}}, SHIFT(859), + [1915] = {.entry = {.count = 1, .reusable = true}}, SHIFT(669), + [1917] = {.entry = {.count = 1, .reusable = true}}, SHIFT(862), + [1919] = {.entry = {.count = 1, .reusable = true}}, SHIFT(863), + [1921] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_map_dat, 1, 0, 0), + [1923] = {.entry = {.count = 1, .reusable = true}}, SHIFT(71), + [1925] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_map_dat, 1, 0, 0), + [1927] = {.entry = {.count = 1, .reusable = true}}, SHIFT(70), + [1929] = {.entry = {.count = 1, .reusable = true}}, SHIFT(72), + [1931] = {.entry = {.count = 1, .reusable = true}}, SHIFT(73), + [1933] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_pln_flw, 1, 0, 0), + [1935] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sgl_pln_flw, 1, 0, 0), + [1937] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_mtl_pln_flw, 1, 0, 0), + [1939] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_mtl_pln_flw, 1, 0, 0), + [1941] = {.entry = {.count = 1, .reusable = true}}, SHIFT(907), + [1943] = {.entry = {.count = 1, .reusable = true}}, SHIFT(690), + [1945] = {.entry = {.count = 1, .reusable = true}}, SHIFT(908), + [1947] = {.entry = {.count = 1, .reusable = true}}, SHIFT(691), + [1949] = {.entry = {.count = 1, .reusable = true}}, SHIFT(911), + [1951] = {.entry = {.count = 1, .reusable = true}}, SHIFT(912), + [1953] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__s_dir_rsv, 1, 0, 0), + [1955] = {.entry = {.count = 1, .reusable = true}}, SHIFT(758), + [1957] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym__s_dir_rsv_repeat1, 2, 0, 0), + [1959] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__s_dir_rsv_repeat1, 2, 0, 0), SHIFT_REPEAT(698), + [1962] = {.entry = {.count = 1, .reusable = true}}, SHIFT(910), + [1964] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1096), + [1966] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__r_sqt_str_repeat1, 2, 0, 0), SHIFT_REPEAT(648), + [1969] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym__r_sqt_str_repeat1, 2, 0, 0), + [1971] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1098), + [1973] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__s_dir_rsv, 2, 0, 0), + [1975] = {.entry = {.count = 1, .reusable = true}}, SHIFT(698), + [1977] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1377), + [1979] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1378), + [1981] = {.entry = {.count = 1, .reusable = true}}, SHIFT(295), + [1983] = {.entry = {.count = 1, .reusable = true}}, SHIFT(296), + [1985] = {.entry = {.count = 1, .reusable = true}}, SHIFT(742), + [1987] = {.entry = {.count = 1, .reusable = true}}, SHIFT(743), + [1989] = {.entry = {.count = 1, .reusable = true}}, SHIFT(624), + [1991] = {.entry = {.count = 1, .reusable = true}}, SHIFT(626), + [1993] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1399), + [1995] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1403), + [1997] = {.entry = {.count = 1, .reusable = true}}, SHIFT(860), + [1999] = {.entry = {.count = 1, .reusable = true}}, SHIFT(861), + [2001] = {.entry = {.count = 1, .reusable = true}}, SHIFT(909), + [2003] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_imp_br_par, 2, 0, 9), + [2005] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_imp_br_par, 2, 0, 9), + [2007] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_seq_itm, 1, 0, 6), + [2009] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_seq_itm, 1, 0, 6), + [2011] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_seq_itm, 1, 0, 7), + [2013] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_seq_itm, 1, 0, 7), + [2015] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_exp_par, 2, 0, 11), + [2017] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_exp_par, 2, 0, 11), + [2019] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_njl_ann_par, 2, 0, 5), + [2021] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_map_itm, 1, 0, 6), + [2023] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_map_itm, 1, 0, 6), + [2025] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_jsl_ann_par, 2, 0, 5), + [2027] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__flw_seq_dat_rpt, 2, 0, 0), + [2029] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_jsl_ann_par, 2, 0, 5), + [2031] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__flw_map_dat_rpt, 2, 0, 0), + [2033] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_map_itm, 1, 0, 7), + [2035] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_map_itm, 1, 0, 7), + [2037] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_mtl_dqt_ctn, 3, 0, 0), + [2039] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__exp_doc_tal, 1, 0, 0), + [2041] = {.entry = {.count = 2, .reusable = true}}, REDUCE(sym__flw_ann_par_tal, 1, 0, 0), REDUCE(sym__sgl_flw_ann_par_tal, 1, 0, 0), + [2044] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__flw_ann_par_tal, 1, 0, 0), + [2046] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_njl_ann_par, 2, 0, 5), + [2048] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_flw_imp_r_par, 2, 0, 9), + [2050] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_flw_imp_r_par, 2, 0, 9), + [2052] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__imp_doc, 1, 0, 0), + [2054] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym__r_sgl_flw_col_dat_repeat1, 2, 0, 0), + [2056] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__r_sgl_flw_col_dat_repeat1, 2, 0, 0), SHIFT_REPEAT(181), + [2059] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_flw_col_dat, 1, 0, 0), + [2061] = {.entry = {.count = 1, .reusable = true}}, SHIFT(175), + [2063] = {.entry = {.count = 1, .reusable = true}}, SHIFT(358), + [2065] = {.entry = {.count = 1, .reusable = true}}, SHIFT(368), + [2067] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__s_dir_tag, 3, 0, 0), + [2069] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1014), + [2071] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1497), + [2073] = {.entry = {.count = 1, .reusable = true}}, SHIFT(977), + [2075] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1067), + [2077] = {.entry = {.count = 1, .reusable = true}}, SHIFT(978), + [2079] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1068), + [2081] = {.entry = {.count = 1, .reusable = true}}, SHIFT(375), + [2083] = {.entry = {.count = 1, .reusable = true}}, SHIFT(377), + [2085] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1029), + [2087] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1499), + [2089] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_flw_col_itm, 1, 0, 0), + [2091] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1023), + [2093] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1072), + [2095] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1024), + [2097] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1074), + [2099] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__r_blk_seq_repeat1, 2, 0, 0), SHIFT_REPEAT(9), + [2102] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym__r_blk_seq_repeat1, 2, 0, 0), + [2104] = {.entry = {.count = 1, .reusable = true}}, SHIFT(993), + [2106] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1451), + [2108] = {.entry = {.count = 1, .reusable = true}}, SHIFT(994), + [2110] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1458), + [2112] = {.entry = {.count = 1, .reusable = true}}, SHIFT(177), + [2114] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1421), + [2116] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1495), + [2118] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1507), + [2120] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1215), + [2122] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1136), + [2124] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1294), + [2126] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1295), + [2128] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1119), + [2130] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1195), + [2132] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1196), + [2134] = {.entry = {.count = 1, .reusable = true}}, SHIFT(90), + [2136] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1020), + [2138] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1249), + [2140] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1021), + [2142] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1255), + [2144] = {.entry = {.count = 1, .reusable = true}}, SHIFT(174), + [2146] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1425), + [2148] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1443), + [2150] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__s_dir_yml, 2, 0, 0), + [2152] = {.entry = {.count = 1, .reusable = true}}, SHIFT(167), + [2154] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1006), + [2156] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1189), + [2158] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1007), + [2160] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1190), + [2162] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1270), + [2164] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1271), + [2166] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1362), + [2168] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__r_sgl_dqt_ctn, 2, 0, 0), SHIFT_REPEAT(1023), + [2171] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__r_sgl_sqt_ctn, 2, 0, 0), SHIFT_REPEAT(1024), + [2174] = {.entry = {.count = 1, .reusable = true}}, SHIFT(203), + [2176] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1363), + [2178] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1032), + [2180] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1391), + [2182] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1033), + [2184] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1392), + [2186] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1444), + [2188] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1405), + [2190] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1406), + [2192] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__r_sgl_flw_col_dat_repeat1, 2, 0, 0), SHIFT_REPEAT(182), + [2195] = {.entry = {.count = 1, .reusable = true}}, SHIFT(359), + [2197] = {.entry = {.count = 1, .reusable = true}}, SHIFT(992), + [2199] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1477), + [2201] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1013), + [2203] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1500), + [2205] = {.entry = {.count = 1, .reusable = true}}, SHIFT(202), + [2207] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1091), + [2209] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_flw_seq, 2, 0, 0), + [2211] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_flw_seq_val, 2, 0, 0), + [2213] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_flw_map_val, 2, 0, 0), + [2215] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_dqt_str_val, 2, 0, 0), + [2217] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_sqt_str_val, 2, 0, 0), + [2219] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym__r_blk_str_repeat1, 2, 0, 0), SHIFT_REPEAT(1056), + [2222] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym__r_blk_str_repeat1, 2, 0, 0), + [2224] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1134), + [2226] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__sgl_flw_seq_tal, 2, 0, 0), + [2228] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__sgl_flw_map_tal, 2, 0, 0), + [2230] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_flw_map, 2, 0, 0), + [2232] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1056), + [2234] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1057), + [2236] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1089), + [2238] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1088), + [2240] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1066), + [2242] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1063), + [2244] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_pln_flw_val, 2, 0, 0), + [2246] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__drs_doc, 2, 0, 0), + [2248] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1055), + [2250] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_flw_seq_val, 1, 0, 0), + [2252] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1120), + [2254] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1229), + [2256] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1121), + [2258] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1230), + [2260] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_flw_map_val, 1, 0, 0), + [2262] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_dqt_str_val, 1, 0, 0), + [2264] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_sqt_str_val, 1, 0, 0), + [2266] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1300), + [2268] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1303), + [2270] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__bgn_imp_doc, 1, 0, 0), + [2272] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1333), + [2274] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1344), + [2276] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_pln_flw_val, 1, 0, 0), + [2278] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1073), + [2280] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1147), + [2282] = {.entry = {.count = 1, .reusable = true}}, SHIFT(361), + [2284] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1148), + [2286] = {.entry = {.count = 1, .reusable = true}}, SHIFT(362), + [2288] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__exp_doc, 2, 0, 0), + [2290] = {.entry = {.count = 1, .reusable = true}}, SHIFT(305), + [2292] = {.entry = {.count = 1, .reusable = true}}, SHIFT(307), + [2294] = {.entry = {.count = 1, .reusable = true}}, SHIFT(320), + [2296] = {.entry = {.count = 1, .reusable = true}}, SHIFT(321), + [2298] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__doc_w_bgn_wo_end, 1, 0, 8), + [2300] = {.entry = {.count = 1, .reusable = true}}, SHIFT(254), + [2302] = {.entry = {.count = 1, .reusable = true}}, SHIFT(732), + [2304] = {.entry = {.count = 1, .reusable = true}}, SHIFT(733), + [2306] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__doc_wo_bgn_wo_end, 1, 0, 8), + [2308] = {.entry = {.count = 1, .reusable = true}}, SHIFT(249), + [2310] = {.entry = {.count = 1, .reusable = true}}, SHIFT(255), + [2312] = {.entry = {.count = 1, .reusable = true}}, SHIFT(602), + [2314] = {.entry = {.count = 1, .reusable = true}}, SHIFT(603), + [2316] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1361), + [2318] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1367), + [2320] = {.entry = {.count = 1, .reusable = true}}, SHIFT(850), + [2322] = {.entry = {.count = 1, .reusable = true}}, SHIFT(851), + [2324] = {.entry = {.count = 1, .reusable = true}}, SHIFT(900), + [2326] = {.entry = {.count = 1, .reusable = true}}, SHIFT(901), + [2328] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_flw_col_itm, 1, 0, 6), + [2330] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_flw_imp_par, 2, 0, 9), + [2332] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__sgl_flw_col_dat_rpt, 2, 0, 0), + [2334] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_flw_col_itm, 1, 0, 7), + [2336] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_blk_seq_itm, 2, 0, 0), + [2338] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_blk_seq_itm, 2, 0, 0), + [2340] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_flw_exp_par, 2, 0, 11), + [2342] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_blk_seq_itm, 2, 0, 0), + [2344] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_flw_njl_ann_par, 2, 0, 5), + [2346] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_flw_jsl_ann_par, 2, 0, 5), + [2348] = {.entry = {.count = 1, .reusable = true}}, SHIFT(227), + [2350] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_als_val, 1, 0, 0), + [2352] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_sgl_dqt_str_val, 2, 0, 0), + [2354] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sgl_flw_seq, 2, 0, 0), + [2356] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sgl_sqt_str_val, 1, 0, 0), + [2358] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_sgl_sqt_str_val, 2, 0, 0), + [2360] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_sgl_pln_blk_val, 2, 0, 0), + [2362] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_stream, 2, 0, 8), + [2364] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1015), + [2366] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1452), + [2368] = {.entry = {.count = 1, .reusable = true}}, ACCEPT_INPUT(), + [2370] = {.entry = {.count = 1, .reusable = true}}, SHIFT(163), + [2372] = {.entry = {.count = 1, .reusable = true}}, SHIFT(102), + [2374] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1079), + [2376] = {.entry = {.count = 1, .reusable = true}}, SHIFT(101), + [2378] = {.entry = {.count = 1, .reusable = true}}, SHIFT(208), + [2380] = {.entry = {.count = 1, .reusable = true}}, SHIFT(275), + [2382] = {.entry = {.count = 1, .reusable = true}}, SHIFT(723), + [2384] = {.entry = {.count = 1, .reusable = true}}, SHIFT(290), + [2386] = {.entry = {.count = 1, .reusable = true}}, SHIFT(196), + [2388] = {.entry = {.count = 1, .reusable = true}}, SHIFT(171), + [2390] = {.entry = {.count = 1, .reusable = true}}, SHIFT(662), + [2392] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1424), + [2394] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_sgl_dqt_str, 3, 0, 0), + [2396] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_sgl_sqt_str, 3, 0, 0), + [2398] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_sgl_flw_seq, 2, 0, 0), + [2400] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sgl_dqt_str_val, 1, 0, 0), + [2402] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1366), + [2404] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1368), + [2406] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sgl_flw_map, 2, 0, 0), + [2408] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_stream, 3, 0, 8), + [2410] = {.entry = {.count = 1, .reusable = true}}, SHIFT(968), + [2412] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__doc_w_bgn_w_end_seq, 2, 0, 0), + [2414] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1414), + [2416] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1501), + [2418] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1448), + [2420] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_sgl_pln_blk, 1, 0, 0), + [2422] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_sgl_dqt_str_val, 1, 0, 0), + [2424] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_stream, 1, 0, 0), + [2426] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1174), + [2428] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1178), + [2430] = {.entry = {.count = 1, .reusable = true}}, SHIFT(161), + [2432] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1061), + [2434] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1039), + [2436] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1062), + [2438] = {.entry = {.count = 1, .reusable = true}}, SHIFT(159), + [2440] = {.entry = {.count = 1, .reusable = true}}, SHIFT(418), + [2442] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1248), + [2444] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1254), + [2446] = {.entry = {.count = 1, .reusable = true}}, SHIFT(156), + [2448] = {.entry = {.count = 1, .reusable = true}}, SHIFT(416), + [2450] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_als, 2, 0, 0), + [2452] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1044), + [2454] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1485), + [2456] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__doc_wo_bgn_w_end_seq, 2, 0, 0), + [2458] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__doc_wo_bgn_wo_end_seq, 2, 0, 0), + [2460] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_sgl_flw_seq_val, 2, 0, 0), + [2462] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_sgl_flw_map_val, 2, 0, 0), + [2464] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_sgl_flw_seq_val, 1, 0, 0), + [2466] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1157), + [2468] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_sgl_flw_map, 2, 0, 0), + [2470] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_sgl_dqt_str, 2, 0, 0), + [2472] = {.entry = {.count = 1, .reusable = true}}, SHIFT(127), + [2474] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_sgl_sqt_str, 2, 0, 0), + [2476] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_sgl_flw_map_val, 1, 0, 0), + [2478] = {.entry = {.count = 1, .reusable = true}}, SHIFT(194), + [2480] = {.entry = {.count = 1, .reusable = true}}, SHIFT(753), + [2482] = {.entry = {.count = 1, .reusable = true}}, SHIFT(593), + [2484] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1158), + [2486] = {.entry = {.count = 1, .reusable = true}}, SHIFT(170), + [2488] = {.entry = {.count = 1, .reusable = true}}, SHIFT(180), + [2490] = {.entry = {.count = 1, .reusable = true}}, SHIFT(890), + [2492] = {.entry = {.count = 1, .reusable = true}}, SHIFT(891), + [2494] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sgl_flw_map_val, 1, 0, 0), + [2496] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1454), + [2498] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1413), + [2500] = {.entry = {.count = 1, .reusable = true}}, SHIFT(129), + [2502] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_sgl_sqt_str_val, 1, 0, 0), + [2504] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1238), + [2506] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__doc_w_bgn_wo_end_seq, 2, 0, 0), + [2508] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1241), + [2510] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__r_sgl_pln_blk_val, 2, 0, 0), + [2512] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sgl_flw_seq_val, 2, 0, 0), + [2514] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sgl_flw_map_val, 2, 0, 0), + [2516] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__b_sgl_pln_blk_val, 1, 0, 0), + [2518] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sgl_dqt_str_val, 2, 0, 0), + [2520] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sgl_sqt_str_val, 2, 0, 0), + [2522] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sgl_pln_blk_val, 2, 0, 0), + [2524] = {.entry = {.count = 1, .reusable = true}}, SHIFT(173), + [2526] = {.entry = {.count = 1, .reusable = true}}, SHIFT(110), + [2528] = {.entry = {.count = 1, .reusable = true}}, SHIFT(915), + [2530] = {.entry = {.count = 1, .reusable = true}}, SHIFT(916), + [2532] = {.entry = {.count = 1, .reusable = true}}, SHIFT(107), + [2534] = {.entry = {.count = 1, .reusable = true}}, SHIFT(247), + [2536] = {.entry = {.count = 1, .reusable = true}}, SHIFT(333), + [2538] = {.entry = {.count = 1, .reusable = true}}, SHIFT(246), + [2540] = {.entry = {.count = 1, .reusable = true}}, SHIFT(225), + [2542] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1099), + [2544] = {.entry = {.count = 1, .reusable = true}}, SHIFT(223), + [2546] = {.entry = {.count = 1, .reusable = true}}, SHIFT(228), + [2548] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1101), + [2550] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__br_sgl_flw_seq_val, 1, 0, 0), + [2552] = {.entry = {.count = 1, .reusable = true}}, SHIFT(212), + [2554] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1352), + [2556] = {.entry = {.count = 1, .reusable = true}}, SHIFT(211), + [2558] = {.entry = {.count = 1, .reusable = true}}, SHIFT(216), + [2560] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1356), + [2562] = {.entry = {.count = 1, .reusable = true}}, SHIFT(217), + [2564] = {.entry = {.count = 1, .reusable = true}}, SHIFT(259), + [2566] = {.entry = {.count = 1, .reusable = true}}, SHIFT(1462), + [2568] = {.entry = {.count = 1, .reusable = true}}, SHIFT(106), + [2570] = {.entry = {.count = 1, .reusable = true}}, SHIFT(235), + [2572] = {.entry = {.count = 1, .reusable = true}}, SHIFT(424), + [2574] = {.entry = {.count = 1, .reusable = true}}, SHIFT(237), + [2576] = {.entry = {.count = 1, .reusable = true}}, SHIFT(397), + [2578] = {.entry = {.count = 1, .reusable = true}}, SHIFT(399), + [2580] = {.entry = {.count = 1, .reusable = true}}, SHIFT(256), + [2582] = {.entry = {.count = 1, .reusable = true}}, SHIFT(239), + [2584] = {.entry = {.count = 1, .reusable = true}}, SHIFT(407), + [2586] = {.entry = {.count = 1, .reusable = true}}, SHIFT(241), + [2588] = {.entry = {.count = 1, .reusable = true}}, SHIFT(410), + [2590] = {.entry = {.count = 1, .reusable = true}}, SHIFT(111), + [2592] = {.entry = {.count = 1, .reusable = true}}, SHIFT(412), + [2594] = {.entry = {.count = 1, .reusable = true}}, SHIFT(402), + [2596] = {.entry = {.count = 1, .reusable = true}}, SHIFT(400), + [2598] = {.entry = {.count = 1, .reusable = true}}, SHIFT(411), + [2600] = {.entry = {.count = 1, .reusable = true}}, SHIFT(414), + [2602] = {.entry = {.count = 1, .reusable = true}}, SHIFT(438), + [2604] = {.entry = {.count = 1, .reusable = true}}, SHIFT(206), +}; + +enum ts_external_scanner_symbol_identifiers { + ts_external_token__eof = 0, + ts_external_token__s_dir_yml_bgn = 1, + ts_external_token__r_dir_yml_ver = 2, + ts_external_token__s_dir_tag_bgn = 3, + ts_external_token__r_dir_tag_hdl = 4, + ts_external_token__r_dir_tag_pfx = 5, + ts_external_token__s_dir_rsv_bgn = 6, + ts_external_token__r_dir_rsv_prm = 7, + ts_external_token__s_drs_end = 8, + ts_external_token__s_doc_end = 9, + ts_external_token__r_blk_seq_bgn = 10, + ts_external_token__br_blk_seq_bgn = 11, + ts_external_token__b_blk_seq_bgn = 12, + ts_external_token__r_blk_key_bgn = 13, + ts_external_token__br_blk_key_bgn = 14, + ts_external_token__b_blk_key_bgn = 15, + ts_external_token__r_blk_val_bgn = 16, + ts_external_token__br_blk_val_bgn = 17, + ts_external_token__b_blk_val_bgn = 18, + ts_external_token__r_blk_imp_bgn = 19, + ts_external_token__r_blk_lit_bgn = 20, + ts_external_token__br_blk_lit_bgn = 21, + ts_external_token__r_blk_fld_bgn = 22, + ts_external_token__br_blk_fld_bgn = 23, + ts_external_token__br_blk_str_ctn = 24, + ts_external_token__r_flw_seq_bgn = 25, + ts_external_token__br_flw_seq_bgn = 26, + ts_external_token__b_flw_seq_bgn = 27, + ts_external_token__r_flw_seq_end = 28, + ts_external_token__br_flw_seq_end = 29, + ts_external_token__b_flw_seq_end = 30, + ts_external_token__r_flw_map_bgn = 31, + ts_external_token__br_flw_map_bgn = 32, + ts_external_token__b_flw_map_bgn = 33, + ts_external_token__r_flw_map_end = 34, + ts_external_token__br_flw_map_end = 35, + ts_external_token__b_flw_map_end = 36, + ts_external_token__r_flw_sep_bgn = 37, + ts_external_token__br_flw_sep_bgn = 38, + ts_external_token__r_flw_key_bgn = 39, + ts_external_token__br_flw_key_bgn = 40, + ts_external_token__r_flw_jsv_bgn = 41, + ts_external_token__br_flw_jsv_bgn = 42, + ts_external_token__r_flw_njv_bgn = 43, + ts_external_token__br_flw_njv_bgn = 44, + ts_external_token__r_dqt_str_bgn = 45, + ts_external_token__br_dqt_str_bgn = 46, + ts_external_token__b_dqt_str_bgn = 47, + ts_external_token__r_dqt_str_ctn = 48, + ts_external_token__br_dqt_str_ctn = 49, + ts_external_token__r_dqt_esc_nwl = 50, + ts_external_token__br_dqt_esc_nwl = 51, + ts_external_token__r_dqt_esc_seq = 52, + ts_external_token__br_dqt_esc_seq = 53, + ts_external_token__r_dqt_str_end = 54, + ts_external_token__br_dqt_str_end = 55, + ts_external_token__r_sqt_str_bgn = 56, + ts_external_token__br_sqt_str_bgn = 57, + ts_external_token__b_sqt_str_bgn = 58, + ts_external_token__r_sqt_str_ctn = 59, + ts_external_token__br_sqt_str_ctn = 60, + ts_external_token__r_sqt_esc_sqt = 61, + ts_external_token__br_sqt_esc_sqt = 62, + ts_external_token__r_sqt_str_end = 63, + ts_external_token__br_sqt_str_end = 64, + ts_external_token__r_sgl_pln_nul_blk = 65, + ts_external_token__br_sgl_pln_nul_blk = 66, + ts_external_token__b_sgl_pln_nul_blk = 67, + ts_external_token__r_sgl_pln_nul_flw = 68, + ts_external_token__br_sgl_pln_nul_flw = 69, + ts_external_token__r_sgl_pln_bol_blk = 70, + ts_external_token__br_sgl_pln_bol_blk = 71, + ts_external_token__b_sgl_pln_bol_blk = 72, + ts_external_token__r_sgl_pln_bol_flw = 73, + ts_external_token__br_sgl_pln_bol_flw = 74, + ts_external_token__r_sgl_pln_int_blk = 75, + ts_external_token__br_sgl_pln_int_blk = 76, + ts_external_token__b_sgl_pln_int_blk = 77, + ts_external_token__r_sgl_pln_int_flw = 78, + ts_external_token__br_sgl_pln_int_flw = 79, + ts_external_token__r_sgl_pln_flt_blk = 80, + ts_external_token__br_sgl_pln_flt_blk = 81, + ts_external_token__b_sgl_pln_flt_blk = 82, + ts_external_token__r_sgl_pln_flt_flw = 83, + ts_external_token__br_sgl_pln_flt_flw = 84, + ts_external_token__r_sgl_pln_tms_blk = 85, + ts_external_token__br_sgl_pln_tms_blk = 86, + ts_external_token__b_sgl_pln_tms_blk = 87, + ts_external_token__r_sgl_pln_tms_flw = 88, + ts_external_token__br_sgl_pln_tms_flw = 89, + ts_external_token__r_sgl_pln_str_blk = 90, + ts_external_token__br_sgl_pln_str_blk = 91, + ts_external_token__b_sgl_pln_str_blk = 92, + ts_external_token__r_sgl_pln_str_flw = 93, + ts_external_token__br_sgl_pln_str_flw = 94, + ts_external_token__r_mtl_pln_str_blk = 95, + ts_external_token__br_mtl_pln_str_blk = 96, + ts_external_token__r_mtl_pln_str_flw = 97, + ts_external_token__br_mtl_pln_str_flw = 98, + ts_external_token__r_tag = 99, + ts_external_token__br_tag = 100, + ts_external_token__b_tag = 101, + ts_external_token__r_acr_bgn = 102, + ts_external_token__br_acr_bgn = 103, + ts_external_token__b_acr_bgn = 104, + ts_external_token__r_acr_ctn = 105, + ts_external_token__r_als_bgn = 106, + ts_external_token__br_als_bgn = 107, + ts_external_token__b_als_bgn = 108, + ts_external_token__r_als_ctn = 109, + ts_external_token__bl = 110, + ts_external_token_comment = 111, + ts_external_token__err_rec = 112, +}; + +static const TSSymbol ts_external_scanner_symbol_map[EXTERNAL_TOKEN_COUNT] = { + [ts_external_token__eof] = sym__eof, + [ts_external_token__s_dir_yml_bgn] = sym__s_dir_yml_bgn, + [ts_external_token__r_dir_yml_ver] = sym__r_dir_yml_ver, + [ts_external_token__s_dir_tag_bgn] = sym__s_dir_tag_bgn, + [ts_external_token__r_dir_tag_hdl] = sym__r_dir_tag_hdl, + [ts_external_token__r_dir_tag_pfx] = sym__r_dir_tag_pfx, + [ts_external_token__s_dir_rsv_bgn] = sym__s_dir_rsv_bgn, + [ts_external_token__r_dir_rsv_prm] = sym__r_dir_rsv_prm, + [ts_external_token__s_drs_end] = sym__s_drs_end, + [ts_external_token__s_doc_end] = sym__s_doc_end, + [ts_external_token__r_blk_seq_bgn] = sym__r_blk_seq_bgn, + [ts_external_token__br_blk_seq_bgn] = sym__br_blk_seq_bgn, + [ts_external_token__b_blk_seq_bgn] = sym__b_blk_seq_bgn, + [ts_external_token__r_blk_key_bgn] = sym__r_blk_key_bgn, + [ts_external_token__br_blk_key_bgn] = sym__br_blk_key_bgn, + [ts_external_token__b_blk_key_bgn] = sym__b_blk_key_bgn, + [ts_external_token__r_blk_val_bgn] = sym__r_blk_val_bgn, + [ts_external_token__br_blk_val_bgn] = sym__br_blk_val_bgn, + [ts_external_token__b_blk_val_bgn] = sym__b_blk_val_bgn, + [ts_external_token__r_blk_imp_bgn] = sym__r_blk_imp_bgn, + [ts_external_token__r_blk_lit_bgn] = sym__r_blk_lit_bgn, + [ts_external_token__br_blk_lit_bgn] = sym__br_blk_lit_bgn, + [ts_external_token__r_blk_fld_bgn] = sym__r_blk_fld_bgn, + [ts_external_token__br_blk_fld_bgn] = sym__br_blk_fld_bgn, + [ts_external_token__br_blk_str_ctn] = sym__br_blk_str_ctn, + [ts_external_token__r_flw_seq_bgn] = sym__r_flw_seq_bgn, + [ts_external_token__br_flw_seq_bgn] = sym__br_flw_seq_bgn, + [ts_external_token__b_flw_seq_bgn] = sym__b_flw_seq_bgn, + [ts_external_token__r_flw_seq_end] = sym__r_flw_seq_end, + [ts_external_token__br_flw_seq_end] = sym__br_flw_seq_end, + [ts_external_token__b_flw_seq_end] = sym__b_flw_seq_end, + [ts_external_token__r_flw_map_bgn] = sym__r_flw_map_bgn, + [ts_external_token__br_flw_map_bgn] = sym__br_flw_map_bgn, + [ts_external_token__b_flw_map_bgn] = sym__b_flw_map_bgn, + [ts_external_token__r_flw_map_end] = sym__r_flw_map_end, + [ts_external_token__br_flw_map_end] = sym__br_flw_map_end, + [ts_external_token__b_flw_map_end] = sym__b_flw_map_end, + [ts_external_token__r_flw_sep_bgn] = sym__r_flw_sep_bgn, + [ts_external_token__br_flw_sep_bgn] = sym__br_flw_sep_bgn, + [ts_external_token__r_flw_key_bgn] = sym__r_flw_key_bgn, + [ts_external_token__br_flw_key_bgn] = sym__br_flw_key_bgn, + [ts_external_token__r_flw_jsv_bgn] = sym__r_flw_jsv_bgn, + [ts_external_token__br_flw_jsv_bgn] = sym__br_flw_jsv_bgn, + [ts_external_token__r_flw_njv_bgn] = sym__r_flw_njv_bgn, + [ts_external_token__br_flw_njv_bgn] = sym__br_flw_njv_bgn, + [ts_external_token__r_dqt_str_bgn] = sym__r_dqt_str_bgn, + [ts_external_token__br_dqt_str_bgn] = sym__br_dqt_str_bgn, + [ts_external_token__b_dqt_str_bgn] = sym__b_dqt_str_bgn, + [ts_external_token__r_dqt_str_ctn] = sym__r_dqt_str_ctn, + [ts_external_token__br_dqt_str_ctn] = sym__br_dqt_str_ctn, + [ts_external_token__r_dqt_esc_nwl] = sym__r_dqt_esc_nwl, + [ts_external_token__br_dqt_esc_nwl] = sym__br_dqt_esc_nwl, + [ts_external_token__r_dqt_esc_seq] = sym__r_dqt_esc_seq, + [ts_external_token__br_dqt_esc_seq] = sym__br_dqt_esc_seq, + [ts_external_token__r_dqt_str_end] = sym__r_dqt_str_end, + [ts_external_token__br_dqt_str_end] = sym__br_dqt_str_end, + [ts_external_token__r_sqt_str_bgn] = sym__r_sqt_str_bgn, + [ts_external_token__br_sqt_str_bgn] = sym__br_sqt_str_bgn, + [ts_external_token__b_sqt_str_bgn] = sym__b_sqt_str_bgn, + [ts_external_token__r_sqt_str_ctn] = sym__r_sqt_str_ctn, + [ts_external_token__br_sqt_str_ctn] = sym__br_sqt_str_ctn, + [ts_external_token__r_sqt_esc_sqt] = sym__r_sqt_esc_sqt, + [ts_external_token__br_sqt_esc_sqt] = sym__br_sqt_esc_sqt, + [ts_external_token__r_sqt_str_end] = sym__r_sqt_str_end, + [ts_external_token__br_sqt_str_end] = sym__br_sqt_str_end, + [ts_external_token__r_sgl_pln_nul_blk] = sym__r_sgl_pln_nul_blk, + [ts_external_token__br_sgl_pln_nul_blk] = sym__br_sgl_pln_nul_blk, + [ts_external_token__b_sgl_pln_nul_blk] = sym__b_sgl_pln_nul_blk, + [ts_external_token__r_sgl_pln_nul_flw] = sym__r_sgl_pln_nul_flw, + [ts_external_token__br_sgl_pln_nul_flw] = sym__br_sgl_pln_nul_flw, + [ts_external_token__r_sgl_pln_bol_blk] = sym__r_sgl_pln_bol_blk, + [ts_external_token__br_sgl_pln_bol_blk] = sym__br_sgl_pln_bol_blk, + [ts_external_token__b_sgl_pln_bol_blk] = sym__b_sgl_pln_bol_blk, + [ts_external_token__r_sgl_pln_bol_flw] = sym__r_sgl_pln_bol_flw, + [ts_external_token__br_sgl_pln_bol_flw] = sym__br_sgl_pln_bol_flw, + [ts_external_token__r_sgl_pln_int_blk] = sym__r_sgl_pln_int_blk, + [ts_external_token__br_sgl_pln_int_blk] = sym__br_sgl_pln_int_blk, + [ts_external_token__b_sgl_pln_int_blk] = sym__b_sgl_pln_int_blk, + [ts_external_token__r_sgl_pln_int_flw] = sym__r_sgl_pln_int_flw, + [ts_external_token__br_sgl_pln_int_flw] = sym__br_sgl_pln_int_flw, + [ts_external_token__r_sgl_pln_flt_blk] = sym__r_sgl_pln_flt_blk, + [ts_external_token__br_sgl_pln_flt_blk] = sym__br_sgl_pln_flt_blk, + [ts_external_token__b_sgl_pln_flt_blk] = sym__b_sgl_pln_flt_blk, + [ts_external_token__r_sgl_pln_flt_flw] = sym__r_sgl_pln_flt_flw, + [ts_external_token__br_sgl_pln_flt_flw] = sym__br_sgl_pln_flt_flw, + [ts_external_token__r_sgl_pln_tms_blk] = sym__r_sgl_pln_tms_blk, + [ts_external_token__br_sgl_pln_tms_blk] = sym__br_sgl_pln_tms_blk, + [ts_external_token__b_sgl_pln_tms_blk] = sym__b_sgl_pln_tms_blk, + [ts_external_token__r_sgl_pln_tms_flw] = sym__r_sgl_pln_tms_flw, + [ts_external_token__br_sgl_pln_tms_flw] = sym__br_sgl_pln_tms_flw, + [ts_external_token__r_sgl_pln_str_blk] = sym__r_sgl_pln_str_blk, + [ts_external_token__br_sgl_pln_str_blk] = sym__br_sgl_pln_str_blk, + [ts_external_token__b_sgl_pln_str_blk] = sym__b_sgl_pln_str_blk, + [ts_external_token__r_sgl_pln_str_flw] = sym__r_sgl_pln_str_flw, + [ts_external_token__br_sgl_pln_str_flw] = sym__br_sgl_pln_str_flw, + [ts_external_token__r_mtl_pln_str_blk] = sym__r_mtl_pln_str_blk, + [ts_external_token__br_mtl_pln_str_blk] = sym__br_mtl_pln_str_blk, + [ts_external_token__r_mtl_pln_str_flw] = sym__r_mtl_pln_str_flw, + [ts_external_token__br_mtl_pln_str_flw] = sym__br_mtl_pln_str_flw, + [ts_external_token__r_tag] = sym__r_tag, + [ts_external_token__br_tag] = sym__br_tag, + [ts_external_token__b_tag] = sym__b_tag, + [ts_external_token__r_acr_bgn] = sym__r_acr_bgn, + [ts_external_token__br_acr_bgn] = sym__br_acr_bgn, + [ts_external_token__b_acr_bgn] = sym__b_acr_bgn, + [ts_external_token__r_acr_ctn] = sym__r_acr_ctn, + [ts_external_token__r_als_bgn] = sym__r_als_bgn, + [ts_external_token__br_als_bgn] = sym__br_als_bgn, + [ts_external_token__b_als_bgn] = sym__b_als_bgn, + [ts_external_token__r_als_ctn] = sym__r_als_ctn, + [ts_external_token__bl] = sym__bl, + [ts_external_token_comment] = sym_comment, + [ts_external_token__err_rec] = sym__err_rec, +}; + +static const bool ts_external_scanner_states[110][EXTERNAL_TOKEN_COUNT] = { + [1] = { + [ts_external_token__eof] = true, + [ts_external_token__s_dir_yml_bgn] = true, + [ts_external_token__r_dir_yml_ver] = true, + [ts_external_token__s_dir_tag_bgn] = true, + [ts_external_token__r_dir_tag_hdl] = true, + [ts_external_token__r_dir_tag_pfx] = true, + [ts_external_token__s_dir_rsv_bgn] = true, + [ts_external_token__r_dir_rsv_prm] = true, + [ts_external_token__s_drs_end] = true, + [ts_external_token__s_doc_end] = true, + [ts_external_token__r_blk_seq_bgn] = true, + [ts_external_token__br_blk_seq_bgn] = true, + [ts_external_token__b_blk_seq_bgn] = true, + [ts_external_token__r_blk_key_bgn] = true, + [ts_external_token__br_blk_key_bgn] = true, + [ts_external_token__b_blk_key_bgn] = true, + [ts_external_token__r_blk_val_bgn] = true, + [ts_external_token__br_blk_val_bgn] = true, + [ts_external_token__b_blk_val_bgn] = true, + [ts_external_token__r_blk_imp_bgn] = true, + [ts_external_token__r_blk_lit_bgn] = true, + [ts_external_token__br_blk_lit_bgn] = true, + [ts_external_token__r_blk_fld_bgn] = true, + [ts_external_token__br_blk_fld_bgn] = true, + [ts_external_token__br_blk_str_ctn] = true, + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__b_flw_seq_bgn] = true, + [ts_external_token__r_flw_seq_end] = true, + [ts_external_token__br_flw_seq_end] = true, + [ts_external_token__b_flw_seq_end] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__b_flw_map_bgn] = true, + [ts_external_token__r_flw_map_end] = true, + [ts_external_token__br_flw_map_end] = true, + [ts_external_token__b_flw_map_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__br_flw_sep_bgn] = true, + [ts_external_token__r_flw_key_bgn] = true, + [ts_external_token__br_flw_key_bgn] = true, + [ts_external_token__r_flw_jsv_bgn] = true, + [ts_external_token__br_flw_jsv_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__br_flw_njv_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__b_dqt_str_bgn] = true, + [ts_external_token__r_dqt_str_ctn] = true, + [ts_external_token__br_dqt_str_ctn] = true, + [ts_external_token__r_dqt_esc_nwl] = true, + [ts_external_token__br_dqt_esc_nwl] = true, + [ts_external_token__r_dqt_esc_seq] = true, + [ts_external_token__br_dqt_esc_seq] = true, + [ts_external_token__r_dqt_str_end] = true, + [ts_external_token__br_dqt_str_end] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__b_sqt_str_bgn] = true, + [ts_external_token__r_sqt_str_ctn] = true, + [ts_external_token__br_sqt_str_ctn] = true, + [ts_external_token__r_sqt_esc_sqt] = true, + [ts_external_token__br_sqt_esc_sqt] = true, + [ts_external_token__r_sqt_str_end] = true, + [ts_external_token__br_sqt_str_end] = true, + [ts_external_token__r_sgl_pln_nul_blk] = true, + [ts_external_token__br_sgl_pln_nul_blk] = true, + [ts_external_token__b_sgl_pln_nul_blk] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__br_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_blk] = true, + [ts_external_token__br_sgl_pln_bol_blk] = true, + [ts_external_token__b_sgl_pln_bol_blk] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__br_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_blk] = true, + [ts_external_token__br_sgl_pln_int_blk] = true, + [ts_external_token__b_sgl_pln_int_blk] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__br_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_blk] = true, + [ts_external_token__br_sgl_pln_flt_blk] = true, + [ts_external_token__b_sgl_pln_flt_blk] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__br_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_blk] = true, + [ts_external_token__br_sgl_pln_tms_blk] = true, + [ts_external_token__b_sgl_pln_tms_blk] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__br_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_blk] = true, + [ts_external_token__br_sgl_pln_str_blk] = true, + [ts_external_token__b_sgl_pln_str_blk] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__br_sgl_pln_str_flw] = true, + [ts_external_token__r_mtl_pln_str_blk] = true, + [ts_external_token__br_mtl_pln_str_blk] = true, + [ts_external_token__r_mtl_pln_str_flw] = true, + [ts_external_token__br_mtl_pln_str_flw] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__b_tag] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__b_acr_bgn] = true, + [ts_external_token__r_acr_ctn] = true, + [ts_external_token__r_als_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token__b_als_bgn] = true, + [ts_external_token__r_als_ctn] = true, + [ts_external_token__bl] = true, + [ts_external_token_comment] = true, + [ts_external_token__err_rec] = true, + }, + [2] = { + [ts_external_token__eof] = true, + [ts_external_token__s_dir_yml_bgn] = true, + [ts_external_token__s_dir_tag_bgn] = true, + [ts_external_token__s_dir_rsv_bgn] = true, + [ts_external_token__s_drs_end] = true, + [ts_external_token__s_doc_end] = true, + [ts_external_token__r_blk_seq_bgn] = true, + [ts_external_token__br_blk_seq_bgn] = true, + [ts_external_token__r_blk_key_bgn] = true, + [ts_external_token__br_blk_key_bgn] = true, + [ts_external_token__r_blk_val_bgn] = true, + [ts_external_token__br_blk_val_bgn] = true, + [ts_external_token__r_blk_lit_bgn] = true, + [ts_external_token__br_blk_lit_bgn] = true, + [ts_external_token__r_blk_fld_bgn] = true, + [ts_external_token__br_blk_fld_bgn] = true, + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_blk] = true, + [ts_external_token__br_sgl_pln_nul_blk] = true, + [ts_external_token__r_sgl_pln_bol_blk] = true, + [ts_external_token__br_sgl_pln_bol_blk] = true, + [ts_external_token__r_sgl_pln_int_blk] = true, + [ts_external_token__br_sgl_pln_int_blk] = true, + [ts_external_token__r_sgl_pln_flt_blk] = true, + [ts_external_token__br_sgl_pln_flt_blk] = true, + [ts_external_token__r_sgl_pln_tms_blk] = true, + [ts_external_token__br_sgl_pln_tms_blk] = true, + [ts_external_token__r_sgl_pln_str_blk] = true, + [ts_external_token__br_sgl_pln_str_blk] = true, + [ts_external_token__r_mtl_pln_str_blk] = true, + [ts_external_token__br_mtl_pln_str_blk] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__r_als_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token_comment] = true, + }, + [3] = { + [ts_external_token__r_blk_seq_bgn] = true, + [ts_external_token__br_blk_seq_bgn] = true, + [ts_external_token__b_blk_seq_bgn] = true, + [ts_external_token__r_blk_key_bgn] = true, + [ts_external_token__br_blk_key_bgn] = true, + [ts_external_token__b_blk_key_bgn] = true, + [ts_external_token__r_blk_val_bgn] = true, + [ts_external_token__br_blk_val_bgn] = true, + [ts_external_token__b_blk_val_bgn] = true, + [ts_external_token__r_blk_lit_bgn] = true, + [ts_external_token__br_blk_lit_bgn] = true, + [ts_external_token__r_blk_fld_bgn] = true, + [ts_external_token__br_blk_fld_bgn] = true, + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__b_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__b_flw_map_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__b_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__b_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_blk] = true, + [ts_external_token__br_sgl_pln_nul_blk] = true, + [ts_external_token__b_sgl_pln_nul_blk] = true, + [ts_external_token__r_sgl_pln_bol_blk] = true, + [ts_external_token__br_sgl_pln_bol_blk] = true, + [ts_external_token__b_sgl_pln_bol_blk] = true, + [ts_external_token__r_sgl_pln_int_blk] = true, + [ts_external_token__br_sgl_pln_int_blk] = true, + [ts_external_token__b_sgl_pln_int_blk] = true, + [ts_external_token__r_sgl_pln_flt_blk] = true, + [ts_external_token__br_sgl_pln_flt_blk] = true, + [ts_external_token__b_sgl_pln_flt_blk] = true, + [ts_external_token__r_sgl_pln_tms_blk] = true, + [ts_external_token__br_sgl_pln_tms_blk] = true, + [ts_external_token__b_sgl_pln_tms_blk] = true, + [ts_external_token__r_sgl_pln_str_blk] = true, + [ts_external_token__br_sgl_pln_str_blk] = true, + [ts_external_token__b_sgl_pln_str_blk] = true, + [ts_external_token__r_mtl_pln_str_blk] = true, + [ts_external_token__br_mtl_pln_str_blk] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__b_tag] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__b_acr_bgn] = true, + [ts_external_token__r_als_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token__b_als_bgn] = true, + [ts_external_token__bl] = true, + [ts_external_token_comment] = true, + }, + [4] = { + [ts_external_token__r_blk_seq_bgn] = true, + [ts_external_token__br_blk_seq_bgn] = true, + [ts_external_token__b_blk_seq_bgn] = true, + [ts_external_token__r_blk_key_bgn] = true, + [ts_external_token__br_blk_key_bgn] = true, + [ts_external_token__r_blk_val_bgn] = true, + [ts_external_token__br_blk_val_bgn] = true, + [ts_external_token__r_blk_lit_bgn] = true, + [ts_external_token__br_blk_lit_bgn] = true, + [ts_external_token__r_blk_fld_bgn] = true, + [ts_external_token__br_blk_fld_bgn] = true, + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_blk] = true, + [ts_external_token__br_sgl_pln_nul_blk] = true, + [ts_external_token__r_sgl_pln_bol_blk] = true, + [ts_external_token__br_sgl_pln_bol_blk] = true, + [ts_external_token__r_sgl_pln_int_blk] = true, + [ts_external_token__br_sgl_pln_int_blk] = true, + [ts_external_token__r_sgl_pln_flt_blk] = true, + [ts_external_token__br_sgl_pln_flt_blk] = true, + [ts_external_token__r_sgl_pln_tms_blk] = true, + [ts_external_token__br_sgl_pln_tms_blk] = true, + [ts_external_token__r_sgl_pln_str_blk] = true, + [ts_external_token__br_sgl_pln_str_blk] = true, + [ts_external_token__r_mtl_pln_str_blk] = true, + [ts_external_token__br_mtl_pln_str_blk] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__r_als_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token__bl] = true, + [ts_external_token_comment] = true, + }, + [5] = { + [ts_external_token__br_blk_seq_bgn] = true, + [ts_external_token__b_blk_seq_bgn] = true, + [ts_external_token__br_blk_key_bgn] = true, + [ts_external_token__b_blk_key_bgn] = true, + [ts_external_token__br_blk_val_bgn] = true, + [ts_external_token__b_blk_val_bgn] = true, + [ts_external_token__r_blk_lit_bgn] = true, + [ts_external_token__br_blk_lit_bgn] = true, + [ts_external_token__r_blk_fld_bgn] = true, + [ts_external_token__br_blk_fld_bgn] = true, + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__b_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__b_flw_map_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__b_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__b_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_blk] = true, + [ts_external_token__br_sgl_pln_nul_blk] = true, + [ts_external_token__b_sgl_pln_nul_blk] = true, + [ts_external_token__r_sgl_pln_bol_blk] = true, + [ts_external_token__br_sgl_pln_bol_blk] = true, + [ts_external_token__b_sgl_pln_bol_blk] = true, + [ts_external_token__r_sgl_pln_int_blk] = true, + [ts_external_token__br_sgl_pln_int_blk] = true, + [ts_external_token__b_sgl_pln_int_blk] = true, + [ts_external_token__r_sgl_pln_flt_blk] = true, + [ts_external_token__br_sgl_pln_flt_blk] = true, + [ts_external_token__b_sgl_pln_flt_blk] = true, + [ts_external_token__r_sgl_pln_tms_blk] = true, + [ts_external_token__br_sgl_pln_tms_blk] = true, + [ts_external_token__b_sgl_pln_tms_blk] = true, + [ts_external_token__r_sgl_pln_str_blk] = true, + [ts_external_token__br_sgl_pln_str_blk] = true, + [ts_external_token__b_sgl_pln_str_blk] = true, + [ts_external_token__r_mtl_pln_str_blk] = true, + [ts_external_token__br_mtl_pln_str_blk] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__b_tag] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__b_acr_bgn] = true, + [ts_external_token__r_als_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token__b_als_bgn] = true, + [ts_external_token__bl] = true, + [ts_external_token_comment] = true, + }, + [6] = { + [ts_external_token__eof] = true, + [ts_external_token__s_drs_end] = true, + [ts_external_token__s_doc_end] = true, + [ts_external_token__br_blk_seq_bgn] = true, + [ts_external_token__br_blk_key_bgn] = true, + [ts_external_token__br_blk_val_bgn] = true, + [ts_external_token__r_blk_lit_bgn] = true, + [ts_external_token__br_blk_lit_bgn] = true, + [ts_external_token__r_blk_fld_bgn] = true, + [ts_external_token__br_blk_fld_bgn] = true, + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_blk] = true, + [ts_external_token__br_sgl_pln_nul_blk] = true, + [ts_external_token__r_sgl_pln_bol_blk] = true, + [ts_external_token__br_sgl_pln_bol_blk] = true, + [ts_external_token__r_sgl_pln_int_blk] = true, + [ts_external_token__br_sgl_pln_int_blk] = true, + [ts_external_token__r_sgl_pln_flt_blk] = true, + [ts_external_token__br_sgl_pln_flt_blk] = true, + [ts_external_token__r_sgl_pln_tms_blk] = true, + [ts_external_token__br_sgl_pln_tms_blk] = true, + [ts_external_token__r_sgl_pln_str_blk] = true, + [ts_external_token__br_sgl_pln_str_blk] = true, + [ts_external_token__r_mtl_pln_str_blk] = true, + [ts_external_token__br_mtl_pln_str_blk] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__r_als_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token_comment] = true, + }, + [7] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_flw_map_end] = true, + [ts_external_token__br_flw_map_end] = true, + [ts_external_token__b_flw_map_end] = true, + [ts_external_token__r_flw_key_bgn] = true, + [ts_external_token__br_flw_key_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__br_flw_njv_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__br_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__br_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__br_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__br_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__br_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__br_sgl_pln_str_flw] = true, + [ts_external_token__r_mtl_pln_str_flw] = true, + [ts_external_token__br_mtl_pln_str_flw] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__r_als_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token_comment] = true, + }, + [8] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_seq_end] = true, + [ts_external_token__br_flw_seq_end] = true, + [ts_external_token__b_flw_seq_end] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_flw_key_bgn] = true, + [ts_external_token__br_flw_key_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__br_flw_njv_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__br_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__br_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__br_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__br_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__br_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__br_sgl_pln_str_flw] = true, + [ts_external_token__r_mtl_pln_str_flw] = true, + [ts_external_token__br_mtl_pln_str_flw] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__r_als_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token_comment] = true, + }, + [9] = { + [ts_external_token__br_blk_seq_bgn] = true, + [ts_external_token__b_blk_seq_bgn] = true, + [ts_external_token__br_blk_key_bgn] = true, + [ts_external_token__b_blk_key_bgn] = true, + [ts_external_token__br_blk_val_bgn] = true, + [ts_external_token__b_blk_val_bgn] = true, + [ts_external_token__r_blk_lit_bgn] = true, + [ts_external_token__br_blk_lit_bgn] = true, + [ts_external_token__r_blk_fld_bgn] = true, + [ts_external_token__br_blk_fld_bgn] = true, + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__b_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__b_flw_map_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__b_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__b_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_blk] = true, + [ts_external_token__br_sgl_pln_nul_blk] = true, + [ts_external_token__b_sgl_pln_nul_blk] = true, + [ts_external_token__r_sgl_pln_bol_blk] = true, + [ts_external_token__br_sgl_pln_bol_blk] = true, + [ts_external_token__b_sgl_pln_bol_blk] = true, + [ts_external_token__r_sgl_pln_int_blk] = true, + [ts_external_token__br_sgl_pln_int_blk] = true, + [ts_external_token__b_sgl_pln_int_blk] = true, + [ts_external_token__r_sgl_pln_flt_blk] = true, + [ts_external_token__br_sgl_pln_flt_blk] = true, + [ts_external_token__b_sgl_pln_flt_blk] = true, + [ts_external_token__r_sgl_pln_tms_blk] = true, + [ts_external_token__br_sgl_pln_tms_blk] = true, + [ts_external_token__b_sgl_pln_tms_blk] = true, + [ts_external_token__r_sgl_pln_str_blk] = true, + [ts_external_token__br_sgl_pln_str_blk] = true, + [ts_external_token__b_sgl_pln_str_blk] = true, + [ts_external_token__r_mtl_pln_str_blk] = true, + [ts_external_token__br_mtl_pln_str_blk] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__b_tag] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__b_acr_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token__b_als_bgn] = true, + [ts_external_token__bl] = true, + [ts_external_token_comment] = true, + }, + [10] = { + [ts_external_token__eof] = true, + [ts_external_token__s_dir_yml_bgn] = true, + [ts_external_token__s_dir_tag_bgn] = true, + [ts_external_token__s_dir_rsv_bgn] = true, + [ts_external_token__s_drs_end] = true, + [ts_external_token__s_doc_end] = true, + [ts_external_token__br_blk_seq_bgn] = true, + [ts_external_token__br_blk_key_bgn] = true, + [ts_external_token__br_blk_val_bgn] = true, + [ts_external_token__br_blk_lit_bgn] = true, + [ts_external_token__br_blk_fld_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__br_sgl_pln_nul_blk] = true, + [ts_external_token__br_sgl_pln_bol_blk] = true, + [ts_external_token__br_sgl_pln_int_blk] = true, + [ts_external_token__br_sgl_pln_flt_blk] = true, + [ts_external_token__br_sgl_pln_tms_blk] = true, + [ts_external_token__br_sgl_pln_str_blk] = true, + [ts_external_token__br_mtl_pln_str_blk] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token_comment] = true, + }, + [11] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_flw_map_end] = true, + [ts_external_token__br_flw_map_end] = true, + [ts_external_token__b_flw_map_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__br_flw_sep_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__br_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__br_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__br_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__br_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__br_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__br_sgl_pln_str_flw] = true, + [ts_external_token__r_mtl_pln_str_flw] = true, + [ts_external_token__br_mtl_pln_str_flw] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__r_als_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token_comment] = true, + }, + [12] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_seq_end] = true, + [ts_external_token__br_flw_seq_end] = true, + [ts_external_token__b_flw_seq_end] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__br_flw_sep_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__br_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__br_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__br_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__br_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__br_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__br_sgl_pln_str_flw] = true, + [ts_external_token__r_mtl_pln_str_flw] = true, + [ts_external_token__br_mtl_pln_str_flw] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__r_als_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token_comment] = true, + }, + [13] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_flw_key_bgn] = true, + [ts_external_token__br_flw_key_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__br_flw_njv_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__br_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__br_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__br_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__br_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__br_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__br_sgl_pln_str_flw] = true, + [ts_external_token__r_mtl_pln_str_flw] = true, + [ts_external_token__br_mtl_pln_str_flw] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__r_als_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token_comment] = true, + }, + [14] = { + [ts_external_token__eof] = true, + [ts_external_token__s_drs_end] = true, + [ts_external_token__s_doc_end] = true, + [ts_external_token__br_blk_seq_bgn] = true, + [ts_external_token__br_blk_key_bgn] = true, + [ts_external_token__br_blk_val_bgn] = true, + [ts_external_token__r_blk_lit_bgn] = true, + [ts_external_token__br_blk_lit_bgn] = true, + [ts_external_token__r_blk_fld_bgn] = true, + [ts_external_token__br_blk_fld_bgn] = true, + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_blk] = true, + [ts_external_token__br_sgl_pln_nul_blk] = true, + [ts_external_token__r_sgl_pln_bol_blk] = true, + [ts_external_token__br_sgl_pln_bol_blk] = true, + [ts_external_token__r_sgl_pln_int_blk] = true, + [ts_external_token__br_sgl_pln_int_blk] = true, + [ts_external_token__r_sgl_pln_flt_blk] = true, + [ts_external_token__br_sgl_pln_flt_blk] = true, + [ts_external_token__r_sgl_pln_tms_blk] = true, + [ts_external_token__br_sgl_pln_tms_blk] = true, + [ts_external_token__r_sgl_pln_str_blk] = true, + [ts_external_token__br_sgl_pln_str_blk] = true, + [ts_external_token__r_mtl_pln_str_blk] = true, + [ts_external_token__br_mtl_pln_str_blk] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token_comment] = true, + }, + [15] = { + [ts_external_token__br_blk_seq_bgn] = true, + [ts_external_token__b_blk_seq_bgn] = true, + [ts_external_token__br_blk_key_bgn] = true, + [ts_external_token__br_blk_val_bgn] = true, + [ts_external_token__r_blk_lit_bgn] = true, + [ts_external_token__br_blk_lit_bgn] = true, + [ts_external_token__r_blk_fld_bgn] = true, + [ts_external_token__br_blk_fld_bgn] = true, + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_blk] = true, + [ts_external_token__br_sgl_pln_nul_blk] = true, + [ts_external_token__r_sgl_pln_bol_blk] = true, + [ts_external_token__br_sgl_pln_bol_blk] = true, + [ts_external_token__r_sgl_pln_int_blk] = true, + [ts_external_token__br_sgl_pln_int_blk] = true, + [ts_external_token__r_sgl_pln_flt_blk] = true, + [ts_external_token__br_sgl_pln_flt_blk] = true, + [ts_external_token__r_sgl_pln_tms_blk] = true, + [ts_external_token__br_sgl_pln_tms_blk] = true, + [ts_external_token__r_sgl_pln_str_blk] = true, + [ts_external_token__br_sgl_pln_str_blk] = true, + [ts_external_token__r_mtl_pln_str_blk] = true, + [ts_external_token__br_mtl_pln_str_blk] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token__bl] = true, + [ts_external_token_comment] = true, + }, + [16] = { + [ts_external_token__br_blk_seq_bgn] = true, + [ts_external_token__b_blk_seq_bgn] = true, + [ts_external_token__br_blk_key_bgn] = true, + [ts_external_token__b_blk_key_bgn] = true, + [ts_external_token__br_blk_val_bgn] = true, + [ts_external_token__b_blk_val_bgn] = true, + [ts_external_token__r_blk_imp_bgn] = true, + [ts_external_token__r_blk_lit_bgn] = true, + [ts_external_token__br_blk_lit_bgn] = true, + [ts_external_token__r_blk_fld_bgn] = true, + [ts_external_token__br_blk_fld_bgn] = true, + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__b_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__b_flw_map_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__b_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__b_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_blk] = true, + [ts_external_token__br_sgl_pln_nul_blk] = true, + [ts_external_token__b_sgl_pln_nul_blk] = true, + [ts_external_token__r_sgl_pln_bol_blk] = true, + [ts_external_token__br_sgl_pln_bol_blk] = true, + [ts_external_token__b_sgl_pln_bol_blk] = true, + [ts_external_token__r_sgl_pln_int_blk] = true, + [ts_external_token__br_sgl_pln_int_blk] = true, + [ts_external_token__b_sgl_pln_int_blk] = true, + [ts_external_token__r_sgl_pln_flt_blk] = true, + [ts_external_token__br_sgl_pln_flt_blk] = true, + [ts_external_token__b_sgl_pln_flt_blk] = true, + [ts_external_token__r_sgl_pln_tms_blk] = true, + [ts_external_token__br_sgl_pln_tms_blk] = true, + [ts_external_token__b_sgl_pln_tms_blk] = true, + [ts_external_token__r_sgl_pln_str_blk] = true, + [ts_external_token__br_sgl_pln_str_blk] = true, + [ts_external_token__b_sgl_pln_str_blk] = true, + [ts_external_token__r_mtl_pln_str_blk] = true, + [ts_external_token__br_mtl_pln_str_blk] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__b_tag] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__b_acr_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token__b_als_bgn] = true, + [ts_external_token__bl] = true, + [ts_external_token_comment] = true, + }, + [17] = { + [ts_external_token__br_blk_seq_bgn] = true, + [ts_external_token__b_blk_seq_bgn] = true, + [ts_external_token__br_blk_key_bgn] = true, + [ts_external_token__b_blk_key_bgn] = true, + [ts_external_token__br_blk_val_bgn] = true, + [ts_external_token__b_blk_val_bgn] = true, + [ts_external_token__r_blk_lit_bgn] = true, + [ts_external_token__br_blk_lit_bgn] = true, + [ts_external_token__r_blk_fld_bgn] = true, + [ts_external_token__br_blk_fld_bgn] = true, + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__b_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__b_flw_map_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__b_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__b_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_blk] = true, + [ts_external_token__br_sgl_pln_nul_blk] = true, + [ts_external_token__b_sgl_pln_nul_blk] = true, + [ts_external_token__r_sgl_pln_bol_blk] = true, + [ts_external_token__br_sgl_pln_bol_blk] = true, + [ts_external_token__b_sgl_pln_bol_blk] = true, + [ts_external_token__r_sgl_pln_int_blk] = true, + [ts_external_token__br_sgl_pln_int_blk] = true, + [ts_external_token__b_sgl_pln_int_blk] = true, + [ts_external_token__r_sgl_pln_flt_blk] = true, + [ts_external_token__br_sgl_pln_flt_blk] = true, + [ts_external_token__b_sgl_pln_flt_blk] = true, + [ts_external_token__r_sgl_pln_tms_blk] = true, + [ts_external_token__br_sgl_pln_tms_blk] = true, + [ts_external_token__b_sgl_pln_tms_blk] = true, + [ts_external_token__r_sgl_pln_str_blk] = true, + [ts_external_token__br_sgl_pln_str_blk] = true, + [ts_external_token__b_sgl_pln_str_blk] = true, + [ts_external_token__r_mtl_pln_str_blk] = true, + [ts_external_token__br_mtl_pln_str_blk] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__b_tag] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__b_acr_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token__b_als_bgn] = true, + [ts_external_token__bl] = true, + [ts_external_token_comment] = true, + }, + [18] = { + [ts_external_token__br_blk_seq_bgn] = true, + [ts_external_token__b_blk_seq_bgn] = true, + [ts_external_token__br_blk_key_bgn] = true, + [ts_external_token__b_blk_key_bgn] = true, + [ts_external_token__br_blk_val_bgn] = true, + [ts_external_token__b_blk_val_bgn] = true, + [ts_external_token__r_blk_imp_bgn] = true, + [ts_external_token__r_blk_lit_bgn] = true, + [ts_external_token__br_blk_lit_bgn] = true, + [ts_external_token__r_blk_fld_bgn] = true, + [ts_external_token__br_blk_fld_bgn] = true, + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__b_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__b_flw_map_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__b_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__b_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_blk] = true, + [ts_external_token__br_sgl_pln_nul_blk] = true, + [ts_external_token__b_sgl_pln_nul_blk] = true, + [ts_external_token__r_sgl_pln_bol_blk] = true, + [ts_external_token__br_sgl_pln_bol_blk] = true, + [ts_external_token__b_sgl_pln_bol_blk] = true, + [ts_external_token__r_sgl_pln_int_blk] = true, + [ts_external_token__br_sgl_pln_int_blk] = true, + [ts_external_token__b_sgl_pln_int_blk] = true, + [ts_external_token__r_sgl_pln_flt_blk] = true, + [ts_external_token__br_sgl_pln_flt_blk] = true, + [ts_external_token__b_sgl_pln_flt_blk] = true, + [ts_external_token__r_sgl_pln_tms_blk] = true, + [ts_external_token__br_sgl_pln_tms_blk] = true, + [ts_external_token__b_sgl_pln_tms_blk] = true, + [ts_external_token__r_sgl_pln_str_blk] = true, + [ts_external_token__br_sgl_pln_str_blk] = true, + [ts_external_token__b_sgl_pln_str_blk] = true, + [ts_external_token__r_mtl_pln_str_blk] = true, + [ts_external_token__br_mtl_pln_str_blk] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__b_tag] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__b_acr_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token__b_als_bgn] = true, + [ts_external_token__bl] = true, + [ts_external_token_comment] = true, + }, + [19] = { + [ts_external_token__br_blk_seq_bgn] = true, + [ts_external_token__b_blk_seq_bgn] = true, + [ts_external_token__br_blk_key_bgn] = true, + [ts_external_token__b_blk_key_bgn] = true, + [ts_external_token__br_blk_val_bgn] = true, + [ts_external_token__b_blk_val_bgn] = true, + [ts_external_token__r_blk_imp_bgn] = true, + [ts_external_token__r_blk_lit_bgn] = true, + [ts_external_token__br_blk_lit_bgn] = true, + [ts_external_token__r_blk_fld_bgn] = true, + [ts_external_token__br_blk_fld_bgn] = true, + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__b_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__b_flw_map_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__b_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__b_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_blk] = true, + [ts_external_token__br_sgl_pln_nul_blk] = true, + [ts_external_token__b_sgl_pln_nul_blk] = true, + [ts_external_token__r_sgl_pln_bol_blk] = true, + [ts_external_token__br_sgl_pln_bol_blk] = true, + [ts_external_token__b_sgl_pln_bol_blk] = true, + [ts_external_token__r_sgl_pln_int_blk] = true, + [ts_external_token__br_sgl_pln_int_blk] = true, + [ts_external_token__b_sgl_pln_int_blk] = true, + [ts_external_token__r_sgl_pln_flt_blk] = true, + [ts_external_token__br_sgl_pln_flt_blk] = true, + [ts_external_token__b_sgl_pln_flt_blk] = true, + [ts_external_token__r_sgl_pln_tms_blk] = true, + [ts_external_token__br_sgl_pln_tms_blk] = true, + [ts_external_token__b_sgl_pln_tms_blk] = true, + [ts_external_token__r_sgl_pln_str_blk] = true, + [ts_external_token__br_sgl_pln_str_blk] = true, + [ts_external_token__b_sgl_pln_str_blk] = true, + [ts_external_token__r_mtl_pln_str_blk] = true, + [ts_external_token__br_mtl_pln_str_blk] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__b_tag] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__b_acr_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token__b_als_bgn] = true, + [ts_external_token__bl] = true, + [ts_external_token_comment] = true, + }, + [20] = { + [ts_external_token__br_blk_seq_bgn] = true, + [ts_external_token__b_blk_seq_bgn] = true, + [ts_external_token__br_blk_key_bgn] = true, + [ts_external_token__b_blk_key_bgn] = true, + [ts_external_token__br_blk_val_bgn] = true, + [ts_external_token__b_blk_val_bgn] = true, + [ts_external_token__r_blk_lit_bgn] = true, + [ts_external_token__br_blk_lit_bgn] = true, + [ts_external_token__r_blk_fld_bgn] = true, + [ts_external_token__br_blk_fld_bgn] = true, + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__b_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__b_flw_map_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__b_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__b_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_blk] = true, + [ts_external_token__br_sgl_pln_nul_blk] = true, + [ts_external_token__b_sgl_pln_nul_blk] = true, + [ts_external_token__r_sgl_pln_bol_blk] = true, + [ts_external_token__br_sgl_pln_bol_blk] = true, + [ts_external_token__b_sgl_pln_bol_blk] = true, + [ts_external_token__r_sgl_pln_int_blk] = true, + [ts_external_token__br_sgl_pln_int_blk] = true, + [ts_external_token__b_sgl_pln_int_blk] = true, + [ts_external_token__r_sgl_pln_flt_blk] = true, + [ts_external_token__br_sgl_pln_flt_blk] = true, + [ts_external_token__b_sgl_pln_flt_blk] = true, + [ts_external_token__r_sgl_pln_tms_blk] = true, + [ts_external_token__br_sgl_pln_tms_blk] = true, + [ts_external_token__b_sgl_pln_tms_blk] = true, + [ts_external_token__r_sgl_pln_str_blk] = true, + [ts_external_token__br_sgl_pln_str_blk] = true, + [ts_external_token__b_sgl_pln_str_blk] = true, + [ts_external_token__r_mtl_pln_str_blk] = true, + [ts_external_token__br_mtl_pln_str_blk] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__b_tag] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__b_acr_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token__b_als_bgn] = true, + [ts_external_token__bl] = true, + [ts_external_token_comment] = true, + }, + [21] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_flw_map_end] = true, + [ts_external_token__br_flw_map_end] = true, + [ts_external_token__b_flw_map_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__br_flw_sep_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__br_flw_njv_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__br_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__br_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__br_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__br_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__br_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__br_sgl_pln_str_flw] = true, + [ts_external_token__r_mtl_pln_str_flw] = true, + [ts_external_token__br_mtl_pln_str_flw] = true, + [ts_external_token_comment] = true, + }, + [22] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_seq_end] = true, + [ts_external_token__br_flw_seq_end] = true, + [ts_external_token__b_flw_seq_end] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__br_flw_sep_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__br_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__br_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__br_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__br_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__br_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__br_sgl_pln_str_flw] = true, + [ts_external_token__r_mtl_pln_str_flw] = true, + [ts_external_token__br_mtl_pln_str_flw] = true, + [ts_external_token_comment] = true, + }, + [23] = { + [ts_external_token__eof] = true, + [ts_external_token__s_drs_end] = true, + [ts_external_token__s_doc_end] = true, + [ts_external_token__br_blk_seq_bgn] = true, + [ts_external_token__br_blk_key_bgn] = true, + [ts_external_token__br_blk_val_bgn] = true, + [ts_external_token__r_blk_imp_bgn] = true, + [ts_external_token__r_blk_lit_bgn] = true, + [ts_external_token__br_blk_lit_bgn] = true, + [ts_external_token__r_blk_fld_bgn] = true, + [ts_external_token__br_blk_fld_bgn] = true, + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_blk] = true, + [ts_external_token__br_sgl_pln_nul_blk] = true, + [ts_external_token__r_sgl_pln_bol_blk] = true, + [ts_external_token__br_sgl_pln_bol_blk] = true, + [ts_external_token__r_sgl_pln_int_blk] = true, + [ts_external_token__br_sgl_pln_int_blk] = true, + [ts_external_token__r_sgl_pln_flt_blk] = true, + [ts_external_token__br_sgl_pln_flt_blk] = true, + [ts_external_token__r_sgl_pln_tms_blk] = true, + [ts_external_token__br_sgl_pln_tms_blk] = true, + [ts_external_token__r_sgl_pln_str_blk] = true, + [ts_external_token__br_sgl_pln_str_blk] = true, + [ts_external_token__r_mtl_pln_str_blk] = true, + [ts_external_token__br_mtl_pln_str_blk] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token_comment] = true, + }, + [24] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_seq_end] = true, + [ts_external_token__br_flw_seq_end] = true, + [ts_external_token__b_flw_seq_end] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__br_flw_sep_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__br_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__br_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__br_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__br_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__br_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__br_sgl_pln_str_flw] = true, + [ts_external_token__r_mtl_pln_str_flw] = true, + [ts_external_token__br_mtl_pln_str_flw] = true, + [ts_external_token_comment] = true, + }, + [25] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_flw_map_end] = true, + [ts_external_token__br_flw_map_end] = true, + [ts_external_token__b_flw_map_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__br_flw_sep_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__br_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__br_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__br_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__br_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__br_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__br_sgl_pln_str_flw] = true, + [ts_external_token__r_mtl_pln_str_flw] = true, + [ts_external_token__br_mtl_pln_str_flw] = true, + [ts_external_token_comment] = true, + }, + [26] = { + [ts_external_token__br_blk_seq_bgn] = true, + [ts_external_token__b_blk_seq_bgn] = true, + [ts_external_token__br_blk_key_bgn] = true, + [ts_external_token__br_blk_val_bgn] = true, + [ts_external_token__r_blk_imp_bgn] = true, + [ts_external_token__r_blk_lit_bgn] = true, + [ts_external_token__br_blk_lit_bgn] = true, + [ts_external_token__r_blk_fld_bgn] = true, + [ts_external_token__br_blk_fld_bgn] = true, + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_blk] = true, + [ts_external_token__br_sgl_pln_nul_blk] = true, + [ts_external_token__r_sgl_pln_bol_blk] = true, + [ts_external_token__br_sgl_pln_bol_blk] = true, + [ts_external_token__r_sgl_pln_int_blk] = true, + [ts_external_token__br_sgl_pln_int_blk] = true, + [ts_external_token__r_sgl_pln_flt_blk] = true, + [ts_external_token__br_sgl_pln_flt_blk] = true, + [ts_external_token__r_sgl_pln_tms_blk] = true, + [ts_external_token__br_sgl_pln_tms_blk] = true, + [ts_external_token__r_sgl_pln_str_blk] = true, + [ts_external_token__br_sgl_pln_str_blk] = true, + [ts_external_token__r_mtl_pln_str_blk] = true, + [ts_external_token__br_mtl_pln_str_blk] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token__bl] = true, + [ts_external_token_comment] = true, + }, + [27] = { + [ts_external_token__eof] = true, + [ts_external_token__s_drs_end] = true, + [ts_external_token__s_doc_end] = true, + [ts_external_token__br_blk_seq_bgn] = true, + [ts_external_token__br_blk_key_bgn] = true, + [ts_external_token__br_blk_val_bgn] = true, + [ts_external_token__r_blk_lit_bgn] = true, + [ts_external_token__br_blk_lit_bgn] = true, + [ts_external_token__r_blk_fld_bgn] = true, + [ts_external_token__br_blk_fld_bgn] = true, + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_blk] = true, + [ts_external_token__br_sgl_pln_nul_blk] = true, + [ts_external_token__r_sgl_pln_bol_blk] = true, + [ts_external_token__br_sgl_pln_bol_blk] = true, + [ts_external_token__r_sgl_pln_int_blk] = true, + [ts_external_token__br_sgl_pln_int_blk] = true, + [ts_external_token__r_sgl_pln_flt_blk] = true, + [ts_external_token__br_sgl_pln_flt_blk] = true, + [ts_external_token__r_sgl_pln_tms_blk] = true, + [ts_external_token__br_sgl_pln_tms_blk] = true, + [ts_external_token__r_sgl_pln_str_blk] = true, + [ts_external_token__br_sgl_pln_str_blk] = true, + [ts_external_token__r_mtl_pln_str_blk] = true, + [ts_external_token__br_mtl_pln_str_blk] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token_comment] = true, + }, + [28] = { + [ts_external_token__b_blk_key_bgn] = true, + [ts_external_token__b_blk_val_bgn] = true, + [ts_external_token__b_flw_seq_bgn] = true, + [ts_external_token__b_flw_map_bgn] = true, + [ts_external_token__b_dqt_str_bgn] = true, + [ts_external_token__b_sqt_str_bgn] = true, + [ts_external_token__b_sgl_pln_nul_blk] = true, + [ts_external_token__b_sgl_pln_bol_blk] = true, + [ts_external_token__b_sgl_pln_int_blk] = true, + [ts_external_token__b_sgl_pln_flt_blk] = true, + [ts_external_token__b_sgl_pln_tms_blk] = true, + [ts_external_token__b_sgl_pln_str_blk] = true, + [ts_external_token__b_tag] = true, + [ts_external_token__b_acr_bgn] = true, + [ts_external_token__b_als_bgn] = true, + [ts_external_token__bl] = true, + [ts_external_token_comment] = true, + }, + [29] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__r_flw_map_end] = true, + [ts_external_token__r_flw_key_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__r_als_bgn] = true, + [ts_external_token_comment] = true, + }, + [30] = { + [ts_external_token__eof] = true, + [ts_external_token__s_drs_end] = true, + [ts_external_token__s_doc_end] = true, + [ts_external_token__br_blk_seq_bgn] = true, + [ts_external_token__br_blk_key_bgn] = true, + [ts_external_token__br_blk_val_bgn] = true, + [ts_external_token__r_blk_imp_bgn] = true, + [ts_external_token__r_blk_lit_bgn] = true, + [ts_external_token__br_blk_lit_bgn] = true, + [ts_external_token__r_blk_fld_bgn] = true, + [ts_external_token__br_blk_fld_bgn] = true, + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_blk] = true, + [ts_external_token__br_sgl_pln_nul_blk] = true, + [ts_external_token__r_sgl_pln_bol_blk] = true, + [ts_external_token__br_sgl_pln_bol_blk] = true, + [ts_external_token__r_sgl_pln_int_blk] = true, + [ts_external_token__br_sgl_pln_int_blk] = true, + [ts_external_token__r_sgl_pln_flt_blk] = true, + [ts_external_token__br_sgl_pln_flt_blk] = true, + [ts_external_token__r_sgl_pln_tms_blk] = true, + [ts_external_token__br_sgl_pln_tms_blk] = true, + [ts_external_token__r_sgl_pln_str_blk] = true, + [ts_external_token__br_sgl_pln_str_blk] = true, + [ts_external_token__r_mtl_pln_str_blk] = true, + [ts_external_token__br_mtl_pln_str_blk] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token_comment] = true, + }, + [31] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__r_flw_seq_end] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__r_flw_key_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__r_als_bgn] = true, + [ts_external_token_comment] = true, + }, + [32] = { + [ts_external_token__br_blk_seq_bgn] = true, + [ts_external_token__b_blk_seq_bgn] = true, + [ts_external_token__br_blk_key_bgn] = true, + [ts_external_token__br_blk_val_bgn] = true, + [ts_external_token__r_blk_imp_bgn] = true, + [ts_external_token__r_blk_lit_bgn] = true, + [ts_external_token__br_blk_lit_bgn] = true, + [ts_external_token__r_blk_fld_bgn] = true, + [ts_external_token__br_blk_fld_bgn] = true, + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_blk] = true, + [ts_external_token__br_sgl_pln_nul_blk] = true, + [ts_external_token__r_sgl_pln_bol_blk] = true, + [ts_external_token__br_sgl_pln_bol_blk] = true, + [ts_external_token__r_sgl_pln_int_blk] = true, + [ts_external_token__br_sgl_pln_int_blk] = true, + [ts_external_token__r_sgl_pln_flt_blk] = true, + [ts_external_token__br_sgl_pln_flt_blk] = true, + [ts_external_token__r_sgl_pln_tms_blk] = true, + [ts_external_token__br_sgl_pln_tms_blk] = true, + [ts_external_token__r_sgl_pln_str_blk] = true, + [ts_external_token__br_sgl_pln_str_blk] = true, + [ts_external_token__r_mtl_pln_str_blk] = true, + [ts_external_token__br_mtl_pln_str_blk] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token__bl] = true, + [ts_external_token_comment] = true, + }, + [33] = { + [ts_external_token__eof] = true, + [ts_external_token__s_drs_end] = true, + [ts_external_token__s_doc_end] = true, + [ts_external_token__br_blk_seq_bgn] = true, + [ts_external_token__br_blk_key_bgn] = true, + [ts_external_token__br_blk_val_bgn] = true, + [ts_external_token__r_blk_imp_bgn] = true, + [ts_external_token__r_blk_lit_bgn] = true, + [ts_external_token__br_blk_lit_bgn] = true, + [ts_external_token__r_blk_fld_bgn] = true, + [ts_external_token__br_blk_fld_bgn] = true, + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_blk] = true, + [ts_external_token__br_sgl_pln_nul_blk] = true, + [ts_external_token__r_sgl_pln_bol_blk] = true, + [ts_external_token__br_sgl_pln_bol_blk] = true, + [ts_external_token__r_sgl_pln_int_blk] = true, + [ts_external_token__br_sgl_pln_int_blk] = true, + [ts_external_token__r_sgl_pln_flt_blk] = true, + [ts_external_token__br_sgl_pln_flt_blk] = true, + [ts_external_token__r_sgl_pln_tms_blk] = true, + [ts_external_token__br_sgl_pln_tms_blk] = true, + [ts_external_token__r_sgl_pln_str_blk] = true, + [ts_external_token__br_sgl_pln_str_blk] = true, + [ts_external_token__r_mtl_pln_str_blk] = true, + [ts_external_token__br_mtl_pln_str_blk] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token_comment] = true, + }, + [34] = { + [ts_external_token__eof] = true, + [ts_external_token__s_drs_end] = true, + [ts_external_token__s_doc_end] = true, + [ts_external_token__br_blk_seq_bgn] = true, + [ts_external_token__br_blk_key_bgn] = true, + [ts_external_token__br_blk_val_bgn] = true, + [ts_external_token__r_blk_lit_bgn] = true, + [ts_external_token__br_blk_lit_bgn] = true, + [ts_external_token__r_blk_fld_bgn] = true, + [ts_external_token__br_blk_fld_bgn] = true, + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_blk] = true, + [ts_external_token__br_sgl_pln_nul_blk] = true, + [ts_external_token__r_sgl_pln_bol_blk] = true, + [ts_external_token__br_sgl_pln_bol_blk] = true, + [ts_external_token__r_sgl_pln_int_blk] = true, + [ts_external_token__br_sgl_pln_int_blk] = true, + [ts_external_token__r_sgl_pln_flt_blk] = true, + [ts_external_token__br_sgl_pln_flt_blk] = true, + [ts_external_token__r_sgl_pln_tms_blk] = true, + [ts_external_token__br_sgl_pln_tms_blk] = true, + [ts_external_token__r_sgl_pln_str_blk] = true, + [ts_external_token__br_sgl_pln_str_blk] = true, + [ts_external_token__r_mtl_pln_str_blk] = true, + [ts_external_token__br_mtl_pln_str_blk] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token_comment] = true, + }, + [35] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__br_flw_njv_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__br_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__br_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__br_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__br_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__br_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__br_sgl_pln_str_flw] = true, + [ts_external_token__r_mtl_pln_str_flw] = true, + [ts_external_token__br_mtl_pln_str_flw] = true, + [ts_external_token_comment] = true, + }, + [36] = { + [ts_external_token__br_blk_seq_bgn] = true, + [ts_external_token__b_blk_seq_bgn] = true, + [ts_external_token__br_blk_key_bgn] = true, + [ts_external_token__br_blk_val_bgn] = true, + [ts_external_token__r_blk_imp_bgn] = true, + [ts_external_token__r_blk_lit_bgn] = true, + [ts_external_token__br_blk_lit_bgn] = true, + [ts_external_token__r_blk_fld_bgn] = true, + [ts_external_token__br_blk_fld_bgn] = true, + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_blk] = true, + [ts_external_token__br_sgl_pln_nul_blk] = true, + [ts_external_token__r_sgl_pln_bol_blk] = true, + [ts_external_token__br_sgl_pln_bol_blk] = true, + [ts_external_token__r_sgl_pln_int_blk] = true, + [ts_external_token__br_sgl_pln_int_blk] = true, + [ts_external_token__r_sgl_pln_flt_blk] = true, + [ts_external_token__br_sgl_pln_flt_blk] = true, + [ts_external_token__r_sgl_pln_tms_blk] = true, + [ts_external_token__br_sgl_pln_tms_blk] = true, + [ts_external_token__r_sgl_pln_str_blk] = true, + [ts_external_token__br_sgl_pln_str_blk] = true, + [ts_external_token__r_mtl_pln_str_blk] = true, + [ts_external_token__br_mtl_pln_str_blk] = true, + [ts_external_token__br_tag] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token__br_als_bgn] = true, + [ts_external_token__bl] = true, + [ts_external_token_comment] = true, + }, + [37] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__r_flw_key_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__r_als_bgn] = true, + [ts_external_token_comment] = true, + }, + [38] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_flw_map_end] = true, + [ts_external_token__br_flw_map_end] = true, + [ts_external_token__b_flw_map_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__br_flw_sep_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__br_flw_njv_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__br_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__br_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__br_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__br_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__br_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__br_sgl_pln_str_flw] = true, + [ts_external_token__r_mtl_pln_str_flw] = true, + [ts_external_token__br_mtl_pln_str_flw] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token_comment] = true, + }, + [39] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_seq_end] = true, + [ts_external_token__br_flw_seq_end] = true, + [ts_external_token__b_flw_seq_end] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__br_flw_sep_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__br_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__br_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__br_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__br_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__br_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__br_sgl_pln_str_flw] = true, + [ts_external_token__r_mtl_pln_str_flw] = true, + [ts_external_token__br_mtl_pln_str_flw] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token_comment] = true, + }, + [40] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__r_flw_map_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__r_als_bgn] = true, + [ts_external_token_comment] = true, + }, + [41] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_flw_map_end] = true, + [ts_external_token__br_flw_map_end] = true, + [ts_external_token__b_flw_map_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__br_flw_sep_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__br_flw_njv_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__br_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__br_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__br_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__br_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__br_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__br_sgl_pln_str_flw] = true, + [ts_external_token__r_mtl_pln_str_flw] = true, + [ts_external_token__br_mtl_pln_str_flw] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__br_tag] = true, + [ts_external_token_comment] = true, + }, + [42] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_seq_end] = true, + [ts_external_token__br_flw_seq_end] = true, + [ts_external_token__b_flw_seq_end] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__br_flw_sep_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__br_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__br_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__br_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__br_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__br_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__br_sgl_pln_str_flw] = true, + [ts_external_token__r_mtl_pln_str_flw] = true, + [ts_external_token__br_mtl_pln_str_flw] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token_comment] = true, + }, + [43] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_flw_map_end] = true, + [ts_external_token__br_flw_map_end] = true, + [ts_external_token__b_flw_map_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__br_flw_sep_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__br_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__br_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__br_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__br_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__br_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__br_sgl_pln_str_flw] = true, + [ts_external_token__r_mtl_pln_str_flw] = true, + [ts_external_token__br_mtl_pln_str_flw] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token_comment] = true, + }, + [44] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__r_flw_seq_end] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__r_als_bgn] = true, + [ts_external_token_comment] = true, + }, + [45] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_seq_end] = true, + [ts_external_token__br_flw_seq_end] = true, + [ts_external_token__b_flw_seq_end] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__br_flw_sep_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__br_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__br_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__br_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__br_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__br_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__br_sgl_pln_str_flw] = true, + [ts_external_token__r_mtl_pln_str_flw] = true, + [ts_external_token__br_mtl_pln_str_flw] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__br_tag] = true, + [ts_external_token_comment] = true, + }, + [46] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_flw_map_end] = true, + [ts_external_token__br_flw_map_end] = true, + [ts_external_token__b_flw_map_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__br_flw_sep_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__br_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__br_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__br_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__br_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__br_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__br_sgl_pln_str_flw] = true, + [ts_external_token__r_mtl_pln_str_flw] = true, + [ts_external_token__br_mtl_pln_str_flw] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__br_tag] = true, + [ts_external_token_comment] = true, + }, + [47] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_seq_end] = true, + [ts_external_token__br_flw_seq_end] = true, + [ts_external_token__b_flw_seq_end] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__br_flw_sep_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__br_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__br_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__br_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__br_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__br_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__br_sgl_pln_str_flw] = true, + [ts_external_token__r_mtl_pln_str_flw] = true, + [ts_external_token__br_mtl_pln_str_flw] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__br_tag] = true, + [ts_external_token_comment] = true, + }, + [48] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__br_flw_njv_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__br_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__br_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__br_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__br_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__br_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__br_sgl_pln_str_flw] = true, + [ts_external_token__r_mtl_pln_str_flw] = true, + [ts_external_token__br_mtl_pln_str_flw] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token__br_acr_bgn] = true, + [ts_external_token_comment] = true, + }, + [49] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__br_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__br_flw_map_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__br_flw_njv_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__br_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__br_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__br_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__br_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__br_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__br_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__br_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__br_sgl_pln_str_flw] = true, + [ts_external_token__r_mtl_pln_str_flw] = true, + [ts_external_token__br_mtl_pln_str_flw] = true, + [ts_external_token__r_tag] = true, + [ts_external_token__br_tag] = true, + [ts_external_token_comment] = true, + }, + [50] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__r_flw_seq_end] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token_comment] = true, + }, + [51] = { + [ts_external_token__b_blk_key_bgn] = true, + [ts_external_token__b_blk_val_bgn] = true, + [ts_external_token__r_blk_imp_bgn] = true, + [ts_external_token__b_flw_seq_bgn] = true, + [ts_external_token__b_flw_map_bgn] = true, + [ts_external_token__b_dqt_str_bgn] = true, + [ts_external_token__b_sqt_str_bgn] = true, + [ts_external_token__b_sgl_pln_nul_blk] = true, + [ts_external_token__b_sgl_pln_bol_blk] = true, + [ts_external_token__b_sgl_pln_int_blk] = true, + [ts_external_token__b_sgl_pln_flt_blk] = true, + [ts_external_token__b_sgl_pln_tms_blk] = true, + [ts_external_token__b_sgl_pln_str_blk] = true, + [ts_external_token__b_tag] = true, + [ts_external_token__b_acr_bgn] = true, + [ts_external_token__b_als_bgn] = true, + [ts_external_token__bl] = true, + [ts_external_token_comment] = true, + }, + [52] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__r_flw_map_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token_comment] = true, + }, + [53] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__r_flw_seq_end] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token_comment] = true, + }, + [54] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__r_flw_map_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token_comment] = true, + }, + [55] = { + [ts_external_token__r_blk_imp_bgn] = true, + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_blk] = true, + [ts_external_token__r_sgl_pln_bol_blk] = true, + [ts_external_token__r_sgl_pln_int_blk] = true, + [ts_external_token__r_sgl_pln_flt_blk] = true, + [ts_external_token__r_sgl_pln_tms_blk] = true, + [ts_external_token__r_sgl_pln_str_blk] = true, + [ts_external_token_comment] = true, + }, + [56] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token_comment] = true, + }, + [57] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__r_flw_seq_end] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token_comment] = true, + }, + [58] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__r_flw_map_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token_comment] = true, + }, + [59] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__r_flw_map_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token_comment] = true, + }, + [60] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__r_flw_seq_end] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__r_tag] = true, + [ts_external_token_comment] = true, + }, + [61] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__r_flw_seq_end] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token_comment] = true, + }, + [62] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__r_flw_map_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__r_tag] = true, + [ts_external_token_comment] = true, + }, + [63] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__r_flw_seq_end] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__r_tag] = true, + [ts_external_token_comment] = true, + }, + [64] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token_comment] = true, + }, + [65] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__r_flw_map_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__r_tag] = true, + [ts_external_token_comment] = true, + }, + [66] = { + [ts_external_token__r_blk_imp_bgn] = true, + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_blk] = true, + [ts_external_token__r_sgl_pln_bol_blk] = true, + [ts_external_token__r_sgl_pln_int_blk] = true, + [ts_external_token__r_sgl_pln_flt_blk] = true, + [ts_external_token__r_sgl_pln_tms_blk] = true, + [ts_external_token__r_sgl_pln_str_blk] = true, + [ts_external_token__r_acr_bgn] = true, + [ts_external_token_comment] = true, + }, + [67] = { + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_flw] = true, + [ts_external_token__r_sgl_pln_bol_flw] = true, + [ts_external_token__r_sgl_pln_int_flw] = true, + [ts_external_token__r_sgl_pln_flt_flw] = true, + [ts_external_token__r_sgl_pln_tms_flw] = true, + [ts_external_token__r_sgl_pln_str_flw] = true, + [ts_external_token__r_tag] = true, + [ts_external_token_comment] = true, + }, + [68] = { + [ts_external_token__r_blk_imp_bgn] = true, + [ts_external_token__r_flw_seq_bgn] = true, + [ts_external_token__r_flw_map_bgn] = true, + [ts_external_token__r_dqt_str_bgn] = true, + [ts_external_token__r_sqt_str_bgn] = true, + [ts_external_token__r_sgl_pln_nul_blk] = true, + [ts_external_token__r_sgl_pln_bol_blk] = true, + [ts_external_token__r_sgl_pln_int_blk] = true, + [ts_external_token__r_sgl_pln_flt_blk] = true, + [ts_external_token__r_sgl_pln_tms_blk] = true, + [ts_external_token__r_sgl_pln_str_blk] = true, + [ts_external_token__r_tag] = true, + [ts_external_token_comment] = true, + }, + [69] = { + [ts_external_token__r_dqt_str_ctn] = true, + [ts_external_token__br_dqt_str_ctn] = true, + [ts_external_token__r_dqt_esc_nwl] = true, + [ts_external_token__br_dqt_esc_nwl] = true, + [ts_external_token__r_dqt_esc_seq] = true, + [ts_external_token__br_dqt_esc_seq] = true, + [ts_external_token__r_dqt_str_end] = true, + [ts_external_token__br_dqt_str_end] = true, + [ts_external_token_comment] = true, + }, + [70] = { + [ts_external_token__eof] = true, + [ts_external_token__s_drs_end] = true, + [ts_external_token__s_doc_end] = true, + [ts_external_token_comment] = true, + }, + [71] = { + [ts_external_token__r_flw_map_end] = true, + [ts_external_token__br_flw_map_end] = true, + [ts_external_token__b_flw_map_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__br_flw_sep_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__br_flw_njv_bgn] = true, + [ts_external_token_comment] = true, + }, + [72] = { + [ts_external_token__s_dir_yml_bgn] = true, + [ts_external_token__s_dir_tag_bgn] = true, + [ts_external_token__s_dir_rsv_bgn] = true, + [ts_external_token__s_drs_end] = true, + [ts_external_token_comment] = true, + }, + [73] = { + [ts_external_token__r_sqt_str_ctn] = true, + [ts_external_token__br_sqt_str_ctn] = true, + [ts_external_token__r_sqt_esc_sqt] = true, + [ts_external_token__br_sqt_esc_sqt] = true, + [ts_external_token__r_sqt_str_end] = true, + [ts_external_token__br_sqt_str_end] = true, + [ts_external_token_comment] = true, + }, + [74] = { + [ts_external_token__r_flw_map_end] = true, + [ts_external_token__br_flw_map_end] = true, + [ts_external_token__b_flw_map_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__br_flw_sep_bgn] = true, + [ts_external_token__r_flw_jsv_bgn] = true, + [ts_external_token__br_flw_jsv_bgn] = true, + [ts_external_token_comment] = true, + }, + [75] = { + [ts_external_token__r_flw_seq_end] = true, + [ts_external_token__br_flw_seq_end] = true, + [ts_external_token__b_flw_seq_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__br_flw_sep_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token_comment] = true, + }, + [76] = { + [ts_external_token__br_dqt_str_ctn] = true, + [ts_external_token__br_dqt_esc_nwl] = true, + [ts_external_token__br_dqt_esc_seq] = true, + [ts_external_token__r_dqt_str_end] = true, + [ts_external_token__br_dqt_str_end] = true, + [ts_external_token_comment] = true, + }, + [77] = { + [ts_external_token__r_flw_seq_end] = true, + [ts_external_token__br_flw_seq_end] = true, + [ts_external_token__b_flw_seq_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__br_flw_sep_bgn] = true, + [ts_external_token_comment] = true, + }, + [78] = { + [ts_external_token__r_flw_seq_end] = true, + [ts_external_token__br_flw_seq_end] = true, + [ts_external_token__b_flw_seq_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__br_flw_sep_bgn] = true, + [ts_external_token__r_flw_jsv_bgn] = true, + [ts_external_token_comment] = true, + }, + [79] = { + [ts_external_token__r_flw_map_end] = true, + [ts_external_token__br_flw_map_end] = true, + [ts_external_token__b_flw_map_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__br_flw_sep_bgn] = true, + [ts_external_token_comment] = true, + }, + [80] = { + [ts_external_token__br_sqt_str_ctn] = true, + [ts_external_token__br_sqt_esc_sqt] = true, + [ts_external_token__r_sqt_str_end] = true, + [ts_external_token__br_sqt_str_end] = true, + [ts_external_token_comment] = true, + }, + [81] = { + [ts_external_token__s_dir_yml_bgn] = true, + [ts_external_token__s_dir_tag_bgn] = true, + [ts_external_token__s_dir_rsv_bgn] = true, + [ts_external_token__r_dir_rsv_prm] = true, + [ts_external_token__s_drs_end] = true, + [ts_external_token_comment] = true, + }, + [82] = { + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token__br_flw_njv_bgn] = true, + [ts_external_token_comment] = true, + }, + [83] = { + [ts_external_token__eof] = true, + [ts_external_token__s_drs_end] = true, + [ts_external_token__s_doc_end] = true, + [ts_external_token__r_blk_imp_bgn] = true, + [ts_external_token_comment] = true, + }, + [84] = { + [ts_external_token__r_flw_seq_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token_comment] = true, + }, + [85] = { + [ts_external_token__r_flw_map_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token_comment] = true, + }, + [86] = { + [ts_external_token__b_blk_seq_bgn] = true, + [ts_external_token__bl] = true, + [ts_external_token_comment] = true, + }, + [87] = { + [ts_external_token__b_blk_seq_bgn] = true, + [ts_external_token__r_blk_imp_bgn] = true, + [ts_external_token__bl] = true, + [ts_external_token_comment] = true, + }, + [88] = { + [ts_external_token__r_dqt_str_ctn] = true, + [ts_external_token__r_dqt_esc_seq] = true, + [ts_external_token__r_dqt_str_end] = true, + [ts_external_token_comment] = true, + }, + [89] = { + [ts_external_token__r_sqt_str_ctn] = true, + [ts_external_token__r_sqt_esc_sqt] = true, + [ts_external_token__r_sqt_str_end] = true, + [ts_external_token_comment] = true, + }, + [90] = { + [ts_external_token__r_flw_seq_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token_comment] = true, + }, + [91] = { + [ts_external_token__r_flw_jsv_bgn] = true, + [ts_external_token__br_flw_jsv_bgn] = true, + [ts_external_token_comment] = true, + }, + [92] = { + [ts_external_token__r_flw_seq_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__r_flw_jsv_bgn] = true, + [ts_external_token_comment] = true, + }, + [93] = { + [ts_external_token__r_flw_map_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token_comment] = true, + }, + [94] = { + [ts_external_token__r_flw_map_end] = true, + [ts_external_token__r_flw_sep_bgn] = true, + [ts_external_token__r_flw_jsv_bgn] = true, + [ts_external_token_comment] = true, + }, + [95] = { + [ts_external_token__br_blk_str_ctn] = true, + [ts_external_token__bl] = true, + [ts_external_token_comment] = true, + }, + [96] = { + [ts_external_token__r_flw_seq_end] = true, + [ts_external_token__br_flw_seq_end] = true, + [ts_external_token__b_flw_seq_end] = true, + [ts_external_token_comment] = true, + }, + [97] = { + [ts_external_token__r_flw_map_end] = true, + [ts_external_token__br_flw_map_end] = true, + [ts_external_token__b_flw_map_end] = true, + [ts_external_token_comment] = true, + }, + [98] = { + [ts_external_token__r_blk_imp_bgn] = true, + [ts_external_token_comment] = true, + }, + [99] = { + [ts_external_token__r_flw_njv_bgn] = true, + [ts_external_token_comment] = true, + }, + [100] = { + [ts_external_token__r_flw_jsv_bgn] = true, + [ts_external_token_comment] = true, + }, + [101] = { + [ts_external_token__r_acr_ctn] = true, + [ts_external_token_comment] = true, + }, + [102] = { + [ts_external_token_comment] = true, + }, + [103] = { + [ts_external_token__r_dir_yml_ver] = true, + [ts_external_token_comment] = true, + }, + [104] = { + [ts_external_token__eof] = true, + [ts_external_token_comment] = true, + }, + [105] = { + [ts_external_token__r_als_ctn] = true, + [ts_external_token_comment] = true, + }, + [106] = { + [ts_external_token__r_flw_seq_end] = true, + [ts_external_token_comment] = true, + }, + [107] = { + [ts_external_token__r_flw_map_end] = true, + [ts_external_token_comment] = true, + }, + [108] = { + [ts_external_token__r_dir_tag_pfx] = true, + [ts_external_token_comment] = true, + }, + [109] = { + [ts_external_token__r_dir_tag_hdl] = true, + [ts_external_token_comment] = true, + }, +}; + +#ifdef __cplusplus +extern "C" { +#endif +void *tree_sitter_yaml_external_scanner_create(void); +void tree_sitter_yaml_external_scanner_destroy(void *); +bool tree_sitter_yaml_external_scanner_scan(void *, TSLexer *, const bool *); +unsigned tree_sitter_yaml_external_scanner_serialize(void *, char *); +void tree_sitter_yaml_external_scanner_deserialize(void *, const char *, unsigned); + +#ifdef TREE_SITTER_HIDE_SYMBOLS +#define TS_PUBLIC +#elif defined(_WIN32) +#define TS_PUBLIC __declspec(dllexport) +#else +#define TS_PUBLIC __attribute__((visibility("default"))) +#endif + +TS_PUBLIC const TSLanguage *tree_sitter_yaml(void) { + static const TSLanguage language = { + .abi_version = LANGUAGE_VERSION, + .symbol_count = SYMBOL_COUNT, + .alias_count = ALIAS_COUNT, + .token_count = TOKEN_COUNT, + .external_token_count = EXTERNAL_TOKEN_COUNT, + .state_count = STATE_COUNT, + .large_state_count = LARGE_STATE_COUNT, + .production_id_count = PRODUCTION_ID_COUNT, + .field_count = FIELD_COUNT, + .max_alias_sequence_length = MAX_ALIAS_SEQUENCE_LENGTH, + .parse_table = &ts_parse_table[0][0], + .small_parse_table = ts_small_parse_table, + .small_parse_table_map = ts_small_parse_table_map, + .parse_actions = ts_parse_actions, + .symbol_names = ts_symbol_names, + .field_names = ts_field_names, + .field_map_slices = ts_field_map_slices, + .field_map_entries = ts_field_map_entries, + .symbol_metadata = ts_symbol_metadata, + .public_symbol_map = ts_symbol_map, + .alias_map = ts_non_terminal_alias_map, + .alias_sequences = &ts_alias_sequences[0][0], + .lex_modes = (const void*)ts_lex_modes, + .lex_fn = ts_lex, + .external_scanner = { + &ts_external_scanner_states[0][0], + ts_external_scanner_symbol_map, + tree_sitter_yaml_external_scanner_create, + tree_sitter_yaml_external_scanner_destroy, + tree_sitter_yaml_external_scanner_scan, + tree_sitter_yaml_external_scanner_serialize, + tree_sitter_yaml_external_scanner_deserialize, + }, + .primary_state_ids = ts_primary_state_ids, + }; + return &language; +} +#ifdef __cplusplus +} +#endif diff --git a/Sources/TreeSitterYAML/provenance.json b/Sources/TreeSitterYAML/provenance.json new file mode 100644 index 0000000..18a53e8 --- /dev/null +++ b/Sources/TreeSitterYAML/provenance.json @@ -0,0 +1,38 @@ +{ + "upstream": "https://github.com/tree-sitter-grammars/tree-sitter-yaml", + "revision": "7708026449bed86239b1cd5bce6e3c34dbca6415", + "files": { + "parser.c": { + "source": "src/parser.c", + "sha256": "8a3baaab33fb63cf9a89f97ec61dbb3ab0d4ef69be9f0f229092c79d129617c9" + }, + "scanner.c": { + "source": "src/scanner.c", + "sha256": "9cd962f7c7541247cfc7ebf661abaa5d9b642d27de16575c87093496557aae59" + }, + "schema.core.c": { + "source": "src/schema.core.c", + "sha256": "91e56c3f3ae6fad1803b739ce4eb4568a782a9aec710f733db2f3e38d407a4d5" + }, + "tree_sitter/alloc.h": { + "source": "src/tree_sitter/alloc.h", + "sha256": "b29c1c9fb7cc82f58c84b376df1297d6e2737a1d655fd356db0859e3c29c2fea" + }, + "tree_sitter/array.h": { + "source": "src/tree_sitter/array.h", + "sha256": "5bdf6ed1a78e3409fd443e085ca967a64c188a5d082aaf7f819bccd53a471c94" + }, + "tree_sitter/parser.h": { + "source": "src/tree_sitter/parser.h", + "sha256": "180b893c8734778fd32f372dfbc27bd6ad1cd2221f26150b31256ff6716320d2" + }, + "include/yaml.h": { + "source": "bindings/swift/TreeSitterYAML/yaml.h", + "sha256": "b03b74d6fca5ff3e9339610153ea1772e9f2e1d6189acb918a249de0a3fb6107" + }, + "LICENSE": { + "source": "LICENSE", + "sha256": "2d181298822a124f6d106118dcc69c8d4d26ac668559be29682c452e712b0947" + } + } +} diff --git a/Sources/TreeSitterYAML/scanner.c b/Sources/TreeSitterYAML/scanner.c new file mode 100644 index 0000000..7168d53 --- /dev/null +++ b/Sources/TreeSitterYAML/scanner.c @@ -0,0 +1,1415 @@ +#include "tree_sitter/array.h" +#include "tree_sitter/parser.h" + +#define _str(x) #x +#define _file(x) _str(schema.x.c) + +#ifndef YAML_SCHEMA +#define YAML_SCHEMA core +#endif + +#include _file(YAML_SCHEMA) + +// clang-format off + +typedef enum { + END_OF_FILE, + + S_DIR_YML_BGN, R_DIR_YML_VER, + S_DIR_TAG_BGN, R_DIR_TAG_HDL, R_DIR_TAG_PFX, + S_DIR_RSV_BGN, R_DIR_RSV_PRM, + S_DRS_END, + S_DOC_END, + R_BLK_SEQ_BGN, BR_BLK_SEQ_BGN, B_BLK_SEQ_BGN, + R_BLK_KEY_BGN, BR_BLK_KEY_BGN, B_BLK_KEY_BGN, + R_BLK_VAL_BGN, BR_BLK_VAL_BGN, B_BLK_VAL_BGN, + R_BLK_IMP_BGN, + R_BLK_LIT_BGN, BR_BLK_LIT_BGN, + R_BLK_FLD_BGN, BR_BLK_FLD_BGN, + BR_BLK_STR_CTN, + R_FLW_SEQ_BGN, BR_FLW_SEQ_BGN, B_FLW_SEQ_BGN, + R_FLW_SEQ_END, BR_FLW_SEQ_END, B_FLW_SEQ_END, + R_FLW_MAP_BGN, BR_FLW_MAP_BGN, B_FLW_MAP_BGN, + R_FLW_MAP_END, BR_FLW_MAP_END, B_FLW_MAP_END, + R_FLW_SEP_BGN, BR_FLW_SEP_BGN, + R_FLW_KEY_BGN, BR_FLW_KEY_BGN, + R_FLW_JSV_BGN, BR_FLW_JSV_BGN, + R_FLW_NJV_BGN, BR_FLW_NJV_BGN, + R_DQT_STR_BGN, BR_DQT_STR_BGN, B_DQT_STR_BGN, + R_DQT_STR_CTN, BR_DQT_STR_CTN, + R_DQT_ESC_NWL, BR_DQT_ESC_NWL, + R_DQT_ESC_SEQ, BR_DQT_ESC_SEQ, + R_DQT_STR_END, BR_DQT_STR_END, + R_SQT_STR_BGN, BR_SQT_STR_BGN, B_SQT_STR_BGN, + R_SQT_STR_CTN, BR_SQT_STR_CTN, + R_SQT_ESC_SQT, BR_SQT_ESC_SQT, + R_SQT_STR_END, BR_SQT_STR_END, + + R_SGL_PLN_NUL_BLK, BR_SGL_PLN_NUL_BLK, B_SGL_PLN_NUL_BLK, R_SGL_PLN_NUL_FLW, BR_SGL_PLN_NUL_FLW, + R_SGL_PLN_BOL_BLK, BR_SGL_PLN_BOL_BLK, B_SGL_PLN_BOL_BLK, R_SGL_PLN_BOL_FLW, BR_SGL_PLN_BOL_FLW, + R_SGL_PLN_INT_BLK, BR_SGL_PLN_INT_BLK, B_SGL_PLN_INT_BLK, R_SGL_PLN_INT_FLW, BR_SGL_PLN_INT_FLW, + R_SGL_PLN_FLT_BLK, BR_SGL_PLN_FLT_BLK, B_SGL_PLN_FLT_BLK, R_SGL_PLN_FLT_FLW, BR_SGL_PLN_FLT_FLW, + R_SGL_PLN_TMS_BLK, BR_SGL_PLN_TMS_BLK, B_SGL_PLN_TMS_BLK, R_SGL_PLN_TMS_FLW, BR_SGL_PLN_TMS_FLW, + R_SGL_PLN_STR_BLK, BR_SGL_PLN_STR_BLK, B_SGL_PLN_STR_BLK, R_SGL_PLN_STR_FLW, BR_SGL_PLN_STR_FLW, + + R_MTL_PLN_STR_BLK, BR_MTL_PLN_STR_BLK, + R_MTL_PLN_STR_FLW, BR_MTL_PLN_STR_FLW, + + R_TAG, BR_TAG, B_TAG, + R_ACR_BGN, BR_ACR_BGN, B_ACR_BGN, R_ACR_CTN, + R_ALS_BGN, BR_ALS_BGN, B_ALS_BGN, R_ALS_CTN, + + BL, + COMMENT, + + ERR_REC, +} TokenType; + +// clang-format on + +#define SCN_SUCC 1 +#define SCN_STOP 0 +#define SCN_FAIL (-1) + +#define IND_ROT 'r' +#define IND_MAP 'm' +#define IND_SEQ 'q' +#define IND_STR 's' + +#define RET_SYM(RESULT_SYMBOL) \ + { \ + flush(scanner); \ + lexer->result_symbol = RESULT_SYMBOL; \ + return true; \ + } + +#define POP_IND() \ + { \ + /* incorrect status caused by error recovering */ \ + if (scanner->ind_typ_stk.size == 1) { \ + return false; \ + } \ + pop_ind(scanner); \ + } + +#define PUSH_IND(TYP, LEN) push_ind(scanner, TYP, LEN) + +#define PUSH_BGN_IND(TYP) \ + { \ + if (has_tab_ind) \ + return false; \ + push_ind(scanner, TYP, bgn_col); \ + } + +#define MAY_PUSH_IMP_IND(TYP) \ + { \ + if (cur_ind != scanner->blk_imp_col) { \ + if (scanner->blk_imp_tab) \ + return false; \ + push_ind(scanner, IND_MAP, scanner->blk_imp_col); \ + } \ + } + +#define MAY_PUSH_SPC_SEQ_IND() \ + { \ + if (cur_ind_typ == IND_MAP) { \ + push_ind(scanner, IND_SEQ, bgn_col); \ + } \ + } + +#define MAY_UPD_IMP_COL() \ + { \ + if (scanner->blk_imp_row != bgn_row) { \ + scanner->blk_imp_row = bgn_row; \ + scanner->blk_imp_col = bgn_col; \ + scanner->blk_imp_tab = has_tab_ind; \ + } \ + } + +#if HAS_TIMESTAMP +#define SGL_PLN_SYM(POS, CTX) \ + (scanner->rlt_sch == RS_NULL ? POS##_SGL_PLN_NUL_##CTX \ + : scanner->rlt_sch == RS_BOOL ? POS##_SGL_PLN_BOL_##CTX \ + : scanner->rlt_sch == RS_INT ? POS##_SGL_PLN_INT_##CTX \ + : scanner->rlt_sch == RS_FLOAT ? POS##_SGL_PLN_FLT_##CTX \ + : scanner->rlt_sch == RS_TIMESTAMP ? POS##_SGL_PLN_TMS_##CTX \ + : POS##_SGL_PLN_STR_##CTX) +#else +#define SGL_PLN_SYM(POS, CTX) \ + (scanner->rlt_sch == RS_NULL ? POS##_SGL_PLN_NUL_##CTX \ + : scanner->rlt_sch == RS_BOOL ? POS##_SGL_PLN_BOL_##CTX \ + : scanner->rlt_sch == RS_INT ? POS##_SGL_PLN_INT_##CTX \ + : scanner->rlt_sch == RS_FLOAT ? POS##_SGL_PLN_FLT_##CTX \ + : POS##_SGL_PLN_STR_##CTX) +#endif + +typedef struct { + int16_t row; + int16_t col; + int16_t blk_imp_row; + int16_t blk_imp_col; + int16_t blk_imp_tab; + Array(int16_t) ind_typ_stk; + Array(int16_t) ind_len_stk; + + // temp + int16_t end_row; + int16_t end_col; + int16_t cur_row; + int16_t cur_col; + int32_t cur_chr; + int8_t sch_stt; + ResultSchema rlt_sch; +} Scanner; + +static unsigned serialize(Scanner *scanner, char *buffer) { + size_t size = 0; + *(int16_t *)&buffer[size] = scanner->row; + size += sizeof(int16_t); + *(int16_t *)&buffer[size] = scanner->col; + size += sizeof(int16_t); + *(int16_t *)&buffer[size] = scanner->blk_imp_row; + size += sizeof(int16_t); + *(int16_t *)&buffer[size] = scanner->blk_imp_col; + size += sizeof(int16_t); + *(int16_t *)&buffer[size] = scanner->blk_imp_tab; + size += sizeof(int16_t); + int16_t *typ_itr = scanner->ind_typ_stk.contents + 1; + int16_t *typ_end = scanner->ind_typ_stk.contents + scanner->ind_typ_stk.size; + int16_t *len_itr = scanner->ind_len_stk.contents + 1; + for (; typ_itr != typ_end && size < TREE_SITTER_SERIALIZATION_BUFFER_SIZE; ++typ_itr, ++len_itr) { + *(int16_t *)&buffer[size] = *typ_itr; + size += sizeof(int16_t); + *(int16_t *)&buffer[size] = *len_itr; + size += sizeof(int16_t); + } + return size; +} + +static void deserialize(Scanner *scanner, const char *buffer, unsigned length) { + scanner->row = 0; + scanner->col = 0; + scanner->blk_imp_row = -1; + scanner->blk_imp_col = -1; + scanner->blk_imp_tab = 0; + array_delete(&scanner->ind_typ_stk); + array_push(&scanner->ind_typ_stk, IND_ROT); + array_delete(&scanner->ind_len_stk); + array_push(&scanner->ind_len_stk, -1); + if (length > 0) { + size_t size = 0; + scanner->row = *(int16_t *)&buffer[size]; + size += sizeof(int16_t); + scanner->col = *(int16_t *)&buffer[size]; + size += sizeof(int16_t); + scanner->blk_imp_row = *(int16_t *)&buffer[size]; + size += sizeof(int16_t); + scanner->blk_imp_col = *(int16_t *)&buffer[size]; + size += sizeof(int16_t); + scanner->blk_imp_tab = *(int16_t *)&buffer[size]; + size += sizeof(int16_t); + while (size < length) { + array_push(&scanner->ind_typ_stk, *(int16_t *)&buffer[size]); + size += sizeof(int16_t); + array_push(&scanner->ind_len_stk, *(int16_t *)&buffer[size]); + size += sizeof(int16_t); + } + assert(size == length); + } +} + +static inline void adv(Scanner *scanner, TSLexer *lexer) { + scanner->cur_col++; + scanner->cur_chr = lexer->lookahead; + lexer->advance(lexer, false); +} + +static inline void adv_nwl(Scanner *scanner, TSLexer *lexer) { + scanner->cur_row++; + scanner->cur_col = 0; + scanner->cur_chr = lexer->lookahead; + lexer->advance(lexer, false); +} + +static inline void skp(Scanner *scanner, TSLexer *lexer) { + scanner->cur_col++; + scanner->cur_chr = lexer->lookahead; + lexer->advance(lexer, true); +} + +static inline void skp_nwl(Scanner *scanner, TSLexer *lexer) { + scanner->cur_row++; + scanner->cur_col = 0; + scanner->cur_chr = lexer->lookahead; + lexer->advance(lexer, true); +} + +static inline void mrk_end(Scanner *scanner, TSLexer *lexer) { + scanner->end_row = scanner->cur_row; + scanner->end_col = scanner->cur_col; + lexer->mark_end(lexer); +} + +static inline void init(Scanner *scanner) { + scanner->cur_row = scanner->row; + scanner->cur_col = scanner->col; + scanner->cur_chr = 0; + scanner->sch_stt = 0; + scanner->rlt_sch = RS_STR; +} + +static inline void flush(Scanner *scanner) { + scanner->row = scanner->end_row; + scanner->col = scanner->end_col; +} + +static inline void pop_ind(Scanner *scanner) { + array_pop(&scanner->ind_len_stk); + array_pop(&scanner->ind_typ_stk); +} + +static inline void push_ind(Scanner *scanner, int16_t typ, int16_t len) { + array_push(&scanner->ind_len_stk, len); + array_push(&scanner->ind_typ_stk, typ); +} + +static inline bool is_wsp(int32_t c) { return c == ' ' || c == '\t'; } + +static inline bool is_nwl(int32_t c) { return c == '\r' || c == '\n'; } + +static inline bool is_wht(int32_t c) { return is_wsp(c) || is_nwl(c) || c == 0; } + +static inline bool is_ns_dec_digit(int32_t c) { return c >= '0' && c <= '9'; } + +static inline bool is_ns_hex_digit(int32_t c) { + return is_ns_dec_digit(c) || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); +} + +static inline bool is_ns_word_char(int32_t c) { + return c == '-' || (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); +} + +static inline bool is_nb_json(int32_t c) { return c == 0x09 || (c >= 0x20 && c <= 0x10ffff); } + +static inline bool is_nb_double_char(int32_t c) { return is_nb_json(c) && c != '\\' && c != '"'; } + +static inline bool is_nb_single_char(int32_t c) { return is_nb_json(c) && c != '\''; } + +static inline bool is_ns_char(int32_t c) { + return (c >= 0x21 && c <= 0x7e) || c == 0x85 || (c >= 0xa0 && c <= 0xd7ff) || (c >= 0xe000 && c <= 0xfefe) || + (c >= 0xff00 && c <= 0xfffd) || (c >= 0x10000 && c <= 0x10ffff); +} + +static inline bool is_c_indicator(int32_t c) { + return c == '-' || c == '?' || c == ':' || c == ',' || c == '[' || c == ']' || c == '{' || c == '}' || c == '#' || + c == '&' || c == '*' || c == '!' || c == '|' || c == '>' || c == '\'' || c == '"' || c == '%' || c == '@' || + c == '`'; +} + +static inline bool is_c_flow_indicator(int32_t c) { return c == ',' || c == '[' || c == ']' || c == '{' || c == '}'; } + +static inline bool is_plain_safe_in_block(int32_t c) { return is_ns_char(c); } + +static inline bool is_plain_safe_in_flow(int32_t c) { return is_ns_char(c) && !is_c_flow_indicator(c); } + +static inline bool is_ns_uri_char(int32_t c) { + return is_ns_word_char(c) || c == '#' || c == ';' || c == '/' || c == '?' || c == ':' || c == '@' || c == '&' || + c == '=' || c == '+' || c == '$' || c == ',' || c == '_' || c == '.' || c == '!' || c == '~' || c == '*' || + c == '\'' || c == '(' || c == ')' || c == '[' || c == ']'; +} + +static inline bool is_ns_tag_char(int32_t c) { + return is_ns_word_char(c) || c == '#' || c == ';' || c == '/' || c == '?' || c == ':' || c == '@' || c == '&' || + c == '=' || c == '+' || c == '$' || c == '_' || c == '.' || c == '~' || c == '*' || c == '\'' || c == '(' || + c == ')'; +} + +static inline bool is_ns_anchor_char(int32_t c) { return is_ns_char(c) && !is_c_flow_indicator(c); } + +static char scn_uri_esc(Scanner *scanner, TSLexer *lexer) { + if (lexer->lookahead != '%') { + return SCN_STOP; + } + mrk_end(scanner, lexer); + adv(scanner, lexer); + if (!is_ns_hex_digit(lexer->lookahead)) { + return SCN_FAIL; + } + adv(scanner, lexer); + if (!is_ns_hex_digit(lexer->lookahead)) { + return SCN_FAIL; + } + adv(scanner, lexer); + return SCN_SUCC; +} + +static char scn_ns_uri_char(Scanner *scanner, TSLexer *lexer) { + if (is_ns_uri_char(lexer->lookahead)) { + adv(scanner, lexer); + return SCN_SUCC; + } + return scn_uri_esc(scanner, lexer); +} + +static char scn_ns_tag_char(Scanner *scanner, TSLexer *lexer) { + if (is_ns_tag_char(lexer->lookahead)) { + adv(scanner, lexer); + return SCN_SUCC; + } + return scn_uri_esc(scanner, lexer); +} + +static bool scn_dir_bgn(Scanner *scanner, TSLexer *lexer) { + adv(scanner, lexer); + if (lexer->lookahead == 'Y') { + adv(scanner, lexer); + if (lexer->lookahead == 'A') { + adv(scanner, lexer); + if (lexer->lookahead == 'M') { + adv(scanner, lexer); + if (lexer->lookahead == 'L') { + adv(scanner, lexer); + if (is_wht(lexer->lookahead)) { + mrk_end(scanner, lexer); + RET_SYM(S_DIR_YML_BGN); + } + } + } + } + } else if (lexer->lookahead == 'T') { + adv(scanner, lexer); + if (lexer->lookahead == 'A') { + adv(scanner, lexer); + if (lexer->lookahead == 'G') { + adv(scanner, lexer); + if (is_wht(lexer->lookahead)) { + mrk_end(scanner, lexer); + RET_SYM(S_DIR_TAG_BGN); + } + } + } + } + for (;;) { + if (!is_ns_char(lexer->lookahead)) { + break; + } + adv(scanner, lexer); + } + if (scanner->cur_col > 1 && is_wht(lexer->lookahead)) { + mrk_end(scanner, lexer); + RET_SYM(S_DIR_RSV_BGN); + } + return false; +} + +static bool scn_dir_yml_ver(Scanner *scanner, TSLexer *lexer, TSSymbol result_symbol) { + uint16_t n1 = 0; + uint16_t n2 = 0; + while (is_ns_dec_digit(lexer->lookahead)) { + adv(scanner, lexer); + n1++; + } + if (lexer->lookahead != '.') { + return false; + } + adv(scanner, lexer); + while (is_ns_dec_digit(lexer->lookahead)) { + adv(scanner, lexer); + n2++; + } + if (n1 == 0 || n2 == 0) { + return false; + } + mrk_end(scanner, lexer); + RET_SYM(result_symbol); +} + +static bool scn_tag_hdl_tal(Scanner *scanner, TSLexer *lexer) { + if (lexer->lookahead == '!') { + adv(scanner, lexer); + return true; + } + uint16_t n = 0; + while (is_ns_word_char(lexer->lookahead)) { + adv(scanner, lexer); + n++; + } + if (n == 0) { + return true; + } + if (lexer->lookahead == '!') { + adv(scanner, lexer); + return true; + } + return false; +} + +static bool scn_dir_tag_hdl(Scanner *scanner, TSLexer *lexer, TSSymbol result_symbol) { + if (lexer->lookahead == '!') { + adv(scanner, lexer); + if (scn_tag_hdl_tal(scanner, lexer)) { + mrk_end(scanner, lexer); + RET_SYM(result_symbol); + } + } + return false; +} + +static bool scn_dir_tag_pfx(Scanner *scanner, TSLexer *lexer, TSSymbol result_symbol) { + if (lexer->lookahead == '!') { + adv(scanner, lexer); + } else if (scn_ns_tag_char(scanner, lexer) == SCN_SUCC) { + ; + } else { + return false; + } + for (;;) { + switch (scn_ns_uri_char(scanner, lexer)) { + case SCN_STOP: + mrk_end(scanner, lexer); + case SCN_FAIL: + RET_SYM(result_symbol); + default: + break; + } + } +} + +static bool scn_dir_rsv_prm(Scanner *scanner, TSLexer *lexer, TSSymbol result_symbol) { + if (!is_ns_char(lexer->lookahead)) { + return false; + } + adv(scanner, lexer); + while (is_ns_char(lexer->lookahead)) { + adv(scanner, lexer); + } + mrk_end(scanner, lexer); + RET_SYM(result_symbol); +} + +static bool scn_tag(Scanner *scanner, TSLexer *lexer, TSSymbol result_symbol) { + if (lexer->lookahead != '!') { + return false; + } + adv(scanner, lexer); + if (is_wht(lexer->lookahead)) { + mrk_end(scanner, lexer); + RET_SYM(result_symbol); + } + if (lexer->lookahead == '<') { + adv(scanner, lexer); + if (scn_ns_uri_char(scanner, lexer) != SCN_SUCC) { + return false; + } + for (;;) { + switch (scn_ns_uri_char(scanner, lexer)) { + case SCN_STOP: + if (lexer->lookahead == '>') { + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(result_symbol); + } + case SCN_FAIL: + return false; + default: + break; + } + } + } else { + if (scn_tag_hdl_tal(scanner, lexer) && scn_ns_tag_char(scanner, lexer) != SCN_SUCC) { + return false; + } + for (;;) { + switch (scn_ns_tag_char(scanner, lexer)) { + case SCN_STOP: + mrk_end(scanner, lexer); + case SCN_FAIL: + RET_SYM(result_symbol); + default: + break; + } + } + } + return false; +} + +static bool scn_acr_bgn(Scanner *scanner, TSLexer *lexer, TSSymbol result_symbol) { + if (lexer->lookahead != '&') { + return false; + } + adv(scanner, lexer); + if (!is_ns_anchor_char(lexer->lookahead)) { + return false; + } + mrk_end(scanner, lexer); + RET_SYM(result_symbol); +} + +static bool scn_acr_ctn(Scanner *scanner, TSLexer *lexer, TSSymbol result_symbol) { + while (is_ns_anchor_char(lexer->lookahead)) { + adv(scanner, lexer); + } + mrk_end(scanner, lexer); + RET_SYM(result_symbol); +} + +static bool scn_als_bgn(Scanner *scanner, TSLexer *lexer, TSSymbol result_symbol) { + if (lexer->lookahead != '*') { + return false; + } + adv(scanner, lexer); + if (!is_ns_anchor_char(lexer->lookahead)) { + return false; + } + mrk_end(scanner, lexer); + RET_SYM(result_symbol); +} + +static bool scn_als_ctn(Scanner *scanner, TSLexer *lexer, TSSymbol result_symbol) { + while (is_ns_anchor_char(lexer->lookahead)) { + adv(scanner, lexer); + } + mrk_end(scanner, lexer); + RET_SYM(result_symbol); +} + +static bool scn_dqt_esc_seq(Scanner *scanner, TSLexer *lexer, TSSymbol result_symbol) { + uint16_t i; + switch (lexer->lookahead) { + case '0': + case 'a': + case 'b': + case 't': + case '\t': + case 'n': + case 'v': + case 'r': + case 'e': + case 'f': + case ' ': + case '"': + case '/': + case '\\': + case 'N': + case '_': + case 'L': + case 'P': + adv(scanner, lexer); + break; + case 'U': + adv(scanner, lexer); + for (i = 0; i < 8; i++) { + if (is_ns_hex_digit(lexer->lookahead)) { + adv(scanner, lexer); + } else { + return false; + } + } + break; + case 'u': + adv(scanner, lexer); + for (i = 0; i < 4; i++) { + if (is_ns_hex_digit(lexer->lookahead)) { + adv(scanner, lexer); + } else { + return false; + } + } + break; + case 'x': + adv(scanner, lexer); + for (i = 0; i < 2; i++) { + if (is_ns_hex_digit(lexer->lookahead)) { + adv(scanner, lexer); + } else { + return false; + } + } + break; + default: + return false; + } + mrk_end(scanner, lexer); + RET_SYM(result_symbol); +} + +static bool scn_drs_doc_end(Scanner *scanner, TSLexer *lexer) { + if (lexer->lookahead != '-' && lexer->lookahead != '.') { + return false; + } + int32_t delimeter = lexer->lookahead; + adv(scanner, lexer); + if (lexer->lookahead == delimeter) { + adv(scanner, lexer); + if (lexer->lookahead == delimeter) { + adv(scanner, lexer); + if (is_wht(lexer->lookahead)) { + return true; + } + } + } + mrk_end(scanner, lexer); + return false; +} + +static bool scn_dqt_str_cnt(Scanner *scanner, TSLexer *lexer, TSSymbol result_symbol) { + if (!is_nb_double_char(lexer->lookahead)) { + return false; + } + if (scanner->cur_col == 0 && scn_drs_doc_end(scanner, lexer)) { + mrk_end(scanner, lexer); + RET_SYM(scanner->cur_chr == '-' ? S_DRS_END : S_DOC_END); + } else { + adv(scanner, lexer); + } + while (is_nb_double_char(lexer->lookahead)) { + adv(scanner, lexer); + } + mrk_end(scanner, lexer); + RET_SYM(result_symbol); +} + +static bool scn_sqt_str_cnt(Scanner *scanner, TSLexer *lexer, TSSymbol result_symbol) { + if (!is_nb_single_char(lexer->lookahead)) { + return false; + } + if (scanner->cur_col == 0 && scn_drs_doc_end(scanner, lexer)) { + mrk_end(scanner, lexer); + RET_SYM(scanner->cur_chr == '-' ? S_DRS_END : S_DOC_END); + } else { + adv(scanner, lexer); + } + while (is_nb_single_char(lexer->lookahead)) { + adv(scanner, lexer); + } + mrk_end(scanner, lexer); + RET_SYM(result_symbol); +} + +static bool scn_blk_str_bgn(Scanner *scanner, TSLexer *lexer, TSSymbol result_symbol) { + if (lexer->lookahead != '|' && lexer->lookahead != '>') { + return false; + } + adv(scanner, lexer); + int16_t cur_ind = *array_back(&scanner->ind_len_stk); + int16_t ind = -1; + if (lexer->lookahead >= '1' && lexer->lookahead <= '9') { + ind = lexer->lookahead - '1'; + adv(scanner, lexer); + if (lexer->lookahead == '+' || lexer->lookahead == '-') { + adv(scanner, lexer); + } + } else if (lexer->lookahead == '+' || lexer->lookahead == '-') { + adv(scanner, lexer); + if (lexer->lookahead >= '1' && lexer->lookahead <= '9') { + ind = lexer->lookahead - '1'; + adv(scanner, lexer); + } + } + if (!is_wht(lexer->lookahead)) { + return false; + } + mrk_end(scanner, lexer); + if (ind != -1) { + ind += cur_ind; + } else { + ind = cur_ind; + while (is_wsp(lexer->lookahead)) { + adv(scanner, lexer); + } + if (lexer->lookahead == '#') { + adv(scanner, lexer); + while (!is_nwl(lexer->lookahead) && lexer->lookahead != 0) { + adv(scanner, lexer); + } + } + if (is_nwl(lexer->lookahead)) { + adv_nwl(scanner, lexer); + } + while (lexer->lookahead != 0) { + if (lexer->lookahead == ' ') { + adv(scanner, lexer); + } else if (is_nwl(lexer->lookahead)) { + if (scanner->cur_col - 1 < ind) { + break; + } + ind = scanner->cur_col - 1; + adv_nwl(scanner, lexer); + } else { + if (scanner->cur_col - 1 > ind) { + ind = scanner->cur_col - 1; + } + break; + } + } + } + PUSH_IND(IND_STR, ind); + RET_SYM(result_symbol); +} + +static bool scn_blk_str_cnt(Scanner *scanner, TSLexer *lexer, TSSymbol result_symbol) { + if (!is_ns_char(lexer->lookahead)) { + return false; + } + if (scanner->cur_col == 0 && scn_drs_doc_end(scanner, lexer)) { + POP_IND(); + RET_SYM(BL); + } else { + adv(scanner, lexer); + } + mrk_end(scanner, lexer); + for (;;) { + if (is_ns_char(lexer->lookahead)) { + adv(scanner, lexer); + while (is_ns_char(lexer->lookahead)) { + adv(scanner, lexer); + } + mrk_end(scanner, lexer); + } + if (is_wsp(lexer->lookahead)) { + adv(scanner, lexer); + while (is_wsp(lexer->lookahead)) { + adv(scanner, lexer); + } + } else { + break; + } + } + RET_SYM(result_symbol); +} + +static char scn_pln_cnt(Scanner *scanner, TSLexer *lexer, bool (*is_plain_safe)(int32_t)) { + bool is_cur_wsp = is_wsp(scanner->cur_chr); + bool is_cur_saf = is_plain_safe(scanner->cur_chr); + bool is_lka_wsp = is_wsp(lexer->lookahead); + bool is_lka_saf = is_plain_safe(lexer->lookahead); + if (is_lka_saf || is_lka_wsp) { + for (;;) { + if (is_lka_saf && lexer->lookahead != '#' && lexer->lookahead != ':') { + adv(scanner, lexer); + mrk_end(scanner, lexer); + scanner->sch_stt = adv_sch_stt(scanner->sch_stt, scanner->cur_chr, &scanner->rlt_sch); + } else if (is_cur_saf && lexer->lookahead == '#') { + adv(scanner, lexer); + mrk_end(scanner, lexer); + scanner->sch_stt = adv_sch_stt(scanner->sch_stt, scanner->cur_chr, &scanner->rlt_sch); + } else if (is_lka_wsp) { + adv(scanner, lexer); + scanner->sch_stt = adv_sch_stt(scanner->sch_stt, scanner->cur_chr, &scanner->rlt_sch); + } else if (lexer->lookahead == ':') { + adv(scanner, lexer); // check later + } else { + break; + } + + is_cur_wsp = is_lka_wsp; + is_cur_saf = is_lka_saf; + is_lka_wsp = is_wsp(lexer->lookahead); + is_lka_saf = is_plain_safe(lexer->lookahead); + + if (scanner->cur_chr == ':') { + if (is_lka_saf) { + mrk_end(scanner, lexer); + scanner->sch_stt = adv_sch_stt(scanner->sch_stt, scanner->cur_chr, &scanner->rlt_sch); + } else { + return SCN_FAIL; + } + } + } + } else { + return SCN_STOP; + } + return SCN_SUCC; +} + +static bool scan(Scanner *scanner, TSLexer *lexer, const bool *valid_symbols) { + init(scanner); + mrk_end(scanner, lexer); + + bool allow_comment = !(valid_symbols[R_DQT_STR_CTN] || valid_symbols[BR_DQT_STR_CTN] || + valid_symbols[R_SQT_STR_CTN] || valid_symbols[BR_SQT_STR_CTN]); + int16_t *ind_ptr = scanner->ind_len_stk.contents + scanner->ind_len_stk.size - 1; + int16_t *ind_end = scanner->ind_len_stk.contents - 1; + int16_t cur_ind = *ind_ptr--; + int16_t prt_ind = ind_ptr == ind_end ? -1 : *ind_ptr; + int16_t cur_ind_typ = *array_back(&scanner->ind_typ_stk); + + bool has_tab_ind = false; + int16_t leading_spaces = 0; + + for (;;) { + if (lexer->lookahead == ' ') { + if (!has_tab_ind) { + leading_spaces++; + } + skp(scanner, lexer); + } else if (lexer->lookahead == '\t') { + has_tab_ind = true; + skp(scanner, lexer); + } else if (is_nwl(lexer->lookahead)) { + has_tab_ind = false; + leading_spaces = 0; + skp_nwl(scanner, lexer); + } else if (allow_comment && lexer->lookahead == '#') { + if (valid_symbols[BR_BLK_STR_CTN] && valid_symbols[BL] && scanner->cur_col <= cur_ind) { + POP_IND(); + RET_SYM(BL); + } + if (valid_symbols[BR_BLK_STR_CTN] + ? scanner->cur_row == scanner->row + : scanner->cur_col == 0 || scanner->cur_row != scanner->row || scanner->cur_col > scanner->col) { + adv(scanner, lexer); + while (!is_nwl(lexer->lookahead) && lexer->lookahead != 0) { + adv(scanner, lexer); + } + mrk_end(scanner, lexer); + RET_SYM(COMMENT); + } else { + break; + } + } else { + break; + } + } + + if (lexer->lookahead == 0) { + if (valid_symbols[BL]) { + mrk_end(scanner, lexer); + POP_IND(); + RET_SYM(BL) + } + if (valid_symbols[END_OF_FILE]) { + mrk_end(scanner, lexer); + RET_SYM(END_OF_FILE) + } + return false; + } + + int16_t bgn_row = scanner->cur_row; + int16_t bgn_col = scanner->cur_col; + int32_t bgn_chr = lexer->lookahead; + + if (valid_symbols[BL] && bgn_col <= cur_ind && !has_tab_ind) { + if (cur_ind == prt_ind && cur_ind_typ == IND_SEQ ? bgn_col < cur_ind || lexer->lookahead != '-' + : bgn_col <= prt_ind || cur_ind_typ == IND_STR) { + POP_IND(); + RET_SYM(BL); + } + } + + bool has_nwl = scanner->cur_row > scanner->row; + bool is_r = !has_nwl; + bool is_br = has_nwl && leading_spaces > cur_ind; + bool is_b = has_nwl && leading_spaces == cur_ind && !has_tab_ind; + bool is_s = bgn_col == 0; + + if (valid_symbols[R_DIR_YML_VER] && is_r) { + return scn_dir_yml_ver(scanner, lexer, R_DIR_YML_VER); + } + if (valid_symbols[R_DIR_TAG_HDL] && is_r) { + return scn_dir_tag_hdl(scanner, lexer, R_DIR_TAG_HDL); + } + if (valid_symbols[R_DIR_TAG_PFX] && is_r) { + return scn_dir_tag_pfx(scanner, lexer, R_DIR_TAG_PFX); + } + if (valid_symbols[R_DIR_RSV_PRM] && is_r) { + return scn_dir_rsv_prm(scanner, lexer, R_DIR_RSV_PRM); + } + if (valid_symbols[BR_BLK_STR_CTN] && is_br && scn_blk_str_cnt(scanner, lexer, BR_BLK_STR_CTN)) { + return true; + } + + if ((valid_symbols[R_DQT_STR_CTN] && is_r && scn_dqt_str_cnt(scanner, lexer, R_DQT_STR_CTN)) || + (valid_symbols[BR_DQT_STR_CTN] && is_br && scn_dqt_str_cnt(scanner, lexer, BR_DQT_STR_CTN))) { + return true; + } + + if ((valid_symbols[R_SQT_STR_CTN] && is_r && scn_sqt_str_cnt(scanner, lexer, R_SQT_STR_CTN)) || + (valid_symbols[BR_SQT_STR_CTN] && is_br && scn_sqt_str_cnt(scanner, lexer, BR_SQT_STR_CTN))) { + return true; + } + + if (valid_symbols[R_ACR_CTN] && is_r) { + return scn_acr_ctn(scanner, lexer, R_ACR_CTN); + } + if (valid_symbols[R_ALS_CTN] && is_r) { + return scn_als_ctn(scanner, lexer, R_ALS_CTN); + } + + if (lexer->lookahead == '%') { + if (valid_symbols[S_DIR_YML_BGN] && is_s) { + return scn_dir_bgn(scanner, lexer); + } + } else if (lexer->lookahead == '*') { + if (valid_symbols[R_ALS_BGN] && is_r) { + MAY_UPD_IMP_COL(); + return scn_als_bgn(scanner, lexer, R_ALS_BGN); + } + if (valid_symbols[BR_ALS_BGN] && is_br) { + MAY_UPD_IMP_COL(); + return scn_als_bgn(scanner, lexer, BR_ALS_BGN); + } + if (valid_symbols[B_ALS_BGN] && is_b) { + MAY_UPD_IMP_COL(); + return scn_als_bgn(scanner, lexer, B_ALS_BGN); + } + } else if (lexer->lookahead == '&') { + if (valid_symbols[R_ACR_BGN] && is_r) { + MAY_UPD_IMP_COL(); + return scn_acr_bgn(scanner, lexer, R_ACR_BGN); + } + if (valid_symbols[BR_ACR_BGN] && is_br) { + MAY_UPD_IMP_COL(); + return scn_acr_bgn(scanner, lexer, BR_ACR_BGN); + } + if (valid_symbols[B_ACR_BGN] && is_b) { + MAY_UPD_IMP_COL(); + return scn_acr_bgn(scanner, lexer, B_ACR_BGN); + } + } else if (lexer->lookahead == '!') { + if (valid_symbols[R_TAG] && is_r) { + MAY_UPD_IMP_COL(); + return scn_tag(scanner, lexer, R_TAG); + } + if (valid_symbols[BR_TAG] && is_br) { + MAY_UPD_IMP_COL(); + return scn_tag(scanner, lexer, BR_TAG); + } + if (valid_symbols[B_TAG] && is_b) { + MAY_UPD_IMP_COL(); + return scn_tag(scanner, lexer, B_TAG); + } + } else if (lexer->lookahead == '[') { + if (valid_symbols[R_FLW_SEQ_BGN] && is_r) { + MAY_UPD_IMP_COL(); + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(R_FLW_SEQ_BGN) + } + if (valid_symbols[BR_FLW_SEQ_BGN] && is_br) { + MAY_UPD_IMP_COL(); + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(BR_FLW_SEQ_BGN) + } + if (valid_symbols[B_FLW_SEQ_BGN] && is_b) { + MAY_UPD_IMP_COL(); + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(B_FLW_SEQ_BGN) + } + } else if (lexer->lookahead == ']') { + if (valid_symbols[R_FLW_SEQ_END] && is_r) { + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(R_FLW_SEQ_END) + } + if (valid_symbols[BR_FLW_SEQ_END] && is_br) { + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(BR_FLW_SEQ_END) + } + if (valid_symbols[B_FLW_SEQ_END] && is_b) { + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(BR_FLW_SEQ_END) + } + } else if (lexer->lookahead == '{') { + if (valid_symbols[R_FLW_MAP_BGN] && is_r) { + MAY_UPD_IMP_COL(); + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(R_FLW_MAP_BGN) + } + if (valid_symbols[BR_FLW_MAP_BGN] && is_br) { + MAY_UPD_IMP_COL(); + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(BR_FLW_MAP_BGN) + } + if (valid_symbols[B_FLW_MAP_BGN] && is_b) { + MAY_UPD_IMP_COL(); + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(B_FLW_MAP_BGN) + } + } else if (lexer->lookahead == '}') { + if (valid_symbols[R_FLW_MAP_END] && is_r) { + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(R_FLW_MAP_END) + } + if (valid_symbols[BR_FLW_MAP_END] && is_br) { + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(BR_FLW_MAP_END) + } + if (valid_symbols[B_FLW_MAP_END] && is_b) { + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(BR_FLW_MAP_END) + } + } else if (lexer->lookahead == ',') { + if (valid_symbols[R_FLW_SEP_BGN] && is_r) { + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(R_FLW_SEP_BGN) + } + if (valid_symbols[BR_FLW_SEP_BGN] && is_br) { + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(BR_FLW_SEP_BGN) + } + } else if (lexer->lookahead == '"') { + if (valid_symbols[R_DQT_STR_BGN] && is_r) { + MAY_UPD_IMP_COL(); + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(R_DQT_STR_BGN) + } + if (valid_symbols[BR_DQT_STR_BGN] && is_br) { + MAY_UPD_IMP_COL(); + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(BR_DQT_STR_BGN) + } + if (valid_symbols[B_DQT_STR_BGN] && is_b) { + MAY_UPD_IMP_COL(); + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(B_DQT_STR_BGN) + } + if (valid_symbols[R_DQT_STR_END] && is_r) { + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(R_DQT_STR_END) + } + if (valid_symbols[BR_DQT_STR_END] && is_br) { + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(BR_DQT_STR_END) + } + } else if (lexer->lookahead == '\'') { + if (valid_symbols[R_SQT_STR_BGN] && is_r) { + MAY_UPD_IMP_COL(); + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(R_SQT_STR_BGN) + } + if (valid_symbols[BR_SQT_STR_BGN] && is_br) { + MAY_UPD_IMP_COL(); + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(BR_SQT_STR_BGN) + } + if (valid_symbols[B_SQT_STR_BGN] && is_b) { + MAY_UPD_IMP_COL(); + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(B_SQT_STR_BGN) + } + if (valid_symbols[R_SQT_STR_END] && is_r) { + adv(scanner, lexer); + if (lexer->lookahead == '\'') { + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(R_SQT_ESC_SQT) + } else { + mrk_end(scanner, lexer); + RET_SYM(R_SQT_STR_END) + } + } + if (valid_symbols[BR_SQT_STR_END] && is_br) { + adv(scanner, lexer); + if (lexer->lookahead == '\'') { + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(BR_SQT_ESC_SQT) + } else { + mrk_end(scanner, lexer); + RET_SYM(BR_SQT_STR_END) + } + } + } else if (lexer->lookahead == '?') { + bool is_r_blk_key_bgn = valid_symbols[R_BLK_KEY_BGN] && is_r; + bool is_br_blk_key_bgn = valid_symbols[BR_BLK_KEY_BGN] && is_br; + bool is_b_blk_key_bgn = valid_symbols[B_BLK_KEY_BGN] && is_b; + bool is_r_flw_key_bgn = valid_symbols[R_FLW_KEY_BGN] && is_r; + bool is_br_flw_key_bgn = valid_symbols[BR_FLW_KEY_BGN] && is_br; + if (is_r_blk_key_bgn || is_br_blk_key_bgn || is_b_blk_key_bgn || is_r_flw_key_bgn || is_br_flw_key_bgn) { + adv(scanner, lexer); + if (is_wht(lexer->lookahead)) { + mrk_end(scanner, lexer); + if (is_r_blk_key_bgn) { + PUSH_BGN_IND(IND_MAP); + RET_SYM(R_BLK_KEY_BGN); + } + if (is_br_blk_key_bgn) { + PUSH_BGN_IND(IND_MAP); + RET_SYM(BR_BLK_KEY_BGN); + } + if (is_b_blk_key_bgn) + RET_SYM(B_BLK_KEY_BGN); + if (is_r_flw_key_bgn) + RET_SYM(R_FLW_KEY_BGN); + if (is_br_flw_key_bgn) + RET_SYM(BR_FLW_KEY_BGN); + } + } + } else if (lexer->lookahead == ':') { + if (valid_symbols[R_FLW_JSV_BGN] && is_r) { + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(R_FLW_JSV_BGN); + } + if (valid_symbols[BR_FLW_JSV_BGN] && is_br) { + adv(scanner, lexer); + mrk_end(scanner, lexer); + RET_SYM(BR_FLW_JSV_BGN); + } + bool is_r_blk_val_bgn = valid_symbols[R_BLK_VAL_BGN] && is_r; + bool is_br_blk_val_bgn = valid_symbols[BR_BLK_VAL_BGN] && is_br; + bool is_b_blk_val_bgn = valid_symbols[B_BLK_VAL_BGN] && is_b; + bool is_r_blk_imp_bgn = valid_symbols[R_BLK_IMP_BGN] && is_r; + bool is_r_flw_njv_bgn = valid_symbols[R_FLW_NJV_BGN] && is_r; + bool is_br_flw_njv_bgn = valid_symbols[BR_FLW_NJV_BGN] && is_br; + if (is_r_blk_val_bgn || is_br_blk_val_bgn || is_b_blk_val_bgn || is_r_blk_imp_bgn || is_r_flw_njv_bgn || + is_br_flw_njv_bgn) { + adv(scanner, lexer); + bool is_lka_wht = is_wht(lexer->lookahead); + if (is_lka_wht) { + if (is_r_blk_val_bgn) { + PUSH_BGN_IND(IND_MAP); + mrk_end(scanner, lexer); + RET_SYM(R_BLK_VAL_BGN); + } + if (is_br_blk_val_bgn) { + PUSH_BGN_IND(IND_MAP); + mrk_end(scanner, lexer); + RET_SYM(BR_BLK_VAL_BGN); + } + if (is_b_blk_val_bgn) { + mrk_end(scanner, lexer); + RET_SYM(B_BLK_VAL_BGN); + } + if (is_r_blk_imp_bgn) { + MAY_PUSH_IMP_IND(); + mrk_end(scanner, lexer); + RET_SYM(R_BLK_IMP_BGN); + } + } + if (is_lka_wht || lexer->lookahead == ',' || lexer->lookahead == ']' || lexer->lookahead == '}') { + if (is_r_flw_njv_bgn) { + mrk_end(scanner, lexer); + RET_SYM(R_FLW_NJV_BGN); + } + if (is_br_flw_njv_bgn) { + mrk_end(scanner, lexer); + RET_SYM(BR_FLW_NJV_BGN); + } + } + } + } else if (lexer->lookahead == '-') { + bool is_r_blk_seq_bgn = valid_symbols[R_BLK_SEQ_BGN] && is_r; + bool is_br_blk_seq_bgn = valid_symbols[BR_BLK_SEQ_BGN] && is_br; + bool is_b_blk_seq_bgn = valid_symbols[B_BLK_SEQ_BGN] && is_b; + bool is_s_drs_end = is_s; + if (is_r_blk_seq_bgn || is_br_blk_seq_bgn || is_b_blk_seq_bgn || is_s_drs_end) { + adv(scanner, lexer); + if (is_wht(lexer->lookahead)) { + if (is_r_blk_seq_bgn) { + PUSH_BGN_IND(IND_SEQ); + mrk_end(scanner, lexer); + RET_SYM(R_BLK_SEQ_BGN) + } + if (is_br_blk_seq_bgn) { + PUSH_BGN_IND(IND_SEQ); + mrk_end(scanner, lexer); + RET_SYM(BR_BLK_SEQ_BGN) + } + if (is_b_blk_seq_bgn) { + MAY_PUSH_SPC_SEQ_IND(); + mrk_end(scanner, lexer); + RET_SYM(B_BLK_SEQ_BGN) + } + } else if (lexer->lookahead == '-' && is_s_drs_end) { + adv(scanner, lexer); + if (lexer->lookahead == '-') { + adv(scanner, lexer); + if (is_wht(lexer->lookahead)) { + if (valid_symbols[BL]) { + POP_IND(); + RET_SYM(BL); + } + mrk_end(scanner, lexer); + RET_SYM(S_DRS_END); + } + } + } + } + } else if (lexer->lookahead == '.') { + if (is_s) { + adv(scanner, lexer); + if (lexer->lookahead == '.') { + adv(scanner, lexer); + if (lexer->lookahead == '.') { + adv(scanner, lexer); + if (is_wht(lexer->lookahead)) { + if (valid_symbols[BL]) { + POP_IND(); + RET_SYM(BL); + } + mrk_end(scanner, lexer); + RET_SYM(S_DOC_END); + } + } + } + } + } else if (lexer->lookahead == '\\') { + bool is_r_dqt_esc_nwl = valid_symbols[R_DQT_ESC_NWL] && is_r; + bool is_br_dqt_esc_nwl = valid_symbols[BR_DQT_ESC_NWL] && is_br; + bool is_r_dqt_esc_seq = valid_symbols[R_DQT_ESC_SEQ] && is_r; + bool is_br_dqt_esc_seq = valid_symbols[BR_DQT_ESC_SEQ] && is_br; + if (is_r_dqt_esc_nwl || is_br_dqt_esc_nwl || is_r_dqt_esc_seq || is_br_dqt_esc_seq) { + adv(scanner, lexer); + if (is_nwl(lexer->lookahead)) { + if (is_r_dqt_esc_nwl) { + mrk_end(scanner, lexer); + RET_SYM(R_DQT_ESC_NWL) + } + if (is_br_dqt_esc_nwl) { + mrk_end(scanner, lexer); + RET_SYM(BR_DQT_ESC_NWL) + } + } + if (is_r_dqt_esc_seq) { + return scn_dqt_esc_seq(scanner, lexer, R_DQT_ESC_SEQ); + } + if (is_br_dqt_esc_seq) { + return scn_dqt_esc_seq(scanner, lexer, BR_DQT_ESC_SEQ); + } + return false; + } + } else if (lexer->lookahead == '|') { + if (valid_symbols[R_BLK_LIT_BGN] && is_r) { + return scn_blk_str_bgn(scanner, lexer, R_BLK_LIT_BGN); + } + if (valid_symbols[BR_BLK_LIT_BGN] && is_br) { + return scn_blk_str_bgn(scanner, lexer, BR_BLK_LIT_BGN); + } + } else if (lexer->lookahead == '>') { + if (valid_symbols[R_BLK_FLD_BGN] && is_r) { + return scn_blk_str_bgn(scanner, lexer, R_BLK_FLD_BGN); + } + if (valid_symbols[BR_BLK_FLD_BGN] && is_br) { + return scn_blk_str_bgn(scanner, lexer, BR_BLK_FLD_BGN); + } + } + + bool maybe_sgl_pln_blk = (valid_symbols[R_SGL_PLN_STR_BLK] && is_r) || + (valid_symbols[BR_SGL_PLN_STR_BLK] && is_br) || (valid_symbols[B_SGL_PLN_STR_BLK] && is_b); + bool maybe_sgl_pln_flw = (valid_symbols[R_SGL_PLN_STR_FLW] && is_r) || (valid_symbols[BR_SGL_PLN_STR_FLW] && is_br); + bool maybe_mtl_pln_blk = (valid_symbols[R_MTL_PLN_STR_BLK] && is_r) || (valid_symbols[BR_MTL_PLN_STR_BLK] && is_br); + bool maybe_mtl_pln_flw = (valid_symbols[R_MTL_PLN_STR_FLW] && is_r) || (valid_symbols[BR_MTL_PLN_STR_FLW] && is_br); + + if (maybe_sgl_pln_blk || maybe_sgl_pln_flw || maybe_mtl_pln_blk || maybe_mtl_pln_flw) { + bool is_in_blk = maybe_sgl_pln_blk || maybe_mtl_pln_blk; + bool (*is_plain_safe)(int32_t) = is_in_blk ? is_plain_safe_in_block : is_plain_safe_in_flow; + if (scanner->cur_col - bgn_col == 0) { + adv(scanner, lexer); + } + if (scanner->cur_col - bgn_col == 1) { + bool is_plain_first = + (is_ns_char(bgn_chr) && !is_c_indicator(bgn_chr)) || + ((bgn_chr == '-' || bgn_chr == '?' || bgn_chr == ':') && is_plain_safe(lexer->lookahead)); + if (!is_plain_first) { + return false; + } + scanner->sch_stt = adv_sch_stt(scanner->sch_stt, scanner->cur_chr, &scanner->rlt_sch); + } else { + // no need to check the following cases: + // ..X + // ...X + // --X + // ---X + // X: lookahead + scanner->sch_stt = SCH_STT_FRZ; // must be RS_STR + } + + mrk_end(scanner, lexer); + + for (;;) { + if (!is_nwl(lexer->lookahead)) { + if (scn_pln_cnt(scanner, lexer, is_plain_safe) != SCN_SUCC) { + break; + } + } + if (lexer->lookahead == 0 || !is_nwl(lexer->lookahead)) { + break; + } + for (;;) { + if (is_nwl(lexer->lookahead)) { + adv_nwl(scanner, lexer); + } else if (is_wsp(lexer->lookahead)) { + adv(scanner, lexer); + } else { + break; + } + } + if (lexer->lookahead == 0 || scanner->cur_col <= cur_ind) { + break; + } + if (scanner->cur_col == 0 && scn_drs_doc_end(scanner, lexer)) { + break; + } + } + + if (scanner->end_row == bgn_row) { + if (maybe_sgl_pln_blk) { + MAY_UPD_IMP_COL(); + RET_SYM(is_r ? SGL_PLN_SYM(R, BLK) : is_br ? SGL_PLN_SYM(BR, BLK) : SGL_PLN_SYM(B, BLK)); + } + if (maybe_sgl_pln_flw) + RET_SYM(is_r ? SGL_PLN_SYM(R, FLW) : SGL_PLN_SYM(BR, FLW)); + } else { + if (maybe_mtl_pln_blk) { + MAY_UPD_IMP_COL(); + RET_SYM(is_r ? R_MTL_PLN_STR_BLK : BR_MTL_PLN_STR_BLK); + } + if (maybe_mtl_pln_flw) + RET_SYM(is_r ? R_MTL_PLN_STR_FLW : BR_MTL_PLN_STR_FLW); + } + + return false; + } + + return !valid_symbols[ERR_REC]; +} + +void *tree_sitter_yaml_external_scanner_create() { + Scanner *scanner = ts_calloc(1, sizeof(Scanner)); + deserialize(scanner, NULL, 0); + return scanner; +} + +void tree_sitter_yaml_external_scanner_destroy(void *payload) { + Scanner *scanner = (Scanner *)payload; + array_delete(&scanner->ind_len_stk); + array_delete(&scanner->ind_typ_stk); + ts_free(scanner); +} + +unsigned tree_sitter_yaml_external_scanner_serialize(void *payload, char *buffer) { + Scanner *scanner = (Scanner *)payload; + return serialize(scanner, buffer); +} + +void tree_sitter_yaml_external_scanner_deserialize(void *payload, const char *buffer, unsigned length) { + Scanner *scanner = (Scanner *)payload; + deserialize(scanner, buffer, length); +} + +bool tree_sitter_yaml_external_scanner_scan(void *payload, TSLexer *lexer, const bool *valid_symbols) { + Scanner *scanner = (Scanner *)payload; + return scan(scanner, lexer, valid_symbols); +} diff --git a/Sources/TreeSitterYAML/schema.core.c b/Sources/TreeSitterYAML/schema.core.c new file mode 100644 index 0000000..ae7812a --- /dev/null +++ b/Sources/TreeSitterYAML/schema.core.c @@ -0,0 +1,204 @@ +#include + +#include + +#define SCH_STT_FRZ -1 + +#define HAS_TIMESTAMP 0 + +typedef enum { + RS_STR, + RS_INT, + RS_NULL, + RS_BOOL, + RS_FLOAT, +} ResultSchema; + +static int8_t adv_sch_stt(int8_t sch_stt, int32_t cur_chr, ResultSchema *rlt_sch) { + switch (sch_stt) { + case SCH_STT_FRZ: + break; + case 0: + if (cur_chr == '.') {*rlt_sch = RS_STR; return 6;} + if (cur_chr == '0') {*rlt_sch = RS_INT; return 37;} + if (cur_chr == 'F') {*rlt_sch = RS_STR; return 2;} + if (cur_chr == 'N') {*rlt_sch = RS_STR; return 16;} + if (cur_chr == 'T') {*rlt_sch = RS_STR; return 13;} + if (cur_chr == 'f') {*rlt_sch = RS_STR; return 17;} + if (cur_chr == 'n') {*rlt_sch = RS_STR; return 29;} + if (cur_chr == 't') {*rlt_sch = RS_STR; return 26;} + if (cur_chr == '~') {*rlt_sch = RS_NULL; return 35;} + if (cur_chr == '+') {*rlt_sch = RS_STR; return 1;} + if (cur_chr == '-') {*rlt_sch = RS_STR; return 1;} + if (('1' <= cur_chr && cur_chr <= '9')) {*rlt_sch = RS_INT; return 38;} + break; + case 1: + if (cur_chr == '.') {*rlt_sch = RS_STR; return 7;} + if (('0' <= cur_chr && cur_chr <= '9')) {*rlt_sch = RS_INT; return 38;} + break; + case 2: + if (cur_chr == 'A') {*rlt_sch = RS_STR; return 9;} + if (cur_chr == 'a') {*rlt_sch = RS_STR; return 22;} + break; + case 3: + if (cur_chr == 'A') {*rlt_sch = RS_STR; return 12;} + if (cur_chr == 'a') {*rlt_sch = RS_STR; return 12;} + break; + case 4: + if (cur_chr == 'E') {*rlt_sch = RS_BOOL; return 36;} + break; + case 5: + if (cur_chr == 'F') {*rlt_sch = RS_FLOAT; return 41;} + break; + case 6: + if (cur_chr == 'I') {*rlt_sch = RS_STR; return 11;} + if (cur_chr == 'N') {*rlt_sch = RS_STR; return 3;} + if (cur_chr == 'i') {*rlt_sch = RS_STR; return 24;} + if (cur_chr == 'n') {*rlt_sch = RS_STR; return 18;} + if (('0' <= cur_chr && cur_chr <= '9')) {*rlt_sch = RS_FLOAT; return 42;} + break; + case 7: + if (cur_chr == 'I') {*rlt_sch = RS_STR; return 11;} + if (cur_chr == 'i') {*rlt_sch = RS_STR; return 24;} + if (('0' <= cur_chr && cur_chr <= '9')) {*rlt_sch = RS_FLOAT; return 42;} + break; + case 8: + if (cur_chr == 'L') {*rlt_sch = RS_NULL; return 35;} + break; + case 9: + if (cur_chr == 'L') {*rlt_sch = RS_STR; return 14;} + break; + case 10: + if (cur_chr == 'L') {*rlt_sch = RS_STR; return 8;} + break; + case 11: + if (cur_chr == 'N') {*rlt_sch = RS_STR; return 5;} + if (cur_chr == 'n') {*rlt_sch = RS_STR; return 20;} + break; + case 12: + if (cur_chr == 'N') {*rlt_sch = RS_FLOAT; return 41;} + break; + case 13: + if (cur_chr == 'R') {*rlt_sch = RS_STR; return 15;} + if (cur_chr == 'r') {*rlt_sch = RS_STR; return 28;} + break; + case 14: + if (cur_chr == 'S') {*rlt_sch = RS_STR; return 4;} + break; + case 15: + if (cur_chr == 'U') {*rlt_sch = RS_STR; return 4;} + break; + case 16: + if (cur_chr == 'U') {*rlt_sch = RS_STR; return 10;} + if (cur_chr == 'u') {*rlt_sch = RS_STR; return 23;} + break; + case 17: + if (cur_chr == 'a') {*rlt_sch = RS_STR; return 22;} + break; + case 18: + if (cur_chr == 'a') {*rlt_sch = RS_STR; return 25;} + break; + case 19: + if (cur_chr == 'e') {*rlt_sch = RS_BOOL; return 36;} + break; + case 20: + if (cur_chr == 'f') {*rlt_sch = RS_FLOAT; return 41;} + break; + case 21: + if (cur_chr == 'l') {*rlt_sch = RS_NULL; return 35;} + break; + case 22: + if (cur_chr == 'l') {*rlt_sch = RS_STR; return 27;} + break; + case 23: + if (cur_chr == 'l') {*rlt_sch = RS_STR; return 21;} + break; + case 24: + if (cur_chr == 'n') {*rlt_sch = RS_STR; return 20;} + break; + case 25: + if (cur_chr == 'n') {*rlt_sch = RS_FLOAT; return 41;} + break; + case 26: + if (cur_chr == 'r') {*rlt_sch = RS_STR; return 28;} + break; + case 27: + if (cur_chr == 's') {*rlt_sch = RS_STR; return 19;} + break; + case 28: + if (cur_chr == 'u') {*rlt_sch = RS_STR; return 19;} + break; + case 29: + if (cur_chr == 'u') {*rlt_sch = RS_STR; return 23;} + break; + case 30: + if (cur_chr == '+' || + cur_chr == '-') {*rlt_sch = RS_STR; return 32;} + if (('0' <= cur_chr && cur_chr <= '9')) {*rlt_sch = RS_FLOAT; return 43;} + break; + case 31: + if (('0' <= cur_chr && cur_chr <= '7')) {*rlt_sch = RS_INT; return 39;} + break; + case 32: + if (('0' <= cur_chr && cur_chr <= '9')) {*rlt_sch = RS_FLOAT; return 43;} + break; + case 33: + if (('0' <= cur_chr && cur_chr <= '9') || + ('A' <= cur_chr && cur_chr <= 'F') || + ('a' <= cur_chr && cur_chr <= 'f')) {*rlt_sch = RS_INT; return 40;} + break; + case 34: + abort(); + break; + case 35: + *rlt_sch = RS_NULL; + break; + case 36: + *rlt_sch = RS_BOOL; + break; + case 37: + *rlt_sch = RS_INT; + if (cur_chr == '.') {*rlt_sch = RS_FLOAT; return 42;} + if (cur_chr == 'o') {*rlt_sch = RS_STR; return 31;} + if (cur_chr == 'x') {*rlt_sch = RS_STR; return 33;} + if (cur_chr == 'E' || + cur_chr == 'e') {*rlt_sch = RS_STR; return 30;} + if (('0' <= cur_chr && cur_chr <= '9')) {*rlt_sch = RS_INT; return 38;} + break; + case 38: + *rlt_sch = RS_INT; + if (cur_chr == '.') {*rlt_sch = RS_FLOAT; return 42;} + if (cur_chr == 'E' || + cur_chr == 'e') {*rlt_sch = RS_STR; return 30;} + if (('0' <= cur_chr && cur_chr <= '9')) {*rlt_sch = RS_INT; return 38;} + break; + case 39: + *rlt_sch = RS_INT; + if (('0' <= cur_chr && cur_chr <= '7')) {*rlt_sch = RS_INT; return 39;} + break; + case 40: + *rlt_sch = RS_INT; + if (('0' <= cur_chr && cur_chr <= '9') || + ('A' <= cur_chr && cur_chr <= 'F') || + ('a' <= cur_chr && cur_chr <= 'f')) {*rlt_sch = RS_INT; return 40;} + break; + case 41: + *rlt_sch = RS_FLOAT; + break; + case 42: + *rlt_sch = RS_FLOAT; + if (cur_chr == 'E' || + cur_chr == 'e') {*rlt_sch = RS_STR; return 30;} + if (('0' <= cur_chr && cur_chr <= '9')) {*rlt_sch = RS_FLOAT; return 42;} + break; + case 43: + *rlt_sch = RS_FLOAT; + if (('0' <= cur_chr && cur_chr <= '9')) {*rlt_sch = RS_FLOAT; return 43;} + break; + default: + *rlt_sch = RS_STR; + return SCH_STT_FRZ; + } + if (cur_chr != '\r' && cur_chr != '\n' && cur_chr != ' ' && cur_chr != 0) *rlt_sch = RS_STR; + return SCH_STT_FRZ; +} diff --git a/Sources/TreeSitterYAML/tree_sitter/alloc.h b/Sources/TreeSitterYAML/tree_sitter/alloc.h new file mode 100644 index 0000000..1abdd12 --- /dev/null +++ b/Sources/TreeSitterYAML/tree_sitter/alloc.h @@ -0,0 +1,54 @@ +#ifndef TREE_SITTER_ALLOC_H_ +#define TREE_SITTER_ALLOC_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include + +// Allow clients to override allocation functions +#ifdef TREE_SITTER_REUSE_ALLOCATOR + +extern void *(*ts_current_malloc)(size_t size); +extern void *(*ts_current_calloc)(size_t count, size_t size); +extern void *(*ts_current_realloc)(void *ptr, size_t size); +extern void (*ts_current_free)(void *ptr); + +#ifndef ts_malloc +#define ts_malloc ts_current_malloc +#endif +#ifndef ts_calloc +#define ts_calloc ts_current_calloc +#endif +#ifndef ts_realloc +#define ts_realloc ts_current_realloc +#endif +#ifndef ts_free +#define ts_free ts_current_free +#endif + +#else + +#ifndef ts_malloc +#define ts_malloc malloc +#endif +#ifndef ts_calloc +#define ts_calloc calloc +#endif +#ifndef ts_realloc +#define ts_realloc realloc +#endif +#ifndef ts_free +#define ts_free free +#endif + +#endif + +#ifdef __cplusplus +} +#endif + +#endif // TREE_SITTER_ALLOC_H_ diff --git a/Sources/TreeSitterYAML/tree_sitter/array.h b/Sources/TreeSitterYAML/tree_sitter/array.h new file mode 100644 index 0000000..a17a574 --- /dev/null +++ b/Sources/TreeSitterYAML/tree_sitter/array.h @@ -0,0 +1,291 @@ +#ifndef TREE_SITTER_ARRAY_H_ +#define TREE_SITTER_ARRAY_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include "./alloc.h" + +#include +#include +#include +#include +#include + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4101) +#elif defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wunused-variable" +#endif + +#define Array(T) \ + struct { \ + T *contents; \ + uint32_t size; \ + uint32_t capacity; \ + } + +/// Initialize an array. +#define array_init(self) \ + ((self)->size = 0, (self)->capacity = 0, (self)->contents = NULL) + +/// Create an empty array. +#define array_new() \ + { NULL, 0, 0 } + +/// Get a pointer to the element at a given `index` in the array. +#define array_get(self, _index) \ + (assert((uint32_t)(_index) < (self)->size), &(self)->contents[_index]) + +/// Get a pointer to the first element in the array. +#define array_front(self) array_get(self, 0) + +/// Get a pointer to the last element in the array. +#define array_back(self) array_get(self, (self)->size - 1) + +/// Clear the array, setting its size to zero. Note that this does not free any +/// memory allocated for the array's contents. +#define array_clear(self) ((self)->size = 0) + +/// Reserve `new_capacity` elements of space in the array. If `new_capacity` is +/// less than the array's current capacity, this function has no effect. +#define array_reserve(self, new_capacity) \ + _array__reserve((Array *)(self), array_elem_size(self), new_capacity) + +/// Free any memory allocated for this array. Note that this does not free any +/// memory allocated for the array's contents. +#define array_delete(self) _array__delete((Array *)(self)) + +/// Push a new `element` onto the end of the array. +#define array_push(self, element) \ + (_array__grow((Array *)(self), 1, array_elem_size(self)), \ + (self)->contents[(self)->size++] = (element)) + +/// Increase the array's size by `count` elements. +/// New elements are zero-initialized. +#define array_grow_by(self, count) \ + do { \ + if ((count) == 0) break; \ + _array__grow((Array *)(self), count, array_elem_size(self)); \ + memset((self)->contents + (self)->size, 0, (count) * array_elem_size(self)); \ + (self)->size += (count); \ + } while (0) + +/// Append all elements from one array to the end of another. +#define array_push_all(self, other) \ + array_extend((self), (other)->size, (other)->contents) + +/// Append `count` elements to the end of the array, reading their values from the +/// `contents` pointer. +#define array_extend(self, count, contents) \ + _array__splice( \ + (Array *)(self), array_elem_size(self), (self)->size, \ + 0, count, contents \ + ) + +/// Remove `old_count` elements from the array starting at the given `index`. At +/// the same index, insert `new_count` new elements, reading their values from the +/// `new_contents` pointer. +#define array_splice(self, _index, old_count, new_count, new_contents) \ + _array__splice( \ + (Array *)(self), array_elem_size(self), _index, \ + old_count, new_count, new_contents \ + ) + +/// Insert one `element` into the array at the given `index`. +#define array_insert(self, _index, element) \ + _array__splice((Array *)(self), array_elem_size(self), _index, 0, 1, &(element)) + +/// Remove one element from the array at the given `index`. +#define array_erase(self, _index) \ + _array__erase((Array *)(self), array_elem_size(self), _index) + +/// Pop the last element off the array, returning the element by value. +#define array_pop(self) ((self)->contents[--(self)->size]) + +/// Assign the contents of one array to another, reallocating if necessary. +#define array_assign(self, other) \ + _array__assign((Array *)(self), (const Array *)(other), array_elem_size(self)) + +/// Swap one array with another +#define array_swap(self, other) \ + _array__swap((Array *)(self), (Array *)(other)) + +/// Get the size of the array contents +#define array_elem_size(self) (sizeof *(self)->contents) + +/// Search a sorted array for a given `needle` value, using the given `compare` +/// callback to determine the order. +/// +/// If an existing element is found to be equal to `needle`, then the `index` +/// out-parameter is set to the existing value's index, and the `exists` +/// out-parameter is set to true. Otherwise, `index` is set to an index where +/// `needle` should be inserted in order to preserve the sorting, and `exists` +/// is set to false. +#define array_search_sorted_with(self, compare, needle, _index, _exists) \ + _array__search_sorted(self, 0, compare, , needle, _index, _exists) + +/// Search a sorted array for a given `needle` value, using integer comparisons +/// of a given struct field (specified with a leading dot) to determine the order. +/// +/// See also `array_search_sorted_with`. +#define array_search_sorted_by(self, field, needle, _index, _exists) \ + _array__search_sorted(self, 0, _compare_int, field, needle, _index, _exists) + +/// Insert a given `value` into a sorted array, using the given `compare` +/// callback to determine the order. +#define array_insert_sorted_with(self, compare, value) \ + do { \ + unsigned _index, _exists; \ + array_search_sorted_with(self, compare, &(value), &_index, &_exists); \ + if (!_exists) array_insert(self, _index, value); \ + } while (0) + +/// Insert a given `value` into a sorted array, using integer comparisons of +/// a given struct field (specified with a leading dot) to determine the order. +/// +/// See also `array_search_sorted_by`. +#define array_insert_sorted_by(self, field, value) \ + do { \ + unsigned _index, _exists; \ + array_search_sorted_by(self, field, (value) field, &_index, &_exists); \ + if (!_exists) array_insert(self, _index, value); \ + } while (0) + +// Private + +typedef Array(void) Array; + +/// This is not what you're looking for, see `array_delete`. +static inline void _array__delete(Array *self) { + if (self->contents) { + ts_free(self->contents); + self->contents = NULL; + self->size = 0; + self->capacity = 0; + } +} + +/// This is not what you're looking for, see `array_erase`. +static inline void _array__erase(Array *self, size_t element_size, + uint32_t index) { + assert(index < self->size); + char *contents = (char *)self->contents; + memmove(contents + index * element_size, contents + (index + 1) * element_size, + (self->size - index - 1) * element_size); + self->size--; +} + +/// This is not what you're looking for, see `array_reserve`. +static inline void _array__reserve(Array *self, size_t element_size, uint32_t new_capacity) { + if (new_capacity > self->capacity) { + if (self->contents) { + self->contents = ts_realloc(self->contents, new_capacity * element_size); + } else { + self->contents = ts_malloc(new_capacity * element_size); + } + self->capacity = new_capacity; + } +} + +/// This is not what you're looking for, see `array_assign`. +static inline void _array__assign(Array *self, const Array *other, size_t element_size) { + _array__reserve(self, element_size, other->size); + self->size = other->size; + memcpy(self->contents, other->contents, self->size * element_size); +} + +/// This is not what you're looking for, see `array_swap`. +static inline void _array__swap(Array *self, Array *other) { + Array swap = *other; + *other = *self; + *self = swap; +} + +/// This is not what you're looking for, see `array_push` or `array_grow_by`. +static inline void _array__grow(Array *self, uint32_t count, size_t element_size) { + uint32_t new_size = self->size + count; + if (new_size > self->capacity) { + uint32_t new_capacity = self->capacity * 2; + if (new_capacity < 8) new_capacity = 8; + if (new_capacity < new_size) new_capacity = new_size; + _array__reserve(self, element_size, new_capacity); + } +} + +/// This is not what you're looking for, see `array_splice`. +static inline void _array__splice(Array *self, size_t element_size, + uint32_t index, uint32_t old_count, + uint32_t new_count, const void *elements) { + uint32_t new_size = self->size + new_count - old_count; + uint32_t old_end = index + old_count; + uint32_t new_end = index + new_count; + assert(old_end <= self->size); + + _array__reserve(self, element_size, new_size); + + char *contents = (char *)self->contents; + if (self->size > old_end) { + memmove( + contents + new_end * element_size, + contents + old_end * element_size, + (self->size - old_end) * element_size + ); + } + if (new_count > 0) { + if (elements) { + memcpy( + (contents + index * element_size), + elements, + new_count * element_size + ); + } else { + memset( + (contents + index * element_size), + 0, + new_count * element_size + ); + } + } + self->size += new_count - old_count; +} + +/// A binary search routine, based on Rust's `std::slice::binary_search_by`. +/// This is not what you're looking for, see `array_search_sorted_with` or `array_search_sorted_by`. +#define _array__search_sorted(self, start, compare, suffix, needle, _index, _exists) \ + do { \ + *(_index) = start; \ + *(_exists) = false; \ + uint32_t size = (self)->size - *(_index); \ + if (size == 0) break; \ + int comparison; \ + while (size > 1) { \ + uint32_t half_size = size / 2; \ + uint32_t mid_index = *(_index) + half_size; \ + comparison = compare(&((self)->contents[mid_index] suffix), (needle)); \ + if (comparison <= 0) *(_index) = mid_index; \ + size -= half_size; \ + } \ + comparison = compare(&((self)->contents[*(_index)] suffix), (needle)); \ + if (comparison == 0) *(_exists) = true; \ + else if (comparison < 0) *(_index) += 1; \ + } while (0) + +/// Helper macro for the `_sorted_by` routines below. This takes the left (existing) +/// parameter by reference in order to work with the generic sorting function above. +#define _compare_int(a, b) ((int)*(a) - (int)(b)) + +#ifdef _MSC_VER +#pragma warning(pop) +#elif defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic pop +#endif + +#ifdef __cplusplus +} +#endif + +#endif // TREE_SITTER_ARRAY_H_ diff --git a/Sources/TreeSitterYAML/tree_sitter/parser.h b/Sources/TreeSitterYAML/tree_sitter/parser.h new file mode 100644 index 0000000..858107d --- /dev/null +++ b/Sources/TreeSitterYAML/tree_sitter/parser.h @@ -0,0 +1,286 @@ +#ifndef TREE_SITTER_PARSER_H_ +#define TREE_SITTER_PARSER_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include + +#define ts_builtin_sym_error ((TSSymbol)-1) +#define ts_builtin_sym_end 0 +#define TREE_SITTER_SERIALIZATION_BUFFER_SIZE 1024 + +#ifndef TREE_SITTER_API_H_ +typedef uint16_t TSStateId; +typedef uint16_t TSSymbol; +typedef uint16_t TSFieldId; +typedef struct TSLanguage TSLanguage; +typedef struct TSLanguageMetadata { + uint8_t major_version; + uint8_t minor_version; + uint8_t patch_version; +} TSLanguageMetadata; +#endif + +typedef struct { + TSFieldId field_id; + uint8_t child_index; + bool inherited; +} TSFieldMapEntry; + +// Used to index the field and supertype maps. +typedef struct { + uint16_t index; + uint16_t length; +} TSMapSlice; + +typedef struct { + bool visible; + bool named; + bool supertype; +} TSSymbolMetadata; + +typedef struct TSLexer TSLexer; + +struct TSLexer { + int32_t lookahead; + TSSymbol result_symbol; + void (*advance)(TSLexer *, bool); + void (*mark_end)(TSLexer *); + uint32_t (*get_column)(TSLexer *); + bool (*is_at_included_range_start)(const TSLexer *); + bool (*eof)(const TSLexer *); + void (*log)(const TSLexer *, const char *, ...); +}; + +typedef enum { + TSParseActionTypeShift, + TSParseActionTypeReduce, + TSParseActionTypeAccept, + TSParseActionTypeRecover, +} TSParseActionType; + +typedef union { + struct { + uint8_t type; + TSStateId state; + bool extra; + bool repetition; + } shift; + struct { + uint8_t type; + uint8_t child_count; + TSSymbol symbol; + int16_t dynamic_precedence; + uint16_t production_id; + } reduce; + uint8_t type; +} TSParseAction; + +typedef struct { + uint16_t lex_state; + uint16_t external_lex_state; +} TSLexMode; + +typedef struct { + uint16_t lex_state; + uint16_t external_lex_state; + uint16_t reserved_word_set_id; +} TSLexerMode; + +typedef union { + TSParseAction action; + struct { + uint8_t count; + bool reusable; + } entry; +} TSParseActionEntry; + +typedef struct { + int32_t start; + int32_t end; +} TSCharacterRange; + +struct TSLanguage { + uint32_t abi_version; + uint32_t symbol_count; + uint32_t alias_count; + uint32_t token_count; + uint32_t external_token_count; + uint32_t state_count; + uint32_t large_state_count; + uint32_t production_id_count; + uint32_t field_count; + uint16_t max_alias_sequence_length; + const uint16_t *parse_table; + const uint16_t *small_parse_table; + const uint32_t *small_parse_table_map; + const TSParseActionEntry *parse_actions; + const char * const *symbol_names; + const char * const *field_names; + const TSMapSlice *field_map_slices; + const TSFieldMapEntry *field_map_entries; + const TSSymbolMetadata *symbol_metadata; + const TSSymbol *public_symbol_map; + const uint16_t *alias_map; + const TSSymbol *alias_sequences; + const TSLexerMode *lex_modes; + bool (*lex_fn)(TSLexer *, TSStateId); + bool (*keyword_lex_fn)(TSLexer *, TSStateId); + TSSymbol keyword_capture_token; + struct { + const bool *states; + const TSSymbol *symbol_map; + void *(*create)(void); + void (*destroy)(void *); + bool (*scan)(void *, TSLexer *, const bool *symbol_whitelist); + unsigned (*serialize)(void *, char *); + void (*deserialize)(void *, const char *, unsigned); + } external_scanner; + const TSStateId *primary_state_ids; + const char *name; + const TSSymbol *reserved_words; + uint16_t max_reserved_word_set_size; + uint32_t supertype_count; + const TSSymbol *supertype_symbols; + const TSMapSlice *supertype_map_slices; + const TSSymbol *supertype_map_entries; + TSLanguageMetadata metadata; +}; + +static inline bool set_contains(const TSCharacterRange *ranges, uint32_t len, int32_t lookahead) { + uint32_t index = 0; + uint32_t size = len - index; + while (size > 1) { + uint32_t half_size = size / 2; + uint32_t mid_index = index + half_size; + const TSCharacterRange *range = &ranges[mid_index]; + if (lookahead >= range->start && lookahead <= range->end) { + return true; + } else if (lookahead > range->end) { + index = mid_index; + } + size -= half_size; + } + const TSCharacterRange *range = &ranges[index]; + return (lookahead >= range->start && lookahead <= range->end); +} + +/* + * Lexer Macros + */ + +#ifdef _MSC_VER +#define UNUSED __pragma(warning(suppress : 4101)) +#else +#define UNUSED __attribute__((unused)) +#endif + +#define START_LEXER() \ + bool result = false; \ + bool skip = false; \ + UNUSED \ + bool eof = false; \ + int32_t lookahead; \ + goto start; \ + next_state: \ + lexer->advance(lexer, skip); \ + start: \ + skip = false; \ + lookahead = lexer->lookahead; + +#define ADVANCE(state_value) \ + { \ + state = state_value; \ + goto next_state; \ + } + +#define ADVANCE_MAP(...) \ + { \ + static const uint16_t map[] = { __VA_ARGS__ }; \ + for (uint32_t i = 0; i < sizeof(map) / sizeof(map[0]); i += 2) { \ + if (map[i] == lookahead) { \ + state = map[i + 1]; \ + goto next_state; \ + } \ + } \ + } + +#define SKIP(state_value) \ + { \ + skip = true; \ + state = state_value; \ + goto next_state; \ + } + +#define ACCEPT_TOKEN(symbol_value) \ + result = true; \ + lexer->result_symbol = symbol_value; \ + lexer->mark_end(lexer); + +#define END_STATE() return result; + +/* + * Parse Table Macros + */ + +#define SMALL_STATE(id) ((id) - LARGE_STATE_COUNT) + +#define STATE(id) id + +#define ACTIONS(id) id + +#define SHIFT(state_value) \ + {{ \ + .shift = { \ + .type = TSParseActionTypeShift, \ + .state = (state_value) \ + } \ + }} + +#define SHIFT_REPEAT(state_value) \ + {{ \ + .shift = { \ + .type = TSParseActionTypeShift, \ + .state = (state_value), \ + .repetition = true \ + } \ + }} + +#define SHIFT_EXTRA() \ + {{ \ + .shift = { \ + .type = TSParseActionTypeShift, \ + .extra = true \ + } \ + }} + +#define REDUCE(symbol_name, children, precedence, prod_id) \ + {{ \ + .reduce = { \ + .type = TSParseActionTypeReduce, \ + .symbol = symbol_name, \ + .child_count = children, \ + .dynamic_precedence = precedence, \ + .production_id = prod_id \ + }, \ + }} + +#define RECOVER() \ + {{ \ + .type = TSParseActionTypeRecover \ + }} + +#define ACCEPT_INPUT() \ + {{ \ + .type = TSParseActionTypeAccept \ + }} + +#ifdef __cplusplus +} +#endif + +#endif // TREE_SITTER_PARSER_H_ diff --git a/Tests/AgentsCoreTests/AcquisitionCacheTests.swift b/Tests/AgentsCoreTests/AcquisitionCacheTests.swift new file mode 100644 index 0000000..e35639d --- /dev/null +++ b/Tests/AgentsCoreTests/AcquisitionCacheTests.swift @@ -0,0 +1,218 @@ +import Foundation +import StateTestSupport +import Testing + +@testable import AgentsCore + +@Suite struct AcquisitionCacheTests { + @Test func inspectionIsReadOnlyAndRootSelectionUsesTheSuppliedHome() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let cache = fixtureCache(root) + #expect(try cache.inspect().entries.isEmpty) + #expect(try cache.preview(.clean).candidates.isEmpty) + #expect(!FileManager.default.fileExists(atPath: cache.root.path)) + #expect(throws: AcquisitionCacheError.invalidAge) { try cache.preview(.prune(days: -1)) } + let env = RuntimeEnvironment( + projectDirectory: root, homeDirectory: root.appendingPathComponent("home"), + environment: ["AGENTS_CACHE_DIR": "custom"]) + #expect( + AcquisitionCache(environment: env).root.path == root.appendingPathComponent("custom").path) + var fallback = env + fallback.environment = [:] + #if os(macOS) + let suffix = "home/Library/Caches/agents" + #else + let suffix = "home/.cache/agents" + #endif + #expect( + AcquisitionCache(environment: fallback).root.path == root.appendingPathComponent(suffix).path) + } + + @Test func unsafeRootAndSymlinkHazardsNeverTouchExternalData() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let sentinel = root.appendingPathComponent("sentinel") + try Data("survive".utf8).write(to: sentinel) + var env = fixtureCache(root).environment + let protected = root.appendingPathComponent("protected/nested") + env.protectedAcquisitionPaths = [protected] + for invalid in [ + URL(fileURLWithPath: "/"), env.homeDirectory, root, + env.projectDirectory.appendingPathComponent(".agent/cache"), + root.appendingPathComponent("protected"), protected.appendingPathComponent("cache"), + ] { + env.acquisitionCacheRoot = invalid + #expect(throws: AcquisitionCacheError.self) { + try AcquisitionCache(environment: env).write( + Data("value".utf8), store: .http, key: key("a"), object: "response") + } + } + let unmarked = root.appendingPathComponent("foreign") + try FileManager.default.createDirectory(at: unmarked, withIntermediateDirectories: false) + try Data().write(to: unmarked.appendingPathComponent("foreign-file")) + env.acquisitionCacheRoot = unmarked + #expect(throws: AcquisitionCacheError.self) { try AcquisitionCache(environment: env).inspect() } + #expect(try FileManager.default.contentsOfDirectory(atPath: unmarked.path) == ["foreign-file"]) + + let cache = fixtureCache(root) + try cache.write(Data("value".utf8), store: .http, key: key("b"), object: "response") + let unauthorized = cache.root.appendingPathComponent("http/" + key("c")) + try FileManager.default.createSymbolicLink(at: unauthorized, withDestinationURL: sentinel) + let result = try cache.apply(cache.preview(.clean)) + #expect(result.removed.count == 1) + #expect(result.failures.map(\.path) == ["http/" + key("c")]) + #expect(try Data(contentsOf: sentinel) == Data("survive".utf8)) + #expect( + try FileManager.default.destinationOfSymbolicLink(atPath: unauthorized.path) == sentinel.path) + } + + @Test func pruneSkipsAReusedGroupAndCleanCountsOnlyActualRemovals() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let cache = fixtureCache(root) + let old = Date(timeIntervalSince1970: 1_000) + let now = old.addingTimeInterval(40 * 86_400) + for value in ["a", "b"] { + try cache.write(Data(value.utf8), store: .git, key: key(value), object: value, now: old) + } + try cache.write( + Data("response".utf8), store: .http, key: key("c"), object: "response", now: old) + try cache.rememberDeployedBytes(Data("deployed".utf8)) + let preview = try cache.preview(.prune(), now: now) + #expect(preview.candidates.count == 2) + #expect( + try cache.read(.git, key: key("a"), maximumBytes: 8, now: now) { $0.data } == Data("a".utf8)) + let pruned = try cache.apply(preview) + #expect(pruned.isComplete) + #expect(pruned.removed.map(\.object) == ["b"]) + #expect(pruned.skipped.map(\.object) == ["a"]) + #expect(pruned.reclaimedBytes == pruned.removed.first?.bytes) + #expect( + try cache.preview(.prune(days: 0), now: now.addingTimeInterval(1)).candidates.count == 1) + let inventory = try cache.inspect() + #expect(inventory.bytes(in: .git) > 1) + #expect(inventory.bytes(in: .http) > 8) + #expect(inventory.bytes(in: .deployed) > 8) + let cleaned = try cache.apply(cache.preview(.clean)) + #expect(cleaned.reclaimedBytes == inventory.totalBytes) + #expect(try cache.inspect().totalBytes == 0) + } + + @Test func rootAndPayloadReplacementInvalidateReviewedEvidence() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let cache = fixtureCache(root) + try cache.write(Data("one".utf8), store: .git, key: key("a"), object: "one") + let reviewed = try cache.preview(.clean) + let file = cache.root.appendingPathComponent("git/" + key("a") + "/bytes") + try Data("two".utf8).write(to: file) + let changed = try cache.apply(reviewed) + #expect(changed.skipped.count == 1) + #expect(changed.reclaimedBytes == 0) + try FileManager.default.moveItem(at: cache.root, to: root.appendingPathComponent("old-cache")) + try cache.write(Data("three".utf8), store: .git, key: key("b"), object: "three") + #expect(throws: AcquisitionCacheError.rootChanged) { try cache.apply(reviewed) } + #expect(try cache.inspect().entries.map(\.object) == ["three"]) + } + + @Test func deployedBytesAreRehashedAndColdMissesAreHarmless() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let cache = fixtureCache(root) + let bytes = Data("expected".utf8) + let digest = FileHash.sha256Hex(data: bytes) + #expect(try cache.verifiedDeployedBytes(sha256: digest) == nil) + try cache.rememberDeployedBytes(bytes) + #expect(try cache.verifiedDeployedBytes(sha256: digest) == bytes) + try Data("tampered".utf8).write( + to: cache.root.appendingPathComponent("deployed/" + digest + "/bytes")) + #expect(try cache.verifiedDeployedBytes(sha256: digest) == nil) + try cache.rememberDeployedBytes(bytes) + #expect(try cache.verifiedDeployedBytes(sha256: digest) == bytes) + } + + @Test func unwriteableEntryReportsPartialFailureAndItsTrashCanBeRetried() throws { + guard geteuid() != 0 else { return } + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let cache = fixtureCache(root) + try cache.write(Data("first".utf8), store: .git, key: key("a"), object: "one") + try cache.write(Data("second".utf8), store: .git, key: key("b"), object: "two") + let trash = cache.root.appendingPathComponent(".trash") + defer { makeDirectoriesWritable(root) } + + var blockedFirst = false + let result = try cache.apply( + cache.preview(.clean), + afterDetach: { + guard !blockedFirst else { return } + blockedFirst = true + let files = try FileManager.default.contentsOfDirectory(atPath: trash.path) + let entry = try #require(files.first { $0.hasSuffix(".entry") }) + try FileManager.default.setAttributes( + [.posixPermissions: 0o500], ofItemAtPath: trash.appendingPathComponent(entry).path) + }) + #expect(!result.isComplete) + #expect(result.removed.map(\.object) == ["two"]) + #expect(result.failures.map(\.path) == ["git/" + key("a")]) + let inventory = try cache.inspect() + let pending = try #require(inventory.entries.first) + #expect(pending.pendingDisposal) + #expect(pending.bytes > 0) + let detached = cache.root.appendingPathComponent(".trash/" + pending.id + ".entry") + try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: detached.path) + let retry = try cache.apply(cache.preview(.clean)) + #expect(retry.isComplete) + #expect(retry.reclaimedBytes == inventory.totalBytes) + } + + @Test func independentReadersAndPublishersCoordinateWithCleanAndRecoverDetachedTrash() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let cache = fixtureCache(root) + let first = try stateTestProcess(root: root, arguments: ["acquisition-publish"]) + let second = try stateTestProcess(root: root, arguments: ["acquisition-publish"]) + defer { + terminateProcess(first) + terminateProcess(second) + } + try finishProcesses([first, second], root: root) + #expect(try cache.inspect().entries.count == 1) + try cache.write(Data("other".utf8), store: .http, key: key("b"), object: "response") + + let reader = try stateTestProcess(root: root, arguments: ["acquisition-read", "leased"]) + defer { terminateProcess(reader) } + try ProcessWait.marker(root.appendingPathComponent("ready"), child: reader, root: root) + try ProcessWait.stopped(reader, root: root, timeout: 10) + let partial = try cache.apply(cache.preview(.clean)) + #expect(partial.removed.map(\.store) == [.http]) + #expect(partial.failures.map(\.reason) == [AcquisitionCacheError.busy.localizedDescription]) + #expect(kill(reader.processIdentifier, SIGCONT) == 0) + try finishProcesses([reader], root: root) + try FileManager.default.removeItem(at: root.appendingPathComponent("ready")) + + let cleaner = try stateTestProcess(root: root, arguments: ["acquisition-clean", "detached"]) + defer { terminateProcess(cleaner) } + try ProcessWait.marker(root.appendingPathComponent("ready"), child: cleaner, root: root) + try ProcessWait.stopped(cleaner, root: root, timeout: 10) + try ProcessWait.terminate(cleaner) + let interrupted = try cache.inspect() + #expect(interrupted.entries.count == 1) + #expect(interrupted.entries.first?.pendingDisposal == true) + let retry = try cache.apply(cache.preview(.prune(days: 0))) + #expect(retry.reclaimedBytes == interrupted.totalBytes) + #expect(retry.isComplete) + #expect(try cache.inspect().entries.isEmpty) + } + + private func fixtureCache(_ root: URL) -> AcquisitionCache { + AcquisitionCache( + environment: RuntimeEnvironment( + projectDirectory: root.appendingPathComponent("project"), + homeDirectory: root.appendingPathComponent("home"), environment: [:], + acquisitionCacheRoot: root.appendingPathComponent("shared/cache"))) + } + + private func key(_ letter: String) -> String { String(repeating: letter, count: 64) } +} diff --git a/Tests/AgentsCoreTests/AgentClientObservationTests.swift b/Tests/AgentsCoreTests/AgentClientObservationTests.swift new file mode 100644 index 0000000..b5561e1 --- /dev/null +++ b/Tests/AgentsCoreTests/AgentClientObservationTests.swift @@ -0,0 +1,72 @@ +import AgentsCore +import CPlatform +import Foundation +import Testing + +struct AgentClientObservationTests { + @Test func metadataReadsOrdinarySymlinksAndKeepsVersionAndBuildSeparate() throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + let bundle = root.appendingPathComponent("Editor.app") + let metadata = bundle.appendingPathComponent("Contents/Info.plist") + try FileManager.default.createDirectory( + at: metadata.deletingLastPathComponent(), withIntermediateDirectories: true) + let source = root.appendingPathComponent("metadata.plist") + let bytes = try PropertyListSerialization.data( + fromPropertyList: [ + "CFBundleIdentifier": "fixture.editor", "CFBundleShortVersionString": "3.27-preview", + "CFBundleVersion": "42", + ], format: .xml, options: 0) + try bytes.write(to: source) + try FileManager.default.createSymbolicLink(at: metadata, withDestinationURL: source) + let (state, version) = AgentClientObservation.bundleVersion( + at: bundle, identifier: "fixture.editor") + #expect(state == .present) + #expect(version.version == "3.27-preview") + #expect(version.build == "42") + #expect(version.unknown == nil) + #expect(version.metadata == metadata) + #expect( + AgentClientObservation.bundleVersion(at: bundle, identifier: "another.editor").0 == .invalid) + } + + @Test func metadataFailuresAreBoundedAndDoNotReadNonRegularObjects() throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + let missing = root.appendingPathComponent("missing") + #expect(throws: ClientVersionUnknownError.self) { try AgentClientObservation.metadata(missing) } + let oversized = root.appendingPathComponent("oversized") + try Data(repeating: 1, count: 1_048_577).write(to: oversized) + do { + _ = try AgentClientObservation.metadata(oversized) + Issue.record("oversized metadata was admitted") + } catch let error as ClientVersionUnknownError { #expect(error.reason == .oversizedMetadata) } + let pipe = root.appendingPathComponent("pipe") + #expect(mkfifo(pipe.path, 0o600) == 0) + do { + _ = try AgentClientObservation.metadata(pipe) + Issue.record("FIFO metadata was admitted") + } catch let error as ClientVersionUnknownError { #expect(error.reason == .nonRegularMetadata) } + let bundle = root.appendingPathComponent("Broken.app") + let plist = bundle.appendingPathComponent("Contents/Info.plist") + try FileManager.default.createDirectory( + at: plist.deletingLastPathComponent(), withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink(at: plist, withDestinationURL: pipe) + let nonRegular = AgentClientObservation.bundleVersion(at: bundle, identifier: "fixture") + #expect(nonRegular.0 == .invalid) + #expect(nonRegular.1.unknown == .nonRegularMetadata) + try FileManager.default.removeItem(at: plist) + try Data("invalid plist".utf8).write(to: plist) + #expect( + AgentClientObservation.bundleVersion(at: bundle, identifier: "fixture").1.unknown + == .malformedMetadata) + try PropertyListSerialization.data( + fromPropertyList: ["CFBundleIdentifier": "fixture", "CFBundleVersion": "11"], + format: .binary, options: 0 + ).write(to: plist) + let observation = AgentClientObservation.bundleVersion(at: bundle, identifier: "fixture").1 + #expect(observation.unknown == .missingVersion) + #expect(observation.build == "11") + } +} diff --git a/Tests/AgentsCoreTests/CachePublicationTests.swift b/Tests/AgentsCoreTests/CachePublicationTests.swift index fed75c4..593ab2d 100644 --- a/Tests/AgentsCoreTests/CachePublicationTests.swift +++ b/Tests/AgentsCoreTests/CachePublicationTests.swift @@ -1,5 +1,7 @@ -import Darwin +import AgentsManifest +import CPlatform import Foundation +import StateTestSupport import Testing @testable import AgentsCore @@ -9,21 +11,27 @@ struct CachePublicationTests { @Test( arguments: ["cache-content", "cache-git"], [ - "stage.0.copy.directory", "stage.0.copy.entry", "stage.0.verified", "replace.0.renamed", - "journal.committed.renamed", + TransactionCheckpoint.copy( + 0, .init(path: TransactionSlot.staged.name(0), step: .directoryCreated) + ).name, + TransactionCheckpoint.copy( + 0, .init(path: TransactionSlot.staged.name(0) + "/SKILL.md", step: .entryCopied) + ).name, TransactionCheckpoint.progress(0, .ready).name, + TransactionCheckpoint.publication(0, .created).name, + TransactionCheckpoint.persisted(.committed, .terminal, .renamed).name, ]) func interruptedTreePublicationRecoversAndRetries(_ kind: String, _ point: String) throws { let fixture = try CacheFixture(git: kind == "cache-git") try interrupt(fixture, kind: kind, point: point) - if point.hasPrefix("stage.") { - #expect(!FileManager.default.fileExists(atPath: fixture.destination.path)) - } else { + let committed = point == TransactionCheckpoint.persisted(.committed, .terminal, .renamed).name + if committed || point == TransactionCheckpoint.publication(0, .created).name { #expect(try FileHash.folderHash(fixture.destination) == fixture.hash) + } else { + #expect(try FileSnapshot.read(at: fixture.destination) == nil) } #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { - try fixture.store.loadResolved() + try fixture.store.withLock {} } - let committed = point.hasPrefix("journal.committed") #expect(FileManager.default.fileExists(atPath: fixture.destination.path) == committed) #expect(try Data(contentsOf: fixture.store.resolvedURL) == fixture.lockBytes) try fixture.publish() @@ -37,13 +45,16 @@ struct CachePublicationTests { } @Test(arguments: [ - "stage.0.written", "stage.0.verified", "replace.0.renamed", "journal.committed.renamed", + TransactionCheckpoint.stage(0, .constructed).name, + TransactionCheckpoint.progress(0, .ready).name, + TransactionCheckpoint.publication(0, .created).name, + TransactionCheckpoint.persisted(.committed, .terminal, .renamed).name, ]) func interruptedArtifactBytesAreNeverPublishedPartially(_ point: String) throws { let fixture = try CacheFixture() try interrupt(fixture, kind: "cache-bytes", point: point) #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { - try fixture.store.loadResolved() + try fixture.store.withLock {} } let cache = SourceCache(store: fixture.store) let payload = try Data(contentsOf: fixture.root.appendingPathComponent("payload")) @@ -54,13 +65,16 @@ struct CachePublicationTests { #expect(try Data(contentsOf: fixture.store.resolvedURL) == fixture.lockBytes) } - @Test(arguments: ["prepare.0.directory", "prepare.0.ready"]) - func interruptedExtractionCleansJournalOwnedScratch(_ point: String) throws { + @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(!FileManager.default.fileExists(atPath: fixture.destination.path)) + #expect(try FileSnapshot.read(at: fixture.destination) == nil) #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { - try fixture.store.loadResolved() + try fixture.store.withLock {} } #expect( try FileManager.default.contentsOfDirectory( @@ -73,23 +87,33 @@ struct CachePublicationTests { @Test func verifiesPrivateCopyBeforePublication() throws { let fixture = try CacheFixture() + let beforeState = try FileSnapshot.read(at: fixture.store.resolvedURL) + var tampered = false let cache = SourceCache(store: fixture.store) { step in - if step == "stage.0.copy.entry" { + if step == TransactionCheckpoint.stage(0, .constructed).name { let parent = fixture.destination.deletingLastPathComponent() for name in try FileManager.default.contentsOfDirectory(atPath: parent.path) - where name.hasSuffix(".new") { - try Data("tampered".utf8).write(to: parent.appendingPathComponent(name + "/injected")) + where name.hasPrefix(".agents-") { + try Data("tampered".utf8).write( + to: parent.appendingPathComponent(name).appendingPathComponent( + TransactionSlot.staged.name(0) + "/injected")) + tampered = true } } } - #expect(throws: CoreError.self) { + #expect { try fixture.store.withLock { try cache.materializeArtifact( fixture.root.appendingPathComponent("new"), digest: fixture.digest, hash: "sha256:" + fixture.hash) } + } throws: { error in + guard case CoreError.invalidState = error else { return false } + return true } - #expect(!FileManager.default.fileExists(atPath: fixture.destination.path)) + #expect(tampered) + #expect(try FileSnapshot.read(at: fixture.destination) == nil) + #expect(try FileSnapshot.read(at: fixture.store.resolvedURL) == beforeState) #expect( try FileManager.default.contentsOfDirectory( atPath: fixture.destination.deletingLastPathComponent().path @@ -99,44 +123,65 @@ struct CachePublicationTests { @Test func verifiesPrivateBytesBeforePublication() throws { let fixture = try CacheFixture() + let beforeState = try FileSnapshot.read(at: fixture.store.resolvedURL) let cache = SourceCache(store: fixture.store) { step in - if step == "stage.0.written" { + if step == TransactionCheckpoint.stage(0, .constructed).name { let parent = fixture.store.cacheDirectory.appendingPathComponent("artifacts") for name in try FileManager.default.contentsOfDirectory(atPath: parent.path) - where name.hasSuffix(".new") { - try Data("tampered".utf8).write(to: parent.appendingPathComponent(name)) + where name.hasPrefix(".agents-") { + try Data("tampered".utf8).write( + to: parent.appendingPathComponent(name).appendingPathComponent( + TransactionSlot.staged.name(0))) } } } - #expect(throws: CoreError.self) { + #expect(throws: CoreError.invalidState("staged content bytes mismatch")) { try fixture.store.withLock { try cache.storeArtifact( Data(contentsOf: fixture.root.appendingPathComponent("payload")), digest: fixture.digest) } } let final = try cache.artifactURL(digest: fixture.digest) - #expect(!FileManager.default.fileExists(atPath: final.path)) + #expect(try FileSnapshot.read(at: final) == nil) + #expect(try FileSnapshot.read(at: fixture.store.resolvedURL) == beforeState) #expect( try FileManager.default.contentsOfDirectory(atPath: final.deletingLastPathComponent().path) .isEmpty) } - private func interrupt(_ fixture: CacheFixture, kind: String, point: String) throws { - let child = try stateTestProcess(root: fixture.root, arguments: [kind, point]) - defer { - if child.isRunning { - kill(child.processIdentifier, SIGKILL) - child.waitUntilExit() + @Test(arguments: [false, true]) + func concurrentCacheCreatorKeepsItsBytesAndInode(_ equalBytes: Bool) throws { + let fixture = try CacheFixture() + let beforeState = try FileSnapshot.read(at: fixture.store.resolvedURL) + let payload = try Data(contentsOf: fixture.root.appendingPathComponent("payload")) + let final = try SourceCache(store: fixture.store).artifactURL(digest: fixture.digest) + var external: FileSnapshot? + let cache = SourceCache(store: fixture.store) { step in + if step == TransactionCheckpoint.publication(0, .validated).name { + try (equalBytes ? payload : Data("external cache bytes".utf8)).write(to: final) + external = try FileSnapshot.read(at: final) } } - let marker = fixture.root.appendingPathComponent("ready") - let deadline = Date().addingTimeInterval(10) - while !FileManager.default.fileExists(atPath: marker.path), child.isRunning, Date() < deadline { - Thread.sleep(forTimeInterval: 0.01) + #expect { + try fixture.store.withLock { try cache.storeArtifact(payload, digest: fixture.digest) } + } throws: { error in + guard case CoreError.invalidState = error else { return false } + return true } - try #require(FileManager.default.fileExists(atPath: marker.path)) - kill(child.processIdentifier, SIGKILL) - child.waitUntilExit() + #expect(external != nil) + #expect(try FileSnapshot.read(at: final) == external) + #expect(try FileSnapshot.read(at: fixture.store.resolvedURL) == beforeState) + #expect( + try FileManager.default.contentsOfDirectory(atPath: final.deletingLastPathComponent().path) + == [final.lastPathComponent]) + } + + private func interrupt(_ fixture: CacheFixture, kind: String, point: String) throws { + let child = try stateTestProcess(root: fixture.root, arguments: [kind, point]) + defer { terminateProcess(child) } + let marker = fixture.root.appendingPathComponent("ready") + try ProcessWait.marker(marker, child: child, root: fixture.root) + terminateProcess(child) } } @@ -191,9 +236,18 @@ private final class CacheFixture { destination = store.cacheDirectory.appendingPathComponent( "artifact-content/" + digest.dropFirst(7)) } - try store.save( - declaration: Declaration(), - resolved: ResolvedState(sources: [sourceID: source], skills: ["demo": skill])) + var ledger = ResolvedLedger() + ledger.sources["source"] = LedgerSource( + kind: source.kind, + transport: source.kind == .wellKnown ? sourceID : source.url, + location: source.kind == .local + ? .init(kind: .absolute, path: String(sourceID.dropFirst(6))) : nil, + revision: revision ?? digest) + ledger.resources["resource"] = LedgerResource( + kind: revision == nil ? .artifact : .git, + source: "source", path: ".", hash: skill.hash!, + entries: [.init(path: ".", kind: .directory, executable: false)], artifact: skill.artifact) + try store.save(declaration: Declaration(), ledger: ledger) lockBytes = try Data(contentsOf: store.resolvedURL) } catch { removeTemporaryDirectory(root) diff --git a/Tests/AgentsCoreTests/CheckpointUniquenessTests.swift b/Tests/AgentsCoreTests/CheckpointUniquenessTests.swift new file mode 100644 index 0000000..7c0c3ae --- /dev/null +++ b/Tests/AgentsCoreTests/CheckpointUniquenessTests.swift @@ -0,0 +1,133 @@ +import AgentsManifest +import Foundation +import StateTestSupport +import Testing + +@testable import AgentsCore + +/// The recorder fails on a repeated name, so repeated work in one process must name each +/// repetition. Every scenario completes under the recorder and can stop at a second repetition. +@Suite("Recorded checkpoint uniqueness") +struct CheckpointUniquenessTests { + @Test func eachStaleWatchReferenceHasItsOwnPoint() throws { + let fixture = try WatchGitFixture() + try fixture.watch.add("source", environment: fixture.environment) + var stale = [try fixture.head()] + try fixture.rewrite("second") + try fixture.watch.seen("source", environment: fixture.environment) + stale.append(try fixture.head()) + try fixture.rewrite("third") + try fixture.watch.seen("source", environment: fixture.environment) + let current = try fixture.head() + func restoreStaleReferences() throws { + for revision in stale { + try fixture.mirrorGit(["update-ref", "refs/agents-watch/" + revision, revision]) + } + try Data().write(to: fixture.store.directory.appendingPathComponent("watch-refs.pending")) + } + try restoreStaleReferences() + try fixture.recordCompletely("watch-recover") + #expect(try fixture.watchRefs() == [current]) + try restoreStaleReferences() + let second = "watch.references.0.1.deleted" + try fixture.kill( + try stateTestProcess(root: fixture.root, arguments: ["watch-recover", second]), at: second) + #expect(try fixture.recoveredWatch().sources[fixture.id]?.seen == .revision(current)) + #expect(try fixture.watchRefs() == [current]) + } + + @Test func eachAbandonedGitLockHasItsOwnPoint() throws { + let fixture = try WatchGitFixture() + try fixture.watch.add("source", environment: fixture.environment) + let locks = ["config.lock", "objects/pack/abandoned.lock"].map { + fixture.mirror.appendingPathComponent($0) + } + func abandonLocks() throws { + for lock in locks { try Data("abandoned".utf8).write(to: lock) } + } + try abandonLocks() + try fixture.recordCompletely("watch-recover") + try abandonLocks() + let second = "watch.git-lock.0.1.unlinked" + try fixture.kill( + try stateTestProcess(root: fixture.root, arguments: ["watch-recover", second]), at: second) + for lock in locks { #expect(!FileManager.default.fileExists(atPath: lock.path)) } + _ = try fixture.recoveredWatch() + #expect( + !FileManager.default.fileExists( + atPath: fixture.store.directory.appendingPathComponent("watch-refs.pending").path)) + } + + /// Payload, content and watch transactions write the same transaction names; the two nested + /// cache transactions are scoped by artifact and role. + @Test func nestedArtifactTransactionsHaveScopedPoints() throws { + let ready = TransactionCheckpoint.progress(0, .ready).name + let complete = try ArtifactWatchFixture() + let trace = try complete.record("never") + for point in [ + "watch.artifact.0.payload.0." + ready, "watch.artifact.0.content." + ready, ready, + ] { + #expect(trace.contains(point)) + } + #expect(try complete.store.loadWatch().sources.count == 1) + + let interrupted = try ArtifactWatchFixture() + let content = "watch.artifact.0.content." + ready + let child = try stateTestProcess( + root: interrupted.root, arguments: ["watch-add-artifact", content]) + defer { terminateProcess(child) } + try ProcessWait.marker( + interrupted.root.appendingPathComponent("ready"), child: child, root: interrupted.root) + try ProcessWait.stopped(child, root: interrupted.root) + terminateProcess(child) + #expect(throws: CoreError.transactionRecovered(interrupted.store.directory.path)) { + try interrupted.store.withLock {} + } + #expect(try interrupted.store.loadWatch().sources.isEmpty) + let contents = interrupted.store.cacheDirectory.appendingPathComponent("artifact-content") + #expect((try? FileManager.default.contentsOfDirectory(atPath: contents.path)) ?? [] == []) + } +} + +private final class ArtifactWatchFixture { + let root: URL + let store: StateStore + + init() throws { + root = try temporaryDirectory() + store = StateStore( + scope: .project, + environment: RuntimeEnvironment( + projectDirectory: root, homeDirectory: root.appendingPathComponent("home"), + environment: [:])) + do { + try store.save(declaration: Declaration(), resolved: ResolvedState()) + } catch { + removeTemporaryDirectory(root) + throw error + } + } + + deinit { removeTemporaryDirectory(root) } + + func record(_ point: String) throws -> [String] { + let child = try stateTestProcess(root: root, arguments: ["watch-add-artifact", point]) + defer { terminateProcess(child) } + try ProcessWait.exit(child, root: root) + #expect(child.terminationStatus == 0) + return try String( + contentsOf: root.appendingPathComponent("checkpoint-\(child.processIdentifier).log"), + encoding: .utf8 + ).split(separator: "\n").map(String.init) + } +} + +extension WatchGitFixture { + /// Runs `command` to completion under the recorder, which fails on any repeated name. + fileprivate func recordCompletely(_ command: String) throws { + let child = try stateTestProcess(root: root, arguments: [command, "never"]) + defer { terminateProcess(child) } + try ProcessWait.exit(child, root: root) + #expect(child.terminationStatus == 0) + } +} diff --git a/Tests/AgentsCoreTests/ClientBackupTests.swift b/Tests/AgentsCoreTests/ClientBackupTests.swift new file mode 100644 index 0000000..0dd61e4 --- /dev/null +++ b/Tests/AgentsCoreTests/ClientBackupTests.swift @@ -0,0 +1,847 @@ +import CPlatform +import Foundation +import Testing + +@testable import AgentsCore + +@Suite struct ClientBackupTests { + @Test(arguments: [true, false]) + func codexRestoresWALStateAndKeepsUnrelatedSessions(sourceSetsSQLiteHome: Bool) throws { + let fixture = try Fixture() + let sourceHome = try fixture.directory("source") + let backupFolder = try fixture.directory("backups") + let oldProject = try fixture.directory("work/old") + let newProject = try fixture.directory("work/new") + let sourceClient = try fixture.directory("source/codex-config") + let sourceDB = try fixture.directory("source/codex-db") + let source = fixture.environment( + sourceHome, + [ + "CODEX_HOME": sourceClient.path, "CODEX_SQLITE_HOME": sourceDB.path, + ]) + let rolloutName = "sessions/2026/11/25/rollout-thread.jsonl" + let sourceRollout = sourceClient.appendingPathComponent(rolloutName) + let event = try fixture.json([ + "type": "session_meta", + "payload": [ + "cwd": oldProject.path, "id": "thread", + "runtime_workspace_roots": [oldProject.path], + ], + ]) + try fixture.put(sourceRollout, event + "\n{\"type\":\"response_item\"}\n") + try fixture.put( + sourceClient, "archived_sessions/archived.jsonl", "{\"type\":\"session_meta\"}\n") + try fixture.put(sourceClient, "attachments/thread/data.bin", "attachment") + try fixture.put( + sourceClient, "session_index.jsonl", "{\"id\":\"thread\",\"thread_name\":\"restored\"}\n") + try fixture.put(sourceClient, "auth.json", "{\"token\":\"fixture-secret\"}") + let archivedConfig = + sourceSetsSQLiteHome + ? "# keep this comment\nsqlite_home = \"\(sourceDB.path)\"\n" + : "# keep this comment\n[features]\n" + try fixture.put(sourceClient, "config.toml", archivedConfig) + try fixture.put(oldProject, ".codex/config.toml", "model = \"fixture\"\n") + try fixture.put(oldProject, ".git/irrelevant", "exclude") + try fixture.put(oldProject, "work.txt", "exclude") + + let state = try createCodexDB(sourceDB, wal: true) + try state.execute( + "INSERT INTO threads VALUES (?,?,?)", + [ + .text("thread"), .text(oldProject.path), .text(sourceRollout.path), + ]) + try state.execute("INSERT INTO thread_attachments VALUES ('thread','one','attachment')") + try state.execute("INSERT INTO thread_read_receipts VALUES ('thread',42)") + let projection = sourceDB.appendingPathComponent("thread_history_1.sqlite") + try Data().write(to: projection) + do { + let history = try BackupSQL(projection, writable: true) + try history.execute( + """ + CREATE TABLE thread_history_projection_state ( + thread_id TEXT PRIMARY KEY, next_rollout_byte_offset INTEGER + ) + """) + try history.execute( + "INSERT INTO thread_history_projection_state VALUES ('thread',?)", + [ + .integer(Int64(event.utf8.count + 1)) + ]) + } + #expect( + FileManager.default.fileExists( + atPath: sourceDB.appendingPathComponent("state_5.sqlite-wal").path)) + let package = try ClientBackups.create( + client: .codex, projects: [oldProject], to: backupFolder, environment: source) + #expect(try ClientBackups.inspect(package).projects == [oldProject.path]) + let mode = + try FileManager.default.attributesOfItem(atPath: package.path)[.posixPermissions] as? Int + #expect(mode == 0o600) + try fixture.remove(sourceHome) + try fixture.remove(oldProject) + withExtendedLifetime(state) {} + + let home = try fixture.directory("destination") + let client = try fixture.directory("destination/.codex") + let database = sourceSetsSQLiteHome ? client : try fixture.directory("destination/custom-db") + if !sourceSetsSQLiteHome { + try fixture.put(client, "config.toml", "sqlite_home = \"\(database.path)\"\n") + } + let destination = fixture.environment(home) + let existing = try createCodexDB(database) + try existing.execute( + "INSERT INTO threads VALUES ('unrelated','/elsewhere','/elsewhere/rollout')") + try existing.execute("INSERT INTO thread_attachments VALUES ('unrelated','other','keep')") + try fixture.put(client, "session_index.jsonl", "{\"id\":\"unrelated\"}\n") + let preview = try ClientBackups.preview( + package, projects: [oldProject.path: newProject], environment: destination) + #expect( + preview.files.contains { + $0.path == database.appendingPathComponent("state_5.sqlite").path && $0.kind == .replace + }) + #expect(!preview.files.contains { $0.path.contains("fixture-secret") }) + #expect(!preview.files.contains { $0.path.hasSuffix("work.txt") || $0.path.contains("/.git/") }) + try ClientBackups.restore(preview) + let newRollout = client.appendingPathComponent(rolloutName) + let restoredRecord = try fixture.read(newRollout) + #expect(restoredRecord.contains(newProject.path)) + #expect(!restoredRecord.contains(oldProject.path)) + #expect(try fixture.read(client, "attachments/thread/data.bin") == "attachment") + #expect(try fixture.read(client, "auth.json").contains("fixture-secret")) + let restoredConfig = try fixture.read(client, "config.toml") + let expectedConfig = + sourceSetsSQLiteHome + ? "# keep this comment\nsqlite_home = \"\(database.path)\"\n" + : "sqlite_home = \"\(database.path)\"\n" + archivedConfig + #expect(restoredConfig == expectedConfig) + let effective = try BackupRoots(.codex, environment: destination, projects: [:]) + #expect(effective.database.path == database.path) + do { + let history = try BackupSQL(database.appendingPathComponent("thread_history_1.sqlite")) + let newMeta = try #require(try fixture.read(newRollout).split(separator: "\n").first) + try history.rows("SELECT next_rollout_byte_offset FROM thread_history_projection_state") { + row in + let offset = try BackupSQL.integer(row, 0) + #expect(offset == Int64(newMeta.utf8.count + 1)) + } + } + #expect(try fixture.read(client, "session_index.jsonl").contains("unrelated")) + #expect(try fixture.read(newProject, ".codex/config.toml") == "model = \"fixture\"\n") + do { + let restored = try BackupSQL( + database.appendingPathComponent("state_5.sqlite"), writable: true) + var roots: [String: [String]] = [:] + try restored.rows("SELECT id,cwd,rollout_path FROM threads") { row in + roots[try BackupSQL.text(row, 0)] = [ + try BackupSQL.text(row, 1), try BackupSQL.text(row, 2), + ] + } + #expect(roots["thread"] == [newProject.path, newRollout.path]) + #expect(roots["unrelated"] == ["/elsewhere", "/elsewhere/rollout"]) + var attachments: [String] = [] + try restored.rows("SELECT content FROM thread_attachments ORDER BY content") { + attachments.append(try BackupSQL.text($0, 0)) + } + #expect(attachments == ["attachment", "keep"]) + try restored.execute("UPDATE thread_read_receipts SET turn=43 WHERE thread_id='thread'") + } + try fixture.append(newRollout, "{\"type\":\"response_item\",\"turn\":3}\n") + #expect(try fixture.read(newRollout).contains("\"turn\":3")) + try fixture.put(newProject, ".codex/config.toml", "model = \"updated\"\n") + #expect(try fixture.read(newProject, ".codex/config.toml").contains("updated")) + } + + @Test( + .enabled(if: BackupZstd.executable(path: ProcessInfo.processInfo.environment["PATH"]) != nil)) + func codexRelocatesCompressedRolloutsWithoutChangingPackageBytes() throws { + let fixture = try Fixture() + let source = try fixture.directory("source") + let client = try fixture.directory("source/.codex") + let destination = try fixture.directory("destination") + let project = try fixture.directory("project") + let moved = try fixture.directory("moved") + let backups = try fixture.directory("packages") + let rollout = "archived_sessions/rollout-thread.jsonl.zst" + let text = source.appendingPathComponent("original.jsonl") + let original = + try fixture.json([ + "type": "session_meta", "payload": ["cwd": project.path, "id": "thread"], + ]) + "\n" + try fixture.put(text, original) + let available = BackupZstd.executable(path: ProcessInfo.processInfo.environment["PATH"]) + let tool = try #require(available) + let archiveFolder = try fixture.directory("source/.codex/archived_sessions") + try BackupIO.write("rollout-thread.jsonl.zst", in: DirectoryHandle(at: archiveFolder)) { + try BackupZstd.transcode(text, into: $0, using: tool, decode: false) + } + let compressedURL = client.appendingPathComponent(rollout) + let compressed = try Data(contentsOf: compressedURL) + do { + let db = try createCodexDB(client) + try db.execute( + "INSERT INTO threads VALUES (?,?,?)", + [ + .text("thread"), .text(project.path), .text(compressedURL.path), + ]) + } + let package = try ClientBackups.create( + client: .codex, projects: [project], to: backups, environment: fixture.environment(source)) + try fixture.remove(source) + let archive = try BackupArchive(reading: package) + let archived = try #require(archive.manifest.entries.first { $0.path == rollout }) + var bytes = Data() + try archive.read(archived) { bytes.append($0) } + #expect(compressed == bytes) + let preview = try ClientBackups.preview( + package, projects: [project.path: moved], environment: fixture.environment(destination)) + try ClientBackups.restore(preview) + let restored = destination.appendingPathComponent(".codex/" + rollout) + try BackupIO.write("decoded.jsonl", in: DirectoryHandle(at: fixture.root)) { + try BackupZstd.transcode(restored, into: $0, using: tool, decode: true) + } + let relocated = try fixture.read(fixture.root, "decoded.jsonl") + #expect(relocated.contains(moved.path) && !relocated.contains(project.path)) + let db = try BackupSQL(destination.appendingPathComponent(".codex/state_5.sqlite")) + try db.rows("SELECT cwd,rollout_path FROM threads WHERE id='thread'") { row in + let cwd = try BackupSQL.text(row, 0) + let path = try BackupSQL.text(row, 1) + #expect(cwd == moved.path && path == restored.path) + } + } + + @Test func claudeAndGeminiProduceIndependentPackagesAndRemapNativeIndexes() throws { + let fixture = try Fixture() + let source = try fixture.directory("source") + let output = try fixture.directory("packages") + let oldProject = try fixture.directory("projects/original") + let newProject = try fixture.directory("projects/relocated") + let otherProject = try fixture.directory("projects/other") + let sourceClaude = try fixture.directory("source/claude-profile") + let sourceGeminiHome = try fixture.directory("source/gemini-home") + let sourceGemini = try fixture.directory("source/gemini-home/.gemini") + let originalKey = fixture.claudeKey(oldProject) + let localKey = fixture.claudeKey(newProject) + let sessionFolder = "projects/\(originalKey)" + let originalSession = sourceClaude.appendingPathComponent(sessionFolder + "/thread.jsonl") + try fixture.put(originalSession, fixture.json(["cwd": oldProject.path, "type": "user"]) + "\n") + try fixture.put( + sourceClaude, sessionFolder + "/thread/subagents/agent.jsonl", "{\"type\":\"assistant\"}\n") + try fixture.put(sourceClaude, sessionFolder + "/thread/tool-results/result.txt", "tool output") + try fixture.put( + sourceClaude, sessionFolder + "/sessions-index.json", + fixture.json([ + "version": 1, "entries": [["sessionId": "thread", "fullPath": originalSession.path]], + ])) + try fixture.put( + sourceClaude, ".claude.json", + fixture.json([ + "projects": [oldProject.path: ["mcpServers": ["test": ["command": "fixture"]]]] + ])) + try fixture.put(sourceClaude, "settings.json", "{\"theme\":\"dark\"}") + try fixture.put(oldProject, ".claude/hooks/run.sh", "#!/bin/sh\nexit 0\n", mode: 0o700) + try fixture.put(oldProject, ".claude/settings.local.json", "{\"model\":\"custom\"}") + try fixture.put(sourceGemini, "tmp/original/.project_root", oldProject.path) + try fixture.put( + sourceGemini, "tmp/original/chats/session-fixture.json", + fixture.json([ + "sessionId": "gemini", "projectHash": FileHash.sha256Hex(data: Data(oldProject.path.utf8)), + "messages": [["type": "user", "content": "hello"]], + ])) + try fixture.put(sourceGemini, "tmp/original/cache/download", "exclude") + try fixture.put(sourceGemini, "tmp/other/.project_root", otherProject.path) + try fixture.put(sourceGemini, "tmp/other/chats/second.json", "{\"messages\":[]}") + try fixture.put( + sourceGemini, "projects.json", + fixture.json([ + "projects": [oldProject.path: "original", otherProject.path: "other"] + ])) + try fixture.put(sourceGemini, "settings.json", "{\"model\":{\"name\":\"fixture\"}}") + try fixture.put( + oldProject, ".gemini/settings.json", "{\"context\":{\"fileName\":\"GEMINI.md\"}}") + let sourceEnvironment = fixture.environment( + source, + [ + "CLAUDE_CONFIG_DIR": sourceClaude.path, "GEMINI_CLI_HOME": sourceGeminiHome.path, + ]) + let claude = try ClientBackups.create( + client: .claudeCode, projects: [oldProject], to: output, environment: sourceEnvironment) + let gemini = try ClientBackups.create( + client: .geminiCLI, projects: [oldProject], to: output, environment: sourceEnvironment) + #expect(claude != gemini) + try fixture.remove(source) + try fixture.remove(oldProject) + + let home = try fixture.directory("destination") + let environment = fixture.environment(home) + let existingProject = try fixture.directory("projects/existing") + try fixture.put( + home, ".claude.json", + fixture.json([ + "projects": [existingProject.path: ["lastSessionId": "keep"]] + ])) + try fixture.put( + home, ".gemini/projects.json", + fixture.json([ + "projects": [newProject.path: "existing", existingProject.path: "keep"] + ])) + try fixture.put(home, ".gemini/tmp/existing/.project_root", newProject.path) + try fixture.put(home, ".gemini/tmp/existing/chats/keep.json", "{\"messages\":[]}") + let map = [oldProject.path: newProject] + let claudePreview = try ClientBackups.preview(claude, projects: map, environment: environment) + let geminiPreview = try ClientBackups.preview(gemini, projects: map, environment: environment) + #expect(claudePreview.client == .claudeCode) + #expect(geminiPreview.client == .geminiCLI) + try ClientBackups.restore(claudePreview) + try ClientBackups.restore(geminiPreview) + let transcript = home.appendingPathComponent(".claude/projects/\(localKey)/thread.jsonl") + #expect(try fixture.read(transcript).contains(newProject.path)) + #expect( + try fixture.read(home, ".claude/projects/\(localKey)/sessions-index.json").contains( + transcript.path)) + #expect( + try fixture.read(home, ".claude/projects/\(localKey)/thread/tool-results/result.txt") + == "tool output") + #expect(try fixture.read(home, ".claude.json").contains(existingProject.path)) + #expect(try fixture.read(home, ".claude.json").contains(newProject.path)) + let hook = newProject.appendingPathComponent(".claude/hooks/run.sh") + #expect( + try FileManager.default.attributesOfItem(atPath: hook.path)[.posixPermissions] as? Int + == 0o700) + try fixture.append(transcript, "{\"type\":\"assistant\"}\n") + #expect(try fixture.read(transcript).contains("assistant")) + let chat = home.appendingPathComponent(".gemini/tmp/existing/chats/session-fixture.json") + #expect(try fixture.read(chat).contains("hello")) + #expect(try fixture.read(chat).contains(FileHash.sha256Hex(data: Data(newProject.path.utf8)))) + try fixture.put(chat, "{\"sessionId\":\"gemini\",\"messages\":[\"hello\",\"continued\"]}") + #expect(try fixture.read(chat).contains("continued")) + #expect(try fixture.read(home, ".gemini/tmp/existing/chats/keep.json") == "{\"messages\":[]}") + #expect(try fixture.read(home, ".gemini/tmp/other/chats/second.json") == "{\"messages\":[]}") + #expect( + !FileManager.default.fileExists( + atPath: home.appendingPathComponent(".gemini/tmp/original/cache").path)) + #expect(try fixture.read(newProject, ".gemini/settings.json").contains("GEMINI.md")) + } + + @Test func stalePreviewsAndFailedPublicationPreserveDestination() throws { + let fixture = try Fixture() + let home = try fixture.directory("home") + let dest = try fixture.directory("restore") + let output = try fixture.directory("output") + try fixture.put(home, ".codex/config.toml", "new") + try fixture.put(home, ".codex/AGENTS.md", "rules") + try fixture.put(home, ".codex/archived_sessions/thread.jsonl", "{}\n") + try fixture.put(dest, ".codex/config.toml", "before") + let package = try ClientBackups.create( + client: .codex, projects: [], to: output, environment: fixture.environment(home)) + let environment = fixture.environment(dest) + let stale = try ClientBackups.preview(package, projects: [:], environment: environment) + try fixture.put(dest, ".codex/config.toml", "changed since preview") + #expect(throws: ClientBackupError.self) { try ClientBackups.restore(stale) } + + let plan = try ClientBackups.preview(package, projects: [:], environment: environment) + let fault: @Sendable (String) throws -> Void = { step in + if step == "published" { throw PublicationFailure.injected } + } + #expect(throws: PublicationFailure.self) { + try BackupRestoreTransaction.$checkpoint.withValue(fault) { + try ClientBackups.restore(plan) + } + } + #expect(try fixture.read(dest, ".codex/config.toml") == "changed since preview") + #expect( + !FileManager.default.fileExists(atPath: dest.appendingPathComponent(".codex/AGENTS.md").path)) + let fresh = try ClientBackups.preview(package, projects: [:], environment: environment) + try ClientBackups.restore(fresh) + let unchanged = try ClientBackups.preview(package, projects: [:], environment: environment) + #expect(unchanged.files.count == 3) + #expect(unchanged.files.allSatisfy { $0.kind == .unchanged }) + try ClientBackups.restore(unchanged) + } + + @Test func pendingJournalRollsBackOnNextRestoreAttempt() throws { + let fixture = try Fixture() + let home = try fixture.directory("home") + let dest = try fixture.directory("restore") + let output = try fixture.directory("output") + try fixture.put(home, ".claude/CLAUDE.md", "restored guidance") + try fixture.put(home, ".claude/settings.json", "{\"theme\":\"source\"}") + try fixture.put(dest, ".claude/CLAUDE.md", "existing guidance") + let package = try ClientBackups.create( + client: .claudeCode, projects: [], to: output, environment: fixture.environment(home)) + let env = fixture.environment(dest) + let preview = try ClientBackups.preview(package, projects: [:], environment: env) + let fault: @Sendable (String) throws -> Void = { step in + if step == "published" || step == "recovering" { throw PublicationFailure.injected } + } + #expect(throws: ClientBackupError.self) { + try BackupRestoreTransaction.$checkpoint.withValue(fault) { + try ClientBackups.restore(preview) + } + } + #expect(try fixture.read(dest, ".claude/CLAUDE.md") == "restored guidance") + let loaded = try ClientBackups.preview(package, projects: [:], environment: env) + #expect(throws: ClientBackupError.self) { try ClientBackups.restore(loaded) } + #expect(try fixture.read(dest, ".claude/CLAUDE.md") == "existing guidance") + let verified = try ClientBackups.preview(package, projects: [:], environment: env) + try ClientBackups.restore(verified) + #expect(try fixture.read(dest, ".claude/CLAUDE.md") == "restored guidance") + } + + @Test func rejectsCorruptionUnsafePathsAndUnknownDatabaseConflicts() throws { + let fixture = try Fixture() + let home = try fixture.directory("home") + let dest = try fixture.directory("restore") + let outside = try fixture.directory("outside") + let output = try fixture.directory("output") + try fixture.put(home, ".codex/AGENTS.md", "rules") + try fixture.put(home, ".codex/archived_sessions/session.jsonl", "{}\n") + let skill = try fixture.directory("outside/owned-skill") + let skills = try fixture.directory("home/.codex/skills") + try fixture.put(skill, "SKILL.md", "---\nname: test\ndescription: Example\n---\n# Test\n") + try fixture.put(skill, "references/notes.md", "owned resource") + try FileManager.default.createSymbolicLink( + at: skills.appendingPathComponent("owned"), withDestinationURL: skill) + let package = try ClientBackups.create( + client: .codex, projects: [], to: output, environment: fixture.environment(home)) + try fixture.put(outside, "session.jsonl", "outside") + let client = try fixture.directory("restore/.codex") + let link = client.appendingPathComponent("archived_sessions") + try FileManager.default.createSymbolicLink(at: link, withDestinationURL: outside) + let env = fixture.environment(dest) + #expect(throws: ClientBackupError.self) { + _ = try ClientBackups.preview(package, projects: [:], environment: env) + } + #expect(try fixture.read(outside, "session.jsonl") == "outside") + try fixture.remove(link) + try fixture.put(client, "agents.md", "case conflict") + #expect(throws: ClientBackupError.self) { + _ = try ClientBackups.preview(package, projects: [:], environment: env) + } + try fixture.remove(client.appendingPathComponent("agents.md")) + let linked = try ClientBackups.preview(package, projects: [:], environment: env) + #expect(linked.files.contains { $0.path.hasSuffix("skills/owned/references/notes.md") }) + #expect(!linked.files.contains { $0.path.contains("/unowned/") }) + try ClientBackups.restore(linked) + #expect(try fixture.read(client, "skills/owned/references/notes.md") == "owned resource") + + let writable = try BackupSQL(package, writable: true) + try writable.execute("UPDATE chunks SET bytes=X'FF' WHERE file=1 AND part=0") + #expect(throws: ClientBackupError.self) { _ = try ClientBackups.inspect(package) } + #expect(throws: ClientBackupError.self) { + _ = try ClientBackups.preview(package, projects: [:], environment: env) + } + let folder = try DirectoryHandle(at: output) + let invalid = "invalid.agentsbackup" + do { + let header = BackupHeader( + client: .codex, sourceHome: home.path, sourceClient: home.path, + sourceDatabase: home.path, projects: []) + let archive = try BackupArchive(writing: invalid, in: folder, header: header) + let file = try DirectoryHandle(at: home.appendingPathComponent(".codex")) + let current = try BackupIO.generation(file, "AGENTS.md") + let generation = try #require(current) + try archive.add( + root: "client", path: "sessions/../../escape", mode: 0o600, parent: file, + name: "AGENTS.md", generation: generation) + try archive.finish() + } + #expect(throws: ClientBackupError.self) { + _ = try ClientBackups.inspect(output.appendingPathComponent(invalid)) + } + + let sourceDB = try createCodexDB(home.appendingPathComponent(".codex")) + try sourceDB.execute("CREATE TABLE unclassified (id TEXT PRIMARY KEY, value TEXT)") + try sourceDB.execute("INSERT INTO unclassified VALUES ('fixture','sensitive')") + let targetDB = try createCodexDB(client) + try targetDB.execute("CREATE TABLE unclassified (id TEXT PRIMARY KEY, value TEXT)") + let original = try BackupIO.fingerprint(client.appendingPathComponent("state_5.sqlite")) + let conflict = try ClientBackups.create( + client: .codex, projects: [], to: output, environment: fixture.environment(home)) + #expect(throws: ClientBackupError.self) { + _ = try ClientBackups.preview(conflict, projects: [:], environment: env) + } + #expect(try BackupIO.fingerprint(client.appendingPathComponent("state_5.sqlite")) == original) + } + + @Test func restoresSharedAndClaudeSkillLinksAfterDonorIsGone() throws { + let f = try Fixture() + let source = try f.directory("source") + let output = try f.directory("output") + let donor = try f.directory("donor") + let skill = try f.directory("donor/skills/check") + let shared = try f.directory("source/.agents/skills") + let claude = try f.directory("source/.claude/skills") + let unrelated = try f.directory("outside") + try f.put(donor, ".git/HEAD", "donor repository metadata") + try f.put(donor, "unrelated.txt", "outside selected skill") + try f.put(skill, "SKILL.md", "---\nname: check\n---\n# Check\n") + try f.put(skill, "scripts/check.sh", "#!/bin/sh\nexit 0\n", mode: 0o751) + try f.put(unrelated, "scripts/check.sh", "destination donor sentinel") + let sharedLink = shared.appendingPathComponent("check") + try FileManager.default.createSymbolicLink(at: sharedLink, withDestinationURL: skill) + try FileManager.default.createSymbolicLink( + at: claude.appendingPathComponent("check"), withDestinationURL: sharedLink) + try f.put(source, ".claude/projects/example/thread.jsonl", "{\"type\":\"user\"}\n") + let environment = f.environment(source) + + let escaping = skill.appendingPathComponent("escape") + try FileManager.default.createSymbolicLink(at: escaping, withDestinationURL: unrelated) + do { + _ = try ClientBackups.create( + client: .claudeCode, projects: [], to: output, environment: environment) + Issue.record("escaping dependency was admitted") + } catch ClientBackupError.invalidLocation(let path) { + #expect(path == escaping.path) + } + try f.remove(escaping) + let bad = shared.appendingPathComponent("not-a-skill") + try FileManager.default.createSymbolicLink(at: bad, withDestinationURL: unrelated) + do { + _ = try ClientBackups.create( + client: .claudeCode, projects: [], to: output, environment: environment) + Issue.record("unowned skill directory was admitted") + } catch ClientBackupError.invalidLocation(let path) { + #expect(path == bad.path) + } + try f.remove(bad) + + let package = try ClientBackups.create( + client: .claudeCode, projects: [], to: output, environment: environment) + try f.remove(donor) + try f.remove(source) + let empty = try f.directory("empty") + let clean = try ClientBackups.preview(package, projects: [:], environment: f.environment(empty)) + try ClientBackups.restore(clean) + #expect( + clean.files.allSatisfy { !$0.path.hasSuffix("unrelated.txt") && !$0.path.contains("/.git/") }) + for slot in [".agents", ".claude"] { + let script = empty.appendingPathComponent(slot + "/skills/check/scripts/check.sh") + let mode = + try FileManager.default.attributesOfItem(atPath: script.path)[.posixPermissions] as? Int + #expect(mode == 0o751) + #expect(try f.read(script).hasPrefix("#!/bin/sh")) + } + + let existing = try f.directory("existing") + let existingSlot = try f.directory("existing/.claude/skills").appendingPathComponent("check") + try FileManager.default.createSymbolicLink(at: existingSlot, withDestinationURL: unrelated) + let env = f.environment(existing) + let preview = try ClientBackups.preview(package, projects: [:], environment: env) + #expect(preview.files.contains { $0.path == existingSlot.path && $0.kind == .replace }) + #expect(preview.files.contains { $0.path.hasSuffix("thread.jsonl") && $0.kind == .add }) + let rollback: @Sendable (String) throws -> Void = { step in + if step == "published", (try? BackupIO.directory(existingSlot)) != nil { + throw PublicationFailure.injected + } + } + #expect(throws: PublicationFailure.self) { + try BackupRestoreTransaction.$checkpoint.withValue(rollback) { + try ClientBackups.restore(preview) + } + } + #expect( + try FileManager.default.destinationOfSymbolicLink(atPath: existingSlot.path) == unrelated.path + ) + try ClientBackups.restore(ClientBackups.preview(package, projects: [:], environment: env)) + #expect(try BackupIO.directory(existingSlot) != nil) + #expect( + try f.read(existing, ".claude/projects/example/thread.jsonl") == "{\"type\":\"user\"}\n") + #expect(try f.read(unrelated, "scripts/check.sh") == "destination donor sentinel") + } + + @Test func restoresClaudeInstructionImportsFromTheAdmittedScopes() throws { + let f = try Fixture() + let home = try f.directory("home") + let project = try f.directory("project") + let chosen = try f.directory("relocated") + let dest = try f.directory("target") + let output = try f.directory("archive") + try f.put( + project, "CLAUDE.md", + """ + - Workflow @docs/git-instructions.md + - User instructions @~/.claude/preferences.md + - Absolute @\(project.path)/docs/absolute.md + - External @\(f.root.path)/outside/private.md + - Literal `@absent-inline.md` + - Literal "@absent-quoted.md" + ```md + @absent-fenced.md + ``` + """) + try f.put(project, "docs/git-instructions.md", "See @detail\\ notes.md\n") + try f.put(project, "docs/detail notes.md", "Back to @git-instructions.md\n") + try f.put(project, "docs/unrelated.md", "exclude") + try f.put(project, "docs/absolute.md", "absolute source") + try f.put(f.root, "outside/private.md", "excluded unrelated fixture") + try f.put(home, ".claude/preferences.md", "fixture preference") + let package = try ClientBackups.create( + client: .claudeCode, projects: [project], to: output, environment: f.environment(home)) + try f.remove(home) + try f.remove(project) + let preview = try ClientBackups.preview( + package, projects: [project.path: chosen], environment: f.environment(dest)) + try ClientBackups.restore(preview) + #expect(try f.read(chosen, "docs/detail notes.md") == "Back to @git-instructions.md\n") + #expect(try f.read(dest, ".claude/preferences.md") == "fixture preference") + #expect(try f.read(chosen, "docs/absolute.md") == "absolute source") + #expect(try f.read(chosen, "CLAUDE.md").contains("@" + chosen.path + "/docs/absolute.md")) + #expect( + !preview.files.contains { + $0.path.hasSuffix("unrelated.md") || $0.path.hasSuffix("private.md") + }) + } + + @Test func restoresClaudeImportsBetweenSelectedProjectsWithOverlappingRoots() throws { + let f = try Fixture() + let home = try f.directory("source-profile") + let a = try f.directory("source/A") + let b = try f.directory("source/B") + let nested = try f.directory("source/B/nested") + let unselected = try f.directory("source/C") + let newA = try f.directory("restore/first/application") + let newB = try f.directory("restore/second/documentation") + let newNested = try f.directory("restore/third/extension") + let destination = try f.directory("destination-profile") + let output = try f.directory("packages") + try f.put( + a, "CLAUDE.md", + """ + @../B/docs/team.md + @../B/nested/docs/team.md + @../C/docs/unselected.md + """) + try f.put(b, "docs/team.md", "Sibling instructions\n") + try f.put(nested, "docs/team.md", "Nested instructions\n") + try f.put(unselected, "docs/unselected.md", "Unselected instructions\n") + + let package = try ClientBackups.create( + client: .claudeCode, projects: [a, b, nested], to: output, environment: f.environment(home)) + let archive = try BackupArchive(reading: package) + #expect(!archive.manifest.entries.contains { $0.path.hasSuffix("unselected.md") }) + try f.remove(f.root.appendingPathComponent("source")) + try f.remove(home) + + let preview = try ClientBackups.preview( + package, projects: [a.path: newA, b.path: newB, nested.path: newNested], + environment: f.environment(destination)) + try ClientBackups.restore(preview) + let restored = try f.read(newA, "CLAUDE.md") + let imports = restored.split(separator: "\n").map { String($0.dropFirst()) } + #expect( + imports == [ + newB.appendingPathComponent("docs/team.md").path, + newNested.appendingPathComponent("docs/team.md").path, + "../C/docs/unselected.md", + ]) + let sibling = try #require(imports.first) + let extensionFile = try #require(imports.dropFirst().first) + #expect(try f.read(URL(fileURLWithPath: sibling)) == "Sibling instructions\n") + #expect(try f.read(URL(fileURLWithPath: extensionFile)) == "Nested instructions\n") + #expect(!FileManager.default.fileExists(atPath: newB.appendingPathComponent("nested").path)) + } + + @Test func restoresGeminiCheckpointObjectsAndToolOutputWithoutTheShadowRepository() throws { + let f = try Fixture() + let source = try f.directory("source") + let project = try f.directory("project") + let target = try f.directory("target") + let moved = try f.directory("moved") + let output = try f.directory("output") + let client = try f.directory("source/.gemini") + let shadow = try f.directory("source/.gemini/history/example") + let sh = try DirectoryHandle(at: shadow) + try BackupGeminiCheckpoints.git( + ["init", "--quiet", "--initial-branch=main", "--template="], in: sh) + func commit(_ message: String) throws -> String { + try BackupGeminiCheckpoints.git(["add", "."], in: sh) + try BackupGeminiCheckpoints.git( + [ + "-c", "user.name=Fixture", "-c", "user.email=fixture@example.test", + "commit", "--quiet", "-m", message, + ], in: sh) + return try BackupGeminiCheckpoints.git(["rev-parse", "HEAD"], in: sh) + } + try f.put(shadow, "snapshot.txt", "checkpoint snapshot") + let sha = try commit("checkpoint") + try f.put(shadow, "unrelated-object.txt", "exclude unreachable commit") + let unrelated = try commit("later unrelated commit") + try f.put(client, "projects.json", f.json(["projects": [project.path: "example"]])) + try f.put(client, "tmp/example/.project_root", project.path) + try f.put(client, "tmp/example/tool-outputs/session-id/read_1.txt", "tool output") + try f.put( + client, "tmp/example/checkpoints/snapshot.json", + f.json([ + "commitHash": String(sha.prefix(9)), + "toolCall": [ + "name": "write_file", + "args": ["file_path": project.appendingPathComponent("snapshot.txt").path], + ], + ])) + let package = try ClientBackups.create( + client: .geminiCLI, projects: [project], to: output, environment: f.environment(source)) + try f.remove(source) + try f.remove(project) + let native = target.appendingPathComponent(".gemini") + try f.put(native, "projects.json", f.json(["projects": [moved.path: "destination"]])) + try f.put(native, "tmp/destination/.project_root", moved.path) + let env = f.environment(target) + let preview = try ClientBackups.preview( + package, projects: [project.path: moved], environment: env) + try ClientBackups.restore(preview) + let record = try BackupNativeJSON.object( + native.appendingPathComponent("tmp/destination/checkpoints/snapshot.json")) + #expect(record["commitHash"] as? String == sha) + #expect(try f.read(native, "tmp/destination/checkpoints/snapshot.json").contains(moved.path)) + #expect( + try f.read(native, "tmp/destination/tool-outputs/session-id/read_1.txt") == "tool output") + let git = [ + "--git-dir=" + native.appendingPathComponent("history/destination/.git").path, + "--work-tree=" + moved.path, + ] + let working = try DirectoryHandle(at: moved) + #expect(throws: ClientBackupError.self) { + try BackupGeminiCheckpoints.git(git + ["cat-file", "-e", unrelated], in: working) + } + try BackupGeminiCheckpoints.git(git + ["restore", "--source", sha, "."], in: working) + try BackupGeminiCheckpoints.git(git + ["clean", "-fd"], in: working) + #expect(try f.read(moved, "snapshot.txt") == "checkpoint snapshot") + + try f.put(moved, "additional.txt", "existing destination history") + try BackupGeminiCheckpoints.git(git + ["add", "additional.txt"], in: working) + try BackupGeminiCheckpoints.git( + git + [ + "-c", "user.name=Fixture", "-c", "user.email=fixture@example.test", + "commit", "--quiet", "-m", "destination commit", + ], in: working) + let currentHead = try BackupGeminiCheckpoints.git(git + ["rev-parse", "HEAD"], in: working) + let second = try ClientBackups.preview( + package, projects: [project.path: moved], environment: env) + try ClientBackups.restore(second) + let restoredHead = try BackupGeminiCheckpoints.git(git + ["rev-parse", "HEAD"], in: working) + #expect(currentHead == restoredHead) + #expect(try f.read(moved, "additional.txt") == "existing destination history") + } + + @Test func relocatesGeminiChatLargerThanTheFormerDocumentLimit() throws { + let f = try Fixture() + let source = try f.directory("source") + let project = try f.directory("project") + let moved = try f.directory("moved") + let dest = try f.directory("destination") + let output = try f.directory("output") + let client = try f.directory("source/.gemini") + let chats = try f.directory("source/.gemini/tmp/example/chats") + let oldHash = FileHash.sha256Hex(data: Data(project.path.utf8)) + let newHash = FileHash.sha256Hex(data: Data(moved.path.utf8)) + try f.put(client, "tmp/example/.project_root", project.path) + try f.put(client, "projects.json", f.json(["projects": [project.path: "example"]])) + let chunk = Data(repeating: 0x61, count: 1024 * 1024) + let prefix = Data("{\"messages\":[{\"type\":\"user\",\"content\":\"".utf8) + try BackupIO.write("session-large.json", in: DirectoryHandle(at: chats)) { file in + try file.write(contentsOf: prefix) + for _ in 0..<65 { try file.write(contentsOf: chunk) } + try file.write(contentsOf: Data("\"}],\"projectHash\":\"\(oldHash)\"}".utf8)) + } + let package = try ClientBackups.create( + client: .geminiCLI, projects: [project], to: output, environment: f.environment(source)) + try f.remove(source) + try f.remove(project) + let plan = try ClientBackups.preview( + package, projects: [project.path: moved], environment: f.environment(dest)) + try ClientBackups.restore(plan) + let result = dest.appendingPathComponent(".gemini/tmp/example/chats/session-large.json") + let opened = try FileHandle(forReadingFrom: result) + defer { try? opened.close() } + #expect(try opened.read(upToCount: prefix.count) == prefix) + for _ in 0..<65 { #expect(try opened.read(upToCount: chunk.count) == chunk) } + #expect(try opened.readToEnd() == Data("\"}],\"projectHash\":\"\(newHash)\"}".utf8)) + } + + private enum PublicationFailure: Error { case injected } + + private func createCodexDB(_ directory: URL, wal: Bool = false) throws -> BackupSQL { + let root = try DirectoryHandle(at: directory) + let name = "state_5.sqlite" + try BackupIO.write(name, in: root) { _ in } + let db = try BackupSQL(directory.appendingPathComponent(name), writable: true) + if wal { try db.execute("PRAGMA journal_mode=WAL") } + try db.execute("CREATE TABLE threads (id TEXT PRIMARY KEY, cwd TEXT, rollout_path TEXT)") + try db.execute( + """ + CREATE TABLE thread_attachments ( + thread_id TEXT REFERENCES threads(id), id TEXT, content TEXT, PRIMARY KEY(thread_id,id) + ) + """) + try db.execute( + """ + CREATE TABLE thread_read_receipts (thread_id TEXT PRIMARY KEY REFERENCES threads(id), turn INTEGER) + """) + return db + } +} + +private final class Fixture { + let root: URL + + init() throws { + root = FileManager.default.temporaryDirectory.resolvingSymlinksInPath() + .appendingPathComponent("client-backup-fixture-" + UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: false) + } + + deinit { try? remove(root) } + + func directory(_ path: String) throws -> URL { + let url = root.appendingPathComponent(path, isDirectory: true) + try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) + return url + } + + func environment(_ home: URL, _ values: [String: String] = [:]) -> RuntimeEnvironment { + RuntimeEnvironment(projectDirectory: root, homeDirectory: home, environment: values) + } + + func put(_ base: URL, _ path: String, _ value: String, mode: UInt16 = 0o600) throws { + try put(base.appendingPathComponent(path), value, mode: mode) + } + + func put(_ url: URL, _ value: String, mode: UInt16 = 0o600) throws { + try FileManager.default.createDirectory( + at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data(value.utf8).write(to: url) + try FileManager.default.setAttributes([.posixPermissions: mode], ofItemAtPath: url.path) + } + + func read(_ base: URL, _ relative: String) throws -> String { + try read(base.appendingPathComponent(relative)) + } + + func read(_ url: URL) throws -> String { + try String(contentsOf: url, encoding: .utf8) + } + + func append(_ url: URL, _ value: String) throws { + let handle = try FileHandle(forWritingTo: url) + defer { try? handle.close() } + try handle.seekToEnd() + try handle.write(contentsOf: Data(value.utf8)) + } + + func json(_ value: Any) throws -> String { + String(decoding: try BackupNativeJSON.encode(value), as: UTF8.self) + } + + func remove(_ url: URL) throws { + try FileManager.default.removeItem(at: url) + } + + func claudeKey(_ url: URL) -> String { + let name = url.path.replacingOccurrences( + of: #"[^a-zA-Z0-9]"#, with: "-", options: .regularExpression) + if name.count <= 200 { return name } + let unsigned = url.path.utf16.reduce(UInt32(0)) { ($0 &* 31) &+ UInt32($1) } + let suffix = String(Int32(bitPattern: unsigned).magnitude, radix: 36) + return String(name.prefix(200)) + "-" + suffix + } +} diff --git a/Tests/AgentsCoreTests/CoordinationAdmissionTests.swift b/Tests/AgentsCoreTests/CoordinationAdmissionTests.swift new file mode 100644 index 0000000..c5d5c8a --- /dev/null +++ b/Tests/AgentsCoreTests/CoordinationAdmissionTests.swift @@ -0,0 +1,444 @@ +import CPlatform +import Foundation +import StateTestSupport +import Testing + +@testable import AgentsCore + +@Suite struct CoordinationAdmissionTests { + @Test(arguments: [false, true]) + func partialSharedAcquisitionRechecksAbsenceAndReleasesLocks(_ outerInspectionFails: Bool) + throws + { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let store = StateStore( + scope: .user, + environment: RuntimeEnvironment( + projectDirectory: root, homeDirectory: root.appendingPathComponent("home"), + environment: ["CLAUDE_CONFIG_DIR": root.appendingPathComponent("claude").path])) + let routes = try ["a", "b", "c", "d"].map { + try NativeTargetRoute.named(.claudeSkillPlugin, scope: .user, name: $0) + } + let resources = try routes.enumerated().map { index, route in + try SharedResource(store: store, route: route, create: index != 1) + } + let first = try #require(resources[0].metadata) + let absent = resources[1].parent.url.appendingPathComponent(SharedResource.metadataName) + .appendingPathComponent(resources[1].identity.directoryName) + let unlocked = try #require(resources[2].metadata) + let last = try #require(resources[3].metadata) + _ = try first.createPrivateFile("lock") + _ = try last.createPrivateFile("lock") + let contender = open(first.url.appendingPathComponent("lock").path, O_RDWR | O_CLOEXEC) + try #require(contender >= 0) + defer { close(contender) } + let blocker = open(last.url.appendingPathComponent("lock").path, O_RDWR | O_CLOEXEC) + try #require(blocker >= 0) + defer { close(blocker) } + try #require(platform_flock(blocker, LOCK_EX | LOCK_NB) == 0) + + var contended = 0 + var observedAbsentPath = 0 + var reads = 0 + let result = Result { + try store.withCoordination( + routes: Set(routes), writable: false, + checkpoint: { point in + #expect(point == "shared.3.lock.contended") + contended += 1 + try #require(contended == 1) + #expect(platform_flock(contender, LOCK_EX | LOCK_NB) == -1) + _ = try unlocked.createPrivateFile("lock") + if outerInspectionFails { + try FileManager.default.createSymbolicLink(at: absent, withDestinationURL: root) + } else { + try #require(platform_flock(blocker, LOCK_UN) == 0) + } + throw CoordinationTestInterruption.checkpoint + }, + onReadLocation: { if $0.path == absent.path { observedAbsentPath += 1 } } + ) { () -> Int? in + reads += 1 + return nil + } + } + #expect(contended == 1) + if outerInspectionFails { + if case .failure(let error) = result, + case .unsafePath? = error as? CoreError + { + #expect(reads == 0) + } else { + Issue.record("Expected the outer missing metadata check to replace the inner outcome") + } + #expect(observedAbsentPath == 2) + } else { + #expect(try result.get() == nil) + #expect(reads == 1) + #expect(observedAbsentPath == 4) + } + #expect(platform_flock(contender, LOCK_EX | LOCK_NB) == 0) + } + + @Test func missingSharedRootCanSupersedeReadFailure() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let loader = root.appendingPathComponent("claude") + try FileManager.default.createDirectory(at: loader, withIntermediateDirectories: false) + let store = StateStore( + scope: .user, + environment: RuntimeEnvironment( + projectDirectory: root, homeDirectory: root.appendingPathComponent("home"), + environment: ["CLAUDE_CONFIG_DIR": loader.path])) + let route = try NativeTargetRoute.named(.claudeSkillPlugin, scope: .user, name: "demo") + var reads = 0 + let value: Int? = try store.withReadLock(footprint: [route]) { + reads += 1 + if reads == 1 { + try FileManager.default.createDirectory( + at: loader.appendingPathComponent("skills"), withIntermediateDirectories: false) + throw CoordinationTestInterruption.body + } + return nil + } + #expect(reads == 2) + #expect(value == nil) + } + + @Test func standaloneSelectionAndCanonicalChildUseObservedParent() throws { + let fixture = try TransactionFixture() + let store = fixture.store + let root = try store.captureExistingProjectRoot() + let before = try FileSnapshot.read(at: fixture.root) + let target = try store.skillInitializationTarget( + inChildDirectory: "Selected Skill", named: "demo") + #expect(try FileSnapshot.read(at: fixture.root) == before) + #expect(target.file == fixture.root.appendingPathComponent("Selected Skill/demo/SKILL.md")) + try store.withLock(existingRoot: root) { + let transaction = FileTransaction(store: store) + try transaction.initializeSkill(target, bytes: Data("exact template".utf8)) + try transaction.commit() + } + #expect(try Data(contentsOf: target.file) == Data("exact template".utf8)) + #expect(throws: CoreError.self) { + try store.skillInitializationTarget(inChildDirectory: "../escape", named: "demo") + } + } + + @Test func skillBatchReobservesItsParentAfterPreflight() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let loader = root.appendingPathComponent(".agents") + let initial = root.appendingPathComponent("initial") + let replacement = root.appendingPathComponent("replacement") + for parent in [initial, replacement] { + try FileManager.default.createDirectory( + at: parent.appendingPathComponent("skills"), withIntermediateDirectories: true) + } + try FileManager.default.createSymbolicLink(at: loader, withDestinationURL: initial) + let store = StateStore( + scope: .project, + environment: RuntimeEnvironment( + projectDirectory: root, homeDirectory: root.appendingPathComponent("home"), + environment: [:])) + var resolver = SkillInstallationTargetResolver(store: store) + let targets = try [ + resolver.target(for: .codex, named: "first"), + resolver.target(for: .codex, named: "second"), + ] + var redirect: Result? + #expect(throws: CoreError.invalidState("installation authority changed during admission")) { + try store.withReadLock( + footprint: [.codexMCPUser], installations: targets, + onReadLocation: { _ in + guard redirect == nil else { return } + redirect = Result { + try FileManager.default.removeItem(at: loader) + try FileManager.default.createSymbolicLink(at: loader, withDestinationURL: replacement) + } + }, + { Issue.record("The inspection received stale installation authority") }) + } + try #require(redirect).get() + let current = try store.skillInstallationTarget(for: .codex, named: "first") + #expect( + current.url == replacement.resolvingSymlinksInPath().appendingPathComponent("skills/first")) + } + + @Test func legacySymlinkAndPluginKeepDistinctIntentWithOnePhysicalDomain() throws { + let fixture = try TransactionFixture() + let store = StateStore(scope: .user, environment: fixture.store.environment) + let skill = try store.skillInstallationTarget(for: .claudeCode, named: "shared") + let route = try NativeTargetRoute.named(.claudeSkillPlugin, scope: .user, name: "shared") + #expect(skill.footprint == [route]) + #expect(throws: CoreError.self) { + try store.withLock { + let transaction = FileTransaction(store: store) + try transaction.replaceSkill(skill, with: .link(fixture.root.appendingPathComponent("new"))) + } + } + try store.withLock(footprint: skill.footprint) { + let transaction = FileTransaction(store: store) + try transaction.replaceSkill(skill, with: .link(fixture.root.appendingPathComponent("new"))) + try transaction.commit() + #expect(try FileSnapshot.read(at: skill.url)?.isSymbolicLink == true) + let native = try store.nativeTarget(for: route) + #expect(throws: CoreError.self) { try store.preparePrivateMaterialization(native) } + let copy = FileTransaction(store: store) + try copy.replaceSkill(skill, with: .copy(fixture.root.appendingPathComponent("new"))) + try copy.commit() + let privateTree = FileTransaction(store: store) + try privateTree.replacePrivateTree( + store.preparePrivateMaterialization(native, changingAccess: true), + entries: [.init("secret", content: .file(Data("retained".utf8)))], + provider: AdmissionBindings()) + try privateTree.commit() + let generation = try store.materializationReceipt(for: native)?.generation + let refuses = FileTransaction(store: store) + #expect(throws: CoreError.self) { + try refuses.replaceSkill(skill, with: .copy(fixture.root.appendingPathComponent("new"))) + } + let rollback = FileTransaction(store: store) { point in + if point == "entry.0.applied" { throw CoreError.invalidState("bounded rollback") } + } + try rollback.deleteSkill(skill) + #expect(throws: CoreError.self) { try rollback.commit() } + #expect(try store.materializationReceipt(for: native)?.generation == generation) + #expect( + try Data(contentsOf: native.url.appendingPathComponent("secret")) == Data("retained".utf8)) + #expect(!FileManager.default.fileExists(atPath: store.materializationReceiptURL.path)) + } + } + + @Test func compatibleProjectUserAliasesRetainOnePrivateReceiptAndLogicalAuthority() throws { + let fixture = try TransactionFixture() + var environment = fixture.store.environment + environment.environment["CLAUDE_CONFIG_DIR"] = + fixture.root.appendingPathComponent(".claude").path + let project = StateStore(scope: .project, environment: environment) + let user = StateStore(scope: .user, environment: environment) + let local = try NativeTargetRoute.named(.claudeCommand, scope: .project, name: "team/review") + let global = try NativeTargetRoute.named(.claudeCommand, scope: .user, name: "team/review") + var generation: UUID? + try project.withLock(footprint: [local]) { + let target = try project.nativeTarget(for: local) + #expect(target.path == local.root + "/" + local.basename) + let transaction = FileTransaction(store: project) + try transaction.replacePrivate( + project.preparePrivateMaterialization(target), provider: AdmissionBindings() + ) { _ in Data("secret sibling".utf8) } + try transaction.commit() + generation = try project.materializationReceipt(for: target)?.generation + #expect(!FileManager.default.fileExists(atPath: project.materializationReceiptURL.path)) + } + try user.withLock(footprint: [global]) { + let target = try user.nativeTarget(for: global) + #expect(try user.materializationReceipt(for: target)?.generation == generation) + let transaction = FileTransaction(store: user) + try transaction.replace(target.url, with: .data(Data("secret sibling; ordinary edit".utf8))) + try transaction.commit() + #expect(try user.materializationReceipt(for: target)?.generation != generation) + } + try project.withReadLock(footprint: [local]) { + let target = try project.nativeTarget(for: local) + #expect(try project.materializationReceipt(for: target) != nil) + #expect(try Data(contentsOf: target.url) == Data("secret sibling; ordinary edit".utf8)) + } + } +} + +private enum CoordinationTestInterruption: Error { + case checkpoint, body +} + +extension CoordinationAdmissionTests { + @Test func nativeAndLegacyWritersContendBeforeLegacyCallback() throws { + let f = try TransactionFixture() + let config = f.root.appendingPathComponent("home/.claude") + let holder = try stateTestProcess( + root: f.root, + arguments: [ + "private-tree-lock", "tree.locked", "--scope", "user", "--shared-config", config.path, + ]) + defer { terminateProcess(holder) } + try ProcessWait.marker(f.root.appendingPathComponent("ready"), child: holder, root: f.root) + try ProcessWait.stopped(holder, root: f.root) + try FileManager.default.removeItem(at: f.root.appendingPathComponent("ready")) + let waiter = try stateTestProcess( + root: f.root, + arguments: [ + "private-legacy-install", "shared.0.lock.contended", "--scope", "user", "--shared-config", + config.path, + ]) + defer { terminateProcess(waiter) } + try ProcessWait.marker(f.root.appendingPathComponent("ready"), child: waiter, root: f.root) + try ProcessWait.stopped(waiter, root: f.root) + #expect( + !FileManager.default.fileExists(atPath: f.root.appendingPathComponent("legacy-callback").path) + ) + try #require(kill(holder.processIdentifier, SIGCONT) == 0) + try ProcessWait.exit(holder, root: f.root) + #expect(holder.terminationStatus == 0) + try #require(kill(waiter.processIdentifier, SIGCONT) == 0) + try ProcessWait.exit(waiter, root: f.root) + #expect(waiter.terminationStatus == 0) + #expect( + FileManager.default.fileExists( + atPath: config.appendingPathComponent("skills/private-fixture/SKILL.md").path)) + } + + @Test(arguments: ["entry.0.applied", "journal.finalized"]) + func legacyJournalReconstructsOnlyItsClosedCoordinator(_ point: String) throws { + let f = try TransactionFixture() + let config = f.root.appendingPathComponent("home/.claude") + let child = try stateTestProcess( + root: f.root, + arguments: [ + "private-legacy-install", point, "--scope", "user", "--shared-config", config.path, + ]) + defer { terminateProcess(child) } + try ProcessWait.marker(f.root.appendingPathComponent("ready"), child: child, root: f.root) + terminateProcess(child) + var environment = f.store.environment + environment.environment["CLAUDE_CONFIG_DIR"] = config.path + let store = StateStore(scope: .user, environment: environment) + let before = try FileSnapshot.read(at: f.root) + try store.withReadLock( + onPendingRecovery: { + #expect(!FileTransaction.recoveryDiagnostic(store: store).requiresOwner) + }, { Issue.record("expected recovery diagnostic") }) + #expect(try FileSnapshot.read(at: f.root) == before) + #expect(throws: CoreError.transactionRecovered(store.directory.path)) { try store.withLock {} } + let target = try store.skillInstallationTarget(for: .claudeCode, named: "private-fixture") + #expect( + FileManager.default.fileExists(atPath: target.url.path) == (point == "journal.finalized")) + } +} + +extension CoordinationAdmissionTests { + @Test func projectLegacyAliasDoesNotGrantUserNativeScopeAuthority() throws { + let f = try TransactionFixture() + let destination = f.root.appendingPathComponent("home/.claude") + try FileManager.default.createDirectory(at: destination, withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink( + at: f.root.appendingPathComponent(".claude"), withDestinationURL: destination) + let target = try f.store.skillInstallationTarget(for: .claudeCode, named: "legacy") + let userRoute = try NativeTargetRoute.named(.claudeSkillPlugin, scope: .user, name: "legacy") + #expect(throws: CoreError.self) { try f.store.withLock(footprint: [userRoute]) {} } + try f.store.withLock(installations: [target]) { () -> Void in + #expect(throws: CoreError.self) { try f.store.nativeTarget(for: userRoute) } + let transaction = FileTransaction(store: f.store) + try transaction.replaceSkill(target, with: .link(f.root.appendingPathComponent("new"))) + try transaction.commit() + } + #expect(try FileSnapshot.read(at: target.url)?.isSymbolicLink == true) + } + + @Test func incompatibleReadersAndSymlinkDescendantsCannotAcquireAliasAuthority() throws { + let f = try TransactionFixture() + let claude = f.root.appendingPathComponent(".claude") + try FileManager.default.createDirectory(at: claude, withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink( + at: f.root.appendingPathComponent(".gemini"), withDestinationURL: claude) + var environment = f.store.environment + environment.environment["GEMINI_CLI_HOME"] = f.root.path + let store = StateStore(scope: .project, environment: environment) + let before = try FileSnapshot.read(at: f.root) + #expect(throws: CoreError.self) { try store.withLock(footprint: [.claudeSettingsProject]) {} } + #expect(try FileSnapshot.read(at: f.root) == before) + let external = f.root.appendingPathComponent("external") + try FileManager.default.createDirectory(at: external, withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink( + at: claude.appendingPathComponent("commands"), withDestinationURL: external) + let route = try NativeTargetRoute.named(.claudeCommand, scope: .project, name: "example") + #expect(throws: CoreError.self) { try store.withReadLock(footprint: [route]) {} } + #expect( + !FileManager.default.fileExists( + atPath: external.appendingPathComponent(".agents-native").path)) + } +} + +extension CoordinationAdmissionTests { + @Test func finalizedLegacyCleanupPreservesLaterGenerationAfterLogicalAliasReplacement() throws { + let f = try TransactionFixture() + let config = f.root.appendingPathComponent("home/.claude") + try FileManager.default.createDirectory(at: config, withIntermediateDirectories: true) + let alias = f.root.appendingPathComponent(".claude") + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: config) + let child = try stateTestProcess( + root: f.root, + arguments: [ + "private-legacy-install", "shared.0.reservation.removed", "--shared-config", config.path, + ]) + defer { terminateProcess(child) } + try ProcessWait.marker(f.root.appendingPathComponent("ready"), child: child, root: f.root) + terminateProcess(child) + var environment = f.store.environment + environment.environment["CLAUDE_CONFIG_DIR"] = config.path + let later = StateStore(scope: .user, environment: environment) + let target = try later.skillInstallationTarget(for: .claudeCode, named: "private-fixture") + let source = f.root.appendingPathComponent("later") + try FileManager.default.createDirectory(at: source, withIntermediateDirectories: false) + try Data("later generation".utf8).write(to: source.appendingPathComponent("SKILL.md")) + try later.withLock(installations: [target]) { + let transaction = FileTransaction(store: later) + try transaction.replaceSkill(target, with: .copy(source)) + try transaction.commit() + } + try FileManager.default.removeItem(at: alias) + try FileManager.default.createDirectory(at: alias, withIntermediateDirectories: false) + let owner = StateStore(scope: .project, environment: environment) + let before = try FileSnapshot.read(at: f.root) + try owner.withReadLock( + onPendingRecovery: { + #expect(!FileTransaction.recoveryDiagnostic(store: owner).requiresOwner) + }, { Issue.record("expected finalized cleanup diagnostic") }) + #expect(try FileSnapshot.read(at: f.root) == before) + #expect(throws: CoreError.transactionRecovered(owner.directory.path)) { try owner.withLock {} } + #expect( + try Data(contentsOf: target.url.appendingPathComponent("SKILL.md")) + == Data("later generation".utf8)) + #expect(!FileManager.default.fileExists(atPath: alias.appendingPathComponent("skills").path)) + } +} + +extension CoordinationAdmissionTests { + @Test func legacyLoaderReplacementAndArbitraryPayloadCannotExpandAuthority() throws { + let f = try TransactionFixture() + let first = f.root.appendingPathComponent("home/.claude") + let other = f.root.appendingPathComponent("other-loader") + for parent in [first, other] { + try FileManager.default.createDirectory( + at: parent.appendingPathComponent("skills"), withIntermediateDirectories: true) + } + let alias = f.root.appendingPathComponent(".claude") + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: first) + let target = try f.store.skillInstallationTarget(for: .claudeCode, named: "example") + try FileManager.default.removeItem(at: alias) + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: other) + let before = try FileSnapshot.read(at: f.root) + #expect(throws: CoreError.self) { + try f.store.withLock(installations: [target]) { + Issue.record("stale authority must not deliver a callback") + } + } + #expect(try FileSnapshot.read(at: f.root) == before) + try FileManager.default.removeItem(at: alias) + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: first) + try f.store.withLock(installations: [target]) { + #expect(throws: CoreError.self) { + try FileTransaction(store: f.store).replaceSkill(target, with: .data(Data())) + } + } + #expect(throws: CoreError.self) { + try f.store.skillInstallationTarget(for: .claudeCode, named: "../escape") + } + } +} + +private struct AdmissionBindings: RuntimeBindingProvider { + func value(for binding: String, environment: RuntimeEnvironment) throws -> Data { + throw CoreError.invalidState("no binding was requested") + } +} diff --git a/Tests/AgentsCoreTests/CoreTestSupport.swift b/Tests/AgentsCoreTests/CoreTestSupport.swift index 7100df7..128d5e5 100644 --- a/Tests/AgentsCoreTests/CoreTestSupport.swift +++ b/Tests/AgentsCoreTests/CoreTestSupport.swift @@ -19,6 +19,22 @@ func removeTemporaryDirectory(_ directory: URL) { } } +func makeDirectoriesWritable(_ root: URL) { + guard let entries = FileManager.default.enumerator(at: root, includingPropertiesForKeys: nil) + else { + return + } + for case let entry as URL in entries { + var info = stat() + if lstat(entry.path, &info) == 0, info.st_mode & S_IFMT == S_IFDIR { + _ = chmod(entry.path, (info.st_mode & 0o7777) | S_IRWXU) + } + } +} + +/// The inspection error while automatic recovery is pending. +let pendingRecovery = CoreError.recoveryPending(TransactionRecoveryDiagnostic.pendingMessage) + func initGitRepo(_ repo: URL) throws { try ProcessRunner.run( "/usr/bin/env", arguments: ["git", "init", "--initial-branch=master", repo.path]) @@ -45,7 +61,7 @@ func gitHead(_ repo: URL) throws -> String { func stateTestProcess( root: URL, arguments: [String], environment: [String: String] = [:] ) throws -> Process { - var directory = Bundle(for: TransactionTestBundle.self).bundleURL.deletingLastPathComponent() + var directory = Bundle(for: TransactionTestBundle.self).bundleURL while !FileManager.default.isExecutableFile( atPath: directory.appendingPathComponent("StateTestProcess").path), directory.path != "/" { diff --git a/Tests/AgentsCoreTests/DeclarationStateTests.swift b/Tests/AgentsCoreTests/DeclarationStateTests.swift new file mode 100644 index 0000000..f06835b --- /dev/null +++ b/Tests/AgentsCoreTests/DeclarationStateTests.swift @@ -0,0 +1,241 @@ +import AgentsManifest +import Foundation +import StateTestSupport +import Testing + +@testable import AgentsCore + +@Suite("Declaration state") +struct DeclarationStateTests { + @Test func failedFinalValidationAfterDraftBatchesPreservesStateAndTargets() throws { + let fixture = try ScopeFixture() + let store = fixture.store + let declaration = Declaration( + sources: ["s": SourceDeclaration(kind: .local, location: "missing")], + components: (0..<101).map { + .subagent( + name: "a\($0)", description: "d", + prompt: .file(ResourceDeclaration(path: "x.md", source: "s"))) + }) + try store.save(declaration: declaration, resolved: ResolvedState()) + try Data("installed content".utf8).write( + to: fixture.root.appendingPathComponent("installed-target")) + let previous = try store.loadDeclaration() + var next = previous + next.sourceDeclarations = [] + next.components = Array(previous.components.suffix(1)) + let baseline = try StatePrecondition(store: store) + let before = try FileHash.folderHash(fixture.root) + #expect(throws: ManifestFailure.self) { + try store.planDeclaration(next, replacing: previous, prepared: baseline) + } + #expect(try FileHash.folderHash(fixture.root) == before) + #expect(try store.loadDeclaration() == previous) + #expect(try store.loadResolved() == ResolvedState()) + } + + @Test(arguments: ["lock", "watch"]) + func stateWithoutADeclarationStopsEveryAccessWithoutWriting(_ kind: String) throws { + let fixture = try ScopeFixture() + let store = fixture.store + try FileManager.default.createDirectory(at: store.directory, withIntermediateDirectories: true) + if kind == "lock" { + try StateStore.encodeState(ResolvedState()).write(to: store.resolvedURL) + } else { + try StateStore.encode(WatchState()).write(to: store.watchURL) + } + let missing = CoreError.missingDeclaration(store.declarationURL.path) + let before = try FileHash.folderHash(fixture.root) + #expect(throws: missing) { try store.loadDeclaration() } + #expect(throws: missing) { try store.loadManifest() } + #expect(throws: missing) { try store.loadResolved() } + #expect(throws: missing) { try store.loadWatch() } + #expect(throws: missing) { try store.readDeclaration() } + #expect(throws: missing) { try store.withLock {} } + #expect(throws: missing) { + try store.save(declaration: Declaration(agents: [.codex]), resolved: ResolvedState()) + } + #expect(try FileHash.folderHash(fixture.root) == before) + + // A writer that already owns the scope lock recovers first, then reaches the same rule. + FileManager.default.createFile(atPath: fixture.scopeLock.path, contents: nil) + let locked = try FileHash.folderHash(fixture.root) + #expect(throws: missing) { try store.withLock { _ = try store.readDeclaration() } } + #expect(throws: missing) { + try store.save(declaration: Declaration(agents: [.codex]), resolved: ResolvedState()) + } + #expect(try FileHash.folderHash(fixture.root) == locked) + } + + @Test func scopeWithoutStateIsEmptyAndADeclarationAloneIsComplete() throws { + let fixture = try ScopeFixture() + let store = fixture.store + let before = try FileHash.folderHash(fixture.root) + #expect(try store.loadDeclaration() == Declaration()) + #expect(try store.loadManifest() == nil) + #expect(try store.loadResolved() == ResolvedState()) + #expect(try store.loadWatch() == WatchState()) + #expect(try FileHash.folderHash(fixture.root) == before) + + let bytes = manifestText("defaultAgents: [\"cursor\"]\n") + try FileManager.default.createDirectory(at: store.directory, withIntermediateDirectories: true) + try bytes.write(to: store.declarationURL) + let declared = try FileHash.folderHash(fixture.root) + #expect(try store.loadDeclaration() == Declaration(agents: [.cursor])) + #expect(try store.loadManifest()?.bytes == Array(bytes)) + #expect(try store.loadResolved() == ResolvedState()) + #expect(try FileHash.folderHash(fixture.root) == declared) + #expect(try store.withLock { try store.readDeclaration() } == Declaration(agents: [.cursor])) + } + + @Test func completeDeclarationReadsKeepSymbolicIntentWithoutDeploymentSideEffects() throws { + let fixture = try ScopeFixture() + let store = fixture.store + try FileManager.default.createDirectory(at: store.directory, withIntermediateDirectories: true) + let bytes = manifestText( + """ + sources: {"remote": {"url": "https://does-not-exist.invalid/repo.git"}} + components: [{"kind": "mcpServer", "name": "tools", "transport": {"kind": "stdio", "executable": "program-does-not-exist"}}, {"kind": "hook", "name": "hook", "event": "sessionStart", "run": {"executable": "program-does-not-exist"}}, {"kind": "subagent", "name": "agent", "description": "d", "prompt": {"file": {"path": "missing.md", "source": "remote"}}}] + groups: {"unused": {"components": [{"kind": "ignore", "name": "i", "patterns": [], "condition": {"agents": []}}]}} + """) + try bytes.write(to: store.declarationURL) + let before = try FileHash.folderHash(fixture.root) + let declaration = try store.loadDeclaration() + #expect(declaration.components.map(\.kind) == [.mcpServer, .hook, .subagent]) + #expect(declaration.groups.map(\.name) == ["unused"]) + #expect( + declaration.sources["remote"]?.environment + == SourceEnvironment( + projectDirectory: store.environment.projectDirectory, + homeDirectory: store.environment.homeDirectory)) + #expect(try store.loadManifest()?.bytes == Array(bytes)) + #expect(try store.readDeclaration() == declaration) + #expect(try FileHash.folderHash(fixture.root) == before) + } + + /// A writer interrupted after moving the declaration aside leaves lock state without a + /// declaration. Readers report the pending recovery without touching any file, and the next + /// writer recovers before the missing-declaration rule applies. + @Test func pendingRecoveryPrecedesTheMissingDeclarationRule() throws { + let fixture = try ScopeFixture() + let store = fixture.store + try store.save(declaration: Declaration(agents: [.cursor]), resolved: ResolvedState()) + struct Interrupted: Error {} + try FileLock.withLock(at: fixture.scopeLock) { + let transaction = FileTransaction(store: store) { point in + if point == TransactionCheckpoint.progress(0, .applied).name || point.hasPrefix("recovery.") + { + throw Interrupted() + } + } + try transaction.delete(store.declarationURL) + #expect(throws: Interrupted.self) { try transaction.commit() } + } + try FileManager.default.removeItem(at: fixture.scopeLock) + let journal = store.directory.appendingPathComponent(TransactionJournal.fileName) + let recorded = try #require(try FileSnapshot.read(at: journal)) + #expect(!FileManager.default.fileExists(atPath: store.declarationURL.path)) + #expect(FileManager.default.fileExists(atPath: store.resolvedURL.path)) + let before = try FileHash.folderHash(fixture.root) + + #expect(throws: pendingRecovery) { try store.loadDeclaration() } + #expect(throws: pendingRecovery) { try store.loadManifest() } + #expect(throws: pendingRecovery) { try store.loadResolved() } + #expect(throws: pendingRecovery) { try store.loadWatch() } + #expect(try FileSnapshot.read(at: journal) == recorded) + #expect(try FileHash.folderHash(fixture.root) == before) + + #expect(throws: CoreError.transactionRecovered(store.directory.path)) { try store.withLock {} } + #expect(try store.loadDeclaration() == Declaration(agents: [.cursor])) + #expect(!FileManager.default.fileExists(atPath: journal.path)) + } + + /// Planning from a declaration that the prepared document no longer projects to is a stale + /// preparation, and nothing is planned over the other writer's intent. + @Test func planningFromAnotherGenerationIsAStalePreparation() throws { + let fixture = try ScopeFixture() + let store = fixture.store + try store.save(declaration: Declaration(agents: [.cursor]), resolved: ResolvedState()) + let baseline = try StatePrecondition(store: store) + #expect( + throws: CoreError.invalidState( + "declaration changed during preparation: \(store.declarationURL.path)") + ) { + try store.planDeclaration( + Declaration(agents: [.codex]), replacing: Declaration(), prepared: baseline) + } + #expect( + try store.planDeclaration( + Declaration(agents: [.cursor]), replacing: Declaration(agents: [.cursor]), + prepared: baseline) == nil) + } + + /// A first add killed after publishing the lock but before its commit is recovered by the + /// next writer; neither readers nor writers report a missing declaration. + @Test func interruptedFirstCreationIsPendingRecoveryNotAMissingDeclaration() throws { + let fixture = try StateOperationFixture(.freshSkillAdd) + let store = fixture.store + terminateProcess( + try fixture.pause("skill-add", at: TransactionCheckpoint.publication(2, .created).name)) + #expect(FileManager.default.fileExists(atPath: store.resolvedURL.path)) + #expect(throws: pendingRecovery) { try store.loadDeclaration() } + #expect(throws: pendingRecovery) { try store.loadResolved() } + #expect(throws: CoreError.transactionRecovered(store.directory.path)) { try store.withLock {} } + try fixture.check(committed: false) + } + + /// Ref reconciliation reads watch state and the lock only, so an unreadable declaration + /// cannot hold it back. + @Test func watchReferenceRecoveryDoesNotReadTheDeclaration() throws { + let fixture = try WatchGitFixture() + try fixture.watch.add("source", environment: fixture.environment) + let stale = try fixture.head() + try fixture.rewrite("second") + try fixture.watch.seen("source", environment: fixture.environment) + let current = try fixture.head() + try fixture.mirrorGit(["update-ref", "refs/agents-watch/" + stale, stale]) + let marker = fixture.store.directory.appendingPathComponent("watch-refs.pending") + try Data().write(to: marker) + let unreadable = Data("version: [\n".utf8) + try unreadable.write(to: fixture.store.declarationURL) + + #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { + try fixture.store.withLock {} + } + #expect(try fixture.watchRefs() == [current]) + #expect(!FileManager.default.fileExists(atPath: marker.path)) + #expect(try Data(contentsOf: fixture.store.declarationURL) == unreadable) + #expect(throws: ManifestFailure.self) { try fixture.store.loadDeclaration() } + } + + @Test func stateTransactionsAcceptOnlyTheCurrentStateFiles() throws { + let fixture = try ScopeFixture() + let paths = TransactionPaths(store: fixture.store) + #expect(try paths.path(for: fixture.store.declarationURL) == "state/agents.yaml") + for name in ["agents.yaml", "agents.resolved", "agents.watch"] { + #expect(try paths.components("state/" + name).descendants == [name]) + } + for name in ["other.json", "agents.yaml.new"] { + #expect(throws: CoreError.unsafePath("unmanaged state transaction path")) { + try paths.components("state/" + name) + } + } + } +} + +private final class ScopeFixture { + let root: URL + let store: StateStore + var scopeLock: URL { store.directory.appendingPathComponent(".agents.lock") } + + init() throws { + root = try temporaryDirectory() + store = StateStore( + scope: .project, + environment: RuntimeEnvironment( + projectDirectory: root, homeDirectory: root.appendingPathComponent("home"), + environment: [:])) + } + + deinit { removeTemporaryDirectory(root) } +} diff --git a/Tests/AgentsCoreTests/DirectoryHandleTests.swift b/Tests/AgentsCoreTests/DirectoryHandleTests.swift new file mode 100644 index 0000000..08964a9 --- /dev/null +++ b/Tests/AgentsCoreTests/DirectoryHandleTests.swift @@ -0,0 +1,122 @@ +import CPlatform +import Foundation +import Testing + +@testable import AgentsCore + +@Suite("Portable filesystem contracts") +struct DirectoryHandleTests { + @Test func linkEvidenceHashesRawDestinationBytes() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let link = root.appendingPathComponent("link") + let bytes = [CChar(bitPattern: 0xff), 0] + try #require(bytes.withUnsafeBufferPointer { symlink($0.baseAddress!, link.path) } == 0) + let directory = try DirectoryHandle(at: root) + #expect(try directory.readLinkData("link") == Data([0xff])) + let snapshot = try #require(try FileSnapshot.read(at: link)) + #expect(snapshot.digest == FileHash.sha256Hex(data: Data([0xff]))) + #expect(snapshot.digest != FileHash.sha256Hex(data: Data("\u{fffd}".utf8))) + } + + @Test func enumeratesHiddenUnicodeAndLongNamesAcrossRepeatedReads() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let names = [".hidden", "目录-🌍", String(repeating: "a", count: 255)] + for name in names { try Data(name.utf8).write(to: root.appendingPathComponent(name)) } + let directory = try DirectoryHandle(at: root) + #expect(try directory.names() == names.sorted()) + #expect(try directory.names() == names.sorted()) + #expect( + try FileManager.default.contentsOfDirectory(atPath: root.path).sorted() == names.sorted()) + } + + @Test func copiesModesAndDanglingLinksWithoutFollowingThem() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let source = root.appendingPathComponent("source") + try FileManager.default.createDirectory(at: source, withIntermediateDirectories: true) + let content = Data(repeating: 0xa5, count: 200_000) + let file = source.appendingPathComponent("executable") + try content.write(to: file) + try FileManager.default.setAttributes([.posixPermissions: 0o751], ofItemAtPath: file.path) + try FileManager.default.createSymbolicLink( + atPath: source.appendingPathComponent("dangling").path, withDestinationPath: "missing") + try FileManager.default.createSymbolicLink( + atPath: source.appendingPathComponent("reference").path, withDestinationPath: "executable") + let directory = try DirectoryHandle(at: root) + try directory.copy("copy", from: directory, named: "source") + let copy = try directory.child("copy") + #expect(try copy.read("executable") == content) + let executableInfo = try #require(try copy.info("executable")) + #expect(executableInfo.st_mode & 0o7777 == 0o751) + #expect(try copy.readLink("dangling") == "missing") + #expect(try copy.readLink("reference") == "executable") + #expect( + try FileHash.folderHash(root.appendingPathComponent("copy")) == FileHash.folderHash(source)) + let dangling = root.appendingPathComponent("copy/dangling") + #expect(!FileManager.default.fileExists(atPath: dangling.path)) + #expect( + try FileManager.default.attributesOfItem(atPath: dangling.path)[.type] as? FileAttributeType + == .typeSymbolicLink) + #expect( + try FileManager.default.attributesOfItem(atPath: file.path)[.posixPermissions] as? NSNumber + == 0o751) + } + + @Test func atomicallyExchangesNonemptyDirectories() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + for name in ["first", "second"] { + let child = root.appendingPathComponent(name) + try FileManager.default.createDirectory(at: child, withIntermediateDirectories: true) + try Data(name.utf8).write(to: child.appendingPathComponent("content")) + } + let directory = try DirectoryHandle(at: root) + try directory.move("first", to: directory, named: "second", mode: .exchange) + #expect(try directory.child("first").read("content") == Data("second".utf8)) + #expect(try directory.child("second").read("content") == Data("first".utf8)) + } + + @Test(arguments: ["file", "directory", "link"]) + func exclusiveRenamePreservesConcurrentObjects(_ kind: String) throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let directory = try DirectoryHandle(at: root) + for name in ["staged", "external"] { + if kind == "directory" { + try directory.makeDirectory(name) + try directory.child(name).write("content", data: Data(name.utf8)) + } else if kind == "link" { + try directory.link(name, destination: name + "-destination") + } else { + try directory.write(name, data: Data(name.utf8)) + } + } + let staged = try FileSnapshot.read("staged", from: directory) + let external = try FileSnapshot.read("external", from: directory) + #expect(throws: CoreError.self) { + try directory.move("staged", to: directory, named: "external", mode: .exclusive) + } + #expect(try FileSnapshot.read("staged", from: directory) == staged) + #expect(try FileSnapshot.read("external", from: directory) == external) + try directory.move("staged", to: directory, named: "published", mode: .exclusive) + #expect(try FileSnapshot.read("published", from: directory) == staged) + #expect(try directory.info("staged") == nil) + } + + @Test func directoryAndRegularFileReadsRejectLinks() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let source = root.appendingPathComponent("source") + try FileManager.default.createDirectory(at: source, withIntermediateDirectories: true) + try Data("content".utf8).write(to: source.appendingPathComponent("file")) + let link = root.appendingPathComponent("link") + try FileManager.default.createSymbolicLink(at: link, withDestinationURL: source) + #expect(throws: CoreError.self) { try DirectoryHandle(at: link) } + let directory = try DirectoryHandle(at: root) + #expect(throws: CoreError.self) { try directory.read("link") } + let linkInfo = try #require(try directory.info("link")) + #expect(linkInfo.st_mode & S_IFMT == S_IFLNK) + } +} diff --git a/Tests/AgentsCoreTests/FileAccessTests.swift b/Tests/AgentsCoreTests/FileAccessTests.swift new file mode 100644 index 0000000..ca765e9 --- /dev/null +++ b/Tests/AgentsCoreTests/FileAccessTests.swift @@ -0,0 +1,246 @@ +import CPlatform +import Foundation +import Testing + +@testable import AgentsCore + +@Suite("Descriptor access and private creation") +struct FileAccessTests { + @Test func verifiesEmptyPrivateObjectsBeforeFirstPayloadWrite() throws { + let fixture = try AccessFixture() + let directory = try fixture.handle.createPrivateDirectory("private") + let file = try directory.createPrivateFile("payload") + var info = stat() + try #require(fstat(file.descriptor, &info) == 0) + #expect(info.st_size == 0) + #expect(info.st_mode & 0o7777 == 0o600) + #expect(info.st_uid == geteuid()) + #expect(file.evidence.group == info.st_gid) + #expect(try FileAccessEvidence.requirePrivate(descriptor: directory.descriptor).mode == 0o700) + let encoded = try JSONEncoder().encode(file.evidence) + #expect(try JSONDecoder().decode(FileAccessEvidence.self, from: encoded) == file.evidence) + let bytes = Data("private payload".utf8) + try file.write(bytes) + #expect(try directory.read("payload") == bytes) + #expect(try directory.accessEvidence("payload") == file.evidence) + } + + @Test(arguments: ["mode", "acl", "parent", "replacement"]) + func refusesChangedAccessBeforeAnyPayload(_ change: String) throws { + let fixture = try AccessFixture() + let file = try fixture.handle.createPrivateFile("payload") + switch change { + case "mode": try #require(fchmod(file.descriptor, 0o644) == 0) + case "acl": try grantRead(fixture.root.appendingPathComponent("payload")) + case "parent": try #require(fchmod(fixture.handle.descriptor, 0o777) == 0) + default: + try #require( + renameat(fixture.handle.descriptor, "payload", fixture.handle.descriptor, "old") == 0) + try fixture.handle.write("payload", data: Data("unrelated".utf8)) + } + #expect(throws: CoreError.self) { try file.write(Data("private payload".utf8)) } + var info = stat() + try #require(fstat(file.descriptor, &info) == 0) + #expect(info.st_size == 0) + if change == "replacement" { + #expect(try fixture.handle.read("payload") == Data("unrelated".utf8)) + } + } + + @Test func accessEvidenceDetectsACLChangesWithoutModeChanges() throws { + let fixture = try AccessFixture() + let file = try fixture.handle.createPrivateFile("payload") + let before = try FileAccessEvidence.capture(descriptor: file.descriptor) + #if os(macOS) + try addACL("everyone allow readsecurity", at: fixture.root.appendingPathComponent("payload")) + #else + try installPOSIXACL( + descriptor: file.descriptor, owner: 6, named: 4, mask: 0, defaultACL: false) + #endif + let after = try FileAccessEvidence.capture(descriptor: file.descriptor) + #expect(before.mode == after.mode) + #expect(before.identity == after.identity) + #expect(before.acl != after.acl) + #expect(throws: CoreError.self) { try before.validate(descriptor: file.descriptor) } + #expect(try FileAccessEvidence.requirePrivate(descriptor: file.descriptor) == after) + } + + @Test func effectiveACLGrantsAndOwnerDenialsAreEvaluated() throws { + let fixture = try AccessFixture() + let file = try fixture.handle.createPrivateFile("payload") + let url = fixture.root.appendingPathComponent("payload") + try grantRead(url) + #expect(throws: CoreError.self) { + try FileAccessEvidence.requirePrivate(descriptor: file.descriptor) + } + #if os(macOS) + var info = stat() + try #require(fstat(file.descriptor, &info) == 0) + #expect(info.st_mode & 0o777 == 0o600) + try addACL("everyone deny read", at: url) + #else + // A named read grant with a zero mask is not effective access. + try installPOSIXACL( + descriptor: file.descriptor, owner: 6, named: 4, mask: 0, defaultACL: false) + _ = try FileAccessEvidence.requirePrivate(descriptor: file.descriptor) + // Mask bits alone grant nothing when every masked entry is empty. + try installPOSIXACL( + descriptor: file.descriptor, owner: 6, named: 0, mask: 4, defaultACL: false) + _ = try FileAccessEvidence.requirePrivate(descriptor: file.descriptor) + try installPOSIXACL( + descriptor: file.descriptor, owner: 0, named: 4, mask: 0, defaultACL: false) + #endif + #expect(throws: CoreError.self) { + try FileAccessEvidence.requirePrivate(descriptor: file.descriptor) + } + // Exercise the actual kernel's current-owner open denial, not just ACL bytes. + try #require(geteuid() != 0) + let denied = open(url.path, O_RDONLY | O_NOFOLLOW | O_CLOEXEC) + let code = errno + if denied >= 0 { close(denied) } + #expect(denied == -1 && (code == EACCES || code == EPERM)) + } + + @Test func inheritanceIsCheckedOnTheCreatedInode() throws { + let fixture = try AccessFixture() + #if os(macOS) + try addACL("everyone allow read,file_inherit,only_inherit", at: fixture.root) + // Inherit-only grants do not grant access to this directory itself. + _ = try FileAccessEvidence.requirePrivate(descriptor: fixture.handle.descriptor) + #expect(throws: CoreError.self) { try fixture.handle.createPrivateFile("payload") } + #expect(try fixture.handle.info("payload") == nil) + #else + try installPOSIXACL( + descriptor: fixture.handle.descriptor, owner: 7, named: 4, mask: 4, defaultACL: true) + let before = try fixture.handle.accessEvidence() + #expect(!before.defaultACL.isEmpty) + let file = try fixture.handle.createPrivateFile("payload") + #expect(!file.evidence.acl.isEmpty) + _ = try FileAccessEvidence.requirePrivate(descriptor: file.descriptor) + try file.write(Data("private payload".utf8)) + // The create mode masks named access; an owner-denying default is still fatal. + try installPOSIXACL( + descriptor: fixture.handle.descriptor, owner: 0, named: 4, mask: 4, defaultACL: true) + #expect(throws: CoreError.self) { try fixture.handle.createPrivateFile("denied") } + #expect(try fixture.handle.info("denied") == nil) + #expect(throws: CoreError.self) { try before.validate(descriptor: fixture.handle.descriptor) } + #endif + } + + @Test func inheritedOwnerDenialDoesNotWriteOrRepairPolicy() throws { + let fixture = try AccessFixture() + try setRestrictiveInheritedDirectoryACL(fixture.root) + let before = try fixture.handle.accessEvidence() + #expect(throws: CoreError.self) { try fixture.handle.createPrivateDirectory("denied") } + #expect(try fixture.handle.info("denied") == nil) + #expect(try fixture.handle.accessEvidence() == before) + try setRestrictiveInheritedFileACL(fixture.root) + let filePolicy = try fixture.handle.accessEvidence() + #expect(throws: CoreError.self) { try fixture.handle.createPrivateFile("denied-file") } + // Some kernels create the empty inode before refusing the creating open. + // Without a returned descriptor, disposal belongs to the caller's recorded intent. + #expect(try fixture.handle.info("denied-file").map { $0.st_size == 0 } ?? true) + #expect(try fixture.handle.accessEvidence() == filePolicy) + } + + @Test func traversableAncestorsAndStickyOwnershipHaveDistinctReplacementRules() throws { + let fixture = try AccessFixture() + try #require(fchmod(fixture.handle.descriptor, 0o755) == 0) + _ = try FileAccessEvidence.requireNonReplaceableDirectory( + descriptor: fixture.handle.descriptor, protectingOwner: geteuid()) + let file = try fixture.handle.createPrivateFile("payload") + try file.write(Data("private payload".utf8)) + try #require(fchmod(fixture.handle.descriptor, 0o777) == 0) + #expect(throws: CoreError.self) { + try FileAccessEvidence.requireNonReplaceableDirectory( + descriptor: fixture.handle.descriptor, protectingOwner: geteuid()) + } + try #require(fchmod(fixture.handle.descriptor, 0o1777) == 0) + _ = try FileAccessEvidence.requireNonReplaceableDirectory( + descriptor: fixture.handle.descriptor, protectingOwner: geteuid()) + #expect(throws: CoreError.self) { + try FileAccessEvidence.requireNonReplaceableDirectory( + descriptor: fixture.handle.descriptor, protectingOwner: geteuid() + 1) + } + } + + @Test func namespaceEvidenceDetectsAncestorExchangeAndRefusesSymlinks() throws { + let fixture = try AccessFixture() + let ancestor = try fixture.handle.createPrivateDirectory("ancestor") + let before = try #require(try fixture.handle.accessEvidence("ancestor")) + try #require( + renameat(fixture.handle.descriptor, "ancestor", fixture.handle.descriptor, "old") == 0) + _ = try fixture.handle.createPrivateDirectory("ancestor") + #expect(try fixture.handle.accessEvidence("ancestor") != before) + // The old descriptor remains valid; callers must compare every namespace edge. + try before.validate(descriptor: ancestor.descriptor) + try fixture.handle.link("link", destination: "ancestor") + #expect(throws: CoreError.self) { try fixture.handle.accessEvidence("link") } + #expect(throws: CoreError.self) { try fixture.handle.createPrivateFile("link") } + #expect(throws: CoreError.self) { try fixture.handle.createPrivateFile("../escape") } + #expect(throws: CoreError.self) { try fixture.handle.createPrivateDirectory("nested/path") } + #expect(try fixture.handle.child("ancestor").names().isEmpty) + } +} + +private final class AccessFixture { + let root: URL + let handle: DirectoryHandle + + init() throws { + root = try temporaryDirectory() + do { + try #require(chmod(root.path, 0o700) == 0) + handle = try DirectoryHandle(at: root) + } catch { + removeTemporaryDirectory(root) + throw error + } + } + + deinit { + #if os(macOS) + do { try ProcessRunner.run("/bin/chmod", arguments: ["-RN", root.path]) } catch { + Issue.record(error) + } + #endif + chmod(root.path, 0o700) + removeTemporaryDirectory(root) + } +} + +private func grantRead(_ url: URL) throws { + #if os(macOS) + try addACL("everyone allow read", at: url) + #else + let file = open(url.path, O_RDONLY | O_NOFOLLOW | O_CLOEXEC) + try #require(file >= 0) + defer { close(file) } + try installPOSIXACL(descriptor: file, owner: 6, named: 4, mask: 4, defaultACL: false) + #endif +} + +#if os(macOS) + private func addACL(_ entry: String, at url: URL) throws { + try ProcessRunner.run("/bin/chmod", arguments: ["+a", entry, url.path]) + } +#else + private func installPOSIXACL( + descriptor: Int32, owner: UInt16, named: UInt16, mask: UInt16, defaultACL: Bool + ) throws { + var bytes = Data([2, 0, 0, 0]) + let foreignOwner: UInt32 = geteuid() == 65_534 ? 65_533 : 65_534 + for (tag, permissions, identifier): (UInt16, UInt16, UInt32) in [ + (1, owner, .max), (2, named, foreignOwner), (4, 0, .max), + (16, mask, .max), (32, 0, .max), + ] { + for field in [UInt32(tag) | (UInt32(permissions) << 16), identifier] { + var value = field.littleEndian + withUnsafeBytes(of: &value) { bytes.append(contentsOf: $0) } + } + } + let name = defaultACL ? "system.posix_acl_default" : "system.posix_acl_access" + try #require( + bytes.withUnsafeBytes { fsetxattr(descriptor, name, $0.baseAddress, $0.count, 0) } == 0) + } +#endif diff --git a/Tests/AgentsCoreTests/FileHashTests.swift b/Tests/AgentsCoreTests/FileHashTests.swift index ccc3168..8747760 100644 --- a/Tests/AgentsCoreTests/FileHashTests.swift +++ b/Tests/AgentsCoreTests/FileHashTests.swift @@ -5,6 +5,15 @@ import Testing @Suite("File hashes") struct FileHashTests { + @Test func sha256MatchesStandardVectors() { + #expect( + FileHash.sha256Hex(data: Data()) + == "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855") + #expect( + FileHash.sha256Hex(data: Data("abc".utf8)) + == "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad") + } + @Test func arbitraryBytesCannotImpersonateTreeEntries() throws { let root = try temporaryDirectory() defer { removeTemporaryDirectory(root) } @@ -43,6 +52,25 @@ struct FileHashTests { #expect(try FileHash.folderHash(root) != first) } + @Test func streamedTreeUsesTheCanonicalRecordOrder() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let directory = root.appendingPathComponent("rules") + let content = Data(repeating: 0x7e, count: 150_000) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false) + try content.write(to: directory.appendingPathComponent("guide")) + try Data("extra".utf8).write(to: root.appendingPathComponent("rules-extra")) + try FileManager.default.createSymbolicLink( + atPath: root.appendingPathComponent("rules0").path, withDestinationPath: "rules/guide") + let expected = FileHash.hashRecords([ + ("rules0", Data("link\0rules/guide".utf8)), + ("rules/guide", Data("file\0".utf8) + content), + ("rules-extra", Data("file\0extra".utf8)), + ("rules", Data("directory".utf8)), + ]) + #expect(try FileHash.folderHash(root) == expected) + } + @Test func hashesSymlinkedFolderLikeItsTarget() throws { let root = try temporaryDirectory() defer { removeTemporaryDirectory(root) } diff --git a/Tests/AgentsCoreTests/FileLockProcessTests.swift b/Tests/AgentsCoreTests/FileLockProcessTests.swift index a223281..fc5fb7d 100644 --- a/Tests/AgentsCoreTests/FileLockProcessTests.swift +++ b/Tests/AgentsCoreTests/FileLockProcessTests.swift @@ -1,17 +1,49 @@ import AgentsCore -import Darwin +import CPlatform import Foundation +import StateTestSupport import Testing @Suite("Inherited file locks") struct FileLockProcessTests { + @Test func lockedChildClosesUnrelatedDescriptors() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let file = open(root.appendingPathComponent("private").path, O_CREAT | O_RDWR, 0o600) + try #require(file >= 0) + defer { close(file) } + let unrelated = fcntl(file, F_DUPFD, 64) + try #require(unrelated >= 64) + defer { close(unrelated) } + try FileLock.withDescriptor(at: root.appendingPathComponent("writer.lock")) { descriptor in + let output = try ProcessRunner.run( + "/bin/sh", arguments: ["-c", "test ! -e /dev/fd/$1", "sh", String(unrelated)], + inheritingLock: descriptor) + #expect(output.exitCode == 0) + } + } + + @Test func lockedChildPropagatesLaunchErrors() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + try FileLock.withDescriptor(at: root.appendingPathComponent("writer.lock")) { descriptor in + let error = + try #require(throws: (any Error).self) { + try ProcessRunner.run( + root.appendingPathComponent("missing").path, arguments: [], inheritingLock: descriptor) + } as NSError + #expect(error.domain == NSPOSIXErrorDomain) + #expect(error.code == Int(ENOENT)) + } + } + @Test func childKeepsLockAfterParentClosesItsDescriptor() throws { let root = try temporaryDirectory() defer { try? FileManager.default.removeItem(at: root) } let lock = root.appendingPathComponent("writer.lock") let ready = root.appendingPathComponent("child-ready") var child: Int32? - defer { if let child { Darwin.kill(child, SIGKILL) } } + defer { if let child { CPlatform.kill(child, SIGKILL) } } try FileLock.withDescriptor(at: lock) { descriptor in let script = """ defined(my $child = fork) or die $!; @@ -30,9 +62,11 @@ struct FileLockProcessTests { let identifier = Int32(output.stdout) let pid: Int32 = try #require(identifier) child = pid - let deadline = Date().addingTimeInterval(10) - while !FileManager.default.fileExists(atPath: ready.path), Date() < deadline { - Thread.sleep(forTimeInterval: 0.01) + try ProcessWait.condition( + processIdentifier: pid, root: root, description: "grandchild readiness", + isRunning: { CPlatform.kill(pid, 0) == 0 } + ) { + FileManager.default.fileExists(atPath: ready.path) } #expect(try String(contentsOf: ready, encoding: .utf8) == String(pid)) #expect(fcntl(descriptor, F_GETFD) & FD_CLOEXEC != 0) @@ -40,18 +74,17 @@ struct FileLockProcessTests { let contender = open(lock.path, O_RDWR | O_CLOEXEC) try #require(contender >= 0) defer { close(contender) } - #expect(flock(contender, LOCK_EX | LOCK_NB) == -1) + #expect(platform_flock(contender, LOCK_EX | LOCK_NB) == -1) #expect(errno == EWOULDBLOCK) - Darwin.kill(try #require(child), SIGCONT) - let deadline = Date().addingTimeInterval(10) - var acquired = false - repeat { - if let child { Darwin.kill(child, SIGCONT) } - acquired = flock(contender, LOCK_EX | LOCK_NB) == 0 - if !acquired { Thread.sleep(forTimeInterval: 0.01) } - } while !acquired && Date() < deadline - #expect(acquired) - if acquired { child = nil } + let pid = try #require(child) + try ProcessWait.condition( + processIdentifier: pid, root: root, description: "grandchild lock release", + isRunning: { CPlatform.kill(pid, 0) == 0 }, + ready: { + CPlatform.kill(pid, SIGCONT) + return platform_flock(contender, LOCK_EX | LOCK_NB) == 0 + }) + child = nil } @Test func lockedChildPreservesStreamsDirectoryAndEnvironment() throws { @@ -124,7 +157,7 @@ struct FileLockProcessTests { !FileManager.default.fileExists(atPath: root.appendingPathComponent("lock-acquired").path)) #expect(FileManager.default.fileExists(atPath: gitLock.path)) - try finishProcesses([contender], resuming: pause) + try finishProcesses([contender], root: root, resuming: pause) #expect( FileManager.default.fileExists(atPath: root.appendingPathComponent("lock-acquired").path)) #expect(!FileManager.default.fileExists(atPath: gitLock.path)) @@ -139,7 +172,7 @@ struct FileLockProcessTests { defer { removeTemporaryDirectory(root) } let parent = try stateTestProcess(root: root, arguments: ["closed-streams", String(mask)]) defer { terminateProcess(parent) } - try finishProcesses([parent]) + try finishProcesses([parent], root: root) #expect(try String(contentsOf: root.appendingPathComponent("stdout"), encoding: .utf8) == "out") #expect(try String(contentsOf: root.appendingPathComponent("stderr"), encoding: .utf8) == "err") } diff --git a/Tests/AgentsCoreTests/FileSystemAccessTests.swift b/Tests/AgentsCoreTests/FileSystemAccessTests.swift new file mode 100644 index 0000000..dd7682f --- /dev/null +++ b/Tests/AgentsCoreTests/FileSystemAccessTests.swift @@ -0,0 +1,328 @@ +import CPlatform +import Foundation +import Testing + +@testable import AgentsCore + +@Suite( + "Filesystem access policy", + .enabled(if: geteuid() != 0, "Permission-denial checks require an unprivileged user"), + .timeLimit(.minutes(1))) +struct FileSystemAccessTests { + @Test func firstAndRepeatedLockAcquisitionsReportInheritedDenial() throws { + let fixture = try AccessPolicyFixture(directories: false) + let lock = fixture.directory.appendingPathComponent("writer.lock") + var identity: ino_t? + for _ in 0..<3 { + expectAccessDenied(at: lock) { + try FileLock.withLock(at: lock) { _ = Issue.record("Denied lock must not enter its body") } + } + var info = stat() + try #require(lstat(lock.path, &info) == 0) + if let identity { #expect(info.st_ino == identity) } + identity = info.st_ino + #expect(platform_access(AT_FDCWD, lock.path, R_OK | W_OK) == -1) + try fixture.expectUnchanged() + } + #expect(try fixture.names() == ["user.txt", "writer.lock"]) + } + + @Test(arguments: ["locks", "one/two/locks"]) + func missingLockAncestorsRemainDenied(_ path: String) throws { + let fixture = try AccessPolicyFixture(directories: true) + let directory = fixture.directory.appendingPathComponent(path) + for _ in 0..<3 { + expectAccessDenied(at: directory) { + try FileLock.withLock(at: directory.appendingPathComponent("writer.lock")) { + _ = Issue.record("Denied directory must not reach the operation") + } + } + try fixture.expectUnchanged() + } + #expect(try fixture.names() == [path.components(separatedBy: "/")[0], "user.txt"].sorted()) + } + + @Test func sharedDirectoryCreationReportsFirstAndRepeatedDenial() throws { + let fixture = try AccessPolicyFixture(directories: true) + let target = fixture.directory.appendingPathComponent("workspace") + for _ in 0..<3 { + expectAccessDenied(at: target) { try FileSystem.createDirectory(at: target) } + try fixture.expectUnchanged() + } + #expect(try fixture.names() == ["user.txt", "workspace"]) + } + + @Test func scopeOperationsStopBeforeChangingUserContent() throws { + let fixture = try AccessPolicyFixture(directories: true) + let store = StateStore( + scope: .project, environment: RuntimeEnvironment(projectDirectory: fixture.directory)) + for _ in 0..<3 { + expectAccessDenied(at: store.directory) { + try store.withLock { try Data("changed".utf8).write(to: fixture.userFile) } + } + try fixture.expectUnchanged() + } + } + + @Test(arguments: ["directory", "file", "copied-directory", "copied-file"]) + func entryCreationReportsFirstAndRepeatedDenial(_ kind: String) throws { + let fixture = try AccessPolicyFixture(directories: true) + let source = fixture.root.appendingPathComponent("source") + try FileManager.default.createDirectory(at: source, withIntermediateDirectories: false) + try Data("source".utf8).write(to: source.appendingPathComponent("content")) + let sourceHash = try FileHash.folderHash(source) + let directory = try DirectoryHandle(at: fixture.directory) + let target = fixture.directory.appendingPathComponent("entry") + for _ in 0..<3 { + expectAccessDenied(at: target) { + switch kind { + case "directory": try directory.makeDirectory("entry") + case "file": try directory.write("entry", data: Data("new bytes".utf8)) + case "copied-directory": + try directory.copy("entry", from: DirectoryHandle(at: fixture.root), named: "source") + default: + try directory.copy("entry", from: DirectoryHandle(at: source), named: "content") + } + } + try fixture.expectUnchanged() + #expect(try FileHash.folderHash(source) == sourceHash) + } + #expect(try fixture.names() == ["entry", "user.txt"]) + } + + @Test func deniedParentReportsDirectoryFileAndLinkCreationErrors() throws { + let fixture = try AccessPolicyFixture(directories: false) + let directory = try DirectoryHandle(at: fixture.directory) + try #require(chmod(fixture.directory.path, 0o500) == 0) + for _ in 0..<2 { + expectAccessDenied(at: fixture.directory.appendingPathComponent("child")) { + try directory.makeDirectory("child") + } + expectAccessDenied(at: fixture.directory.appendingPathComponent("file")) { + try directory.write("file", data: Data()) + } + expectAccessDenied(at: fixture.directory.appendingPathComponent("link")) { + try directory.link("link", destination: "user.txt") + } + #expect(try fixture.names() == ["user.txt"]) + #expect(try Data(contentsOf: fixture.userFile) == fixture.bytes) + #expect(try fixtureMetadata(fixture.userFile) == fixture.userMetadata) + } + } + + @Test func foundationPermissionErrorsKeepUserFilesUnchanged() throws { + let fixture = try AccessPolicyFixture(directories: false) + try #require(chmod(fixture.directory.path, 0o500) == 0) + let destination = fixture.directory.appendingPathComponent("copy") + for _ in 0..<2 { + expectAccessDenied(at: destination) { + try FileSystem.withAccessErrors(at: destination) { + try FileSystem.read(at: fixture.userFile).write(to: destination) + } + } + #expect(try Data(contentsOf: fixture.userFile) == fixture.bytes) + #expect(try fixtureMetadata(fixture.userFile) == fixture.userMetadata) + #expect(try fixture.names() == ["user.txt"]) + } + } + + @Test func unreadableCachedArtifactReportsItsPathOnEveryAttempt() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let store = StateStore(scope: .project, environment: RuntimeEnvironment(projectDirectory: root)) + let cache = SourceCache(store: store) + let bytes = Data("cached artifact".utf8) + let digest = "sha256:" + FileHash.sha256Hex(data: bytes) + let cached = try store.withLock { try cache.storeArtifact(bytes, digest: digest) } + var original = stat() + try #require(lstat(cached.path, &original) == 0) + try #require(chmod(cached.path, 0) == 0) + defer { chmod(cached.path, original.st_mode & 0o777) } + for _ in 0..<2 { + expectAccessDenied(at: cached) { + _ = try store.withLock { try cache.storeArtifact(bytes, digest: digest) } + } + expectAccessDenied(at: cached) { _ = try FileHash.sha256Hex(file: cached) } + expectAccessDenied(at: cached) { _ = try FileSystem.readUnlessDenied(at: cached) } + var current = stat() + try #require(lstat(cached.path, ¤t) == 0) + #expect(current.st_mode & 0o777 == 0 && current.st_ino == original.st_ino) + } + try #require(chmod(cached.path, original.st_mode & 0o777) == 0) + #expect(try Data(contentsOf: cached) == bytes) + } + + @Test func unreadableCopySourceReportsSourceInsteadOfDestination() throws { + let fixture = try AccessPolicyFixture(directories: false) + let source = fixture.userFile + let destination = fixture.root.appendingPathComponent("copy") + var original = stat() + try #require(lstat(source.path, &original) == 0) + try #require(chmod(source.path, 0) == 0) + defer { chmod(source.path, original.st_mode & 0o777) } + for _ in 0..<2 { + expectAccessDenied(at: source) { + try FileSystem.withAccessErrors(at: destination) { + try FileManager.default.copyItem(at: source, to: destination) + } + } + var current = stat() + try #require(lstat(source.path, ¤t) == 0) + #expect(current.st_mode & 0o777 == 0 && current.st_ino == original.st_ino) + if FileManager.default.fileExists(atPath: destination.path) { + try FileManager.default.removeItem(at: destination) + } + } + try #require(chmod(source.path, original.st_mode & 0o777) == 0) + try fixture.expectUnchanged() + } +} + +@Suite("Filesystem diagnostics") +struct FileSystemErrorTests { + @Test(arguments: [NSFilePathErrorKey, NSURLErrorKey], [false, true]) + func preservesFoundationPaths(_ key: String, nested: Bool) throws { + let operation = URL(fileURLWithPath: "/fixture/destination") + let source = URL(fileURLWithPath: "/fixture/source/file") + let value: Any = key == NSFilePathErrorKey ? source.path : source + let permission = NSError( + domain: NSCocoaErrorDomain, code: NSFileReadNoPermissionError, + userInfo: [ + key: value, + NSUnderlyingErrorKey: NSError(domain: NSPOSIXErrorDomain, code: Int(EACCES)), + ]) + let error = + nested + ? NSError( + domain: NSCocoaErrorDomain, code: NSFileWriteUnknownError, + userInfo: [NSFilePathErrorKey: operation.path, NSUnderlyingErrorKey: permission]) + : permission + expectAccessDenied(at: source) { + try FileSystem.withAccessErrors(at: operation) { throw error } + } + } + + @Test func optionalReadsTolerateEverythingButPermissionDenial() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + #expect(try FileSystem.readUnlessDenied(at: root.appendingPathComponent("missing")) == nil) + #expect(try FileSystem.readUnlessDenied(at: root) == nil) + } + + @Test(arguments: [EACCES, EPERM]) + func mapsPOSIXAndUnderlyingFoundationPermissionErrors(_ code: Int32) throws { + let path = URL(fileURLWithPath: "/fixture/entry") + let original = NSError(domain: NSPOSIXErrorDomain, code: Int(code)) + expectAccessDenied(at: path) { + throw FileSystem.posixError(code, at: path, otherwise: .invalidState("original")) + } + for error in [ + original, + NSError( + domain: NSCocoaErrorDomain, code: NSFileWriteUnknownError, + userInfo: [NSUnderlyingErrorKey: original]), + ] { + expectAccessDenied(at: path) { + try FileSystem.withAccessErrors(at: path) { throw error } + } + } + } + + @Test func preservesGitAndUnrelatedFailures() throws { + let path = URL(fileURLWithPath: "/fixture/entry") + let git = GitError( + operation: .clone, source: "source", stderr: "Permission denied", + command: ["git", "clone"], exitCode: 128) + #expect(throws: git) { try FileSystem.withAccessErrors(at: path) { throw git } } + let other = CoreError.invalidState("unrelated") + #expect(throws: other) { try FileSystem.withAccessErrors(at: path) { throw other } } + #expect(FileSystem.posixError(ENOSPC, at: path, otherwise: other) as? CoreError == other) + let exhausted = FileSystem.posixError(ENFILE, at: path, otherwise: other) + #expect(exhausted is OpenFileLimitError) + #expect(exhausted.localizedDescription == "Too many open files in the system: \(path.path)") + } + + @Test func existingLockRetainsContentIdentityAndMetadata() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let lock = root.appendingPathComponent("writer.lock") + let bytes = Data("existing lock".utf8) + try bytes.write(to: lock) + try setFixtureMetadata(lock, mode: 0o640, value: Data("owner metadata".utf8)) + let before = try fixtureMetadata(lock) + var original = stat() + try #require(lstat(lock.path, &original) == 0) + for _ in 0..<2 { + try FileLock.withDescriptor(at: lock) { descriptor in + var current = stat() + try #require(fstat(descriptor, ¤t) == 0) + #expect(current.st_ino == original.st_ino && current.st_dev == original.st_dev) + } + #expect(try Data(contentsOf: lock) == bytes) + #expect(try fixtureMetadata(lock) == before) + } + } +} + +private func expectAccessDenied(at url: URL, _ body: () throws -> Void) { + let expected = CoreError.invalidState( + "permission denied: \(url.path); check the directory's permissions and default ACL") + #expect(throws: expected) { try body() } +} + +private final class AccessPolicyFixture { + let root: URL + let directory: URL + let userFile: URL + let bytes = Data("user-owned content".utf8) + let userMetadata: FixtureMetadata + let directoryMetadata: FixtureMetadata + + init(directories: Bool) throws { + root = try temporaryDirectory() + directory = root.appendingPathComponent("policy") + userFile = directory.appendingPathComponent("user.txt") + do { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false) + try bytes.write(to: userFile) + try setFixtureMetadata(userFile, mode: 0o640, value: Data("user metadata".utf8)) + try setFixtureMetadata(directory, mode: 0o700, value: Data("directory metadata".utf8)) + if directories { + try setRestrictiveInheritedDirectoryACL(directory) + } else { + try setRestrictiveInheritedFileACL(directory) + } + userMetadata = try fixtureMetadata(userFile) + directoryMetadata = try fixtureMetadata(directory) + } catch { + removeTemporaryDirectory(root) + throw error + } + } + + deinit { + #if os(macOS) + do { try ProcessRunner.run("/bin/chmod", arguments: ["-RN", root.path]) } catch { + Issue.record(error) + } + #endif + // The test owns these denied entries; only teardown restores access to remove them. + chmod(directory.path, 0o700) + if let entries = FileManager.default.enumerator(atPath: root.path) { + for case let name as String in entries { + chmod(root.appendingPathComponent(name).path, 0o700) + } + } + removeTemporaryDirectory(root) + } + + func names() throws -> [String] { + try FileManager.default.contentsOfDirectory(atPath: directory.path).sorted() + } + + func expectUnchanged() throws { + #expect(try Data(contentsOf: userFile) == bytes) + #expect(try fixtureMetadata(userFile) == userMetadata) + #expect(try fixtureMetadata(directory) == directoryMetadata) + } +} diff --git a/Tests/AgentsCoreTests/GitErrorTests.swift b/Tests/AgentsCoreTests/GitErrorTests.swift index c4c736f..7fd5b81 100644 --- a/Tests/AgentsCoreTests/GitErrorTests.swift +++ b/Tests/AgentsCoreTests/GitErrorTests.swift @@ -1,4 +1,6 @@ +import AgentsManifest import Foundation +import StateTestSupport import Testing @testable import AgentsCore @@ -34,6 +36,30 @@ struct GitErrorTests { } } + @Test func locationContextPreservesSanitizedGitFailure() { + let source = "file://localhost/producer" + let mirror = URL(fileURLWithPath: "/temporary/cache/source.git") + let command = ["git", "-C", mirror.path, "fetch"] + var error = GitError( + operation: .fetch, source: source, + stderr: "Receiving objects: 100% (1/1), done.\nfatal: cannot read '\(mirror.path)'\n", + command: command, exitCode: 128, replacingPaths: [mirror]) + #expect(error.context.isEmpty) + let original = error + let span = SourceSpan( + document: DocumentIdentity("consumer/agents.yaml"), start: 10, end: 40, line: 3, column: 5) + error.context.append(span) + #expect(error.operation == original.operation) + #expect(error.source == original.source) + #expect(error.stderr == original.stderr) + #expect(error.command == original.command) + #expect(error.exitCode == original.exitCode) + #expect(error.context == [span]) + #expect(error.description == original.description + " at consumer/agents.yaml:3:5") + #expect(!error.description.contains(mirror.path)) + #expect(error.stderr == "fatal: cannot read '\(source)'") + } + @Test func missingFileRepositoryIdentifiesCloneAndSource() throws { let root = try temporaryDirectory() defer { removeTemporaryDirectory(root) } @@ -144,11 +170,20 @@ struct GitErrorTests { try initGitRepo(upstream) let store = StateStore(scope: .project, environment: RuntimeEnvironment(projectDirectory: root)) let source = SourceDeclaration(kind: .local, location: upstream.path) - try store.save(declaration: Declaration(sources: ["source": source]), resolved: ResolvedState()) + let id = try source.identity(environment: store.environment) + // Recovery knows a source location from the lock or watch state, never the declaration. + let head = try ProcessRunner.git( + ["-C", upstream.path, "rev-parse", "HEAD"], operation: .resolveRevision(revision: "HEAD"), + source: upstream.path + ).stdout.trimmingCharacters(in: .whitespacesAndNewlines) + var ledger = ResolvedLedger() + ledger.sources[id] = .init( + kind: .local, location: .init(kind: .absolute, path: upstream.path), revision: head) + try store.save(declaration: Declaration(sources: ["source": source]), ledger: ledger) let cache = SourceCache(store: store) _ = try cache.resolve(source) try cache.beginWatchReferenceUpdate() - let mirror = cache.mirrorURL(sourceID: try source.identity(environment: store.environment)) + let mirror = cache.mirrorURL(sourceID: id) try Data("[invalid\n".utf8).write(to: mirror.appendingPathComponent("config")) let error = try #require(throws: GitError.self) { try cache.recoverWatchReferences() } diff --git a/Tests/AgentsCoreTests/IndependentLedgerAdmissionTests.swift b/Tests/AgentsCoreTests/IndependentLedgerAdmissionTests.swift new file mode 100644 index 0000000..9d6110c --- /dev/null +++ b/Tests/AgentsCoreTests/IndependentLedgerAdmissionTests.swift @@ -0,0 +1,217 @@ +import AgentsManifest +import Foundation +import StateTestSupport +import Testing + +@testable import AgentsCore + +@Suite("Independent ledger admission") +struct IndependentLedgerAdmissionTests { + private var limits: LedgerLimits { + LedgerLimits( + encodedBytes: 32_768, depth: 32, nodes: 1_000, + objectBytes: 64, entries: 16, keyBytes: 256) + } + + private func fixture() -> ResolvedLedger { + var ledger = ResolvedLedger() + ledger.sources["source"] = LedgerSource( + kind: .local, revision: "revision", version: "braces { } and \"quoted\"") + let first = Data("a".utf8) + let second = Data("bc".utf8) + let firstID = "sha256:" + FileHash.sha256Hex(data: first) + let secondID = "sha256:" + FileHash.sha256Hex(data: second) + ledger.contentObjects = [firstID: first, secondID: second] + ledger.resources["first"] = LedgerResource( + kind: .embedded, source: "source", path: "first", hash: firstID, + entries: [ + LedgerEntry( + path: ".", kind: .file, object: firstID, executable: false, byteCount: first.count) + ]) + ledger.resources["second"] = LedgerResource( + kind: .embedded, source: "source", path: "second", hash: secondID, + entries: [ + LedgerEntry( + path: ".", kind: .file, object: secondID, executable: true, byteCount: second.count) + ]) + return ledger + } + + private func wire(_ ledger: ResolvedLedger) throws -> Data { + try ResolvedLedgerCodec.encode(ledger, limits: limits) + } + + private func object(_ data: Data) throws -> [String: Any] { + try #require(JSONSerialization.jsonObject(with: data) as? [String: Any]) + } + + private func data(_ object: [String: Any]) throws -> Data { + try JSONSerialization.data(withJSONObject: object, options: [.sortedKeys]) + } + + @Test func validControlsAndUnchangedReplacement() throws { + let ledger = fixture() + let canonical = try wire(ledger) + #expect(try ResolvedLedgerCodec.decode(canonical, limits: limits) == ledger) + + let pretty = try JSONSerialization.data( + withJSONObject: JSONSerialization.jsonObject(with: canonical), + options: [.prettyPrinted, .sortedKeys]) + #expect(pretty != canonical) + #expect(try ResolvedLedgerCodec.decode(pretty, limits: limits) == ledger) + #expect(try ResolvedLedgerCodec.replacement(ledger, existing: pretty, limits: limits) == nil) + var changed = ledger + changed.sources["source"]?.version = "another version" + let replacement = try #require( + try ResolvedLedgerCodec.replacement(changed, existing: pretty, limits: limits)) + #expect(try ResolvedLedgerCodec.decode(replacement, limits: limits) == changed) + } + + @Test func duplicateAndUnknownKeysAreRejected() throws { + let canonical = try wire(fixture()) + let text = try #require(String(data: canonical, encoding: .utf8)) + for prefix in [#""version":2,"#, #""ver\u0073ion":2,"#] { + let duplicate = Data(("{" + prefix + text.dropFirst()).utf8) + #expect(throws: (any Error).self) { + _ = try ResolvedLedgerCodec.decode(duplicate, limits: limits) + } + } + + var root = try object(canonical) + root["unexpected"] = NSNull() + let unknownRoot = try data(root) + #expect(throws: (any Error).self) { + _ = try ResolvedLedgerCodec.decode(unknownRoot, limits: limits) + } + root = try object(canonical) + var sources = try #require(root["sources"] as? [String: Any]) + var source = try #require(sources["source"] as? [String: Any]) + source["unexpected"] = NSNull() + sources["source"] = source + root["sources"] = sources + let unknownNested = try data(root) + #expect(throws: (any Error).self) { + _ = try ResolvedLedgerCodec.decode(unknownNested, limits: limits) + } + } + + @Test func knownOptionalNullIsAccepted() throws { + let ledger = fixture() + var root = try object(wire(ledger)) + var sources = try #require(root["sources"] as? [String: Any]) + var source = try #require(sources["source"] as? [String: Any]) + source["transport"] = NSNull() + sources["source"] = source + root["sources"] = sources + let bytes = try data(root) + #expect(try ResolvedLedgerCodec.decode(bytes, limits: limits) == ledger) + #expect(try ResolvedLedgerCodec.replacement(ledger, existing: bytes, limits: limits) == nil) + } + + @Test func versionsAndTagsAreStrict() throws { + let canonical = try wire(fixture()) + for version in [1, 3] { + var root = try object(canonical) + root["version"] = version + let bytes = try data(root) + #expect(throws: (any Error).self) { + _ = try ResolvedLedgerCodec.decode(bytes, limits: limits) + } + } + var root = try object(canonical) + var resources = try #require(root["resources"] as? [String: Any]) + var resource = try #require(resources["first"] as? [String: Any]) + resource["kind"] = "unknown" + resources["first"] = resource + root["resources"] = resources + let bytes = try data(root) + #expect(throws: (any Error).self) { + _ = try ResolvedLedgerCodec.decode(bytes, limits: limits) + } + } + + @Test func encodedAndAggregateObjectBudgets() throws { + let ledger = fixture() + let bytes = try wire(ledger) + var bound = limits + bound.encodedBytes = bytes.count + bound.objectBytes = 3 + #expect(try ResolvedLedgerCodec.decode(bytes, limits: bound) == ledger) + bound.encodedBytes = bytes.count - 1 + #expect(throws: (any Error).self) { + _ = try ResolvedLedgerCodec.decode(bytes, limits: bound) + } + bound.encodedBytes = bytes.count + bound.objectBytes = 2 + #expect(throws: (any Error).self) { + _ = try ResolvedLedgerCodec.decode(bytes, limits: bound) + } + + // JSON escapes do not change the decoded Base64 value or its byte budget. + let text = try #require(String(data: bytes, encoding: .utf8)) + let escaped = text.replacingOccurrences(of: #""YQ==""#, with: #""\u0059Q==""#) + #expect(escaped != text) + let escapedBytes = Data(escaped.utf8) + bound.encodedBytes = escapedBytes.count + bound.objectBytes = 3 + #expect(try ResolvedLedgerCodec.decode(escapedBytes, limits: bound) == ledger) + } + + @Test func structureAndEntryBudgets() throws { + let bytes = try wire(fixture()) + var bound = limits + bound.entries = 2 + #expect(try ResolvedLedgerCodec.decode(bytes, limits: bound) == fixture()) + bound.entries = 1 + #expect(throws: (any Error).self) { + _ = try ResolvedLedgerCodec.decode(bytes, limits: bound) + } + + let shallow = Data(#"{"a":[1,2]}"#.utf8) + bound = limits + bound.depth = 2 + bound.nodes = 4 + try LedgerAdmission.check(shallow, limits: bound) + bound.depth = 1 + #expect(throws: (any Error).self) { try LedgerAdmission.check(shallow, limits: bound) } + bound.depth = 2 + bound.nodes = 3 + #expect(throws: (any Error).self) { try LedgerAdmission.check(shallow, limits: bound) } + } + + @Test func corruptReferencesAndPathsFailAtCodecBoundary() throws { + let valid = fixture() + #expect(try ResolvedLedgerCodec.decode(wire(valid), limits: limits) == valid) + var broken = valid + let objectID = try #require(broken.resources["first"]?.entries.first?.object) + broken.contentObjects[objectID] = Data("different".utf8) + #expect(throws: (any Error).self) { _ = try wire(broken) } + + broken = valid + broken.contentObjects.removeValue(forKey: objectID) + #expect(throws: (any Error).self) { _ = try wire(broken) } + broken = valid + broken.resources["first"]?.source = "missing" + #expect(throws: (any Error).self) { _ = try wire(broken) } + for path in ["../escape", "/absolute", "a/../b"] { + broken = valid + broken.resources["first"]?.entries[0].path = path + #expect(throws: (any Error).self) { _ = try wire(broken) } + } + } + + @Test func publicDomainInventoryReadsV2WithoutRewriting() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let environment = RuntimeEnvironment( + projectDirectory: root, homeDirectory: root.appendingPathComponent("home"), environment: [:]) + let store = StateStore(scope: .project, environment: environment) + try store.save(declaration: Declaration(), resolved: ResolvedState()) + let declaration = try Data(contentsOf: store.declarationURL) + let bytes = try wire(fixture()) + try bytes.write(to: store.resolvedURL) + #expect(try store.loadResolved() == ResolvedState()) + #expect(try Data(contentsOf: store.resolvedURL) == bytes) + #expect(try Data(contentsOf: store.declarationURL) == declaration) + } +} diff --git a/Tests/AgentsCoreTests/InstructionTransactionTests.swift b/Tests/AgentsCoreTests/InstructionTransactionTests.swift index e28f640..09b5787 100644 --- a/Tests/AgentsCoreTests/InstructionTransactionTests.swift +++ b/Tests/AgentsCoreTests/InstructionTransactionTests.swift @@ -1,4 +1,6 @@ +import AgentsManifest import Foundation +import StateTestSupport import Testing @testable import AgentsCore @@ -30,14 +32,13 @@ struct InstructionTransactionTests { struct Interrupted: Error {} try store.withLock { let transaction = FileTransaction(store: store) { checkpoint in - if checkpoint == "replace.1" { throw Interrupted() } + if checkpoint == TransactionCheckpoint.progress(1, .applied).name { throw Interrupted() } } for file in files { - try transaction.replace( - file.resolvingSymlinksInPath(), content: nil, data: Data("new".utf8)) + try transaction.replace(file.resolvingSymlinksInPath(), with: .data(Data("new".utf8))) } try transaction.replace( - store.declarationURL, content: nil, data: StateStore.encode(Declaration(agents: [.codex]))) + store.declarationURL, with: .data(manifestText("defaultAgents: [\"codex\"]\n"))) #expect(throws: Interrupted.self) { try transaction.commit() } } for file in files { #expect(try Data(contentsOf: file) == Data("original".utf8)) } @@ -54,16 +55,22 @@ struct InstructionTransactionTests { projectDirectory: root, homeDirectory: root, environment: [:]) let store = StateStore(scope: .project, environment: environment) let paths = TransactionPaths(store: store) - #expect(throws: (any Error).self) { try paths.components("instructions-project/other.md") } - #expect(throws: (any Error).self) { try paths.components("instructions-project/../AGENTS.md") } - #expect(throws: (any Error).self) { try paths.components("instructions-codex/AGENTS.md") } - #expect(throws: (any Error).self) { + #expect(throws: CoreError.unsafePath("unmanaged project instruction path")) { + try paths.components("instructions-project/other.md") + } + #expect(throws: CoreError.invalidState("invalid scope-relative transaction path")) { + try paths.components("instructions-project/../AGENTS.md") + } + #expect(throws: CoreError.unsafePath("unmanaged installation transaction path")) { + try paths.components("instructions-codex/AGENTS.md") + } + #expect(throws: CoreError.unsafePath("unmanaged project instruction path")) { try paths.components("instructions-project/.git/AGENTS.md") } - #expect(throws: (any Error).self) { + #expect(throws: CoreError.unsafePath("unmanaged project instruction path")) { try paths.components("instructions-project/.agent/instructions/AGENTS.md") } - #expect(throws: (any Error).self) { + #expect(throws: CoreError.unsafePath("unmanaged project instruction path")) { try paths.components("instructions-project/Sources/CLAUDE.md") } #expect(throws: Never.self) { @@ -79,7 +86,9 @@ struct InstructionTransactionTests { "instructions-authoring/.agent/instructions/Rules.md", "instructions-authoring/.agent/instructions/notes.txt", ] { - #expect(throws: (any Error).self) { try paths.components(path) } + #expect(throws: CoreError.unsafePath("invalid instruction authoring path")) { + try paths.components(path) + } } let outside = root.appendingPathComponent("outside") try FileManager.default.createDirectory(at: outside, withIntermediateDirectories: true) @@ -89,8 +98,13 @@ struct InstructionTransactionTests { try store.withLock { let transaction = FileTransaction(store: store) try transaction.replace( - root.appendingPathComponent(".claude/CLAUDE.md"), content: nil, data: Data("new".utf8)) - #expect(throws: (any Error).self) { try transaction.commit() } + root.appendingPathComponent(".claude/CLAUDE.md"), with: .data(Data("new".utf8))) + #expect { + try transaction.commit() + } throws: { error in + guard case CoreError.unsafePath(let reason) = error else { return false } + return reason.contains("unsafe directory") && reason.contains(".claude") + } } #expect( try String(contentsOf: outside.appendingPathComponent("CLAUDE.md"), encoding: .utf8) diff --git a/Tests/AgentsCoreTests/LedgerAuthorityTests.swift b/Tests/AgentsCoreTests/LedgerAuthorityTests.swift new file mode 100644 index 0000000..878fabe --- /dev/null +++ b/Tests/AgentsCoreTests/LedgerAuthorityTests.swift @@ -0,0 +1,301 @@ +import Foundation +import Testing + +@testable import AgentsCore + +@Suite("Ledger native authority") +struct LedgerAuthorityTests { + private let hash = "sha256:" + String(repeating: "a", count: 64) + private var semantic: LedgerNativeArrayEvidence { + .semantic(format: "native-array@1", digest: hash) + } + + private func fixture() -> ResolvedLedger { + var ledger = ResolvedLedger() + ledger.sources["root"] = .init(kind: .local, revision: "live") + ledger.components["hook"] = .init( + declaringSource: "root", source: "root", root: ".", kind: "hook", name: "hook", + payload: .init(), conditions: [], recipients: [.claudeCode], chatGPT: false, resources: []) + let target = LedgerLocation(kind: .registered, root: "native-claude-project", path: ".mcp.json") + ledger.deployments = [ + .init( + id: "deployment", target: target, route: "test/native@1", owners: ["hook"], + recipients: [.claudeCode], ownership: .ownedValues, expectedHash: hash, created: false) + ] + ledger.lowerings = [ + .init( + id: "lowering", format: "test/native@1", inputs: ["hook"], resources: [], + deployments: ["deployment"], layout: .init(), platform: "macos", artifacts: []) + ] + ledger.nativeAuthorities = [ + .init( + target: target, targetRoute: "claude.mcp.project", documentFormat: "json", + regions: [ + .init( + deployments: ["deployment"], + path: [.key("hooks"), .position(index: 1, evidence: semantic)]) + ], + createdContainers: [ + .init(deployments: ["deployment"], path: [.key("hooks")], kind: "array") + ]) + ] + return ledger + } + + private func encoded(_ ledger: ResolvedLedger) throws -> Data { + try ResolvedLedgerCodec.encode(ledger, limits: .standard) + } + + @Test func publicAndPrivateEvidenceRoundTripWithoutRewriting() throws { + for evidence in [semantic, .privateArray(token: UUID())] { + var ledger = fixture() + ledger.nativeAuthorities![0].regions[0].path[1] = .position(index: 1, evidence: evidence) + let bytes = try encoded(ledger) + let pretty = try JSONSerialization.data( + withJSONObject: JSONSerialization.jsonObject(with: bytes), options: [.prettyPrinted]) + #expect(try ResolvedLedgerCodec.decode(pretty, limits: .standard) == ledger) + #expect( + try ResolvedLedgerCodec.replacement(ledger, existing: pretty, limits: .standard) == nil) + #expect(ledger.deployments[0].created == false) + } + var old = fixture() + old.nativeAuthorities = nil + let oldBytes = try encoded(old) + var wire = try #require(JSONSerialization.jsonObject(with: oldBytes) as? [String: Any]) + #expect(wire["nativeAuthorities"] == nil) + wire["nativeAuthorities"] = NSNull() + let nullable = try JSONSerialization.data(withJSONObject: wire) + #expect(try ResolvedLedgerCodec.decode(nullable, limits: .standard) == old) + #expect(try ResolvedLedgerCodec.replacement(old, existing: nullable, limits: .standard) == nil) + } + + @Test func equivalentRequirementsDoNotMaskPrivateContinuityChanges() throws { + var ledger = fixture() + ledger.sourceUses = [ + .init(source: "root", root: ".", requirement: .range(from: "v1.2.0", to: "2.0.0+meta")) + ] + ledger.nativeAuthorities![0].regions[0].path[1] = .position( + index: 1, evidence: .privateArray(token: UUID())) + let bytes = try encoded(ledger) + var next = ledger + next.sourceUses[0].requirement = .upToNextMajor(from: "1.2.0") + #expect(try ResolvedLedgerCodec.replacement(next, existing: bytes, limits: .standard) == nil) + next.nativeAuthorities![0].regions[0].path[1] = .position( + index: 1, evidence: .privateArray(token: UUID())) + #expect(try ResolvedLedgerCodec.replacement(next, existing: bytes, limits: .standard) != nil) + } + + @Test func strictTaggedWireRejectsUnknownAndWrongFields() throws { + let bytes = try encoded(fixture()) + let root = try #require(JSONSerialization.jsonObject(with: bytes) as? [String: Any]) + let authority = try #require((root["nativeAuthorities"] as? [[String: Any]])?.first) + let region = try #require((authority["regions"] as? [[String: Any]])?.first) + let path = try #require(region["path"] as? [[String: Any]]) + let evidence = try #require(path[1]["evidence"] as? [String: Any]) + for level in 0..<6 { + var changed = root + var a = authority + var r = region + var p = path + var e = evidence + switch level { + case 0: a["unknown"] = NSNull() + case 1: r["unknown"] = NSNull() + case 2: p[0]["index"] = NSNull() + case 3: p[1]["unknown"] = NSNull() + case 4: e["token"] = NSNull() + default: + var containers = try #require(a["createdContainers"] as? [[String: Any]]) + containers[0]["unknown"] = NSNull() + a["createdContainers"] = containers + } + p[1]["evidence"] = e + r["path"] = p + a["regions"] = [r] + changed["nativeAuthorities"] = [a] + #expect(throws: (any Error).self) { + _ = try ResolvedLedgerCodec.decode( + JSONSerialization.data(withJSONObject: changed), limits: .standard) + } + } + for invalid in [ + ["kind": "unknown"], ["kind": "key", "value": "x"], + [ + "kind": "position", "index": 0, + "evidence": ["kind": "privateArray", "token": "not-a-uuid"], + ], + ["kind": "position", "index": 0, "evidence": ["kind": "unknown"]], + ] as [[String: Any]] { + var changed = root + var a = authority + var r = region + r["path"] = [invalid] + a["regions"] = [r] + changed["nativeAuthorities"] = [a] + #expect(throws: (any Error).self) { + _ = try ResolvedLedgerCodec.decode( + JSONSerialization.data(withJSONObject: changed), limits: .standard) + } + } + } + + @Test func ownershipAndCreationRequireSurvivingDescendants() throws { + let original = fixture() + var valid = original + valid.deployments.append(original.deployments[0]) + valid.deployments[1].id = "second" + valid.lowerings[0].deployments.append("second") + valid.nativeAuthorities![0].regions[0].deployments.append("second") + valid.nativeAuthorities![0].createdContainers[0].deployments.append("second") + _ = try encoded(valid) + for failure in 0..<12 { + var ledger = original + switch failure { + case 0: ledger.nativeAuthorities![0].regions[0].deployments = [] + case 1: ledger.nativeAuthorities![0].regions[0].deployments = ["missing"] + case 2: ledger.nativeAuthorities![0].regions[0].deployments.append("deployment") + case 3: ledger.deployments[0].target.path = "other.json" + case 4: ledger.deployments[0].ownership = .generated + case 5: ledger.nativeAuthorities![0].createdContainers[0].path = [] + case 6: ledger.nativeAuthorities![0].createdContainers[0].path = [.key("other")] + case 7: ledger.nativeAuthorities![0].createdContainers[0].kind = "object" + case 8: ledger.nativeAuthorities![0].regions = [] + case 9: ledger.nativeAuthorities![0].createdContainers[0].deployments = [] + case 10: + ledger = valid + ledger.nativeAuthorities![0].regions[0].deployments = ["deployment"] + default: + ledger.nativeAuthorities![0].createdContainers[0].path = + ledger.nativeAuthorities![0].regions[0].path + } + #expect(throws: (any Error).self) { _ = try encoded(ledger) } + } + } + + @Test func closedVersionsFormatsAndOrdinalEvidence() throws { + for failure in 0..<7 { + var ledger = fixture() + switch failure { + case 0: ledger.nativeAuthorities![0].version = 2 + case 1: ledger.nativeAuthorities![0].targetRoute = "arbitrary.route" + case 2: ledger.nativeAuthorities![0].documentFormat = "yaml" + case 3: + ledger.nativeAuthorities![0].regions[0].path[1] = .position(index: -1, evidence: semantic) + case 4: + ledger.nativeAuthorities![0].regions[0].path[1] = .position( + index: 0, evidence: .semantic(format: "native-array@2", digest: hash)) + case 5: + ledger.nativeAuthorities![0].regions[0].path[1] = .position( + index: 0, evidence: .semantic(format: "native-array@1", digest: "bad")) + default: + ledger.nativeAuthorities![0].target = .init( + kind: .authoringRelative, root: "project", path: "x") + } + #expect(throws: (any Error).self) { _ = try encoded(ledger) } + } + for format in ["json", "jsonc", "jsonc-trailing-commas", "toml"] { + var ledger = fixture() + ledger.nativeAuthorities![0].documentFormat = format + _ = try encoded(ledger) + } + } + + @Test func duplicateLocationsAndContradictoryArrayPreimagesFail() throws { + for failure in 0..<5 { + var ledger = fixture() + switch failure { + case 0: ledger.nativeAuthorities!.append(ledger.nativeAuthorities![0]) + case 1: ledger.nativeAuthorities![0].regions.append(ledger.nativeAuthorities![0].regions[0]) + case 2: + ledger.nativeAuthorities![0].createdContainers.append( + ledger.nativeAuthorities![0].createdContainers[0]) + case 3: + ledger.nativeAuthorities![0].regions.append( + .init( + deployments: ["deployment"], + path: [.key("hooks"), .position(index: 0, evidence: .privateArray(token: UUID()))])) + default: + ledger.nativeAuthorities![0].regions.append( + .init( + deployments: ["deployment"], path: [.key("hooks"), .key("not-an-array")])) + } + #expect(throws: (any Error).self) { _ = try encoded(ledger) } + } + var distinct = fixture() + distinct.nativeAuthorities![0].regions.append( + .init( + deployments: ["deployment"], path: [.key("hooks"), .position(index: 0, evidence: semantic)]) + ) + _ = try encoded(distinct) + } + + @Test func nativeStringsAreByteExactAcrossKeysAndStableIDs() throws { + let composed = "é" + let decomposed = "e\u{301}" + #expect(composed == decomposed) + var ledger = fixture() + ledger.nativeAuthorities![0].createdContainers = [] + ledger.nativeAuthorities![0].regions = [composed, decomposed].flatMap { value in + [ + .init(deployments: ["deployment"], path: [.key(value)]), + .init( + deployments: ["deployment"], path: [.key("items"), .stableID(key: "id", value: value)]), + ] as [LedgerNativeOwnedRegion] + } + let encoded = try encoded(ledger) + #expect(try ResolvedLedgerCodec.decode(encoded, limits: .standard) == ledger) + var changed = ledger + changed.nativeAuthorities![0].regions[0].path = [.key(decomposed)] + #expect(changed != ledger) + #expect( + LedgerNativePathStep.stableID(key: composed, value: "x") + != .stableID(key: decomposed, value: "x")) + var mismatch = fixture() + mismatch.deployments[0].id = composed + mismatch.lowerings[0].deployments = [composed] + mismatch.nativeAuthorities![0].regions[0].deployments = [composed] + mismatch.nativeAuthorities![0].createdContainers[0].deployments = [composed] + _ = try self.encoded(mismatch) + mismatch.nativeAuthorities![0].regions[0].deployments = [decomposed] + #expect(throws: (any Error).self) { _ = try self.encoded(mismatch) } + var target = fixture() + target.deployments[0].target.path = composed + target.nativeAuthorities![0].target.path = composed + _ = try self.encoded(target) + target.nativeAuthorities![0].target.path = decomposed + #expect(throws: (any Error).self) { _ = try self.encoded(target) } + } + + @Test func authoritySharesAggregateModelAndWireBudgets() throws { + var ledger = fixture() + ledger.nativeAuthorities![0].createdContainers = [] + // Exercise the codec boundary with a budget measured from the actual encoded object graph. + func nodes(_ value: Any) -> Int { + if let object = value as? [String: Any] { + return 1 + object.values.reduce(0) { $0 + nodes($1) } + } + if let array = value as? [Any] { return 1 + array.reduce(0) { $0 + nodes($1) } } + return 1 + } + let bytes = try encoded(ledger) + let count = nodes(try JSONSerialization.jsonObject(with: bytes)) + var limits = LedgerLimits.standard + limits.nodes = count + limits.encodedBytes = bytes.count + #expect(try ResolvedLedgerCodec.decode(bytes, limits: limits) == ledger) + limits.nodes -= 1 + #expect(throws: (any Error).self) { _ = try ResolvedLedgerCodec.encode(ledger, limits: limits) } + limits = .standard + limits.nodes = 16 + ledger.nativeAuthorities![0].regions = (0..<20).map { + .init(deployments: ["deployment"], path: [.key("key-\($0)")]) + } + #expect(throws: (any Error).self) { try ResolvedLedgerCodec.checkModel(ledger, limits: limits) } + limits = .standard + limits.depth = 8 + ledger.nativeAuthorities![0].regions = [ + .init(deployments: ["deployment"], path: (0..<8).map { .key("\($0)") }) + ] + #expect(throws: (any Error).self) { try ResolvedLedgerCodec.checkModel(ledger, limits: limits) } + } +} diff --git a/Tests/AgentsCoreTests/LedgerCodecTests.swift b/Tests/AgentsCoreTests/LedgerCodecTests.swift new file mode 100644 index 0000000..29be10e --- /dev/null +++ b/Tests/AgentsCoreTests/LedgerCodecTests.swift @@ -0,0 +1,130 @@ +import CPlatform +import Foundation +import Testing + +@testable import AgentsCore + +@Suite("Ledger codec") +struct LedgerCodecTests { + @Test func emptyAndUnchangedBytes() throws { + let value = ResolvedLedger() + let bytes = try ResolvedLedgerCodec.encode(value, limits: .standard) + let spaced = Data(" \n".utf8) + bytes + #expect(try ResolvedLedgerCodec.decode(spaced, limits: .standard) == value) + #expect(try ResolvedLedgerCodec.replacement(value, existing: spaced, limits: .standard) == nil) + #expect(throws: (any Error).self) { _ = try StateStore.decode(bytes, as: ResolvedState.self) } + } + + @Test func strictAdmissionAndReferences() throws { + try LedgerAdmission.check( + Data(("{\"" + String(repeating: "k", count: 20_000) + "\":null}").utf8), limits: .standard) + let bytes = try ResolvedLedgerCodec.encode(ResolvedLedger(), limits: .standard) + var object = try #require(JSONSerialization.jsonObject(with: bytes) as? [String: Any]) + object["unknown"] = NSNull() + let unknown = try JSONSerialization.data(withJSONObject: object) + #expect(throws: (any Error).self) { + _ = try ResolvedLedgerCodec.decode(unknown, limits: .standard) + } + for malformed in [ + "{\"version\":2,\"version\":2}", "{\"a\":1,\"\\u0061\":2}", "[1,]", "[01]", "[true false]", + "\"\\uZZZZ\"", + ] { + #expect(throws: (any Error).self) { + try LedgerAdmission.check(Data(malformed.utf8), limits: .standard) + } + } + var limits = LedgerLimits.standard + limits.encodedBytes = bytes.count - 1 + #expect(throws: (any Error).self) { _ = try ResolvedLedgerCodec.decode(bytes, limits: limits) } + limits = .standard + limits.objectBytes = 2 + #expect(throws: (any Error).self) { + try LedgerAdmission.check(Data("{\"contentObjects\":{\"a\":\"YWJj\"}}".utf8), limits: limits) + } + limits = .standard + limits.depth = 2 + #expect(throws: (any Error).self) { + try LedgerAdmission.check(Data("[[[[]]]]".utf8), limits: limits) + } + var ledger = ResolvedLedger() + ledger.contentObjects["sha256:" + String(repeating: "0", count: 64)] = Data("bad".utf8) + #expect(throws: (any Error).self) { try ledger.validate() } + } + + @Test func locationsKeepAuthoredMeaning() throws { + let roots = ["home": URL(fileURLWithPath: "/new-home")] + #expect( + try LedgerLocation(kind: .registered, root: "home", path: "skills").resolve(roots: roots).path + == "/new-home/skills") + #expect( + try LedgerLocation(kind: .absolute, path: "/old-home/skills").resolve(roots: roots).path + == "/old-home/skills") + #expect( + try LedgerLocation(kind: .authoringRelative, root: "home", path: "../skills").resolve( + roots: roots + ).path == "/skills") + for path in ["../escape", "/absolute", "a/../b", "a//b", "~/x"] { + #expect(throws: (any Error).self) { + try LedgerLocation(kind: .registered, root: "home", path: path).validate() + } + } + } + + @Test func codecMeasurement() throws { + guard ProcessInfo.processInfo.environment["AGENTS_LEDGER_MEASURE"] == "1" else { return } + let count = + Int(ProcessInfo.processInfo.environment["AGENTS_LEDGER_MEASURE_BYTES"] ?? "") ?? 50 * 1024 + * 1024 + let entries = + Int(ProcessInfo.processInfo.environment["AGENTS_LEDGER_MEASURE_ENTRIES"] ?? "") ?? 1_000 + var ledger = ResolvedLedger() + let bytes = Data(repeating: 0x61, count: count) + let digest = "sha256:" + FileHash.sha256Hex(data: bytes) + ledger.contentObjects[digest] = bytes + let emptyDigest = "sha256:" + FileHash.sha256Hex(data: Data()) + ledger.contentObjects[emptyDigest] = Data() + ledger.sources["root"] = LedgerSource( + kind: .local, location: .init(kind: .registered, root: "project", path: "."), revision: "live" + ) + ledger.resources["resource"] = LedgerResource( + kind: .embedded, source: "root", path: ".", hash: digest, + entries: [LedgerEntry(path: ".", kind: .directory, executable: false)] + + (1.. (nodes: Int, depth: Int) { + let children: [Any] + if let object = value as? [String: Any] { + children = Array(object.values) + } else if let array = value as? [Any] { + children = array + } else { + children = [] + } + return children.reduce((1, depth)) { result, child in + let nested = shape(child, depth: depth + 1) + return (result.0 + nested.nodes, max(result.1, nested.depth)) + } + } + let structure = shape(try JSONSerialization.jsonObject(with: encoded)) + var usage = rusage() + #if os(Linux) + _ = getrusage(Int32(RUSAGE_SELF.rawValue), &usage) + #else + _ = getrusage(RUSAGE_SELF, &usage) + #endif + #if os(Linux) + let rss = usage.ru_maxrss * 1024 + #else + let rss = usage.ru_maxrss + #endif + print( + "LEDGER_MEASUREMENT nodes=\(structure.nodes) depth=\(structure.depth) entries=\(entries) peakRSSBytes=\(rss) decodedBytes=\(count) encodedBytes=\(encoded.count) seconds=\(Date().timeIntervalSince(start))" + ) + } +} diff --git a/Tests/AgentsCoreTests/LedgerGraphReviewTests.swift b/Tests/AgentsCoreTests/LedgerGraphReviewTests.swift new file mode 100644 index 0000000..afdd6f9 --- /dev/null +++ b/Tests/AgentsCoreTests/LedgerGraphReviewTests.swift @@ -0,0 +1,115 @@ +import Foundation +import Testing + +@testable import AgentsCore + +@Suite("Ledger graph integrity") +struct LedgerGraphReviewTests { + private let hash = "sha256:" + String(repeating: "0", count: 64) + + private func resource(_ entries: [LedgerEntry], support: [LedgerEntry] = []) -> LedgerResource { + .init( + kind: .embedded, source: "root", path: "vendor", hash: hash, + entries: entries, support: support) + } + + @Test func linksResolveBeforeParentTraversal() throws { + let root = LedgerEntry(path: ".", kind: .directory, executable: false) + let alias = LedgerEntry(path: "a", kind: .symlink, link: ".", executable: false) + let escape = LedgerEntry(path: "b", kind: .symlink, link: "a/../outside", executable: false) + #expect(throws: (any Error).self) { + _ = try LedgerResources.validatedEntries(resource([root, alias, escape])) + } + let valid = LedgerEntry(path: "b", kind: .symlink, link: "a/a", executable: false) + #expect(try LedgerResources.validatedEntries(resource([root, alias, valid])).count == 3) + let missing = LedgerEntry(path: "b", kind: .symlink, link: "absent", executable: false) + #expect(throws: (any Error).self) { + _ = try LedgerResources.validatedEntries(resource([root, missing])) + } + let cycle = LedgerEntry(path: "b", kind: .symlink, link: "b", executable: false) + #expect(throws: (any Error).self) { + _ = try LedgerResources.validatedEntries(resource([root, cycle])) + } + } + + @Test func supportingAndRootLinksUseOwnedRoot() throws { + let selected = LedgerEntry(path: ".", kind: .symlink, link: "shared/file", executable: false) + let directory = LedgerEntry(path: "shared", kind: .directory, executable: false) + let file = LedgerEntry(path: "shared/file", kind: .file, executable: false, byteCount: 0) + #expect( + try LedgerResources.validatedEntries(resource([selected], support: [directory, file])).count + == 4) + #expect(throws: (any Error).self) { + _ = try LedgerResources.validatedEntries(resource([selected], support: [directory])) + } + #expect(throws: (any Error).self) { + _ = try LedgerResources.validatedEntries(resource([selected])) + } + let escaping = LedgerEntry(path: "shared/a", kind: .symlink, link: ".", executable: false) + let outside = LedgerEntry( + path: "shared/b", kind: .symlink, link: "a/../../outside", executable: false) + #expect(throws: (any Error).self) { + _ = try LedgerResources.validatedEntries( + resource([selected], support: [directory, file, escaping, outside])) + } + } + + @Test func capturesIntermediateSupportingLinksAndMaterializesContainedChains() throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + let source = root.appendingPathComponent("source") + let selected = source.appendingPathComponent("vendor") + try FileManager.default.createDirectory(at: selected, withIntermediateDirectories: true) + try FileManager.default.createDirectory( + at: source.appendingPathComponent("shared"), withIntermediateDirectories: true) + try Data("content".utf8).write(to: source.appendingPathComponent("shared/file")) + try FileManager.default.createSymbolicLink( + atPath: source.appendingPathComponent("alias").path, withDestinationPath: "shared") + try FileManager.default.createSymbolicLink( + atPath: selected.appendingPathComponent("a").path, withDestinationPath: ".") + try FileManager.default.createSymbolicLink( + atPath: selected.appendingPathComponent("link").path, withDestinationPath: "a/a/../alias/file" + ) + let captured = try LedgerResources.capture( + selected, embed: true, limits: .standard, sourceRoot: source) + let record = LedgerResource( + kind: .embedded, source: "root", path: "vendor", hash: captured.hash, + entries: captured.entries, support: captured.support) + #expect(record.support.contains { $0.path == "alias" && $0.kind == .symlink }) + let destination = root.appendingPathComponent("materialized") + try LedgerResources.materialize(record, objects: captured.objects, at: destination) + #expect( + try Data(contentsOf: destination.appendingPathComponent("vendor/link")) + == Data("content".utf8)) + let gitCapture = try LedgerResources.capture( + selected, embed: false, limits: .standard, sourceRoot: source) + #expect(gitCapture.support.map(\.path) == captured.support.map(\.path)) + #expect(gitCapture.objects.isEmpty) + var escaped = record + escaped.entries.append( + .init(path: "bad", kind: .symlink, link: "a/../../outside", executable: false)) + let rejected = root.appendingPathComponent("rejected") + #expect(throws: (any Error).self) { + try LedgerResources.materialize(escaped, objects: captured.objects, at: rejected) + } + #expect(!FileManager.default.fileExists(atPath: rejected.path)) + } + + @Test func largeFlatGroupsAreAdmittedAndValidated() throws { + var ledger = ResolvedLedger() + ledger.sources["root"] = .init(kind: .local, revision: "live") + ledger.groups = (0..<100_000).map { + .init(id: $0, source: "root", root: ".", name: "group", manifestHash: hash, children: []) + } + let started = Date() + let encoded = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + #expect(try ResolvedLedgerCodec.decode(encoded, limits: .standard) == ledger) + print( + "LEDGER_GROUP_CONTROL groups=\(ledger.groups.count) encodedBytes=\(encoded.count) seconds=\(Date().timeIntervalSince(started))" + ) + ledger.groups[0].children = [1] + #expect(throws: (any Error).self) { try ledger.validate() } + ledger.groups[1].parent = 0 + try ledger.validate() + } +} diff --git a/Tests/AgentsCoreTests/LedgerProjectionTests.swift b/Tests/AgentsCoreTests/LedgerProjectionTests.swift new file mode 100644 index 0000000..72b287e --- /dev/null +++ b/Tests/AgentsCoreTests/LedgerProjectionTests.swift @@ -0,0 +1,42 @@ +import Foundation +import Testing + +@testable import AgentsCore + +@Suite("Ledger domain projection") +struct LedgerProjectionTests { + @Test func instructionTargetsUseTheirActualRoutes() throws { + let root = URL(fileURLWithPath: "/projection-project") + let home = URL(fileURLWithPath: "/projection-home") + var ledger = ResolvedLedger() + let hash = "sha256:" + String(repeating: "a", count: 64) + ledger.sources["root"] = .init(kind: .local, revision: "live") + ledger.components["input"] = .init( + declaringSource: "root", source: "root", root: ".", kind: "command", name: "review", + payload: .init(), conditions: [], recipients: [.claudeCode], chatGPT: false, resources: []) + for (index, record) in [ + ("agents/instructions@1", "AGENTS.md", LedgerDeployment.Ownership.generated), + ("agents/claude-import@1", "CLAUDE.md", .importBlock), + ("agents/claude-components@1", ".claude/commands/review.md", .generated), + ("agents/claude-components@1", ".claude/plugins/review", .generated), + ("agents/skill@1", ".claude/skills/review", .generated), + ].enumerated() { + let id = "deployment-\(index)" + ledger.deployments.append( + .init( + id: id, target: .init(kind: .registered, root: "project", path: record.1), + route: record.0, owners: ["input"], recipients: [.claudeCode], ownership: record.2, + expectedHash: hash, created: index == 1, importReference: index == 1 ? "AGENTS.md" : nil)) + ledger.lowerings.append( + .init( + id: "lowering-\(index)", format: record.0, inputs: ["input"], resources: [], + deployments: [id], layout: .init(), platform: "macos", artifacts: [])) + } + try ledger.validate() + let projection = try ledger.domainProjection(roots: ["project": root, "home": home]) + #expect(Set(projection.instructions.targets.keys) == ["AGENTS.md", "CLAUDE.md"]) + #expect(projection.instructions.targets["CLAUDE.md"]?.import == "AGENTS.md") + #expect(projection.instructions.targets["CLAUDE.md"]?.created == true) + #expect(projection.instructions.targets["AGENTS.md"]?.blockHash == hash) + } +} diff --git a/Tests/AgentsCoreTests/LedgerRetentionTests.swift b/Tests/AgentsCoreTests/LedgerRetentionTests.swift new file mode 100644 index 0000000..8feff32 --- /dev/null +++ b/Tests/AgentsCoreTests/LedgerRetentionTests.swift @@ -0,0 +1,60 @@ +import Foundation +import Testing + +@testable import AgentsCore + +@Suite("Ledger retention") +struct LedgerRetentionTests { + @Test func completeClosureRetainsNonSkillPinsAndWatch() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let store = StateStore(scope: .project, environment: RuntimeEnvironment(projectDirectory: root)) + try FileSystem.createDirectory(at: store.directory) + let cache = SourceCache(store: store) + let source = "github.com/example/components" + let pin = String(repeating: "a", count: 40) + let obsolete = String(repeating: "b", count: 40) + let kept = cache.materializedURL(sourceID: source, revision: pin) + let unused = cache.materializedURL(sourceID: source, revision: obsolete) + try FileSystem.createDirectory(at: kept) + try FileSystem.createDirectory(at: unused) + var ledger = ResolvedLedger() + ledger.sources["group-source"] = LedgerSource( + kind: .git, + transport: "https://github.com/example/components.git", revision: pin) + ledger.groups = [ + LedgerGroup( + id: 0, source: "group-source", root: ".", name: "empty-export", + manifestHash: "sha256:" + String(repeating: "c", count: 64), children: []) + ] + var references = try RetentionReferences(ledger: ledger, roots: [:]) + #expect(references.git.count == 1) + let tx = FileTransaction(store: store) + try cache.prune(references: references, transaction: tx) + #expect(FileManager.default.fileExists(atPath: unused.path)) + try tx.commit() + #expect(FileManager.default.fileExists(atPath: kept.path)) + #expect(!FileManager.default.fileExists(atPath: unused.path)) + ledger.groups = [] + ledger.sources = [:] + references = try RetentionReferences(ledger: ledger, roots: [:]) + try references.include( + watch: WatchState(sources: [source: WatchSourceState(seen: .revision(pin))])) + let watched = FileTransaction(store: store) + try cache.prune(references: references, transaction: watched) + try watched.commit() + #expect(FileManager.default.fileExists(atPath: kept.path)) + let released = FileTransaction(store: store) + try cache.prune(references: RetentionReferences(), transaction: released) + try released.commit() + #expect(!FileManager.default.fileExists(atPath: kept.path)) + } + + @Test func danglingAncestryAndReferencesReject() throws { + var ledger = ResolvedLedger() + ledger.sources["child"] = LedgerSource(kind: .local, revision: "x", container: "missing") + #expect(throws: (any Error).self) { _ = try RetentionReferences(ledger: ledger, roots: [:]) } + ledger.sources["missing"] = LedgerSource(kind: .local, revision: "x", container: "child") + #expect(throws: (any Error).self) { try ledger.validate() } + } +} diff --git a/Tests/AgentsCoreTests/LedgerWireSpellingTests.swift b/Tests/AgentsCoreTests/LedgerWireSpellingTests.swift new file mode 100644 index 0000000..1881b5a --- /dev/null +++ b/Tests/AgentsCoreTests/LedgerWireSpellingTests.swift @@ -0,0 +1,169 @@ +import Foundation +import Testing + +@testable import AgentsCore + +@Suite("Ledger wire spelling") +struct LedgerWireSpellingTests { + @Test func pendingMarketplaceWireBindsBothClosuresAndSharesContentObjects() throws { + let shared = Data("shared".utf8) + let addition = Data("added".utf8) + let sharedID = "sha256:" + FileHash.sha256Hex(data: shared) + let additionID = "sha256:" + FileHash.sha256Hex(data: addition) + var deployed = ResolvedLedger() + deployed.contentObjects[sharedID] = shared + let original = try ResolvedLedgerCodec.encode(deployed, limits: .standard) + let oldWire = try #require(JSONSerialization.jsonObject(with: original) as? [String: Any]) + #expect(oldWire["pendingMarketplaceDeployment"] == nil) + #expect(try ResolvedLedgerCodec.decode(original, limits: .standard) == deployed) + + var desired = deployed + desired.contentObjects[additionID] = addition + deployed.pendingDeployment = try MarketplacePendingDeploymentRecord( + ledger: desired, deployed: deployed, declarationDigest: sharedID) + var limits = LedgerLimits.standard + limits.objectBytes = shared.count + addition.count + let bytes = try ResolvedLedgerCodec.encode(deployed, limits: limits) + let decoded = try ResolvedLedgerCodec.decode(bytes, limits: limits) + #expect(decoded == deployed) + #expect(try decoded.pendingDeployment?.desired(in: decoded) == desired) + limits.objectBytes -= 1 + #expect(throws: CoreError.self) { try LedgerAdmission.check(bytes, limits: limits) } + + var invalid = decoded + invalid.sources["changed"] = .init(kind: .local, revision: "live") + #expect(throws: CoreError.self) { try ResolvedLedgerCodec.encode(invalid, limits: .standard) } + var root = try #require(JSONSerialization.jsonObject(with: bytes) as? [String: Any]) + var pending = try #require(root["pendingMarketplaceDeployment"] as? [String: Any]) + pending["digest"] = sharedID + root["pendingMarketplaceDeployment"] = pending + #expect(throws: CoreError.self) { + try ResolvedLedgerCodec.decode( + JSONSerialization.data(withJSONObject: root), limits: .standard) + } + } + + @Test func nullableMembersFollowTheirOwningRecords() throws { + var ledger = ResolvedLedger() + ledger.sources["source"] = LedgerSource(kind: .local, revision: "live") + ledger.sourceUses = [ + LedgerSourceUse(source: "source", root: "."), + LedgerSourceUse(source: "source", root: ".", requirement: .upToNextMajor(from: "1.0.0")), + ] + ledger.lowerings = [ + LockedLowering( + id: "value", format: "test/value@1", inputs: [], resources: [], deployments: [], + layout: .init(), platform: "macos", artifacts: []) + ] + let encoded = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + var root = try #require(JSONSerialization.jsonObject(with: encoded) as? [String: Any]) + var sources = try #require(root["sources"] as? [String: Any]) + var source = try #require(sources["source"] as? [String: Any]) + for key in ["transport", "location", "version", "container", "namespace"] { + source[key] = NSNull() + } + sources["source"] = source + root["sources"] = sources + root["sourceUses"] = [ + ["source": "source", "root": ".", "requirement": NSNull()], + ["source": "source", "root": ".", "requirement": ["from": "1.0.0", "to": NSNull()]], + ] + var lowerings = try #require(root["lowerings"] as? [[String: Any]]) + var layout: [String: Any] = ["kind": "null"] + for key in ["text", "integer", "boolean", "array", "object"] { layout[key] = NSNull() } + lowerings[0]["layout"] = layout + root["lowerings"] = lowerings + let bytes = try JSONSerialization.data(withJSONObject: root) + #expect(try ResolvedLedgerCodec.decode(bytes, limits: .standard) == ledger) + #expect(try ResolvedLedgerCodec.replacement(ledger, existing: bytes, limits: .standard) == nil) + + // A member nullable in a source is still unknown at the ledger root or in a tagged value. + root["transport"] = NSNull() + #expect(throws: (any Error).self) { + _ = try ResolvedLedgerCodec.decode( + JSONSerialization.data(withJSONObject: root), limits: .standard) + } + root.removeValue(forKey: "transport") + layout["namespace"] = NSNull() + lowerings[0]["layout"] = layout + root["lowerings"] = lowerings + #expect(throws: (any Error).self) { + _ = try ResolvedLedgerCodec.decode( + JSONSerialization.data(withJSONObject: root), limits: .standard) + } + layout.removeValue(forKey: "namespace") + layout["kind"] = "array" + lowerings[0]["layout"] = layout + root["lowerings"] = lowerings + #expect(throws: (any Error).self) { + _ = try ResolvedLedgerCodec.decode( + JSONSerialization.data(withJSONObject: root), limits: .standard) + } + layout["array"] = [] as [Any] + lowerings[0]["layout"] = layout + root["lowerings"] = lowerings + let emptyArray = try ResolvedLedgerCodec.decode( + JSONSerialization.data(withJSONObject: root), limits: .standard) + #expect(emptyArray.lowerings[0].layout.array == []) + } + + @Test func escapedBase64UsesDecodedAggregateSize() throws { + var limits = LedgerLimits.standard + limits.objectBytes = 3 + for spelling in [#"YQ=="#, #"\u0059Q=="#, #"YQ\u003d\u003D"#] { + let bytes = Data((#"{"contentObjects":{"first":""# + spelling + #"","second":"YmM="}}"#).utf8) + limits.encodedBytes = bytes.count + try LedgerAdmission.check(bytes, limits: limits) + limits.objectBytes = 2 + #expect(throws: (any Error).self) { try LedgerAdmission.check(bytes, limits: limits) } + limits.objectBytes = 3 + } + limits = .standard + limits.objectBytes = 1 + for spelling in [#"/w=="#, #"\/w=="#, #"\u002fw\u003d="#] { + try LedgerAdmission.check( + Data((#"{"contentObjects":{"first":""# + spelling + #""}}"#).utf8), limits: limits) + } + } + + @Test func literalAndEscapedKeysShareDuplicateDetection() throws { + try LedgerAdmission.check(Data(#"{"é":1,"":2}"#.utf8), limits: .standard) + for object in [ + #"{ "key": 1, "\u006bey": 2 }"#, + #"{ "é": 1, "\u00e9": 2 }"#, + "{\"é\":1,\"e\u{301}\":2}", + ] { + #expect(throws: CoreError.invalidState("duplicate ledger key")) { + try LedgerAdmission.check(Data(object.utf8), limits: .standard) + } + } + } + + @Test func keySpellingPreservesWireSizeAndDecodedBudgetSelection() throws { + var limits = LedgerLimits.standard + limits.keyBytes = 4 + try LedgerAdmission.check(Data(#"{"é":0}"#.utf8), limits: limits) + #expect(throws: CoreError.invalidState("ledger key budget")) { + try LedgerAdmission.check(Data(#"{"\u00e9":0}"#.utf8), limits: limits) + } + limits = .standard + limits.entries = 1 + #expect(throws: CoreError.invalidState("ledger entry budget")) { + try LedgerAdmission.check(Data(#"{"\u0065ntries":[1,2]}"#.utf8), limits: limits) + } + limits.objectBytes = 2 + #expect(throws: CoreError.invalidState("ledger content byte budget")) { + try LedgerAdmission.check( + Data(#"{"\u0063ontentObjects":{"data":"YWJj"}}"#.utf8), limits: limits) + } + } + + @Test func invalidEscapedContentCannotBypassAdmission() throws { + for spelling in [#"Y\nQ=="#, #"YQ\u003dA"#, #"\uD800Q=="#, #"YQ===\u003d"#] { + let bytes = Data((#"{"contentObjects":{"first":""# + spelling + #""}}"#).utf8) + #expect(throws: (any Error).self) { + try LedgerAdmission.check(bytes, limits: .standard) + } + } + } +} diff --git a/Tests/AgentsCoreTests/MetadataTestSupport.swift b/Tests/AgentsCoreTests/MetadataTestSupport.swift new file mode 100644 index 0000000..a36aaa3 --- /dev/null +++ b/Tests/AgentsCoreTests/MetadataTestSupport.swift @@ -0,0 +1,139 @@ +import AgentsCore +import CPlatform +import Foundation +import Testing + +struct FixtureMetadata: Equatable { + var mode: mode_t + var acl: Data + var attribute: Data + var defaultACL = Data() +} + +func setRestrictiveInheritedFileACL(_ directory: URL) throws { + do { + #if os(macOS) + try ProcessRunner.run( + "/bin/chmod", + arguments: ["+a", "everyone deny read,write,file_inherit,only_inherit", directory.path]) + #else + try setFixtureMetadata( + directory, mode: 0o700, value: Data(), defaultOwnerPermissions: 5) + #endif + } catch { + throw CoreError.invalidState( + "Restrictive inherited ACL fixture unavailable at \(directory.path): \(error)") + } +} + +func setRestrictiveInheritedDirectoryACL(_ directory: URL) throws { + do { + try setFixtureMetadata(directory, mode: 0o700, value: Data(), defaultOwnerPermissions: 5) + #if os(macOS) + try ProcessRunner.run( + "/bin/chmod", + arguments: [ + "+a", "everyone deny write,append,file_inherit,directory_inherit,only_inherit", + directory.path, + ]) + #endif + } catch { + throw CoreError.invalidState( + "Restrictive inherited directory ACL fixture unavailable at \(directory.path): \(error)") + } +} + +func setFixtureMetadata( + _ url: URL, mode: mode_t, value: Data, defaultOwnerPermissions: UInt16 = 6 +) throws { + var info = stat() + try #require(lstat(url.path, &info) == 0) + #if os(macOS) + try #require( + value.withUnsafeBytes { + setxattr(url.path, "org.agents.tests", $0.baseAddress, $0.count, 0, XATTR_NOFOLLOW) + } == 0) + if info.st_mode & S_IFMT != S_IFLNK { + try ProcessRunner.run( + "/bin/chmod", + arguments: ["+a", "everyone allow readattr,readextattr,readsecurity", url.path]) + } + try #require(lchmod(url.path, mode) == 0) + #else + // Linux symlink modes are fixed at 0777 and user xattrs/ACLs cannot be set + // on symlinks. Never chmod or set attributes through their referents. + guard info.st_mode & S_IFMT != S_IFLNK else { return } + try #require( + value.withUnsafeBytes { + lsetxattr(url.path, "user.org.agents.tests", $0.baseAddress, $0.count, 0) + } == 0) + // Linux's little-endian POSIX ACL xattr format: version 2, owner, named + // nobody (uid 65534), owning group, mask and other. No libacl dependency. + var acl = Data([2, 0, 0, 0]) + for (tag, permissions, identifier): (UInt16, UInt16, UInt32) in [ + (1, 6, .max), (2, 4, 65534), (4, 4, .max), (16, 4, .max), (32, 0, .max), + ] { + for field in [UInt32(tag) | (UInt32(permissions) << 16), identifier] { + var bytes = field.littleEndian + withUnsafeBytes(of: &bytes) { acl.append(contentsOf: $0) } + } + } + try #require( + acl.withUnsafeBytes { + lsetxattr(url.path, "system.posix_acl_access", $0.baseAddress, $0.count, 0) + } == 0) + if info.st_mode & S_IFMT == S_IFDIR { + var defaultACL = acl + defaultACL[6] = UInt8(truncatingIfNeeded: defaultOwnerPermissions) + defaultACL[7] = UInt8(truncatingIfNeeded: defaultOwnerPermissions >> 8) + try #require( + defaultACL.withUnsafeBytes { + lsetxattr(url.path, "system.posix_acl_default", $0.baseAddress, $0.count, 0) + } == 0) + } + try #require(chmod(url.path, mode) == 0) + #endif +} + +func fixtureMetadata(_ url: URL) throws -> FixtureMetadata { + var info = stat() + try #require(lstat(url.path, &info) == 0) + #if os(macOS) + let size = getxattr(url.path, "org.agents.tests", nil, 0, 0, XATTR_NOFOLLOW) + try #require(size >= 0) + var attribute = Data(count: size) + try #require( + attribute.withUnsafeMutableBytes { + getxattr(url.path, "org.agents.tests", $0.baseAddress, $0.count, 0, XATTR_NOFOLLOW) + } == size) + var text = "" + if info.st_mode & S_IFMT != S_IFLNK { + let acl = try #require(acl_get_file(url.path, ACL_TYPE_EXTENDED)) + defer { acl_free(UnsafeMutableRawPointer(acl)) } + if let value = acl_to_text(acl, nil) { + text = String(cString: value) + acl_free(value) + } + } + return FixtureMetadata(mode: info.st_mode, acl: Data(text.utf8), attribute: attribute) + #else + if info.st_mode & S_IFMT == S_IFLNK { + return FixtureMetadata(mode: info.st_mode, acl: Data(), attribute: Data()) + } + func read(_ name: String) throws -> Data { + let size = lgetxattr(url.path, name, nil, 0) + if size < 0 && errno == ENODATA { return Data() } + try #require(size >= 0) + var value = Data(count: size) + try #require( + value.withUnsafeMutableBytes { + lgetxattr(url.path, name, $0.baseAddress, $0.count) + } == size) + return value + } + return FixtureMetadata( + mode: info.st_mode, acl: try read("system.posix_acl_access"), + attribute: try read("user.org.agents.tests"), + defaultACL: info.st_mode & S_IFMT == S_IFDIR ? try read("system.posix_acl_default") : Data()) + #endif +} diff --git a/Tests/AgentsCoreTests/NativeArrayReceiptTests.swift b/Tests/AgentsCoreTests/NativeArrayReceiptTests.swift new file mode 100644 index 0000000..6d4e871 --- /dev/null +++ b/Tests/AgentsCoreTests/NativeArrayReceiptTests.swift @@ -0,0 +1,437 @@ +import CPlatform +import Foundation +import StateTestSupport +import Synchronization +import Testing + +@testable import AgentsCore + +@Suite("Private native array continuity receipts") +struct NativeArrayReceiptTests { + private let original = Data(#"{"hooks":["private-value"],"sibling":0}"#.utf8) + private let sibling = Data(#"{"hooks":["private-value"],"sibling":1}"#.utf8) + + private func array(_ key: String = "hooks", token: UUID = UUID(), digest: String = "array") + -> PrivateNativeArrayRecord + { + .init( + path: [.key(key)], documentFormat: "json", token: token, + semanticDigest: "sha256:" + FileHash.sha256Hex(data: Data(digest.utf8))) + } + + private func install( + _ bytes: Data, arrays: [PrivateNativeArrayRecord], target: MaterializationTarget, + store: StateStore + ) throws { + let transaction = FileTransaction(store: store) + try transaction.replacePrivate( + store.preparePrivateMaterialization(target), provider: NoArrayBindings(), + produce: { _ in + .init( + bytes: bytes, nativeArrayTransitions: arrays.map { .init(previous: nil, current: $0) }) + }) + try transaction.commit() + } + + @Test func overlappingCreatedAncestryUsesOriginalAccessAndStillRefusesRealDrift() throws { + let fixture = try TransactionFixture() + let store = StateStore(scope: .user, environment: fixture.store.environment) + try FileManager.default.createDirectory( + at: store.environment.homeDirectory, withIntermediateDirectories: true) + let named = try NativeTargetRoute.named(.codexAgent, scope: .user, name: "review") + var before = "" + try store.withReadLock(footprint: [.codexMCPUser, named]) { + before = try TargetPrecondition(store.nativeTarget(for: named).url).displayEvidence( + includeContent: false) + } + try store.withLock(footprint: [.codexMCPUser, named]) { + let target = try store.nativeTarget(for: named) + #expect(try TargetPrecondition(target.url).displayEvidence(includeContent: false) == before) + let parent = store.environment.homeDirectory + let mode = try #require( + try DirectoryHandle(at: parent.deletingLastPathComponent()).accessEvidence( + parent.lastPathComponent) + ).mode + defer { _ = chmod(parent.path, mode) } + try #require(chmod(parent.path, mode ^ 0o010) == 0) + #expect(throws: CoreError.self) { + try TargetPrecondition(target.url).displayEvidence(includeContent: false) + } + } + } + + @Test func actualArrayProducerReceivesBindingsOnlyAfterVerifiedEmptyPrivateStage() throws { + let fixture = try TransactionFixture() + let provider = StagedArrayBindings() + try fixture.store.withLock(footprint: [.claudeMCPLocal]) { + let store = fixture.store + let target = try store.nativeTarget(for: .claudeMCPLocal) + let transaction = FileTransaction(store: store) { point in + if point == "stage.0.writeCreated" { + let journal = try StateStore.decode( + Data(contentsOf: store.directory.appendingPathComponent(TransactionJournal.fileName)), + as: TransactionJournal.self) + let parent = try DirectoryHandle(at: target.url.deletingLastPathComponent()) + let container = try parent.child(journal.containerName(0)) + let slot = TransactionSlot.staging(for: journal.entries[0]).name(0) + _ = try container.requirePrivateAccess(slot) + #expect(try container.read(slot).isEmpty) + provider.ready.withLock { $0 = true } + } + } + try transaction.replacePrivate( + store.preparePrivateMaterialization(target), bindings: ["value"], provider: provider, + produce: { values in + let bytes = try values.value(for: "value") + return .init( + bytes: bytes, nativeArrayTransitions: [.init(previous: nil, current: array())]) + }) + try transaction.commit() + #expect(try store.materializationReceipt(for: target)?.nativeArrays?.count == 1) + } + } + + @Test func siblingGenerationPreservesContinuityAndExactNoOpNeedsNoTransition() throws { + let fixture = try TransactionFixture() + try fixture.store.withLock(footprint: [.claudeMCPLocal]) { + let store = fixture.store + let target = try store.nativeTarget(for: .claudeMCPLocal) + let record = array() + try install(original, arrays: [record], target: target, store: store) + let first = try #require(try store.materializationReceipt(for: target)) + let accessFingerprint = try store.preparePrivateMaterialization(target).accessFingerprint() + let transaction = FileTransaction(store: store) + try transaction.replace( + target.url, with: .data(sibling), + nativeArrayTransitions: [.init(previous: record, current: record)]) + try transaction.commit() + let next = try #require(try store.materializationReceipt(for: target)) + #expect(next.generation != first.generation) + #expect(next.nativeArrays == [record]) + #expect( + try store.preparePrivateMaterialization(target).accessFingerprint() == accessFingerprint) + #expect(throws: CoreError.self) { + try store.preparePrivateMaterialization(target, expecting: first.generation) + } + let noOp = FileTransaction(store: store) + try noOp.replace(target.url, with: .data(sibling)) + try noOp.commit() + #expect(try store.materializationReceipt(for: target)?.nativeArrays == [record]) + let raw = try store.materializationReceipts(for: target.path) + #expect(raw.records.version == 2) + #expect(!String(reflecting: next).contains(record.semanticDigest)) + #expect( + !String(reflecting: PrivateMaterializationResult(bytes: original)).contains("private-value") + ) + _ = try DirectoryHandle(at: target.url.deletingLastPathComponent()).requirePrivateAccess( + target.url.lastPathComponent) + } + } + + @Test func anotherScopeUsesTheSamePhysicalArrayReceiptThroughAnAlias() throws { + let fixture = try TransactionFixture() + let config = fixture.root.appendingPathComponent("config") + let alias = fixture.root.appendingPathComponent("config-alias") + try FileManager.default.createDirectory(at: config, withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: config) + var aEnvironment = fixture.store.environment + aEnvironment.environment["CLAUDE_CONFIG_DIR"] = config.path + var bEnvironment = aEnvironment + bEnvironment.environment["CLAUDE_CONFIG_DIR"] = alias.path + bEnvironment.homeDirectory = fixture.root.appendingPathComponent("other-home") + try FileManager.default.createDirectory( + at: bEnvironment.homeDirectory, withIntermediateDirectories: true) + let a = StateStore(scope: .project, environment: aEnvironment) + let b = StateStore(scope: .user, environment: bEnvironment) + let record = array() + var generation: UUID? + var receiptURL: URL! + try a.withLock(footprint: [.claudeMCPLocal]) { + let target = try a.nativeTarget(for: .claudeMCPLocal) + try install(original, arrays: [record], target: target, store: a) + generation = try a.materializationReceipt(for: target)?.generation + receiptURL = try a.materializationReceipts(for: target.path).url + } + try b.withLock(footprint: [.claudeMCPUser]) { + let target = try b.nativeTarget(for: .claudeMCPUser) + #expect(try b.materializationReceipt(for: target)?.nativeArrays == [record]) + #expect( + try b.materializationReceipts(for: target.path).url.resolvingSymlinksInPath() + == receiptURL.resolvingSymlinksInPath()) + let transaction = FileTransaction(store: b) + try transaction.replace( + target.url, with: .data(sibling), + nativeArrayTransitions: [.init(previous: record, current: record)]) + try transaction.commit() + } + try a.withReadLock(footprint: [.claudeMCPLocal]) { + let target = try a.nativeTarget(for: .claudeMCPLocal) + #expect(throws: CoreError.self) { + try a.preparePrivateMaterialization(target, expecting: generation) + } + #expect(try a.materializationReceipt(for: target)?.nativeArrays == [record]) + } + #expect(!FileManager.default.fileExists(atPath: a.materializationReceiptURL.path)) + #expect(!FileManager.default.fileExists(atPath: b.materializationReceiptURL.path)) + } + + @Test(arguments: [ + "missing", "duplicate", "wrong-path", "same-token-change", "unsupported", "incomplete", + "over-depth", "private-error", "mixed-format", "newline-digest", + ]) + func invalidTransitionsPublishNothing(_ kind: String) throws { + let fixture = try TransactionFixture() + try fixture.store.withLock(footprint: [.claudeMCPLocal]) { + let store = fixture.store + let target = try store.nativeTarget(for: .claudeMCPLocal) + let a = array() + let b = array("other") + try install(original, arrays: [a, b], target: target, store: store) + let state = try store.materializationReceipts(for: target.path) + let receipt = try Data(contentsOf: state.url) + var transitions: [PrivateNativeArrayTransition]? = [ + .init(previous: a, current: a), .init(previous: b, current: b), + ] + switch kind { + case "missing": transitions = nil + case "duplicate": transitions!.append(.init(previous: a, current: a)) + case "wrong-path": + transitions![0] = .init(previous: array("wrong", token: a.token), current: a) + case "same-token-change": + transitions![0] = .init(previous: a, current: array(token: a.token, digest: "changed")) + case "unsupported": + transitions![0] = .init( + previous: a, + current: .init( + path: a.path, documentFormat: "yaml", token: UUID(), semanticDigest: a.semanticDigest)) + case "mixed-format": + transitions![0] = .init( + previous: a, + current: .init( + path: a.path, documentFormat: "toml", token: UUID(), semanticDigest: a.semanticDigest)) + case "over-depth": + transitions![0] = .init( + previous: a, + current: .init( + path: Array(repeating: .key("nested"), count: LedgerLimits.standard.depth + 1), + documentFormat: "json", token: UUID(), semanticDigest: a.semanticDigest)) + case "newline-digest": + transitions![0] = .init( + previous: a, + current: .init( + path: a.path, documentFormat: "json", token: UUID(), + semanticDigest: a.semanticDigest + "\n")) + case "private-error": + transitions![0] = .init( + previous: a, + current: .init( + path: a.path, documentFormat: "json", token: UUID(), + semanticDigest: "private-error-must-not-escape")) + default: transitions!.removeLast() + } + let transaction = FileTransaction(store: store) + try transaction.replace(target.url, with: .data(sibling), nativeArrayTransitions: transitions) + do { + try transaction.commit() + Issue.record("expected transition refusal") + } catch { + #expect(!String(describing: error).contains("private-error-must-not-escape")) + } + #expect(try Data(contentsOf: target.url) == original) + #expect(try Data(contentsOf: state.url) == receipt) + #expect(try !TransactionJournal.isPresent(in: DirectoryHandle(at: store.directory))) + } + } + + @Test(arguments: [false, true]) + func arrayRotationRollbackAndWholeFileDeletionAreAtomic(_ rollback: Bool) throws { + let fixture = try TransactionFixture() + try fixture.store.withLock(footprint: [.claudeMCPLocal]) { + let store = fixture.store + let target = try store.nativeTarget(for: .claudeMCPLocal) + let old = array() + let changed = array(digest: "changed") + try install(original, arrays: [old], target: target, store: store) + let state = try store.materializationReceipts(for: target.path) + let receipt = try Data(contentsOf: state.url) + let transaction = FileTransaction(store: store) { point in + if rollback && point == "entry.1.applied" { + throw CoreError.invalidState("injected receipt publication failure") + } + } + try transaction.replace( + target.url, with: .data(sibling), + nativeArrayTransitions: [.init(previous: old, current: changed)]) + if rollback { + #expect(throws: CoreError.self) { try transaction.commit() } + #expect(try Data(contentsOf: target.url) == original) + #expect(try Data(contentsOf: state.url) == receipt) + #expect(try store.materializationReceipt(for: target)?.nativeArrays == [old]) + } else { + try transaction.commit() + #expect(try store.materializationReceipt(for: target)?.nativeArrays == [changed]) + let clear = FileTransaction(store: store) + try clear.replace( + target.url, with: .data(sibling), + nativeArrayTransitions: [.init(previous: changed, current: nil)]) + try clear.commit() + #expect(try store.materializationReceipts(for: target.path).records.version == 2) + #expect(try store.materializationReceipt(for: target)?.nativeArrays == nil) + let deletion = FileTransaction(store: store) + try deletion.delete(target.url) + try deletion.commit() + #expect(!FileManager.default.fileExists(atPath: target.url.path)) + #expect(!FileManager.default.fileExists(atPath: state.url.path)) + } + } + } + + @Test func missingTargetNeedsExplicitFreshArrayEvidence() throws { + let fixture = try TransactionFixture() + try fixture.store.withLock(footprint: [.claudeMCPLocal]) { + let store = fixture.store + let target = try store.nativeTarget(for: .claudeMCPLocal) + let old = array() + let fresh = array() + try install(original, arrays: [old], target: target, store: store) + try FileManager.default.removeItem(at: target.url) + #expect(throws: CoreError.self) { + try FileTransaction(store: store).replace(target.url, with: .data(original)) + } + let stale = FileTransaction(store: store) + try stale.replacePrivate( + store.preparePrivateMaterialization(target), provider: NoArrayBindings(), + produce: { _ in + .init(bytes: original, nativeArrayTransitions: [.init(previous: old, current: old)]) + }) + #expect(throws: CoreError.self) { try stale.commit() } + #expect(!FileManager.default.fileExists(atPath: target.url.path)) + let restore = FileTransaction(store: store) + try restore.replacePrivate( + store.preparePrivateMaterialization(target), provider: NoArrayBindings(), + produce: { _ in + .init(bytes: original, nativeArrayTransitions: [.init(previous: old, current: fresh)]) + }) + try restore.commit() + #expect(try store.materializationReceipt(for: target)?.nativeArrays == [fresh]) + } + } + + @Test(arguments: ["stage.0.constructed", "entry.1.applied", "journal.committed"]) + func restartRecoversSealedArrayReceiptWithoutAProducer(_ point: String) throws { + let fixture = try TransactionFixture() + var environment = fixture.store.environment + environment.environment["CLAUDE_CONFIG_DIR"] = + fixture.root.appendingPathComponent("configured-claude").path + let store = StateStore(scope: .project, environment: environment) + let record = array() + var targetURL: URL! + var receiptURL: URL! + var previousReceipt = Data() + try store.withLock(footprint: [.claudeMCPLocal]) { + let target = try store.nativeTarget(for: .claudeMCPLocal) + targetURL = target.url + try install(original, arrays: [record], target: target, store: store) + receiptURL = try store.materializationReceipts(for: target.path).url + previousReceipt = try Data(contentsOf: receiptURL) + } + let child = try stateTestProcess(root: fixture.root, arguments: ["shared-array-edit", point]) + defer { terminateProcess(child) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: child, root: fixture.root) + terminateProcess(child) + let before = try FileSnapshot.read(at: fixture.root) + try store.withReadLock( + onPendingRecovery: { + #expect(!FileTransaction.recoveryDiagnostic(store: store).requiresOwner) + }, { Issue.record("expected pending array transaction") }) + #expect(try FileSnapshot.read(at: fixture.root) == before) + #expect(throws: CoreError.transactionRecovered(store.directory.path)) { try store.withLock {} } + let committed = point == "journal.committed" + #expect(try Data(contentsOf: targetURL) == (committed ? sibling : original)) + if !committed { #expect(try Data(contentsOf: receiptURL) == previousReceipt) } + try store.withReadLock(footprint: [.claudeMCPLocal]) { + let target = try store.nativeTarget(for: .claudeMCPLocal) + #expect(try store.materializationReceipt(for: target)?.nativeArrays == [record]) + } + #expect( + !FileManager.default.fileExists( + atPath: fixture.root.appendingPathComponent("provider-called").path)) + } + + @Test func receiptVersionsAndNestedFieldsAreStrictAndUTF8AddressesStayDistinct() throws { + let fixture = try TransactionFixture() + try fixture.store.withLock(footprint: [.claudeMCPLocal]) { + let store = fixture.store + let target = try store.nativeTarget(for: .claudeMCPLocal) + let transaction = FileTransaction(store: store) + try transaction.replacePrivate( + store.preparePrivateMaterialization(target), provider: NoArrayBindings() + ) { _ in original } + try transaction.commit() + let v1 = try store.materializationReceipts(for: target.path) + #expect(v1.records.version == 1) + #expect( + try StateStore.decode(Data(contentsOf: v1.url), as: MaterializationReceipts.self).version + == 1) + let records = [array("\u{e9}"), array("e\u{301}")] + #expect(records[0].path != records[1].path) + let upgrade = FileTransaction(store: store) + try upgrade.replace( + target.url, with: .data(original), + nativeArrayTransitions: records.map { .init(previous: nil, current: $0) }) + try upgrade.commit() + let bytes = try Data(contentsOf: v1.url) + let object = try #require(JSONSerialization.jsonObject(with: bytes) as? [String: Any]) + func refuses(_ edit: (inout [String: Any]) -> Void) throws { + var value = object + edit(&value) + let data = try JSONSerialization.data(withJSONObject: value) + #expect(throws: (any Error).self) { + let decoded = try StateStore.decode(data, as: MaterializationReceipts.self) + try decoded.validate(store: store) + } + } + try refuses { $0["version"] = 1 } + try refuses { $0["unknown"] = NSNull() } + for kind in ["record", "step", "duplicate", "negative", "digest", "null"] { + try refuses { value in + var targets = value["targets"] as! [String: Any] + let key = targets.keys.first! + var record = targets[key] as! [String: Any] + var arrays = record["nativeArrays"] as! [[String: Any]] + switch kind { + case "record": arrays[0]["unknown"] = NSNull() + case "step": + var path = arrays[0]["path"] as! [[String: Any]] + path[0]["unknown"] = NSNull() + arrays[0]["path"] = path + case "duplicate": arrays.append(arrays[0]) + case "negative": arrays[0]["path"] = [["kind": "position", "index": -1]] + case "digest": arrays[0]["semanticDigest"] = "invalid" + default: record["nativeArrays"] = NSNull() + } + if kind != "null" { record["nativeArrays"] = arrays } + targets[key] = record + value["targets"] = targets + } + } + } + } +} + +private struct NoArrayBindings: RuntimeBindingProvider { + func value(for binding: String, environment: RuntimeEnvironment) throws -> Data { + throw CoreError.invalidState("unexpected binding request") + } +} + +private final class StagedArrayBindings: RuntimeBindingProvider { + let ready = Mutex(false) + func value(for binding: String, environment: RuntimeEnvironment) throws -> Data { + guard ready.withLock({ $0 }) else { + throw CoreError.invalidState("private stage was not verified") + } + return Data(#"{"hooks":["private-value"],"sibling":0}"#.utf8) + } +} diff --git a/Tests/AgentsCoreTests/PreparationEvidenceTests.swift b/Tests/AgentsCoreTests/PreparationEvidenceTests.swift new file mode 100644 index 0000000..8ad18be --- /dev/null +++ b/Tests/AgentsCoreTests/PreparationEvidenceTests.swift @@ -0,0 +1,186 @@ +import AgentsManifest +import Foundation +import StateTestSupport +import Testing + +@testable import AgentsCore + +@Suite("Prepared state evidence") +struct PreparationEvidenceTests { + @Test func dataSealingRejectsAnUnexpectedExecutableMode() throws { + let fixture = try PublicationFixture(.fileCreate) + let transaction = FileTransaction(store: fixture.store) { point in + if point == TransactionCheckpoint.stage(0, .constructed).name { + let name = try #require( + try FileManager.default.contentsOfDirectory(atPath: fixture.root.path) + .first(where: { $0.hasPrefix(".agents-") })) + let staged = fixture.root.appendingPathComponent(name).appendingPathComponent( + TransactionSlot.staged.name(0)) + try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: staged.path) + } + } + try transaction.replace(fixture.target, with: .data(Data("postimage".utf8))) + #expect(throws: CoreError.invalidState("staged content permissions mismatch")) { + try transaction.commit() + } + try fixture.check(committed: false, journal: nil) + try fixture.expectClean() + } + + @Test func replacedContainerIsNotAdoptedBeforeIdentityPersistence() throws { + let fixture = try PublicationFixture(.fileCreate) + let saved = fixture.root.appendingPathComponent("saved-empty-container") + var external: FileSnapshot? + var original: FileSnapshot? + var location: URL? + let transaction = FileTransaction(store: fixture.store) { point in + if point == TransactionCheckpoint.containerCreated(0).name { + let name = try #require( + try FileManager.default.contentsOfDirectory(atPath: fixture.root.path) + .first(where: { $0.hasPrefix(".agents-") })) + let container = fixture.root.appendingPathComponent(name) + try FileManager.default.moveItem(at: container, to: saved) + original = try FileSnapshot.read(at: saved) + try FileManager.default.createDirectory(at: container, withIntermediateDirectories: false) + try Data("external container".utf8).write(to: container.appendingPathComponent("keep")) + external = try FileSnapshot.read(at: container) + location = container + } + } + try transaction.replace(fixture.target, with: .data(Data("postimage".utf8))) + #expect { try transaction.commit() } throws: { error in + guard case CoreError.invalidState(let reason) = error else { return false } + return reason.contains("private container changed before its identity was durable") + } + try fixture.expectUnresolved(containing: "unidentified private container is not empty") + #expect(try FileSnapshot.read(at: #require(location)) == external) + #expect(try FileSnapshot.read(at: saved) == original) + #expect(try FileSnapshot.read(at: fixture.target) == fixture.beforeTarget) + } + + @Test(arguments: [PublicationOperation.fileCreate, .directoryDelete]) + func reservedSlotIsRejectedBeforeSealingAndDiscarded(_ operation: PublicationOperation) throws { + let fixture = try PublicationFixture(operation) + let transaction = FileTransaction(store: fixture.store) { point in + if point == TransactionCheckpoint.stage(0, .constructed).name { + let name = try #require( + try FileManager.default.contentsOfDirectory(atPath: fixture.root.path) + .first(where: { $0.hasPrefix(".agents-") })) + let slot: TransactionSlot = operation == .directoryDelete ? .staged : .deleted + try Data("private injection".utf8).write( + to: fixture.root.appendingPathComponent(name).appendingPathComponent(slot.name(0))) + } + } + if operation == .fileCreate { + try transaction.replace(fixture.target, with: .data(Data("postimage".utf8))) + } else { + try transaction.delete(fixture.target) + } + #expect(throws: CoreError.invalidState("unexpected private recovery slot before sealing")) { + try transaction.commit() + } + try fixture.check(committed: false, journal: nil) + try fixture.expectClean() + } + + @Test func equalDigestDoesNotTurnDataIntoASymbolicLink() throws { + let fixture = try PublicationFixture(.fileCreate) + let transaction = FileTransaction(store: fixture.store) { point in + if point == TransactionCheckpoint.stage(0, .constructed).name { + let name = try #require( + try FileManager.default.contentsOfDirectory(atPath: fixture.root.path) + .first(where: { $0.hasPrefix(".agents-") })) + let staged = fixture.root.appendingPathComponent(name).appendingPathComponent( + TransactionSlot.staged.name(0)) + try FileManager.default.removeItem(at: staged) + try FileManager.default.createSymbolicLink( + atPath: staged.path, withDestinationPath: "postimage") + } + } + try transaction.replace(fixture.target, with: .data(Data("postimage".utf8))) + #expect(throws: CoreError.invalidState("staged content type mismatch")) { + try transaction.commit() + } + try fixture.check(committed: false, journal: nil) + try fixture.expectClean() + } + + @Test(arguments: [false, true]) + func constructionMustMatchTheRequestedCopyOrLink(_ link: Bool) throws { + let fixture = try PublicationFixture(.fileCreate) + var tampered = false + let transaction = FileTransaction(store: fixture.store) { point in + if point == TransactionCheckpoint.stage(0, .constructed).name { + let name = try #require( + try FileManager.default.contentsOfDirectory(atPath: fixture.root.path) + .first(where: { $0.hasPrefix(".agents-") })) + let staged = fixture.root.appendingPathComponent(name).appendingPathComponent( + TransactionSlot.staged.name(0)) + if link { + try FileManager.default.removeItem(at: staged) + try FileManager.default.createSymbolicLink( + atPath: staged.path, withDestinationPath: "external") + } else { + try Data("injected".utf8).write(to: staged.appendingPathComponent("injected")) + } + tampered = true + } + } + try transaction.replace( + fixture.target, + with: link + ? .link(fixture.root.appendingPathComponent("new")) + : .copy(fixture.root.appendingPathComponent("new"))) + #expect { try transaction.commit() } throws: { error in + guard case CoreError.invalidState = error else { return false } + return true + } + #expect(tampered) + try fixture.check(committed: false, journal: nil) + try fixture.expectClean() + } + + @Test func copyProtocolAlsoAcceptsARegularFile() throws { + let fixture = try PublicationFixture(.fileCreate) + let source = fixture.root.appendingPathComponent("new/nested/file") + let transaction = FileTransaction(store: fixture.store) + try transaction.replace(fixture.target, with: .copy(source)) + try transaction.commit() + #expect(try Data(contentsOf: fixture.target) == Data(contentsOf: source)) + #expect( + try FileSnapshot.read(at: fixture.target)?.identity.kind + == FileSnapshot.read(at: source)?.identity.kind) + try fixture.expectClean() + } + + @Test func parsedBytesAndJournalPreimageUseThePreparedGeneration() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let store = StateStore( + scope: .project, + environment: RuntimeEnvironment(projectDirectory: root, homeDirectory: root, environment: [:]) + ) + try store.save(declaration: Declaration(), resolved: ResolvedState()) + try store.withLock { + let prepared = try StatePrecondition(store: store) + let original = try #require(try prepared.bytes(for: store.declarationURL)) + let declaration = try store.readDeclaration(prepared: prepared) + try (original + Data("\n".utf8)).write(to: store.declarationURL, options: .atomic) + let external = try FileSnapshot.read(at: store.declarationURL) + #expect(try store.readDeclaration(prepared: prepared) == declaration) + #expect(try prepared.bytes(for: store.declarationURL) == original) + let transaction = FileTransaction(store: store) + try transaction.replace( + store.declarationURL, with: .data(original), + expecting: prepared.evidence(for: store.declarationURL)) + #expect { + try transaction.commit() + } throws: { error in + guard case CoreError.invalidState(let reason) = error else { return false } + return reason.contains("path changed during preparation") + } + #expect(try FileSnapshot.read(at: store.declarationURL) == external) + #expect(try store.openDirectoryIfPresent()?.info("transaction.json") == nil) + } + } +} diff --git a/Tests/AgentsCoreTests/PrivateMaterializationTests.swift b/Tests/AgentsCoreTests/PrivateMaterializationTests.swift new file mode 100644 index 0000000..7a8392a --- /dev/null +++ b/Tests/AgentsCoreTests/PrivateMaterializationTests.swift @@ -0,0 +1,525 @@ +import CPlatform +import Foundation +import StateTestSupport +import Synchronization +import Testing + +@testable import AgentsCore + +@Suite("Private materialization transactions") +struct PrivateMaterializationTests { + @Test func preparationIsSymbolicAndAccessChangesAreExplicit() throws { + let fixture = try TransactionFixture() + let target = try fixture.store.materializationTarget( + at: fixture.root.appendingPathComponent("AGENTS.md")) + let provider = TestBindings("secret-sentinel") + try #require(chmod(target.url.path, 0o644) == 0) + let before = try FileSnapshot.read(at: target.url) + #expect(throws: CoreError.self) { try fixture.store.preparePrivateMaterialization(target) } + let prepared = try fixture.store.preparePrivateMaterialization(target, changingAccess: true) + #expect(prepared.accessChange?.before.mode == 0o644) + #expect(prepared.accessChange?.mode == 0o600) + #expect(provider.calls == 0) + #expect(try FileSnapshot.read(at: target.url) == before) + #expect(!FileManager.default.fileExists(atPath: fixture.store.materializationReceiptURL.path)) + #expect(throws: CoreError.self) { + try fixture.store.materializationTarget( + at: fixture.root.appendingPathComponent("outside.json")) + } + #expect(throws: CoreError.self) { + try fixture.store.materializationTarget(at: fixture.store.resolvedURL) + } + } + + @Test(arguments: [false, true]) + func ownerExecuteChangesAreExplicitAndRollbackRestoresTheirMode(_ rollback: Bool) throws { + let fixture = try TransactionFixture() + let target = fixture.root.appendingPathComponent("AGENTS.md") + try #require(chmod(target.path, 0o700) == 0) + try fixture.store.withLock { + let registered = try fixture.store.materializationTarget(at: target) + #expect(throws: CoreError.self) { + try fixture.store.preparePrivateMaterialization(registered) + } + let prepared = try fixture.store.preparePrivateMaterialization( + registered, changingAccess: true) + #expect(prepared.accessChange?.before.mode == 0o700) + #expect(prepared.accessChange?.mode == 0o600) + let transaction = FileTransaction(store: fixture.store) { point in + if rollback && point == "entry.0.applied" { + throw CoreError.invalidState("interrupt owner mode change") + } + } + try transaction.replacePrivate(prepared, provider: TestBindings("unused")) { _ in + Data("private-after".utf8) + } + if rollback { + #expect(throws: CoreError.self) { try transaction.commit() } + } else { + try transaction.commit() + } + } + #expect( + try DirectoryHandle(at: fixture.root).accessEvidence("AGENTS.md")?.mode + == (rollback ? 0o700 : 0o600)) + #expect( + try Data(contentsOf: target) == Data((rollback ? "old instructions" : "private-after").utf8)) + } + + @Test func privateStagingPrecedesProviderAndReceiptCommitsWithTheTarget() throws { + let fixture = try TransactionFixture() + let provider = TestBindings("secret-sentinel") + var observed = false + try fixture.store.withLock { + let target = try fixture.store.materializationTarget( + at: fixture.root.appendingPathComponent("AGENTS.md")) + let prepared = try fixture.store.preparePrivateMaterialization(target, changingAccess: true) + let transaction = FileTransaction(store: fixture.store) { point in + if point == "stage.0.writeCreated" { + let journal = try readMaterializationJournal(fixture) + let container = try DirectoryHandle(at: fixture.root).child(journal.containerName(0)) + let name = TransactionSlot.exchanged.name(0) + let info = try #require(try container.info(name)) + #expect(info.st_size == 0) + _ = try container.requirePrivateAccess(name) + #expect(provider.calls == 0) + observed = true + } + } + try transaction.replacePrivate(prepared, bindings: ["value"], provider: provider) { + #expect(!String(reflecting: $0).contains("secret-sentinel")) + return try $0.value(for: "value") + } + #expect(provider.calls == 0) + try transaction.commit() + } + #expect(observed && provider.calls == 1) + let record = try #require( + try fixture.store.materializationReceipts().records.targets["instructions-project/AGENTS.md"]) + #expect( + try Data(contentsOf: fixture.root.appendingPathComponent("AGENTS.md")) + == Data("secret-sentinel".utf8)) + let parent = try DirectoryHandle(at: fixture.root) + _ = try parent.requirePrivateAccess("AGENTS.md", matching: record.access) + _ = try DirectoryHandle(at: fixture.store.directory).requirePrivateAccess( + MaterializationReceipts.fileName) + let receipt = try Data(contentsOf: fixture.store.materializationReceiptURL) + #expect(!String(decoding: receipt, as: UTF8.self).contains("secret-sentinel")) + #expect(try !TransactionJournal.isPresent(in: DirectoryHandle(at: fixture.store.directory))) + } + + @Test(arguments: ["target-mode", "target-acl", "ancestor", "provider", "renderer"]) + func staleAccessAndValueFailuresPublishNothingAndNeverExposeValues(_ kind: String) throws { + let fixture = try TransactionFixture() + let provider = TestBindings("secret-error-sentinel") + let targetURL = fixture.root.appendingPathComponent("AGENTS.md") + try #require(chmod(targetURL.path, 0o644) == 0) + var errorText = "" + try fixture.store.withLock { + let target = try fixture.store.materializationTarget(at: targetURL) + let prepared = try fixture.store.preparePrivateMaterialization(target, changingAccess: true) + let transaction = FileTransaction(store: fixture.store) + try transaction.replacePrivate(prepared, bindings: ["value"], provider: provider) { values in + if kind == "renderer" { throw CoreError.invalidState("secret-error-sentinel") } + return try values.value(for: "value") + } + switch kind { + case "target-mode": try #require(chmod(targetURL.path, 0o640) == 0) + case "target-acl": try setFixtureMetadata(targetURL, mode: 0o644, value: Data()) + case "ancestor": try #require(chmod(fixture.root.path, 0o775) == 0) + case "provider": provider.fails = true + default: break + } + do { + try transaction.commit() + Issue.record("expected private materialization refusal") + } catch { errorText = String(describing: error) } + #expect(!errorText.contains("secret-error-sentinel")) + } + #expect(!errorText.isEmpty) + #expect(try Data(contentsOf: targetURL) == Data("old instructions".utf8)) + #expect(!FileManager.default.fileExists(atPath: fixture.store.materializationReceiptURL.path)) + #expect(provider.calls == (["provider", "renderer"].contains(kind) ? 1 : 0)) + } + + @Test(arguments: [false, true]) + func ordinaryRegionEditsKeepSensitiveSiblingsAndPrivateReceipt(_ digestMatches: Bool) throws { + let fixture = try TransactionFixture() + try installPrivate("secret sibling; region before", in: fixture) + let target = try fixture.store.materializationTarget( + at: fixture.root.appendingPathComponent("AGENTS.md")) + let before = try fixture.store.preparePrivateMaterialization(target) + let targetBefore = try FileSnapshot.read(at: target.url) + let receiptBefore = try Data(contentsOf: fixture.store.materializationReceiptURL) + let replacement = Data("secret sibling; region after".utf8) + let expectedHash = + "sha256:" + FileHash.sha256Hex(data: digestMatches ? replacement : Data("different".utf8)) + var inspected = false + try fixture.store.withLock { + let transaction = FileTransaction(store: fixture.store) { point in + if point == "stage.0.writeCreated" { + let journal = try readMaterializationJournal(fixture) + let container = target.url.deletingLastPathComponent().appendingPathComponent( + journal.containers[0].name) + let handle = try DirectoryHandle(at: container) + let access = try handle.requirePrivateAccess("entry.0.exchanged") + #expect(access.mode == 0o600) + #expect(try handle.read("entry.0.exchanged").isEmpty) + inspected = true + } + } + try transaction.replace(target.url, with: .data(replacement), expectedHash: expectedHash) + if digestMatches { + try transaction.commit() + } else { + #expect(throws: CoreError.invalidState("staged content digest mismatch")) { + try transaction.commit() + } + } + } + #expect(inspected) + if !digestMatches { + #expect(try FileSnapshot.read(at: target.url) == targetBefore) + #expect(try Data(contentsOf: fixture.store.materializationReceiptURL) == receiptBefore) + #expect( + try fixture.store.preparePrivateMaterialization( + target, requiringReceiptForExistingTarget: true + ).receiptGeneration == before.receiptGeneration) + return + } + #expect(try Data(contentsOf: target.url) == Data("secret sibling; region after".utf8)) + let after = try fixture.store.preparePrivateMaterialization( + target, requiringReceiptForExistingTarget: true) + #expect(after.receiptGeneration != before.receiptGeneration) + #expect(throws: CoreError.self) { try before.evidence.validate() } + } + + @Test func wholeFileDeletionRemovesSensitiveReceipt() throws { + let fixture = try TransactionFixture() + try installPrivate("private-before", in: fixture) + let target = fixture.root.appendingPathComponent("AGENTS.md") + try fixture.store.withLock { + let transaction = FileTransaction(store: fixture.store) + try transaction.delete(target) + try transaction.commit() + } + #expect(try fixture.store.materializationReceipts().records.targets.isEmpty) + #expect(!FileManager.default.fileExists(atPath: target.path)) + } + + @Test(arguments: [ + "containers.identified", "stage.0.writeCreated", "stage.0.constructed", "entry.0.ready", + "publish.0.exchanged", "entry.0.applied", "entry.1.applied", "journal.committed", + "disposal.intent", "disposal.0.removed", + ]) + func killedMaterializationRecoversWithoutCallingProvider(_ point: String) throws { + let fixture = try TransactionFixture() + try installPrivate("private-before", in: fixture) + let beforeReceipt = try Data(contentsOf: fixture.store.materializationReceiptURL) + let child = try stateTestProcess(root: fixture.root, arguments: ["private-install", point]) + defer { terminateProcess(child) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: child, root: fixture.root) + terminateProcess(child) + let called = fixture.root.appendingPathComponent("provider-called") + if FileManager.default.fileExists(atPath: called.path) { + try FileManager.default.removeItem(at: called) + } else { + #expect(["containers.identified", "stage.0.writeCreated"].contains(point)) + } + let recovery = try stateTestProcess( + root: fixture.root, arguments: ["private-recover", "never"]) + defer { terminateProcess(recovery) } + try ProcessWait.exit(recovery, root: fixture.root) + #expect(recovery.terminationStatus == 0) + #expect( + !FileManager.default.fileExists( + atPath: fixture.root.appendingPathComponent("provider-called").path)) + let committed = point == "journal.committed" || point.hasPrefix("disposal.") + #expect( + try Data(contentsOf: fixture.root.appendingPathComponent("AGENTS.md")) + == Data((committed ? "private-after" : "private-before").utf8)) + if !committed { + #expect(try Data(contentsOf: fixture.store.materializationReceiptURL) == beforeReceipt) + } + _ = try fixture.store.materializationReceipts() + #expect(try !TransactionJournal.isPresent(in: DirectoryHandle(at: fixture.store.directory))) + } + + @Test func aNewPrivateTargetRollsBackWithoutLeavingAReceipt() throws { + let fixture = try TransactionFixture() + let target = fixture.root.appendingPathComponent("GEMINI.md") + try fixture.store.withLock { + let prepared = try fixture.store.preparePrivateMaterialization( + fixture.store.materializationTarget(at: target)) + #expect(prepared.accessChange == nil) + let transaction = FileTransaction(store: fixture.store) { point in + if point == "entry.0.applied" { + throw CoreError.invalidState("interrupt new private target") + } + } + try transaction.replacePrivate(prepared, provider: TestBindings("unused")) { _ in + Data("private-new".utf8) + } + #expect(throws: CoreError.self) { try transaction.commit() } + } + #expect(!FileManager.default.fileExists(atPath: target.path)) + #expect(!FileManager.default.fileExists(atPath: fixture.store.materializationReceiptURL.path)) + #expect(try !TransactionJournal.isPresent(in: DirectoryHandle(at: fixture.store.directory))) + } + + @Test func changedStagingAccessStopsBeforeResolvingBindings() throws { + let fixture = try TransactionFixture() + let provider = TestBindings("must-not-be-read") + #expect(throws: CoreError.self) { + try fixture.store.withLock { + let prepared = try fixture.store.preparePrivateMaterialization( + fixture.store.materializationTarget(at: fixture.root.appendingPathComponent("AGENTS.md")), + changingAccess: true) + let transaction = FileTransaction(store: fixture.store) { point in + if point == "stage.0.writeCreated" { + let journal = try readMaterializationJournal(fixture) + let file = fixture.root.appendingPathComponent(journal.containerName(0)) + .appendingPathComponent("entry.0.exchanged") + try #require(chmod(file.path, 0o644) == 0) + } + } + try transaction.replacePrivate(prepared, bindings: ["value"], provider: provider) { + try $0.value(for: "value") + } + try transaction.commit() + } + } + #expect(provider.calls == 0) + #expect( + try Data(contentsOf: fixture.root.appendingPathComponent("AGENTS.md")) + == Data("old instructions".utf8)) + } + + @Test(arguments: [ + "restore.1.exchanged", "restore.0.exchanged", "journal.rolledBack", "disposal.0.removed", + ]) + func recoveryCanBeKilledAndRepeatedWithoutResolvingBindings(_ point: String) throws { + let fixture = try TransactionFixture() + try installPrivate("private-before", in: fixture) + let originalReceipt = try Data(contentsOf: fixture.store.materializationReceiptURL) + let child = try stateTestProcess( + root: fixture.root, arguments: ["private-install", "entry.1.applied"]) + defer { terminateProcess(child) } + let marker = fixture.root.appendingPathComponent("ready") + try ProcessWait.marker(marker, child: child, root: fixture.root) + terminateProcess(child) + try FileManager.default.removeItem(at: marker) + try FileManager.default.removeItem(at: fixture.root.appendingPathComponent("provider-called")) + let first = try stateTestProcess(root: fixture.root, arguments: ["private-recover", point]) + defer { terminateProcess(first) } + try ProcessWait.marker(marker, child: first, root: fixture.root) + terminateProcess(first) + let second = try stateTestProcess(root: fixture.root, arguments: ["private-recover", "never"]) + defer { terminateProcess(second) } + try ProcessWait.exit(second, root: fixture.root) + #expect(second.terminationStatus == 0) + #expect( + try Data(contentsOf: fixture.root.appendingPathComponent("AGENTS.md")) + == Data("private-before".utf8)) + #expect(try Data(contentsOf: fixture.store.materializationReceiptURL) == originalReceipt) + #expect( + !FileManager.default.fileExists( + atPath: fixture.root.appendingPathComponent("provider-called").path)) + #expect(try !TransactionJournal.isPresent(in: DirectoryHandle(at: fixture.store.directory))) + } + + @Test(arguments: ["target", "backup", "ancestor", "restore-race"]) + func unsafeSensitiveRecoveryRetainsJournalAndPrivateEvidence(_ change: String) throws { + let fixture = try TransactionFixture() + try installPrivate("private-before", in: fixture) + let child = try stateTestProcess( + root: fixture.root, arguments: ["private-install", "entry.0.applied"]) + defer { terminateProcess(child) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: child, root: fixture.root) + terminateProcess(child) + let journal = try readMaterializationJournal(fixture) + let backup = fixture.root.appendingPathComponent(journal.containerName(0)) + .appendingPathComponent("entry.0.exchanged") + if change == "target" { + try #require(chmod(fixture.root.appendingPathComponent("AGENTS.md").path, 0o644) == 0) + } + if change == "backup" { try #require(chmod(backup.path, 0o644) == 0) } + if change == "ancestor" { try #require(chmod(fixture.root.path, 0o775) == 0) } + #expect(throws: (any Error).self) { + try fixture.store.withLock( + checkpoint: { point in + if change == "restore-race" && point == "restore.0.validated" { + try #require(chmod(backup.path, 0o644) == 0) + } + }, {}) + } + #expect( + FileManager.default.fileExists( + atPath: fixture.store.directory.appendingPathComponent(TransactionJournal.fileName).path)) + #expect(try Data(contentsOf: backup) == Data("private-before".utf8)) + #expect( + try Data(contentsOf: fixture.root.appendingPathComponent("AGENTS.md")) + == Data("private-after".utf8)) + } + + @Test func receiptInspectionAndExpectedGenerationsDoNotExposeValues() throws { + let fixture = try TransactionFixture() + try installPrivate("receipt-secret-sentinel", in: fixture) + let target = try fixture.store.materializationTarget( + at: fixture.root.appendingPathComponent("AGENTS.md")) + let first = try #require(try fixture.store.materializationReceipt(for: target)) + let prepared = try fixture.store.preparePrivateMaterialization( + target, expecting: first.generation) + let same = try fixture.store.preparePrivateMaterialization(target, expecting: first.generation) + #expect(try prepared.accessFingerprint() == same.accessFingerprint()) + #expect(!String(reflecting: first).contains("receipt-secret-sentinel")) + try installPrivate("rotated-private-value", in: fixture) + #expect(throws: CoreError.self) { + try fixture.store.preparePrivateMaterialization(target, expecting: first.generation) + } + let second = try #require(try fixture.store.materializationReceipt(for: target)) + #expect(second.generation != first.generation) + try FileManager.default.removeItem(at: fixture.store.materializationReceiptURL) + #expect(throws: CoreError.self) { + try fixture.store.preparePrivateMaterialization( + target, requiringReceiptForExistingTarget: true) + } + } + + @Test func receiptWritesAreReservedAcrossLogicalAndPhysicalRootAliases() throws { + let fixture = try TransactionFixture() + try installPrivate("private-before", in: fixture) + let before = try Data(contentsOf: fixture.store.materializationReceiptURL) + let alias = fixture.root.appendingPathComponent("project-alias") + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: fixture.root) + let aliased = StateStore( + scope: .project, environment: RuntimeEnvironment(projectDirectory: alias)) + let transaction = FileTransaction(store: aliased) + #expect(throws: CoreError.self) { + try transaction.replace( + fixture.store.materializationReceiptURL.resolvingSymlinksInPath(), with: .data(Data())) + } + #expect(try Data(contentsOf: fixture.store.materializationReceiptURL) == before) + } + + @Test func anAbsentRecordedTargetCanBeRestoredAndItsReceiptCanBeRemoved() throws { + let fixture = try TransactionFixture() + try installPrivate("private-before", in: fixture) + let target = fixture.root.appendingPathComponent("AGENTS.md") + try FileManager.default.removeItem(at: target) + try fixture.store.withLock { + let prepared = try fixture.store.preparePrivateMaterialization( + fixture.store.materializationTarget(at: target), requiringReceiptForExistingTarget: true) + let transaction = FileTransaction(store: fixture.store) + try transaction.replacePrivate( + prepared, bindings: ["value"], provider: TestBindings("restored-private") + ) { try $0.value(for: "value") } + try transaction.commit() + } + #expect(try Data(contentsOf: target) == Data("restored-private".utf8)) + try FileManager.default.removeItem(at: target) + try fixture.store.withLock { + let transaction = FileTransaction(store: fixture.store) + try transaction.delete(target) + try transaction.commit() + } + #expect(try fixture.store.materializationReceipts().records.targets.isEmpty) + } + + @Test func lastPublicationCheckCannotCopyChangedTargetAccessOntoSecretBytes() throws { + let fixture = try TransactionFixture() + let target = fixture.root.appendingPathComponent("AGENTS.md") + try #require(chmod(target.path, 0o644) == 0) + #expect(throws: CoreError.self) { + try fixture.store.withLock { + let prepared = try fixture.store.preparePrivateMaterialization( + fixture.store.materializationTarget(at: target), changingAccess: true) + let transaction = FileTransaction(store: fixture.store) { point in + if point == "publish.0.validated" { try #require(chmod(target.path, 0o640) == 0) } + } + try transaction.replacePrivate( + prepared, bindings: ["value"], provider: TestBindings("unpublished-secret") + ) { try $0.value(for: "value") } + try transaction.commit() + } + } + #expect(try Data(contentsOf: target) == Data("old instructions".utf8)) + let journal = try readMaterializationJournal(fixture) + let container = try DirectoryHandle(at: fixture.root).child(journal.containerName(0)) + _ = try container.requirePrivateAccess("entry.0.exchanged") + #expect(try container.read("entry.0.exchanged") == Data("unpublished-secret".utf8)) + } + + @Test(arguments: ["security", "preimageAccess", "ancestry", "version"]) + func missingSecurityEvidenceCannotRecoverOrMutateObjects(_ field: String) throws { + let fixture = try TransactionFixture() + try installPrivate("private-before", in: fixture) + let child = try stateTestProcess( + root: fixture.root, arguments: ["private-install", "entry.0.applied"]) + defer { terminateProcess(child) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: child, root: fixture.root) + terminateProcess(child) + let path = fixture.store.directory.appendingPathComponent(TransactionJournal.fileName) + var value = try #require( + JSONSerialization.jsonObject(with: Data(contentsOf: path)) as? [String: Any]) + if field == "version" { + value["version"] = 1 + } else { + var entries = try #require(value["entries"] as? [[String: Any]]) + if field == "security" { + entries[0].removeValue(forKey: field) + } else { + var security = try #require(entries[0]["security"] as? [String: Any]) + security.removeValue(forKey: field) + entries[0]["security"] = security + } + value["entries"] = entries + } + try JSONSerialization.data(withJSONObject: value).write(to: path) + let before = try FileSnapshot.read(at: fixture.root) + #expect(throws: (any Error).self) { try fixture.store.withLock {} } + #expect(try FileSnapshot.read(at: fixture.root) == before) + } +} + +private final class TestBindings: RuntimeBindingProvider { + let value: String + private let state = Mutex((calls: 0, fails: false)) + var calls: Int { state.withLock { $0.calls } } + var fails: Bool { + get { state.withLock { $0.fails } } + set { state.withLock { $0.fails = newValue } } + } + init(_ value: String) { self.value = value } + func value(for binding: String, environment: RuntimeEnvironment) throws -> Data { + let fails = state.withLock { + $0.calls += 1 + return $0.fails + } + if fails { throw CoreError.invalidState(value) } + return Data(value.utf8) + } +} + +private func installPrivate(_ value: String, in fixture: TransactionFixture) throws { + try fixture.store.withLock { + let target = try fixture.store.materializationTarget( + at: fixture.root.appendingPathComponent("AGENTS.md")) + let prepared = try fixture.store.preparePrivateMaterialization(target, changingAccess: true) + let transaction = FileTransaction(store: fixture.store) + try transaction.replacePrivate(prepared, bindings: ["value"], provider: TestBindings(value)) { + try $0.value(for: "value") + } + try transaction.commit() + } +} + +private func readMaterializationJournal(_ fixture: TransactionFixture) throws -> TransactionJournal +{ + try StateStore.decode( + Data(contentsOf: fixture.store.directory.appendingPathComponent(TransactionJournal.fileName)), + as: TransactionJournal.self) +} diff --git a/Tests/AgentsCoreTests/PrivateTreeTests.swift b/Tests/AgentsCoreTests/PrivateTreeTests.swift new file mode 100644 index 0000000..91efc3d --- /dev/null +++ b/Tests/AgentsCoreTests/PrivateTreeTests.swift @@ -0,0 +1,562 @@ +import CPlatform +import Foundation +import StateTestSupport +import Testing + +@testable import AgentsCore + +@Suite("Private complete native trees") +struct PrivateTreeTests { + @Test func completeTreeIsPrivateBeforeProviderAndOrdinarySiblingUpdatesRetainItsReceipt() throws { + let fixture = try TransactionFixture() + let route = try NativeTargetRoute.named( + .claudeSkillPlugin, scope: .user, name: "private-fixture") + var environment = fixture.store.environment + environment.environment["CLAUDE_CONFIG_DIR"] = + fixture.root.appendingPathComponent("configured-claude").path + let store = StateStore(scope: .user, environment: environment) + var first: UUID? + try store.withLock(footprint: [route]) { + let target = try store.nativeTarget(for: route) + let prepared = try store.preparePrivateMaterialization(target) + let provider = TreeBindings { + let journal = try treeJournal(store) + let parent = try DirectoryHandle(at: target.url.deletingLastPathComponent()) + let container = try parent.child(journal.containerName(0)) + let name = TransactionSlot.staging(for: journal.entries[0]).name(0) + let snapshot = try #require(try FileSnapshot.read(name, from: container)) + _ = try container.requirePrivateAccess(name) + let members = try #require( + try TreeMemberAccess.capture( + name, in: container, snapshot: snapshot, requirePrivate: true)) + #expect(members.map(\.path) == ["bin", "bin/run", "config", "sibling"]) + #expect(try container.child(name).read("config").isEmpty) + #expect(try container.child(name).child("bin").read("run").isEmpty) + #expect(members.first { $0.path == "bin/run" }?.access.mode == 0o700) + return Data("fixture-private".utf8) + } + let transaction = FileTransaction(store: store) + try transaction.replacePrivateTree(prepared, entries: treeEntries(), provider: provider) + try transaction.commit() + let receipt = try #require(try store.materializationReceipt(for: target)) + first = receipt.generation + #expect(receipt.treeAccess?.count == 4) + #expect( + try Data(contentsOf: target.url.appendingPathComponent("config")) + == Data("fixture-private".utf8)) + #expect( + try FileManager.default.destinationOfSymbolicLink( + atPath: target.url.appendingPathComponent("alias").path) == "bin/run") + } + // A cold scope has no source/provider need for an ordinary sibling update. + var other = environment + other.homeDirectory = fixture.root.appendingPathComponent("other-home") + try FileManager.default.createDirectory( + at: other.homeDirectory, withIntermediateDirectories: true) + let second = StateStore(scope: .user, environment: other) + try second.withLock(footprint: [route]) { + let target = try second.nativeTarget(for: route) + let privateBytes = try Data(contentsOf: target.url.appendingPathComponent("config")) + let transaction = FileTransaction(store: second) + #expect(throws: CoreError.self) { + try transaction.replace(target.url, with: .copy(fixture.root.appendingPathComponent("new"))) + } + let update = FileTransaction(store: second) + try update.replacePrivateTree( + second.preparePrivateMaterialization(target), + entries: [ + .init("config", content: .file(privateBytes)), + .init("sibling", content: .file(Data("changed ordinary sibling".utf8))), + ], + provider: TreeBindings { + throw CoreError.invalidState("ordinary edit must not resolve bindings") + }) + try update.commit() + let receipt = try #require(try second.materializationReceipt(for: target)) + #expect(receipt.generation != first) + #expect(receipt.treeAccess?.map(\.path) == ["config", "sibling"]) + let remove = FileTransaction(store: second) + try remove.delete(target.url) + try remove.commit() + #expect(try second.materializationReceipt(for: target) == nil) + } + } + + @Test(arguments: ["provider", "entry.0.applied", "entry.1.applied", "journal.committed"]) + func failuresPreserveCompleteGenerationAndReceipt(_ failure: String) throws { + let fixture = try TransactionFixture() + let route = try NativeTargetRoute.named( + .cursorLocalPlugin, scope: .user, name: "rollback-fixture") + let store = StateStore(scope: .user, environment: fixture.store.environment) + try store.withLock(footprint: [route]) { + let target = try store.nativeTarget(for: route) + let original = FileTransaction(store: store) + try original.replacePrivateTree( + store.preparePrivateMaterialization(target), + entries: [ + .init("old", content: .file(Data("old-private".utf8))) + ], provider: TreeBindings { Data() }) + try original.commit() + let before = try FileSnapshot.read(at: target.url) + let generation = try store.materializationReceipt(for: target)?.generation + let outcome = TransactionOutcome() + let transaction = FileTransaction(store: store, outcome: outcome) { point in + if point == failure { throw CoreError.invalidState("bounded tree interruption") } + } + try transaction.replacePrivateTree( + store.preparePrivateMaterialization(target), entries: treeEntries(), + provider: TreeBindings { + if failure == "provider" { throw CoreError.invalidState("private fixture failure") } + return Data("new-private".utf8) + }) + #expect(throws: CoreError.self) { try transaction.commit() } + if failure == "journal.committed" { + #expect(outcome.terminal == .committed) + #expect(try store.materializationReceipt(for: target)?.generation != generation) + #expect( + try Data(contentsOf: target.url.appendingPathComponent("config")) + == Data("new-private".utf8)) + } else { + #expect(try FileSnapshot.read(at: target.url) == before) + #expect(try store.materializationReceipt(for: target)?.generation == generation) + } + #expect(!outcome.recoveryPending) + #expect( + !FileManager.default.fileExists( + atPath: store.directory.appendingPathComponent("transaction.json").path)) + } + } + + @Test func accessChangesArePreparedAndInvalidTreesNeverResolveBindings() throws { + let fixture = try TransactionFixture() + let route = try NativeTargetRoute.named( + .claudeSkillPlugin, scope: .project, name: "private-plugin") + try fixture.store.withLock(footprint: [route]) { + let target = try fixture.store.nativeTarget(for: route) + try FileManager.default.createDirectory(at: target.url, withIntermediateDirectories: true) + try Data("ordinary".utf8).write(to: target.url.appendingPathComponent("ordinary")) + try #require(chmod(target.url.path, 0o755) == 0) + try #require(chmod(target.url.appendingPathComponent("ordinary").path, 0o644) == 0) + #expect(throws: CoreError.self) { try fixture.store.preparePrivateMaterialization(target) } + let prepared = try fixture.store.preparePrivateMaterialization(target, changingAccess: true) + #expect(prepared.accessChange?.mode == 0o700) + #expect(prepared.memberAccessChanges.map(\.path) == ["ordinary"]) + let before = try FileSnapshot.read(at: target.url) + let bad: [[PrivateTreeEntry]] = [ + [.init("../escape", content: .file(Data()))], + [.init("link", content: .symlink(".."))], + [.init("link", content: .symlink("other")), .init("other", content: .symlink("link"))], + [.init("link", content: .symlink("missing")), .init("link/file", content: .file(Data()))], + [.init("duplicate", content: .directory), .init("duplicate", content: .file(Data()))], + ] + for entries in bad { + let transaction = FileTransaction(store: fixture.store) + #expect(throws: CoreError.self) { + try transaction.replacePrivateTree( + prepared, entries: entries, + provider: TreeBindings { throw CoreError.invalidState("must not resolve") }) + } + } + #expect(try FileSnapshot.read(at: target.url) == before) + let update = FileTransaction(store: fixture.store) + try update.replacePrivateTree( + prepared, entries: [.init("safe-dangling", content: .symlink("missing/file"))], + provider: TreeBindings { Data() }) + try update.commit() + #expect(try fixture.store.materializationReceipt(for: target)?.treeAccess == []) + } + } + + @Test func readOnlyOrdinaryPreimageIsRestoredWithItsAccess() throws { + let fixture = try TransactionFixture() + let route = try NativeTargetRoute.named(.claudeSkillPlugin, scope: .project, name: "read-only") + try fixture.store.withLock(footprint: [route]) { + let target = try fixture.store.nativeTarget(for: route) + try FileManager.default.createDirectory(at: target.url, withIntermediateDirectories: true) + try Data("original".utf8).write(to: target.url.appendingPathComponent("old")) + try #require(chmod(target.url.path, 0o555) == 0) + defer { _ = chmod(target.url.path, 0o755) } + let original = try FileSnapshot.read(at: target.url) + let transaction = FileTransaction(store: fixture.store) { point in + if point == "entry.0.applied" { throw CoreError.invalidState("bounded interruption") } + } + try transaction.replacePrivateTree( + fixture.store.preparePrivateMaterialization(target, changingAccess: true), + entries: [.init("new", content: .file(Data()))], provider: TreeBindings { Data() }) + #expect(throws: CoreError.self) { try transaction.commit() } + #expect(try FileSnapshot.read(at: target.url) == original) + #expect( + !FileManager.default.fileExists( + atPath: fixture.store.directory.appendingPathComponent("transaction.json").path)) + } + } + + @Test func changedSealedMemberRetainsRecoveryEvidenceUntilAccessIsRestored() throws { + let fixture = try TransactionFixture() + let route = try NativeTargetRoute.named(.claudeSkillPlugin, scope: .project, name: "freshness") + var changed: URL? + var cleanupPending = false + do { + try fixture.store.withLock(footprint: [route]) { + let target = try fixture.store.nativeTarget(for: route) + let outcome = TransactionOutcome() + let transaction = FileTransaction(store: fixture.store, outcome: outcome) { point in + if point == "entry.0.ready" { + let journal = try treeJournal(fixture.store) + let file = target.url.deletingLastPathComponent() + .appendingPathComponent(journal.containerName(0)) + .appendingPathComponent(TransactionSlot.staging(for: journal.entries[0]).name(0)) + .appendingPathComponent("member") + try #require(chmod(file.path, 0o644) == 0) + changed = file + } + } + try transaction.replacePrivateTree( + fixture.store.preparePrivateMaterialization(target), + entries: [.init("member", content: .file(Data("fixture".utf8)))], + provider: TreeBindings { Data() }) + #expect(throws: CoreError.self) { try transaction.commit() } + #expect(outcome.recoveryPending) + #expect(!FileManager.default.fileExists(atPath: target.url.path)) + let sealed = try #require(changed) + #expect(FileManager.default.fileExists(atPath: sealed.path)) + try #require(chmod(sealed.path, 0o600) == 0) + } + } catch CoreError.invalidState { + cleanupPending = true + } + #expect(cleanupPending) + #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { + try fixture.store.withLock(footprint: [route]) {} + } + #expect( + !FileManager.default.fileExists( + atPath: fixture.store.directory.appendingPathComponent("transaction.json").path)) + } + + @Test(arguments: ["missing", "duplicate", "kind"]) + func malformedTreeReceiptNeverBecomesOrdinary(_ field: String) throws { + let fixture = try TransactionFixture() + let route = try NativeTargetRoute.named(.claudeSkillPlugin, scope: .project, name: "receipt") + try fixture.store.withLock(footprint: [route]) { + let target = try fixture.store.nativeTarget(for: route) + let transaction = FileTransaction(store: fixture.store) + try transaction.replacePrivateTree( + fixture.store.preparePrivateMaterialization(target), + entries: [.init("member", content: .file(Data()))], provider: TreeBindings { Data() }) + try transaction.commit() + let url = fixture.store.materializationReceiptURL + var json = try #require( + JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? [String: Any]) + var targets = try #require(json["targets"] as? [String: [String: Any]]) + var record = try #require(targets[target.path]) + if field == "missing" { + record.removeValue(forKey: "treeAccess") + } else if field == "duplicate" { + var members = try #require(record["treeAccess"] as? [[String: Any]]) + members.append(try #require(members.first)) + record["treeAccess"] = members + } else { + var access = try #require(record["access"] as? [String: Any]) + var identity = try #require(access["identity"] as? [String: Any]) + identity["kind"] = Int(CPlatform.S_IFREG) + access["identity"] = identity + record["access"] = access + } + targets[target.path] = record + json["targets"] = targets + try JSONSerialization.data(withJSONObject: json).write(to: url) + let before = try FileSnapshot.read(at: fixture.root) + #expect(throws: CoreError.self) { try fixture.store.materializationReceipt(for: target) } + #expect(try FileSnapshot.read(at: fixture.root) == before) + } + } + + @Test func missingNativeRootHasStablePreviewEvidenceDuringAdmission() throws { + let fixture = try TransactionFixture() + let store = StateStore(scope: .project, environment: fixture.store.environment) + var before = "" + var privateBefore = "" + try store.withReadLock(footprint: [.cursorMCPUser]) { + let target = try store.nativeTarget(for: .cursorMCPUser) + before = try TargetPrecondition(target.url).displayEvidence(includeContent: false) + privateBefore = try store.preparePrivateMaterialization(target).accessFingerprint() + #expect(!FileManager.default.fileExists(atPath: target.url.deletingLastPathComponent().path)) + } + try store.withLock(footprint: [.cursorMCPUser]) { + let target = try store.nativeTarget(for: .cursorMCPUser) + #expect(try TargetPrecondition(target.url).displayEvidence(includeContent: false) == before) + #expect(try store.preparePrivateMaterialization(target).accessFingerprint() == privateBefore) + } + try store.withReadLock(footprint: [.cursorMCPUser]) { + let target = try store.nativeTarget(for: .cursorMCPUser) + let parent = target.url.deletingLastPathComponent() + try #require(chmod(parent.path, 0o750) == 0) + #expect(try TargetPrecondition(target.url).displayEvidence(includeContent: false) != before) + } + } + + #if os(Linux) + @Test func unicodeDistinctMembersSurviveSnapshotCodecDigestAndDisposal() throws { + let fixture = try TransactionFixture() + let parent = try DirectoryHandle(at: fixture.root.appendingPathComponent("new")) + let nfc = "\u{e9}" + let nfd = "e\u{301}" + try parent.write(nfc, data: Data("nfc".utf8)) + try parent.link(nfd, destination: "SKILL.md") + let before = try #require(try FileSnapshot.read(at: parent.url)) + #expect(before.children?.count == 3) + #expect(before.child(named: nfc)?.isRegular == true) + #expect(before.child(named: nfd)?.isSymbolicLink == true) + let decoded = try StateStore.decode(StateStore.encode(before), as: FileSnapshot.self) + #expect(decoded == before) + try parent.remove(nfc, expecting: before.child(named: nfc)) + let remaining = try #require(try FileSnapshot.read(at: parent.url)) + #expect(before.containsRemaining(remaining)) + try DirectoryHandle(at: fixture.root).remove( + "new", expecting: before, identity: before.identity) + #expect(!FileManager.default.fileExists(atPath: parent.url.path)) + } + #endif +} + +private struct TreeBindings: RuntimeBindingProvider { + let resolve: @Sendable () throws -> Data + init(_ resolve: @escaping @Sendable () throws -> Data) { self.resolve = resolve } + func value(for binding: String, environment: RuntimeEnvironment) throws -> Data { try resolve() } +} + +private func treeEntries() -> [PrivateTreeEntry] { + [ + .init("bin", content: .directory), + .init( + "bin/run", + content: .boundFile(bindings: ["fixture"], executable: true) { try $0.value(for: "fixture") }), + .init("config", content: .boundFile(bindings: ["fixture"]) { try $0.value(for: "fixture") }), + .init("sibling", content: .file(Data("ordinary sibling".utf8))), + .init("alias", content: .symlink("bin/run")), + ] +} + +private func treeJournal(_ store: StateStore) throws -> TransactionJournal { + try StateStore.decode( + Data(contentsOf: store.directory.appendingPathComponent("transaction.json")), + as: TransactionJournal.self) +} + +extension PrivateTreeTests { + @Test(arguments: [ + "stage.0.constructed", "entry.0.ready", "entry.0.applied", "entry.1.applied", + "journal.committed", "disposal.0.unlinked.entry.0.exchanged/old", "journal.finalized", + ]) + func restartRecoveryKeepsCompleteTreeAndSealedDisposalSubset(_ point: String) throws { + let fixture = try TransactionFixture() + let route = try NativeTargetRoute.named( + .claudeSkillPlugin, scope: .user, name: "private-fixture") + var environment = fixture.store.environment + environment.environment["CLAUDE_CONFIG_DIR"] = + fixture.root.appendingPathComponent("configured-claude").path + let store = StateStore(scope: .user, environment: environment) + var generation: UUID? + try store.withLock(footprint: [route]) { + let target = try store.nativeTarget(for: route) + let transaction = FileTransaction(store: store) + try transaction.replacePrivateTree( + store.preparePrivateMaterialization(target), + entries: [ + .init("old", content: .file(Data("old tree".utf8))), + .init("other", content: .file(Data("old sibling".utf8))), + ], provider: TreeBindings { Data() }) + try transaction.commit() + generation = try store.materializationReceipt(for: target)?.generation + } + let child = try stateTestProcess( + root: fixture.root, arguments: ["private-tree-install", point, "--scope", "user"]) + defer { terminateProcess(child) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: child, root: fixture.root) + terminateProcess(child) + let beforeRead = try FileSnapshot.read(at: fixture.root) + try store.withReadLock( + onPendingRecovery: { + #expect(!FileTransaction.recoveryDiagnostic(store: store).requiresOwner) + }, { Issue.record("a sealed tree journal must remain pending on a read") }) + #expect(try FileSnapshot.read(at: fixture.root) == beforeRead) + #expect(throws: CoreError.transactionRecovered(store.directory.path)) { try store.withLock {} } + let committed = + point == "journal.committed" || point.hasPrefix("disposal.") || point == "journal.finalized" + try store.withReadLock(footprint: [route]) { + let target = try store.nativeTarget(for: route) + let receipt = try #require(try store.materializationReceipt(for: target)) + #expect((receipt.generation != generation) == committed) + let directory = try DirectoryHandle(at: target.url) + _ = try FileAccessEvidence.requirePrivate(descriptor: directory.descriptor) + if committed { + #expect(try directory.read("config") == Data("tree-private-after".utf8)) + #expect(try directory.child("nested").read("run") == Data("tree-private-after".utf8)) + #expect(try directory.readLink("alias") == "nested/run") + } else { + #expect(try directory.read("old") == Data("old tree".utf8)) + #expect(try directory.read("other") == Data("old sibling".utf8)) + } + } + } + + @Test func differentHomesShareTreeLockBeforeCallbackAndProvider() throws { + let fixture = try TransactionFixture() + let config = fixture.root.appendingPathComponent("tree-shared-root") + let other = fixture.root.appendingPathComponent("other-project") + try FileManager.default.createDirectory(at: other, withIntermediateDirectories: true) + let holder = try stateTestProcess( + root: fixture.root, + arguments: [ + "private-tree-lock", "tree.locked", "--scope", "user", "--shared-config", config.path, + ]) + defer { terminateProcess(holder) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: holder, root: fixture.root) + let waiter = try stateTestProcess( + root: other, + arguments: [ + "private-tree-install", "shared.0.lock.contended", "--scope", "user", "--shared-config", + config.path, + ]) + defer { terminateProcess(waiter) } + try ProcessWait.marker(other.appendingPathComponent("ready"), child: waiter, root: other) + #expect( + !FileManager.default.fileExists( + atPath: other.appendingPathComponent("tree-provider-resolved").path)) + try #require(kill(holder.processIdentifier, SIGCONT) == 0) + try ProcessWait.exit(holder, root: fixture.root) + #expect(holder.terminationStatus == 0) + try #require(kill(waiter.processIdentifier, SIGCONT) == 0) + try ProcessWait.exit(waiter, root: other) + #expect(waiter.terminationStatus == 0) + #expect( + FileManager.default.fileExists( + atPath: other.appendingPathComponent("tree-provider-resolved").path)) + #expect( + try Data(contentsOf: config.appendingPathComponent("skills/private-fixture/config")) + == Data("tree-private-after".utf8)) + } + + @Test(arguments: ["stagedTreeAccess", "duplicateMember", "coordination", "version"]) + func malformedTreeJournalIsReadOnlyRejected(_ field: String) throws { + let fixture = try TransactionFixture() + let child = try stateTestProcess( + root: fixture.root, + arguments: ["private-tree-install", "entry.0.ready", "--scope", "user"]) + defer { terminateProcess(child) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: child, root: fixture.root) + terminateProcess(child) + var environment = fixture.store.environment + environment.environment["CLAUDE_CONFIG_DIR"] = + fixture.root.appendingPathComponent("configured-claude").path + let store = StateStore(scope: .user, environment: environment) + let journalURL = store.directory.appendingPathComponent("transaction.json") + var json = try #require( + JSONSerialization.jsonObject(with: Data(contentsOf: journalURL)) as? [String: Any]) + var entries = try #require(json["entries"] as? [[String: Any]]) + switch field { + case "version": json["version"] = 3 + case "coordination": entries[0]["coordination"] = 999 + case "duplicateMember": + var staged = try #require(entries[0]["staged"] as? [String: Any]) + var children = try #require(staged["children"] as? [[String: Any]]) + children.append(try #require(children.first)) + staged["children"] = children + entries[0]["staged"] = staged + default: + var security = try #require(entries[0]["security"] as? [String: Any]) + security.removeValue(forKey: field) + entries[0]["security"] = security + } + json["entries"] = entries + try JSONSerialization.data(withJSONObject: json).write(to: journalURL) + let before = try FileSnapshot.read(at: fixture.root) + #expect(throws: (any Error).self) { try store.withLock {} } + #expect(try FileSnapshot.read(at: fixture.root) == before) + } + + @Test func recordedNamedRootsResolveOnColdReadWithoutPathAuthority() throws { + let fixture = try TransactionFixture() + let route = try NativeTargetRoute.named(.claudeCommand, scope: .project, name: "team/review") + var ledger = ResolvedLedger() + ledger.sources["fixture"] = LedgerSource(kind: .local, revision: "live") + ledger.components["command"] = LedgerComponent( + declaringSource: "fixture", source: "fixture", root: ".", kind: "command", + name: "review", payload: .init(object: [:]), conditions: [], recipients: [.claudeCode], + chatGPT: false, resources: []) + ledger.deployments = [ + .init( + id: "deployment", target: .init(kind: .registered, root: route.root, path: route.basename), + route: "fixture/command@1", + owners: ["command"], recipients: [.claudeCode], ownership: .generated, + expectedHash: "sha256:" + String(repeating: "a", count: 64), created: true) + ] + ledger.lowerings = [ + .init( + id: "lowering", format: "fixture/command@1", inputs: ["command"], resources: [], + deployments: ["deployment"], layout: .init(object: [:]), platform: "macos", artifacts: []) + ] + try ResolvedLedgerCodec.encode(ledger, limits: .standard).write(to: fixture.store.resolvedURL) + let cold = StateStore(scope: .project, environment: fixture.store.environment) + let target = try ledger.deployments[0].target.resolve(roots: cold.ledgerRoots) + #expect(target == fixture.root.appendingPathComponent(".claude/commands/team/review.md")) + #expect(throws: CoreError.self) { + try FileTransaction(store: cold).replace(target, with: .data(Data())) + } + try cold.withLock(footprint: [route]) { + let admitted = try cold.nativeTarget(for: route) + let transaction = FileTransaction(store: cold) + try transaction.replace(admitted.url, with: .data(Data("command".utf8))) + try transaction.commit() + } + ledger.deployments[0].target.path = "unrecorded.md" + try ResolvedLedgerCodec.encode(ledger, limits: .standard).write(to: fixture.store.resolvedURL) + #expect(cold.ledgerRoots[route.root] == nil) + ledger.deployments[0].target.root = "native-member-2e2e2f657363617065" + try ResolvedLedgerCodec.encode(ledger, limits: .standard).write(to: fixture.store.resolvedURL) + #expect(cold.ledgerRoots[ledger.deployments[0].target.root!] == nil) + #expect(RuntimeBindingValues([:]).description == "") + } +} + +extension PrivateTreeTests { + @Test func independentNestedCoordinationIsRefusedBeforeCreatingMetadata() throws { + let fixture = try TransactionFixture() + var environment = fixture.store.environment + let configured = fixture.root.appendingPathComponent("configured") + try FileManager.default.createDirectory(at: configured, withIntermediateDirectories: true) + environment.environment["CLAUDE_CONFIG_DIR"] = configured.path + environment.environment["CODEX_HOME"] = configured.appendingPathComponent("skills/plugin").path + let store = StateStore(scope: .user, environment: environment) + let before = try FileSnapshot.read(at: fixture.root) + #expect(throws: CoreError.self) { try store.withReadLock(footprint: [.codexMCPUser]) {} } + #expect(throws: CoreError.self) { try store.withLock(footprint: [.codexMCPUser]) {} } + #expect(try FileSnapshot.read(at: fixture.root) == before) + environment.environment["CODEX_HOME"] = + fixture.root.appendingPathComponent("independent-codex").path + try FileManager.default.createDirectory( + at: fixture.root.appendingPathComponent("independent-codex"), + withIntermediateDirectories: true) + let allowed = StateStore(scope: .user, environment: environment) + let plugin = try NativeTargetRoute.named(.claudeSkillPlugin, scope: .user, name: "plugin") + try allowed.withLock(footprint: [plugin, .codexMCPUser]) { + let target = try allowed.nativeTarget(for: plugin) + let transaction = FileTransaction(store: allowed) + try transaction.replacePrivateTree( + allowed.preparePrivateMaterialization(target), entries: [], + provider: TreeBindings { Data() }) + let codex = try allowed.nativeTarget(for: .codexMCPUser) + try transaction.replacePrivate( + allowed.preparePrivateMaterialization(codex), provider: TreeBindings { Data() } + ) { _ in Data("ordinary fixture".utf8) } + try transaction.commit() + #expect(try allowed.materializationReceipt(for: target)?.treeAccess == []) + #expect(try allowed.materializationReceipt(for: codex)?.treeAccess == nil) + #expect(try allowed.materializationReceipt(for: codex) != nil) + } + } +} diff --git a/Tests/AgentsCoreTests/ProcessLimitsTests.swift b/Tests/AgentsCoreTests/ProcessLimitsTests.swift new file mode 100644 index 0000000..1632447 --- /dev/null +++ b/Tests/AgentsCoreTests/ProcessLimitsTests.swift @@ -0,0 +1,84 @@ +import Foundation +import StateTestSupport +import Testing + +@testable import AgentsCore + +@Suite struct ProcessLimitsTests { + private struct Probe { + let soft: UInt64 + let hard: UInt64 + let after: UInt64 + let result: String + } + + private func createSkillLocks(at root: URL, count: Int) throws { + let store = StateStore( + scope: .user, + environment: RuntimeEnvironment( + projectDirectory: root, homeDirectory: root.appendingPathComponent("home"), + environment: ["CLAUDE_CONFIG_DIR": root.appendingPathComponent("configured-claude").path] + )) + for index in 0.. Probe { + let child = try stateTestProcess( + root: root, arguments: ["open-file-limit", mode, "--scope", "user"]) + defer { terminateProcess(child) } + try ProcessWait.exit(child, root: root, timeout: 30) + try #require(child.terminationReason == .exit) + try #require(child.terminationStatus == 0) + let lines = try String( + contentsOf: root.appendingPathComponent("open-file-limit-\(mode)"), encoding: .utf8 + ).split(separator: "\n") + try #require(lines.count == 5) + let soft = try #require(UInt64(lines[0])) + let hard = try #require(UInt64(lines[1])) + let after = try #require(UInt64(lines[2])) + #expect(UInt64(lines[3]) == hard) + return Probe(soft: soft, hard: hard, after: after, result: String(lines[4])) + } + + private func checkLargeAdmission(_ probe: Probe, count: UInt64) { + // The probe sets a comfortably sufficient budget of 4096 when testing the worker. + // Below three pinned descriptors per route, the full footprint cannot fit. + if probe.after >= 4096 { + #expect(probe.result == "admitted") + } else if probe.after < 3 * count { + #expect(probe.result.hasPrefix("Too many open files for this process:")) + } + } + + @Test func executableOptInPreservesHardLimitAndUsesAvailableCapacity() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + try createSkillLocks(at: root, count: 96) + let original = try runProbe("original", at: root) + #expect(original.after == original.soft) + #expect(original.result.hasPrefix("Too many open files for this process:")) + let raised = try runProbe("raised", at: root) + #expect(raised.soft == original.soft) + #expect(raised.after <= raised.hard) + if raised.hard > raised.soft { #expect(raised.after > raised.soft) } + checkLargeAdmission(raised, count: 96) + let bounded = try runProbe("bounded", at: root) + #expect(bounded.hard <= 64) + #expect(bounded.after == bounded.hard) + #expect(bounded.result.hasPrefix("Too many open files for this process:")) + } + + @Test func heldSharedFootprintFitsBoundedWorkerStack() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + try createSkillLocks(at: root, count: 196) + let worker = try runProbe("worker", at: root) + checkLargeAdmission(worker, count: 196) + } +} diff --git a/Tests/AgentsCoreTests/ProcessTerminationTests.swift b/Tests/AgentsCoreTests/ProcessTerminationTests.swift new file mode 100644 index 0000000..30c0b41 --- /dev/null +++ b/Tests/AgentsCoreTests/ProcessTerminationTests.swift @@ -0,0 +1,67 @@ +import CPlatform +import Foundation +import StateTestSupport +import Testing + +/// A SIGKILL racing a child's own SIGSTOP was observed to be lost on Darwin, leaving the child +/// running or stopped. That interleaving cannot be produced on demand, so these tests pin its +/// handling: a stop is observed before signals that depend on it, and lost SIGKILLs are resent +/// within a bounded deadline. +@Suite("Test process termination") +struct ProcessTerminationTests { + @Test func pausedChildIsObservedStoppedBeforeResuming() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let child = try stateTestProcess(root: root, arguments: ["pause", "paused"]) + defer { terminateProcess(child) } + try ProcessWait.marker(root.appendingPathComponent("ready"), child: child, root: root) + try ProcessWait.stopped(child, root: root) + kill(child.processIdentifier, SIGCONT) + try ProcessWait.exit(child, root: root) + #expect(child.terminationStatus == 0) + } + + @Test func stoppedChildIsTerminatedWhenTheFirstKillIsLost() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let child = try stateTestProcess(root: root, arguments: ["pause", "paused"]) + defer { terminateProcess(child) } + try ProcessWait.marker(root.appendingPathComponent("ready"), child: child, root: root) + try ProcessWait.stopped(child, root: root) + var sends = 0 + try ProcessWait.terminate(child, timeout: 10) { processIdentifier in + sends += 1 + if sends > 1 { kill(processIdentifier, SIGKILL) } + } + #expect(sends >= 2) + #expect(child.terminationReason == .uncaughtSignal) + } + + @Test func markedChildThatNeverStopsIsTerminatedWithinTheDeadline() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let child = try stateTestProcess(root: root, arguments: ["unstopped-marker"]) + defer { terminateProcess(child) } + try ProcessWait.marker(root.appendingPathComponent("ready"), child: child, root: root) + #expect(throws: (any Error).self) { try ProcessWait.stopped(child, root: root, timeout: 0.5) } + let start = Date() + try ProcessWait.terminate(child, timeout: 10) + #expect(Date().timeIntervalSince(start) < 2) + #expect(child.terminationReason == .uncaughtSignal) + } + + @Test func terminationLoopIsBoundedWhenSignalsNeverArrive() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let child = try stateTestProcess(root: root, arguments: ["unstopped-marker"]) + defer { terminateProcess(child) } + try ProcessWait.marker(root.appendingPathComponent("ready"), child: child, root: root) + let start = Date() + #expect(throws: (any Error).self) { + try ProcessWait.terminate(child, timeout: 0.5, send: { _ in }) + } + let elapsed = Date().timeIntervalSince(start) + #expect(elapsed >= 0.5 && elapsed < 2) + #expect(child.isRunning) + } +} diff --git a/Tests/AgentsCoreTests/ProcessTestSupport.swift b/Tests/AgentsCoreTests/ProcessTestSupport.swift index d62a377..574a835 100644 --- a/Tests/AgentsCoreTests/ProcessTestSupport.swift +++ b/Tests/AgentsCoreTests/ProcessTestSupport.swift @@ -1,26 +1,22 @@ -import Darwin +import CPlatform import Foundation +import StateTestSupport import Testing -func finishProcesses(_ processes: [Process], resuming pause: GitTransactionPause? = nil) throws { +func finishProcesses( + _ processes: [Process], root: URL, resuming pause: GitTransactionPause? = nil +) throws { try pause?.resume() for process in processes { - let exited = DispatchSemaphore(value: 0) - process.terminationHandler = { _ in exited.signal() } - if process.isRunning { - try #require(exited.wait(timeout: .now() + 60) == .success) - } - process.waitUntilExit() + try ProcessWait.exit(process, root: root) #expect(process.terminationStatus == 0) } pause?.completed() } +/// A child that survives the termination deadline fails the test instead of blocking the run. func terminateProcess(_ process: Process) { - if process.isRunning { - Darwin.kill(process.processIdentifier, SIGKILL) - process.waitUntilExit() - } + do { try ProcessWait.terminate(process) } catch { Issue.record(error) } } /// FIFO messages establish ordering; the timeout only bounds a failed handshake. @@ -39,7 +35,7 @@ final class ProcessSignal { func send(_ message: String) throws { let data = Data((message + "\n").utf8) - let count = data.withUnsafeBytes { Darwin.write(descriptor, $0.baseAddress, $0.count) } + let count = data.withUnsafeBytes { CPlatform.write(descriptor, $0.baseAddress, $0.count) } try #require(count == data.count) } @@ -53,7 +49,7 @@ final class ProcessSignal { if result < 0 && errno == EINTR { continue } try #require(result > 0, "Timed out waiting for \(url.lastPathComponent)") var byte: UInt8 = 0 - try #require(Darwin.read(descriptor, &byte, 1) == 1) + try #require(CPlatform.read(descriptor, &byte, 1) == 1) if byte == 10 { return String(decoding: bytes, as: UTF8.self) } bytes.append(byte) } @@ -113,6 +109,6 @@ final class GitTransactionPause { let pids = (try? String(contentsOf: marker, encoding: .utf8))? .split(whereSeparator: \.isWhitespace).compactMap { Int32($0) } ?? [] - for pid in pids { Darwin.kill(pid, SIGKILL) } + for pid in pids { CPlatform.kill(pid, SIGKILL) } } } diff --git a/Tests/AgentsCoreTests/PublicationTests.swift b/Tests/AgentsCoreTests/PublicationTests.swift new file mode 100644 index 0000000..afd5e39 --- /dev/null +++ b/Tests/AgentsCoreTests/PublicationTests.swift @@ -0,0 +1,882 @@ +import AgentsManifest +import CPlatform +import Foundation +import StateTestSupport +import Testing + +@testable import AgentsCore + +@Suite("Journal publication and ownership") +struct PublicationTests { + @Test(arguments: PublicationMatrix.publications) + func killedPublicationAtEachStageRecoversPhysicalGeneration(_ fault: PublicationFault) throws { + try fault.checkSetup() + let fixture = try PublicationFixture(fault.operation) + terminateProcess(try fixture.pause("publication", at: fault.point)) + let journal = try fixture.lastJournal() + try fixture.recover(expected: fault.committed ? .committed : .unchanged) + try fixture.check(committed: fault.committed, journal: journal) + try fixture.expectClean() + } + + @Test(arguments: PublicationMatrix.recoveries) + func recoveryCanBeKilledAtEachStageAndRepeated(_ fault: PublicationFault) throws { + try fault.checkSetup() + let fixture = try PublicationFixture(fault.operation) + terminateProcess(try fixture.pause("publication", at: fault.seed!)) + let journal = try fixture.lastJournal() + terminateProcess(try fixture.pause("publication-recover", at: fault.point)) + try fixture.recover(expected: fault.committed ? .committed : .unchanged, afterRecovery: true) + try fixture.check(committed: fault.committed, journal: journal) + #expect(try !FileTransaction.recover(store: fixture.store)) + try fixture.expectClean() + } + + /// An observed `restoring` journal may still lack its directory barrier. Resumed undo syncs + /// it before it grants directory write access or reverses any rename. + @Test func resumedUndoSyncsTheObservedJournalFirst() throws { + let fixture = try PublicationFixture(.directoryReplace) + terminateProcess( + try fixture.pause("publication", at: TransactionCheckpoint.progress(1, .applied).name)) + terminateProcess( + try fixture.pause( + "publication-recover", + at: TransactionCheckpoint.persisted(.applying, .entry(1, .restoring), .renamed).name)) + #expect(try fixture.lastJournal()?.entries[1].progress == .restoring) + let recovery = try fixture.launch("publication-recover", at: "never") + defer { terminateProcess(recovery) } + try ProcessWait.exit(recovery, root: fixture.root) + let trace = try fixture.trace(recovery) + #expect(trace.first == TransactionCheckpoint.journalSynced.name) + let grant = try #require( + trace.firstIndex( + of: TransactionCheckpoint.permissions(1, .undoGrant, .target, .changed).name)) + let undo = try #require( + trace.firstIndex(of: TransactionCheckpoint.restoration(1, .exchanged).name)) + #expect(grant < undo) + #expect(try fixture.result("recovery-result") == "recovered") + try fixture.check(committed: false, journal: nil) + try fixture.expectClean() + } + + /// A preparation that becomes stale before its entry publishes cancels from `ready`: + /// nothing is leased or moved, the journal is removed and the scope stays writable. + @Test(arguments: [PublicationOperation.directoryDelete, .directoryReplace]) + func stalePreparationBeforePublicationCancelsWithoutConflict(_ operation: PublicationOperation) + throws + { + let fixture = try PublicationFixture(operation) + let child = try fixture.pause( + "publication", at: TransactionCheckpoint.progress(0, .applied).name) + defer { terminateProcess(child) } + let original = fixture.root.appendingPathComponent("moved-original") + if operation == .directoryDelete { + try Data("external edit".utf8).write(to: fixture.target.appendingPathComponent("file")) + } else { + try FileManager.default.moveItem(at: fixture.target, to: original) + try FileManager.default.createDirectory( + at: fixture.target, withIntermediateDirectories: false) + try Data("external replacement".utf8).write( + to: fixture.target.appendingPathComponent("file")) + try FileManager.default.setAttributes( + [.posixPermissions: 0o555], ofItemAtPath: fixture.target.path) + } + let external = try FileSnapshot.read(at: fixture.target) + try fixture.resume(child) + let trace = try fixture.trace(child) + #expect(!trace.contains(TransactionCheckpoint.progress(1, .publishing).name)) + #expect(trace.contains("recovery." + TransactionCheckpoint.progress(1, .cancelled).name)) + let result = try fixture.result("publication-result") + #expect(result.hasPrefix("unchanged\n")) + #expect(result.contains("preparation is stale; prepare again")) + #expect(try FileSnapshot.read(at: fixture.target) == external) + if operation == .directoryReplace { + #expect(try FileSnapshot.read(at: original) == fixture.beforeTarget) + } + #expect(try FileSnapshot.read(at: fixture.auxiliary) == fixture.beforeAuxiliary) + try fixture.expectClean() + try fixture.store.withLock {} + } + + @Test func disposalConflictNamesTheChangedContainer() throws { + let fixture = try PublicationFixture(.crossParentReplace) + let child = try fixture.pause("publication", at: TransactionCheckpoint.phase(.committed).name) + defer { terminateProcess(child) } + let journal = try #require(try fixture.lastJournal()) + #expect(journal.containers.map(\.entry) == [0, 1]) + let foreign = fixture.container(1, journal: journal).appendingPathComponent("foreign") + try Data("external".utf8).write(to: foreign) + terminateProcess(child) + try fixture.expectUnresolved(containing: "terminal disposal evidence changed") + let recorded = try #require(try fixture.lastJournal()) + #expect(recorded.entries[0].conflict == nil) + let entry = recorded.entries[1] + let root = try #require(entry.path.split(separator: "/").first) + #expect(entry.conflict?.locations == [entry.path, root + "/" + recorded.containerName(1)]) + #expect(try Data(contentsOf: foreign) == Data("external".utf8)) + } + + @Test(arguments: ["external", "postimage"]) + func concurrentCreatorKeepsItsBytesAndInode(_ bytes: String) throws { + let fixture = try PublicationFixture(.fileCreate) + let child = try fixture.pause( + "publication", at: TransactionCheckpoint.publication(1, .validated).name) + defer { terminateProcess(child) } + try Data(bytes.utf8).write(to: fixture.target) + let external = try FileSnapshot.read(at: fixture.target) + try fixture.resume(child) + #expect(try fixture.result("publication-result").hasPrefix("unchanged\n")) + #expect(try FileSnapshot.read(at: fixture.target) == external) + #expect(try FileSnapshot.read(at: fixture.auxiliary) == fixture.beforeAuxiliary) + try fixture.expectClean() + } + + @Test(arguments: [false, true]) + func changedPreimageBeforeExchangeKeepsExternalBytesAndInode(_ inPlace: Bool) throws { + let fixture = try PublicationFixture(.fileReplace) + let child = try fixture.pause( + "publication", at: TransactionCheckpoint.publication(1, .validated).name) + defer { terminateProcess(child) } + if !inPlace { + try FileManager.default.moveItem( + at: fixture.target, to: fixture.root.appendingPathComponent("original")) + } + try Data("external preimage".utf8).write(to: fixture.target) + let external = try FileSnapshot.read(at: fixture.target) + try fixture.resume(child) + #expect(try fixture.result("publication-result").hasPrefix("unchanged\n")) + #expect(try FileSnapshot.read(at: fixture.target) == external) + #expect(try FileSnapshot.read(at: fixture.auxiliary) == fixture.beforeAuxiliary) + if !inPlace { + #expect( + try FileSnapshot.read(at: fixture.root.appendingPathComponent("original")) + == fixture.beforeTarget) + } + try fixture.expectClean() + } + + @Test(arguments: [false, true]) + func exchangedUnexpectedPreimageIsNeverDiscarded(_ inPlace: Bool) throws { + let fixture = try PublicationFixture(.fileReplace) + let child = try fixture.pause( + "publication", at: TransactionCheckpoint.publication(1, .exchanged).name) + defer { terminateProcess(child) } + let journal = try #require(try fixture.lastJournal()) + let exchanged = fixture.slot(.exchanged, entry: 1, journal: journal) + if !inPlace { + try FileManager.default.moveItem( + at: exchanged, to: fixture.root.appendingPathComponent("original")) + } + try Data("external preimage".utf8).write(to: exchanged) + let external = try FileSnapshot.read(at: exchanged) + terminateProcess(child) + let postimage = try #require(journal.entries[1].staged) + #expect(try FileSnapshot.read(at: fixture.target) == postimage) + #expect( + try FileSnapshot.read(at: fixture.slot(.exchanged, entry: 1, journal: journal)) == external + ) + try fixture.expectUnresolved() + #expect(try FileSnapshot.read(at: fixture.target) == postimage) + #expect( + try FileSnapshot.read(at: fixture.slot(.exchanged, entry: 1, journal: journal)) == external + ) + if !inPlace { + #expect( + try FileSnapshot.read(at: fixture.root.appendingPathComponent("original")) + == fixture.beforeTarget) + } + } + + @Test(arguments: [PublicationOperation.fileReplace, .directoryDelete]) + func missingAppliedPreimageIsUnresolvedBeforeTerminalIntent(_ operation: PublicationOperation) + throws + { + let fixture = try PublicationFixture(operation) + let child = try fixture.pause( + "publication", at: TransactionCheckpoint.progress(1, .applied).name) + defer { terminateProcess(child) } + let journal = try #require(try fixture.lastJournal()) + let slot: TransactionSlot = operation == .directoryDelete ? .deleted : .exchanged + let original = fixture.slot(slot, entry: 1, journal: journal) + let saved = fixture.root.appendingPathComponent("saved-preimage") + let lease = try #require(fixture.beforeTarget).writeLease + if let lease { + try FileManager.default.setAttributes( + [.posixPermissions: lease.grantedMode], ofItemAtPath: original.path) + } + try FileManager.default.moveItem(at: original, to: saved) + if let lease { + try FileManager.default.setAttributes( + [.posixPermissions: lease.originalMode], ofItemAtPath: saved.path) + } + let published = try FileSnapshot.read(at: fixture.target) + terminateProcess(child) + try fixture.expectUnresolved() + #expect(try FileSnapshot.read(at: fixture.target) == published) + #expect(try FileSnapshot.read(at: saved) == fixture.beforeTarget) + #expect(try fixture.lastJournal()?.phase == .applying) + } + + @Test func missingWithdrawnObjectIsUnresolvedBeforeDisposalIntent() throws { + let fixture = try PublicationFixture(.fileCreate) + terminateProcess( + try fixture.pause("publication", at: TransactionCheckpoint.publication(1, .created).name)) + let recovery = try fixture.pause( + "publication-recover", at: TransactionCheckpoint.progress(1, .restored).name) + defer { terminateProcess(recovery) } + let journal = try #require(try fixture.lastJournal()) + let withdrawn = fixture.slot(.withdrawn, entry: 1, journal: journal) + let saved = fixture.root.appendingPathComponent("saved-postimage") + try FileManager.default.moveItem(at: withdrawn, to: saved) + terminateProcess(recovery) + try fixture.expectUnresolved() + #expect(try FileSnapshot.read(at: fixture.target) == nil) + #expect(try FileSnapshot.read(at: saved) == journal.entries[1].staged) + } + + @Test(arguments: [PublicationOperation.fileCreate, .fileReplace, .directoryDelete]) + func externalRecoveryDestinationPreservesBothVersions(_ operation: PublicationOperation) throws { + let fixture = try PublicationFixture(operation) + terminateProcess( + try fixture.pause("publication", at: TransactionCheckpoint.progress(1, .applied).name)) + let recovery = try fixture.pause( + "publication-recover", at: TransactionCheckpoint.restoration(1, .validated).name) + defer { terminateProcess(recovery) } + let journal = try #require(try fixture.lastJournal()) + if try FileSnapshot.read(at: fixture.target) != nil { + try FileManager.default.moveItem( + at: fixture.target, to: fixture.root.appendingPathComponent("saved-postimage")) + } + try Data("external recovery writer".utf8).write(to: fixture.target) + let external = try FileSnapshot.read(at: fixture.target) + try fixture.resume(recovery, marker: "recovery-ready") + #expect(try fixture.result("recovery-result").hasPrefix("unresolved:")) + let location: URL + switch operation { + case .fileCreate: location = fixture.slot(.withdrawn, entry: 1, journal: journal) + case .fileReplace: location = fixture.slot(.exchanged, entry: 1, journal: journal) + default: location = fixture.target + } + #expect(try FileSnapshot.read(at: location) == external) + if operation == .fileReplace { + #expect(try FileSnapshot.read(at: fixture.target) == fixture.beforeTarget) + } + try fixture.expectUnresolved() + #expect(try FileSnapshot.read(at: location) == external) + if operation == .directoryDelete { + #expect( + try FileSnapshot.read(at: fixture.slot(.deleted, entry: 1, journal: journal)) + == fixture.beforeTarget) + } else { + #expect( + try FileSnapshot.read(at: fixture.root.appendingPathComponent("saved-postimage")) + == journal.entries[1].staged) + } + } + + @Test func committedFailureRetainsUserDataAndRecordsConflict() throws { + let fixture = try PublicationFixture(.fileReplace) + let child = try fixture.pause("publication", at: TransactionCheckpoint.phase(.committed).name) + defer { terminateProcess(child) } + let journal = try #require(try fixture.lastJournal()) + let saved = fixture.root.appendingPathComponent("saved-published") + try FileManager.default.moveItem(at: fixture.target, to: saved) + try Data("external committed target".utf8).write(to: fixture.target) + let external = try FileSnapshot.read(at: fixture.target) + terminateProcess(child) + try fixture.expectUnresolved() + #expect(try FileSnapshot.read(at: fixture.target) == external) + #expect(try FileSnapshot.read(at: saved) == journal.entries[1].staged) + #expect( + try FileSnapshot.read(at: fixture.slot(.exchanged, entry: 1, journal: journal)) + == fixture.beforeTarget) + } + + @Test(arguments: [false, true]) + func plannedUnidentifiedContainerOnlyAdmitsEmptyRmdir(_ populate: Bool) throws { + let fixture = try PublicationFixture(.fileCreate) + terminateProcess( + try fixture.pause("publication", at: TransactionCheckpoint.containerCreated(0).name)) + let journal = try #require(try fixture.lastJournal()) + #expect(journal.containers[0].identity == nil) + let container = fixture.container(0, journal: journal) + if populate { + let file = container.appendingPathComponent("keep") + try Data("unidentified bytes".utf8).write(to: file) + let before = try FileSnapshot.read(at: file) + try fixture.expectUnresolved(containing: "unidentified private container is not empty") + #expect(try FileSnapshot.read(at: file) == before) + } else { + try fixture.recover(expected: .unchanged) + try fixture.expectClean() + } + #expect(try FileSnapshot.read(at: fixture.target) == fixture.beforeTarget) + } + + @Test func sealedPrivateObjectChangesAreUnresolved() throws { + let fixture = try PublicationFixture(.fileReplace) + terminateProcess( + try fixture.pause("publication", at: TransactionCheckpoint.progress(1, .ready).name)) + let journal = try #require(try fixture.lastJournal()) + let file = fixture.slot(.exchanged, entry: 1, journal: journal) + try Data("changed after sealing".utf8).write(to: file) + let changed = try FileSnapshot.read(at: file) + try fixture.expectUnresolved() + #expect(try FileSnapshot.read(at: file) == changed) + #expect(try FileSnapshot.read(at: fixture.target) == fixture.beforeTarget) + } + + @Test func directoryPermissionChangesOutsideIntentRemainExternal() throws { + let fixture = try PublicationFixture(.directoryReplace) + let child = try fixture.pause( + "publication", + at: TransactionCheckpoint.permissions(1, .publicationGrant, .target, .synced).name) + defer { terminateProcess(child) } + try FileManager.default.setAttributes( + [.posixPermissions: 0o770], ofItemAtPath: fixture.target.path) + let external = try FileSnapshot.read(at: fixture.target) + terminateProcess(child) + let beforeDiagnosis = try FileSnapshot.read(at: fixture.root) + let diagnosis = FileTransaction.recoveryDiagnostic(store: fixture.store) + #expect(diagnosis.requiresOwner) + #expect(diagnosis.message.contains("directory permissions changed beyond transaction intent")) + #expect(try FileSnapshot.read(at: fixture.root) == beforeDiagnosis) + try fixture.expectUnresolved( + containing: "directory permissions changed beyond transaction intent") + #expect(try FileSnapshot.read(at: fixture.target) == external) + } + + @Test( + arguments: [EINVAL, ENOSYS, ENOTSUP, EOPNOTSUPP, EIO], + [DirectoryHandle.RenameMode.exchange, .exclusive]) + func primitiveFailuresCleanPrivateResourcesBeforeChangingUserData( + _ code: Int32, _ mode: DirectoryHandle.RenameMode + ) throws { + let fixture = try PublicationFixture(.fileReplace) + let outcome = TransactionOutcome() + let transaction = FileTransaction(store: fixture.store, outcome: outcome) + try transaction.replace(fixture.target, with: .data(Data("postimage".utf8))) + let operation = + mode == .exchange ? "exchange atomic probe" : "check exclusive atomic probe collision" + let expected: CoreError = + code == EIO + ? .invalidState("cannot \(operation): \(code) (\(String(cString: strerror(code))))") + : .unsupported( + "atomic rename is required: \(operation): \(code) (\(String(cString: strerror(code))))") + DirectoryHandle.$atomicRenameFailure.withValue( + DirectoryHandle.AtomicRenameFailure(mode: mode, code: code), + operation: { #expect(throws: expected) { try transaction.commit() } }) + #expect(outcome.disposition == .unchanged) + try fixture.check(committed: false, journal: nil) + try fixture.expectClean() + } + + @Test(arguments: ["staged", "parent", "container"]) + func missingJournalEvidenceReachesSemanticValidation(_ field: String) throws { + let fixture = try PublicationFixture(.fileReplace) + terminateProcess( + try fixture.pause("publication", at: TransactionCheckpoint.progress(1, .ready).name)) + var journal = try #require(try fixture.lastJournal()) + switch field { + case "staged": journal.entries[1].staged = nil + case "parent": journal.entries[1].parentIdentity = "" + default: journal.entries[1].container = journal.containers.count + } + // Encode a valid current-format value; failure cannot be a missing Decodable key. + try StateStore.encode(journal).write( + to: fixture.store.directory.appendingPathComponent("transaction.json")) + let before = try FileSnapshot.read(at: fixture.root) + let reason: String + switch field { + case "staged": reason = "operation progress contradicts its evidence or journal phase" + case "parent": reason = "destination parent changed" + default: reason = "overlapping destinations or invalid container" + } + let location = + field == "container" + ? "" + : "instructions-project/" + journal.containerName(0) + #expect( + throws: CoreError.invalidState( + "transaction conflict at instructions-project/AGENTS.md: \(reason); retained container: \(location)" + ) + ) { + try fixture.store.withLock {} + } + #expect(try FileSnapshot.read(at: fixture.root) == before) + } + + @Test(arguments: [Optional.none, .some(999)]) + func oldJournalVersionRequiresItsWritingVersionWithoutMutation(_ version: Int?) throws { + let fixture = try PublicationFixture(.fileReplace) + // This is the unversioned Journal/Entry schema and scratch naming written by ed859e6. + let id = UUID() + let directory = try #require(try fixture.store.openDirectoryIfPresent()) + let backup = directory.url.appendingPathComponent(".agents-\(id.uuidString)-0.old") + try FileManager.default.moveItem(at: fixture.store.declarationURL, to: backup) + try manifestText("defaultAgents: [\"codex\"]\n").write(to: fixture.store.declarationURL) + var old = try StateStore.encode( + LegacyJournal( + id: id, scope: directory.identity, + roots: ["state": directory.identity], phase: "applying", + entries: [ + .init(path: "state/" + StateStore.declarationFileName, existed: true, replacement: true) + ])) + if let version { + var encoded = try #require(JSONSerialization.jsonObject(with: old) as? [String: Any]) + encoded["version"] = version + old = try JSONSerialization.data(withJSONObject: encoded) + } + try old.write(to: directory.url.appendingPathComponent("transaction.json")) + let before = try FileSnapshot.read(at: fixture.root) + #expect( + throws: CoreError.invalidState( + "transaction journal was written by another version; recover it with the version that wrote it (journal version: \(version.map(String.init) ?? "missing"))" + ) + ) { + try fixture.store.withLock {} + } + #expect(try FileSnapshot.read(at: fixture.root) == before) + let diagnostic = FileTransaction.recoveryDiagnostic(store: fixture.store) + #expect(diagnostic.requiresOwner) + #expect(diagnostic.message.contains("version that wrote it")) + } + + @Test(arguments: ["identity", "disposal"]) + func missingContainerEvidenceCannotAuthorizeTerminalDeletion(_ field: String) throws { + let fixture = try PublicationFixture(.fileReplace) + terminateProcess( + try fixture.pause("publication", at: TransactionCheckpoint.phase(.committed).name)) + var journal = try #require(try fixture.lastJournal()) + if field == "identity" { + journal.containers[0].identity = nil + } else { + journal.containers[0].disposal = nil + } + try StateStore.encode(journal).write( + to: fixture.store.directory.appendingPathComponent("transaction.json")) + let before = try FileSnapshot.read(at: fixture.root) + #expect( + throws: CoreError.invalidState( + field == "identity" + ? "sealed operation is missing private container identity" + : "terminal container is missing user-object disposal evidence") + ) { try fixture.store.withLock {} } + #expect(try FileSnapshot.read(at: fixture.root) == before) + } + + @Test func unchangedStateIsNotAnImplicitCachePrecondition() throws { + let fixture = try PublicationFixture(.fileCreate) + let cache = SourceCache(store: fixture.store) + let bytes = Data("artifact".utf8) + let digest = "sha256:" + FileHash.sha256Hex(data: Data("artifact".utf8)) + let transaction = FileTransaction(store: fixture.store) + let target = try cache.artifactURL(digest: digest) + try transaction.replace(target, with: .data(bytes), expectedHash: digest) + try manifestText("defaultAgents: []").write(to: fixture.store.declarationURL) + let state = try FileSnapshot.read(at: fixture.store.declarationURL) + try transaction.commit() + #expect(try Data(contentsOf: target) == bytes) + #expect(try FileSnapshot.read(at: fixture.store.declarationURL) == state) + } +} + +enum PublicationOperation: String, CaseIterable, Sendable { + case fileReplace, directoryReplace, directoryDelete, symlinkCreate, fileCreate + /// The target is in another parent than the auxiliary file, so two containers are used. + case crossParentReplace + + var renamePoint: String { + switch self { + case .directoryDelete: TransactionCheckpoint.publication(1, .deleted).name + case .fileReplace, .directoryReplace, .crossParentReplace: + TransactionCheckpoint.publication(1, .exchanged).name + case .symlinkCreate, .fileCreate: TransactionCheckpoint.publication(1, .created).name + } + } + + /// Undo of the target's publication rename. + var reverseRenamePoint: String { + switch self { + case .directoryDelete: TransactionCheckpoint.restoration(1, .returned).name + case .fileReplace, .directoryReplace, .crossParentReplace: + TransactionCheckpoint.restoration(1, .exchanged).name + case .symlinkCreate, .fileCreate: TransactionCheckpoint.restoration(1, .withdrawn).name + } + } + + var leasesDirectories: Bool { self == .directoryReplace || self == .directoryDelete } + + /// Recovery starts from construction, sealed staging, an interrupted rename or directory + /// grant, an applied entry, the committed marker and terminal disposal. + var recoverySeeds: [RecoverySeed] { + var seeds = [ + RecoverySeed(point: TransactionCheckpoint.stage(1, .constructed).name), + RecoverySeed(point: TransactionCheckpoint.progress(1, .ready).name), + RecoverySeed(point: renamePoint, renamed: true), + RecoverySeed(point: TransactionCheckpoint.progress(1, .applied).name, renamed: true), + RecoverySeed( + point: TransactionCheckpoint.persisted(.committed, .terminal, .renamed).name, + committed: true), + RecoverySeed(point: TransactionCheckpoint.disposalIntent.name, committed: true), + ] + if leasesDirectories { + seeds.append( + RecoverySeed( + point: TransactionCheckpoint.permissions(1, .publicationGrant, .target, .changed).name)) + } + return seeds + } + + /// Points every recovery from `seed` must reach. + func requiredRecoveryPoints(from seed: RecoverySeed) -> Set { + var points = [ + TransactionCheckpoint.journalSynced.name, TransactionCheckpoint.journalRemoved.name, + ] + if !seed.committed { + points.append(TransactionCheckpoint.persisted(.rolledBack, .terminal, .renamed).name) + } + if seed.renamed { points.append(reverseRenamePoint) } + return Set(points) + } +} + +/// A publication interruption that recovery starts from. +struct RecoverySeed: Sendable { + let point: String + var committed = false + /// The target's publication rename has happened, so rollback must reverse it. + var renamed = false +} + +struct PublicationFault: Sendable, CustomTestStringConvertible { + let operation: PublicationOperation + let point: String + var committed = false + var seed: String? + var setupFailure: String? + var testDescription: String { + "\(operation.rawValue), \(seed.map { "from \($0), " } ?? "")\(point)" + } + func checkSetup() throws { + if let setupFailure { + throw CoreError.invalidState("checkpoint recording failed: " + setupFailure) + } + } +} + +/// Kill-point matrices recorded from real traces. By default publication tests kill each +/// operation at representative points, and kill recovery at durable steps from each seeded +/// interruption; `AGENTS_PUBLICATION_MATRIX=full` kills at every recorded point. +private enum PublicationMatrix { + static let complete = ProcessInfo.processInfo.environment["AGENTS_PUBLICATION_MATRIX"] == "full" + static let publications = record(recovery: false) + static let recoveries = record(recovery: true) + + /// Every recovery seed, durable intent, the synced rename, the mode restoration and the + /// removal of the first container. + private static func representativePublication(_ operation: PublicationOperation) -> Set { + var points = + operation.recoverySeeds.map(\.point) + [ + TransactionCheckpoint.progress(1, .publishing).name, + TransactionCheckpoint.publication(1, .synced).name, + TransactionCheckpoint.containerRemoved(0).name, + ] + if operation.leasesDirectories { + // A deleted directory's mode is restored in its slot; a replacement's at the target. + let location: TransactionObjectLocation = + operation == .directoryDelete ? .slot(.deleted) : .target + points.append( + TransactionCheckpoint.permissions(1, .publicationRestore, location, .changed).name) + } + return Set(points) + } + + /// The observed-journal barrier, each durable recovery write, each reverse rename, undo + /// grant and mode restoration, and disposal. + private static let representativeRecovery: Set = { + var points: [TransactionCheckpoint] = [.journalSynced, .containerRemoved(0), .journalRemoved] + for phase in [TransactionJournal.Phase.applying, .committed, .rolledBack] { + points += [.persisted(phase, .terminal, .renamed), .persisted(phase, .disposing, .renamed)] + for index in 0...1 { + for progress in [TransactionJournal.Progress.restoring, .restored, .cancelled] { + points.append(.persisted(phase, .entry(index, progress), .renamed)) + } + } + } + for index in 0...1 { + points += [ + .restoration(index, .exchanged), .restoration(index, .returned), + .restoration(index, .withdrawn), .restoration(index, .synced), + .permissions(index, .undoGrant, .target, .changed), + .permissions(index, .undoRestore, .target, .changed), + .permissions(index, .cancelRestore, .target, .changed), + ] + } + return Set(points.map(\.name)) + }() + + private static func record(recovery: Bool) -> [PublicationFault] { + var cases: [PublicationFault] = [] + let commitMarker = TransactionCheckpoint.persisted(.committed, .terminal, .renamed).name + for operation in PublicationOperation.allCases { + let selected = recovery ? representativeRecovery : representativePublication(operation) + let seeds: [RecoverySeed?] = recovery ? operation.recoverySeeds.map { $0 } : [nil] + for seed in seeds { + do { + let fixture = try PublicationFixture(operation) + if let seed { terminateProcess(try fixture.pause("publication", at: seed.point)) } + let command = recovery ? "publication-recover" : "publication" + let child = try fixture.launch(command, at: "never") + defer { terminateProcess(child) } + try ProcessWait.exit(child, root: fixture.root) + guard child.terminationStatus == 0 else { + throw CoreError.invalidState("checkpoint recorder exited \(child.terminationStatus)") + } + let trace = try fixture.trace(child) + guard !trace.isEmpty, Set(trace).count == trace.count else { + throw CoreError.invalidState("checkpoint names are empty or repeated") + } + let required = seed.map(operation.requiredRecoveryPoints(from:)) ?? selected + if !required.isSubset(of: trace) { + throw CoreError.invalidState( + "representative points were not recorded: \(required.subtracting(trace).sorted())") + } + var committed = seed?.committed ?? false + for point in trace { + if point == commitMarker { committed = true } + guard complete || selected.contains(point) else { continue } + cases.append( + PublicationFault( + operation: operation, point: point, committed: committed, seed: seed?.point)) + } + } catch { + cases.append( + PublicationFault( + operation: operation, point: "recording", seed: seed?.point, + setupFailure: String(describing: error))) + } + } + } + return cases + } +} + +final class PublicationFixture { + let operation: PublicationOperation + let root: URL + let store: StateStore + let target: URL + let auxiliary: URL + let beforeTarget: FileSnapshot? + let beforeAuxiliary: FileSnapshot? + let state: [(URL, FileSnapshot?)] + + init(_ operation: PublicationOperation) throws { + self.operation = operation + root = try temporaryDirectory() + store = StateStore( + scope: .project, + environment: RuntimeEnvironment( + projectDirectory: root, homeDirectory: root.appendingPathComponent("home"), environment: [:] + )) + target = + operation == .crossParentReplace + ? root.appendingPathComponent(".agents/skills/target") + : root.appendingPathComponent("AGENTS.md") + auxiliary = root.appendingPathComponent("GEMINI.md") + do { + try store.save(declaration: Declaration(), resolved: ResolvedState()) + try Data("auxiliary preimage".utf8).write(to: auxiliary) + let source = root.appendingPathComponent("new") + try FileManager.default.createDirectory( + at: source.appendingPathComponent("nested"), withIntermediateDirectories: true) + try Data("tree postimage".utf8).write(to: source.appendingPathComponent("nested/file")) + try FileManager.default.createSymbolicLink( + atPath: source.appendingPathComponent("link").path, withDestinationPath: "nested/file") + if operation == .crossParentReplace { + try FileManager.default.createDirectory( + at: target.deletingLastPathComponent(), withIntermediateDirectories: true) + } + if operation == .fileReplace || operation == .crossParentReplace { + try Data("preimage".utf8).write(to: target) + } + if operation == .directoryReplace || operation == .directoryDelete { + try FileManager.default.createDirectory(at: target, withIntermediateDirectories: true) + try Data("tree preimage".utf8).write(to: target.appendingPathComponent("file")) + try FileManager.default.setAttributes([.posixPermissions: 0o555], ofItemAtPath: target.path) + } + if operation == .directoryReplace { + try FileManager.default.setAttributes([.posixPermissions: 0o555], ofItemAtPath: source.path) + } + beforeTarget = try FileSnapshot.read(at: target) + beforeAuxiliary = try FileSnapshot.read(at: auxiliary) + state = try [store.declarationURL, store.resolvedURL, store.watchURL].map { + ($0, try FileSnapshot.read(at: $0)) + } + } catch { + makeDirectoriesWritable(root) + removeTemporaryDirectory(root) + throw error + } + } + deinit { + makeDirectoriesWritable(root) + removeTemporaryDirectory(root) + } + + func launch(_ command: String, at point: String) throws -> Process { + try stateTestProcess(root: root, arguments: [command, point, operation.rawValue]) + } + + func pause(_ command: String, at point: String) throws -> Process { + let marker = root.appendingPathComponent(command == "publication" ? "ready" : "recovery-ready") + try? FileManager.default.removeItem(at: marker) + try? FileManager.default.removeItem(at: root.appendingPathComponent("stop-at")) + let child = try launch(command, at: point) + do { + try ProcessWait.marker(marker, child: child, root: root) + try ProcessWait.stopped(child, root: root) + return child + } catch { + terminateProcess(child) + throw error + } + } + + /// The child was confirmed stopped by `pause` or `restop`, so SIGCONT cannot be lost. + func resume(_ child: Process, marker: String = "ready") throws { + try? FileManager.default.removeItem(at: root.appendingPathComponent(marker)) + kill(child.processIdentifier, SIGCONT) + try ProcessWait.exit(child, root: root) + #expect(child.terminationStatus == 0) + } + + func restop(_ child: Process, at point: String) throws { + let marker = root.appendingPathComponent("ready") + try? FileManager.default.removeItem(at: marker) + try Data(point.utf8).write(to: root.appendingPathComponent("stop-at")) + kill(child.processIdentifier, SIGCONT) + try ProcessWait.marker(marker, child: child, root: root) + try ProcessWait.stopped(child, root: root) + } + + func trace(_ child: Process) throws -> [String] { + try String( + contentsOf: root.appendingPathComponent("checkpoint-\(child.processIdentifier).log"), + encoding: .utf8 + ).split(separator: "\n").map(String.init) + } + + func result(_ name: String) throws -> String { + try String(contentsOf: root.appendingPathComponent(name), encoding: .utf8) + } + + func lastJournal() throws -> TransactionJournal? { + for url in [ + store.directory.appendingPathComponent("transaction.json"), + store.directory.appendingPathComponent("transaction.new"), + root.appendingPathComponent("last-journal"), + ] { + if FileManager.default.fileExists(atPath: url.path) { + return try StateStore.decode(Data(contentsOf: url), as: TransactionJournal.self) + } + } + return nil + } + + func container(_ index: Int, journal: TransactionJournal) -> URL { + (journal.containers[index].entry == 0 ? auxiliary : target).deletingLastPathComponent() + .appendingPathComponent(journal.containerName(index)) + } + + func slot(_ slot: TransactionSlot, entry index: Int, journal: TransactionJournal) -> URL { + container(journal.entries[index].container, journal: journal) + .appendingPathComponent(slot.name(index)) + } + + /// After an interrupted recovery, a journal already removed has no outcome left to report. + func recover(expected: TransactionOutcome.Disposition, afterRecovery: Bool = false) throws { + let outcome = TransactionOutcome() + outcome.journalID = try lastJournal()?.id + let directory = try #require(try store.openDirectoryIfPresent()) + let pending = + try directory.info("transaction.json") != nil || directory.info("transaction.new") != nil + if pending { + #expect(throws: CoreError.transactionRecovered(store.directory.path)) { + try store.withLock(outcome: outcome, {}) + } + #expect(outcome.disposition == expected) + } else { + try store.withLock(outcome: outcome, {}) + if expected == .committed, !afterRecovery { + #expect(try result("stopped-outcome") == "committed") + } + } + } + + func expectUnresolved( + containing expected: String = + "missing or changed expected target or recovery slot object" + ) throws { + let outcome = TransactionOutcome() + outcome.journalID = try lastJournal()?.id + #expect { try store.withLock(outcome: outcome, {}) } throws: { error in + guard case CoreError.invalidState(let reason) = error else { return false } + return reason.contains(expected) + } + let terminal = try #require(try lastJournal()).phase + #expect(outcome.recoveryPending) + if terminal == .committed { + #expect(outcome.disposition == .committed && outcome.terminal == .committed) + } else if terminal == .rolledBack { + #expect(outcome.disposition == .unchanged && outcome.terminal == .rolledBack) + } else { + #expect(outcome.disposition == .recoveryRequired && outcome.terminal == nil) + } + let diagnostic = FileTransaction.recoveryDiagnostic(store: store) + #expect(diagnostic.requiresOwner) + #expect(diagnostic.message.contains("owner action")) + let journal = try #require(try lastJournal()) + let conflicts = journal.entries.compactMap(\.conflict) + #expect(conflicts.contains { $0.reason.contains(expected) && !$0.locations.isEmpty }) + #expect(try store.openDirectoryIfPresent()?.info("transaction.json") != nil) + #expect( + try FileSnapshot.read(at: auxiliary) + == (journal.phase == .committed ? journal.entries[0].staged : beforeAuxiliary)) + for (url, before) in state { #expect(try FileSnapshot.read(at: url) == before) } + } + + func check(committed: Bool, journal: TransactionJournal?) throws { + #expect( + try FileSnapshot.read(at: target) == (committed ? journal?.entries[1].staged : beforeTarget)) + #expect( + try FileSnapshot.read(at: auxiliary) + == (committed ? journal?.entries[0].staged : beforeAuxiliary)) + for (url, before) in state { #expect(try FileSnapshot.read(at: url) == before) } + } + + func expectClean() throws { + #expect(try store.openDirectoryIfPresent()?.info("transaction.json") == nil) + #expect(try store.openDirectoryIfPresent()?.info("transaction.new") == nil) + for parent in Set([auxiliary, target].map { $0.deletingLastPathComponent().path }) { + #expect( + try !FileManager.default.contentsOfDirectory(atPath: parent).contains { + $0.hasPrefix(".agents-") + }) + } + } +} + +private struct LegacyJournal: Encodable { + let id: UUID + let scope: String + let roots: [String: String] + let phase: String + let entries: [Entry] + struct Entry: Encodable { + let path: String + let existed: Bool + let replacement: Bool + } +} diff --git a/Tests/AgentsCoreTests/ReadDependencyTests.swift b/Tests/AgentsCoreTests/ReadDependencyTests.swift new file mode 100644 index 0000000..97e0209 --- /dev/null +++ b/Tests/AgentsCoreTests/ReadDependencyTests.swift @@ -0,0 +1,21 @@ +import AgentsCore +import Foundation +import Testing + +struct ReadDependencyTests { + @Test func codableRetainsEntryAndSubtreeAtTheSameURL() throws { + let url = URL(fileURLWithPath: "/scope/absent") + let values: [ReadDependency] = [.entry(url), .subtree(url)] + #expect(Set(values).count == 2) + #expect(values.map(\.url) == [url, url]) + let bytes = try JSONEncoder().encode(values) + #expect(try JSONDecoder().decode([ReadDependency].self, from: bytes) == values) + let expected = Data( + "[{\"entry\":{\"_0\":\"file:///scope/absent\"}},{\"subtree\":{\"_0\":\"file:///scope/absent\"}}]" + .utf8) + #expect(try JSONDecoder().decode([ReadDependency].self, from: expected) == values) + #expect( + try JSONSerialization.jsonObject(with: bytes) as? NSArray == JSONSerialization.jsonObject( + with: expected) as? NSArray) + } +} diff --git a/Tests/AgentsCoreTests/RegisteredNativeTargetTests.swift b/Tests/AgentsCoreTests/RegisteredNativeTargetTests.swift new file mode 100644 index 0000000..98a67c4 --- /dev/null +++ b/Tests/AgentsCoreTests/RegisteredNativeTargetTests.swift @@ -0,0 +1,1055 @@ +import CPlatform +import Foundation +import StateTestSupport +import Testing + +@testable import AgentsCore + +@Suite("Registered native MCP files") +struct RegisteredNativeTargetTests { + @Test func absentSharedRootPreviewIsPureAndApplyCreatesPrivateObjects() throws { + let fixture = try NativeRouteFixture() + var environment = fixture.store.environment + let missing = fixture.root.appendingPathComponent("fresh/nested") + environment.environment["CLAUDE_CONFIG_DIR"] = missing.path + let store = StateStore(scope: .project, environment: environment) + let before = try FileSnapshot.read(at: fixture.root) + try store.withReadLock(footprint: [.claudeMCPLocal, .codexMCPUser]) { + let target = try store.nativeTarget(for: .claudeMCPLocal) + #expect(target.url == missing.appendingPathComponent(".claude.json")) + #expect(try store.materializationReceipt(for: target) == nil) + let prepared = try store.preparePrivateMaterialization(target) + #expect(prepared.receiptGeneration == nil && prepared.beforeAccess == nil) + #expect(throws: CoreError.self) { + let transaction = FileTransaction(store: store) + try transaction.replacePrivate(prepared, provider: NativeRouteBindings()) { _ in Data() } + } + } + #expect(try FileSnapshot.read(at: fixture.root) == before) + try store.withLock(footprint: [.claudeMCPLocal]) { + let target = try store.nativeTarget(for: .claudeMCPLocal) + let transaction = FileTransaction(store: store) + try transaction.replacePrivate( + store.preparePrivateMaterialization(target), provider: NativeRouteBindings() + ) { _ in Data("private fixture".utf8) } + try transaction.commit() + #expect(try store.materializationReceipt(for: target) != nil) + _ = try DirectoryHandle(at: missing).requirePrivateAccess(".claude.json") + } + } + + @Test func absentRootAppearanceReadmitsWithoutInventingAMetadataIdentity() throws { + let fixture = try NativeRouteFixture() + var environment = fixture.store.environment + let root = fixture.root.appendingPathComponent("fresh") + environment.environment["CLAUDE_CONFIG_DIR"] = root.path + let store = StateStore(scope: .project, environment: environment) + let bytes = try store.withReadLock(footprint: [.claudeMCPLocal]) { + let target = try store.nativeTarget(for: .claudeMCPLocal) + if !FileManager.default.fileExists(atPath: root.path) { + // An external native writer does not participate in Core coordination. + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + try Data("external generation".utf8).write(to: target.url) + return Data("stale absence".utf8) + } + return try Data(contentsOf: target.url) + } + #expect(bytes == Data("external generation".utf8)) + #expect( + !FileManager.default.fileExists(atPath: root.appendingPathComponent(".agents-native").path)) + #expect(!FileManager.default.fileExists(atPath: store.directory.path)) + } + + @Test(arguments: ["alias", "ancestor"]) + func absentRootInspectionRefusesRedirectedAuthority(_ change: String) throws { + let fixture = try NativeRouteFixture() + let parent = fixture.root.appendingPathComponent("authority") + let other = fixture.root.appendingPathComponent("unrelated") + for path in [parent, other] { + try FileManager.default.createDirectory(at: path, withIntermediateDirectories: true) + } + var environment = fixture.store.environment + let root = parent.appendingPathComponent("fresh") + environment.environment["CLAUDE_CONFIG_DIR"] = root.path + let store = StateStore(scope: .project, environment: environment) + #expect(throws: CoreError.self) { + try store.withReadLock(footprint: [.claudeMCPLocal]) { + _ = try store.nativeTarget(for: .claudeMCPLocal) + if change == "alias" { + try FileManager.default.createSymbolicLink(at: root, withDestinationURL: other) + } else { + try FileManager.default.moveItem(at: parent, to: parent.appendingPathExtension("old")) + try FileManager.default.createDirectory(at: parent, withIntermediateDirectories: true) + } + } + } + #expect(try DirectoryHandle(at: other).names().isEmpty) + #expect(!FileManager.default.fileExists(atPath: store.directory.path)) + } + + @Test(arguments: [false, true], [AgentID.codex, .cursor]) + func legacyInstallationSpellingRequiresItsExactCommittedRecipient( + _ rollback: Bool, _ agent: AgentID + ) throws { + let fixture = try NativeRouteFixture() + let store = fixture.store + let parent = AgentRegistry.installSkillsDirectory( + for: agent, scope: .project, environment: store.environment) + try FileManager.default.createDirectory(at: parent, withIntermediateDirectories: true) + let legacy = parent.appendingPathComponent("Example Skill") + try Data("old".utf8).write(to: legacy) + let ledger = try fixture.recordSkill(name: "Example Skill", agent: agent) + let transaction = FileTransaction(store: store) { point in + if point == "entry.0.applied" { + let journal = try NativeRouteFixture.journal(in: store) + #expect(journal.entries.first?.path == agent.rawValue + "/Example Skill") + } + if rollback && point == "entry.1.applied" { throw CoreError.invalidState("fixture rollback") } + } + try transaction.replace(legacy, with: .data(Data("next".utf8))) + #expect(throws: CoreError.self) { + try transaction.replace( + parent.appendingPathComponent("Unrecorded Skill"), with: .data(Data())) + } + let other = AgentRegistry.installSkillsDirectory( + for: .claudeCode, scope: .project, environment: store.environment) + #expect(throws: CoreError.self) { + try transaction.replace(other.appendingPathComponent("Example Skill"), with: .data(Data())) + } + let outside = fixture.root.appendingPathComponent("outside") + try FileManager.default.createDirectory(at: outside, withIntermediateDirectories: true) + let alias = parent.appendingPathComponent("Traversal Skill") + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: outside) + #expect(throws: CoreError.self) { + try transaction.replace(alias.appendingPathComponent("child"), with: .data(Data())) + } + #expect(try DirectoryHandle(at: outside).names().isEmpty) + for path in ["codex/..", "codex/.", "codex/a/b", "codex/a\\b"] { + #expect(throws: CoreError.self) { try TransactionPaths(store: store).components(path) } + } + try transaction.replace( + store.resolvedURL, + with: .data(ResolvedLedgerCodec.encode(ResolvedLedger(), limits: .standard))) + if rollback { + #expect(throws: CoreError.self) { try transaction.commit() } + #expect( + try ResolvedLedgerCodec.decode(Data(contentsOf: store.resolvedURL), limits: .standard) + == ledger) + } else { + try transaction.commit() + } + #expect(try Data(contentsOf: legacy) == Data((rollback ? "old" : "next").utf8)) + #expect( + !FileManager.default.fileExists(atPath: parent.appendingPathComponent("example-skill").path)) + } + + #if os(Linux) + @Test func distinctUnicodeFilenamesKeepSeparateInstallationAuthority() throws { + let fixture = try NativeRouteFixture() + let recorded = "\u{00E9} Skill" + let alternate = "e\u{0301} Skill" + try fixture.recordSkill(name: recorded, agent: .codex) + let parent = AgentRegistry.installSkillsDirectory( + for: .codex, scope: .project, environment: fixture.store.environment) + try FileManager.default.createDirectory(at: parent, withIntermediateDirectories: true) + let authorized = parent.appendingPathComponent(recorded) + let unrecorded = parent.appendingPathComponent(alternate) + let recordedBytes = Data("old".utf8) + let alternateBytes = Data("unrecorded before".utf8) + let directory = try DirectoryHandle(at: parent) + try directory.write(recorded, data: recordedBytes) + try directory.write(alternate, data: alternateBytes) + try #require(authorized.lastPathComponent.utf8.elementsEqual(recorded.utf8)) + try #require(unrecorded.lastPathComponent.utf8.elementsEqual(alternate.utf8)) + let first = FileObjectIdentity(try #require(try directory.info(recorded))) + let second = FileObjectIdentity(try #require(try directory.info(alternate))) + try #require(first != second) + let names = try directory.names() + try #require(names.contains(where: { $0.utf8.elementsEqual(recorded.utf8) })) + try #require(names.contains(where: { $0.utf8.elementsEqual(alternate.utf8) })) + let refused = FileTransaction(store: fixture.store) + #expect(throws: CoreError.self) { try refused.delete(unrecorded) } + #expect(throws: CoreError.self) { + try refused.replace(unrecorded, with: .data(Data("unauthorized".utf8))) + } + #expect(try directory.info(recorded).map(FileObjectIdentity.init) == first) + #expect(try directory.info(alternate).map(FileObjectIdentity.init) == second) + #expect(try Data(contentsOf: authorized) == recordedBytes) + #expect(try Data(contentsOf: unrecorded) == alternateBytes) + let allowed = FileTransaction(store: fixture.store) + try allowed.replace(authorized, with: .data(Data("recorded after".utf8))) + try allowed.commit() + #expect(try Data(contentsOf: authorized) == Data("recorded after".utf8)) + #expect(try Data(contentsOf: unrecorded) == alternateBytes) + #expect(try directory.info(alternate).map(FileObjectIdentity.init) == second) + #expect(try directory.info(recorded).map(FileObjectIdentity.init) != second) + } + #endif + + @Test(arguments: NativeTargetRoute.mcpRoutes) + func registeredFilesPublishPrivatelyAndRetainTheirReceipt(_ route: NativeTargetRoute) throws { + let fixture = try NativeRouteFixture() + let expected: [NativeTargetRoute: String] = [ + .claudeMCPProject: ".mcp.json", .claudeMCPLocal: "configured/.claude.json", + .claudeMCPUser: "configured/.claude.json", .codexMCPProject: ".codex/config.toml", + .codexMCPUser: "configured/config.toml", .geminiMCPProject: ".gemini/settings.json", + .geminiMCPUser: "configured/.gemini/settings.json", .cursorMCPProject: ".cursor/mcp.json", + .cursorMCPUser: "home/.cursor/mcp.json", .openCodeMCPProjectJSON: "opencode.json", + .openCodeMCPProjectJSONC: "opencode.jsonc", .openCodeMCPUserJSON: "configured/opencode.json", + .openCodeMCPUserJSONC: "configured/opencode.jsonc", + .antigravityMCPProject: ".agents/mcp_config.json", + .antigravityMCPUser: "home/.gemini/config/mcp_config.json", + ] + let store = StateStore( + scope: route.shared ? .user : .project, environment: fixture.store.environment) + var privateBeforeWrite = false + try store.withLock(footprint: [route]) { + let target = try store.nativeTarget(for: route) + #expect(target.url == fixture.root.appendingPathComponent(try #require(expected[route]))) + let transaction = FileTransaction(store: store) { point in + if point == "stage.0.writeCreated" { + let journal = try NativeRouteFixture.journal(in: store) + let container = try DirectoryHandle( + at: target.url.deletingLastPathComponent().appendingPathComponent( + journal.containers[0].name)) + _ = try container.requirePrivateAccess("entry.0.staged") + #expect(try container.read("entry.0.staged").isEmpty) + privateBeforeWrite = true + } + } + try transaction.replacePrivate( + try store.preparePrivateMaterialization(target), bindings: ["fixture"], + provider: NativeRouteBindings() + ) { try $0.value(for: "fixture") } + try transaction.commit() + let receipt = try #require(try store.materializationReceipt(for: target)) + let edit = FileTransaction(store: store) + try edit.replace(target.url, with: .data(Data("owned sibling; next region".utf8))) + try edit.commit() + #expect(try store.materializationReceipt(for: target)?.generation != receipt.generation) + #expect(try Data(contentsOf: target.url) == Data("owned sibling; next region".utf8)) + if !route.shared { #expect(TransactionLockContext.current(store)?.resources.isEmpty == true) } + } + #expect(privateBeforeWrite) + } + + @Test func explicitRootsAndFileVariantsDoNotGuessDiscoveryOrAuthorizeSiblings() throws { + let fixture = try NativeRouteFixture() + let environment = RuntimeEnvironment( + projectDirectory: fixture.root, homeDirectory: fixture.root.appendingPathComponent("home"), + environment: [ + "CURSOR_CONFIG_DIR": fixture.config.path, "XDG_CONFIG_HOME": fixture.config.path, + ]) + let store = StateStore(scope: .project, environment: environment) + #expect( + try store.nativeTarget(for: .codexMCPUser).url + == environment.homeDirectory.appendingPathComponent(".codex/config.toml")) + #expect( + try store.nativeTarget(for: .geminiMCPUser).url + == environment.homeDirectory.appendingPathComponent(".gemini/settings.json")) + #expect( + try store.nativeTarget(for: .cursorMCPUser).url + == environment.homeDirectory.appendingPathComponent(".cursor/mcp.json")) + #expect( + try store.nativeTarget(for: .openCodeMCPUserJSONC).url + == fixture.config.appendingPathComponent("opencode/opencode.jsonc")) + try FileManager.default.createDirectory( + at: fixture.config.appendingPathComponent("opencode"), withIntermediateDirectories: true) + let before = try FileSnapshot.read(at: fixture.root) + try store.withReadLock(footprint: [.openCodeMCPUserJSON, .openCodeMCPUserJSONC]) { + let json = try store.nativeTarget(for: .openCodeMCPUserJSON) + let jsonc = try store.nativeTarget(for: .openCodeMCPUserJSONC) + #expect(json.url.lastPathComponent == "opencode.json") + #expect(jsonc.url.lastPathComponent == "opencode.jsonc") + } + #expect(try FileSnapshot.read(at: fixture.root) == before) + for (key, route) in [ + ("CODEX_HOME", NativeTargetRoute.codexMCPUser), + ("GEMINI_CLI_HOME", .geminiMCPUser), ("OPENCODE_CONFIG_DIR", .openCodeMCPUserJSON), + ("XDG_CONFIG_HOME", .openCodeMCPUserJSON), + ] { + let invalid = StateStore( + scope: .project, + environment: RuntimeEnvironment( + projectDirectory: fixture.root, homeDirectory: environment.homeDirectory, + environment: [key: "relative-root"])) + #expect(throws: CoreError.self) { try invalid.nativeTarget(for: route) } + } + let missing = StateStore( + scope: .project, + environment: RuntimeEnvironment( + projectDirectory: fixture.root, homeDirectory: environment.homeDirectory, + environment: ["CODEX_HOME": fixture.root.appendingPathComponent("missing").path])) + #expect(throws: CoreError.self) { try missing.withLock(footprint: [.codexMCPUser]) {} } + #expect( + !FileManager.default.fileExists(atPath: fixture.root.appendingPathComponent("missing").path)) + try fixture.store.withLock(footprint: [.codexMCPUser]) { + let transaction = FileTransaction(store: fixture.store) + #expect(throws: CoreError.self) { + try transaction.replace( + fixture.config.appendingPathComponent("auth.json"), with: .data(Data())) + } + #expect(throws: CoreError.self) { + try transaction.replace( + fixture.config.appendingPathComponent("other.toml"), with: .data(Data())) + } + } + let user = StateStore(scope: .user, environment: fixture.store.environment) + #expect(throws: CoreError.self) { try user.nativeTarget(for: .codexMCPProject) } + } + + @Test(arguments: ["queued", "staged"]) + func projectRootAliasesCannotRedirectQueuedOrdinaryWrites(_ change: String) throws { + let fixture = try NativeRouteFixture() + let first = fixture.root.appendingPathComponent("first") + let second = fixture.root.appendingPathComponent("second") + for root in [first, second] { + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + } + let alias = fixture.root.appendingPathComponent(".codex") + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: first) + func redirect() throws { + try FileManager.default.removeItem(at: alias) + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: second) + } + #expect(throws: CoreError.self) { + try fixture.store.withLock(footprint: [.codexMCPProject]) { + let target = try fixture.store.nativeTarget(for: .codexMCPProject) + let transaction = FileTransaction(store: fixture.store) { point in + if change == "staged", point == "stage.0.writeCreated" { try redirect() } + } + try transaction.replace(target.url, with: .data(Data("owned region".utf8))) + if change == "queued" { try redirect() } + try transaction.commit() + } + } + let journal = fixture.store.directory.appendingPathComponent("transaction.json") + if change == "staged" { + #expect(FileManager.default.fileExists(atPath: journal.path)) + try FileManager.default.removeItem(at: alias) + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: first) + #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { + try fixture.store.withLock {} + } + } + #expect(!FileManager.default.fileExists(atPath: journal.path)) + #expect( + !FileManager.default.fileExists(atPath: first.appendingPathComponent("config.toml").path)) + #expect( + !FileManager.default.fileExists(atPath: second.appendingPathComponent("config.toml").path)) + } + + @Test func projectAndUserFileCoincidenceRequiresTheSharedAdmission() throws { + let fixture = try NativeRouteFixture() + let root = fixture.root.appendingPathComponent(".codex") + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + let store = StateStore( + scope: .project, + environment: RuntimeEnvironment( + projectDirectory: fixture.root, homeDirectory: fixture.root.appendingPathComponent("home"), + environment: ["CODEX_HOME": root.path])) + #expect(throws: CoreError.self) { + try store.withLock { + let transaction = FileTransaction(store: store) + try transaction.replace(root.appendingPathComponent("config.toml"), with: .data(Data())) + } + } + try store.withLock(footprint: [.codexMCPProject]) { + let target = try store.nativeTarget(for: .codexMCPProject) + let transaction = FileTransaction(store: store) + try transaction.replace(target.url, with: .data(Data("owned region".utf8))) + try transaction.commit() + } + try store.withLock(footprint: [.codexMCPUser]) { + let target = try store.nativeTarget(for: .codexMCPUser) + let transaction = FileTransaction(store: store) + try transaction.replace(target.url, with: .data(Data("shared region".utf8))) + try transaction.commit() + } + #expect( + try Data(contentsOf: root.appendingPathComponent("config.toml")) == Data("shared region".utf8) + ) + } + + @Test func distinctFilesHaveIndependentReceiptsAcrossAliasedHomes() throws { + let fixture = try NativeRouteFixture() + let store = StateStore(scope: .user, environment: fixture.store.environment) + let routes = Set(NativeTargetRoute.sharedRoutes) + var receipts: [NativeTargetRoute: Data] = [:] + var identities: [NativeTargetRoute: SharedResourceIdentity] = [:] + try store.withLock(footprint: routes) { + let transaction = FileTransaction(store: store) + for route in NativeTargetRoute.sharedRoutes { + let target = try store.nativeTarget(for: route) + try transaction.replacePrivate( + try store.preparePrivateMaterialization(target), provider: NativeRouteBindings() + ) { _ in Data(route.rawValue.utf8) } + identities[route] = try TransactionLockContext.current(store).requiredResourceForRoute( + route + ).identity + } + try transaction.commit() + for route in NativeTargetRoute.sharedRoutes { + let target = try store.nativeTarget(for: route) + let receipt = try store.materializationReceipts(for: target.path) + #expect(Set(receipt.records.targets.keys) == [target.path]) + receipts[route] = try Data(contentsOf: receipt.url) + } + } + #expect(Set(identities.values.map(\.orderingKey)).count == NativeTargetRoute.sharedRoutes.count) + let alias = fixture.root.appendingPathComponent("alias") + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: fixture.config) + let other = StateStore( + scope: .user, + environment: RuntimeEnvironment( + projectDirectory: fixture.root, + homeDirectory: fixture.root.appendingPathComponent("other-home"), + environment: [ + "CLAUDE_CONFIG_DIR": alias.path, "CODEX_HOME": alias.path, + "GEMINI_CLI_HOME": alias.path, "OPENCODE_CONFIG_DIR": alias.path, + ])) + let shared = Set([ + NativeTargetRoute.codexMCPUser, .geminiMCPUser, .openCodeMCPUserJSON, .openCodeMCPUserJSONC, + .claudeMCPLocal, + ]) + try other.withLock(footprint: shared) { + for route in shared { + #expect( + try TransactionLockContext.current(other).requiredResourceForRoute(route).identity + == identities[route]) + } + let target = try other.nativeTarget(for: .codexMCPUser) + let transaction = FileTransaction(store: other) + try transaction.replace(target.url, with: .data(Data("owned sibling; new codex region".utf8))) + try transaction.commit() + } + try store.withLock(footprint: routes) { + for route in NativeTargetRoute.sharedRoutes { + let target = try store.nativeTarget(for: route) + #expect(try store.materializationReceipt(for: target) != nil) + let receipt = try store.materializationReceipts(for: target.path) + if route != .codexMCPUser { #expect(try Data(contentsOf: receipt.url) == receipts[route]) } + } + let transaction = FileTransaction(store: store) + try transaction.delete(store.nativeTarget(for: .openCodeMCPUserJSON).url) + try transaction.commit() + #expect( + try store.materializationReceipt(for: store.nativeTarget(for: .openCodeMCPUserJSON)) == nil) + #expect( + try store.materializationReceipt(for: store.nativeTarget(for: .openCodeMCPUserJSONC)) != nil + ) + } + } + + @Test func aChangedPendingRuntimeCannotCreateAnUnrelatedRequestedDomain() throws { + let fixture = try NativeRouteFixture() + let child = try stateTestProcess( + root: fixture.root, + arguments: [ + "shared-install", "shared.ready", "--native-routes", + "codex.mcp.user,opencode.mcp.user.jsonc", "--shared-config", fixture.config.path, + ]) + defer { terminateProcess(child) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: child, root: fixture.root) + terminateProcess(child) + let before = try FileSnapshot.read(at: fixture.root) + let changed = StateStore( + scope: .project, + environment: RuntimeEnvironment( + projectDirectory: fixture.root, homeDirectory: fixture.store.environment.homeDirectory, + environment: [ + "CODEX_HOME": fixture.config.path, + "OPENCODE_CONFIG_DIR": fixture.root.appendingPathComponent("wrong-root").path, + ])) + #expect(throws: CoreError.self) { + try changed.withLock(footprint: [.cursorMCPUser]) { + Issue.record("pending recovery must reject the changed runtime before callback") + } + } + #expect(try FileSnapshot.read(at: fixture.root) == before) + } + + @Test(arguments: [ + "shared.1.reservation.halfWritten", "shared.ready", "entry.0.applied", "journal.finalized", + ]) + func multiplePendingResourcesRecoverUnderTheirOriginalRuntime(_ point: String) throws { + let fixture = try NativeRouteFixture() + let child = try stateTestProcess( + root: fixture.root, + arguments: [ + "shared-install", point, "--native-routes", "codex.mcp.user,opencode.mcp.user.jsonc", + "--shared-config", fixture.config.path, + ]) + defer { terminateProcess(child) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: child, root: fixture.root) + terminateProcess(child) + let before = try FileSnapshot.read(at: fixture.root) + try fixture.store.withReadLock( + onPendingRecovery: { + let diagnostic = FileTransaction.recoveryDiagnostic(store: fixture.store) + #expect(!diagnostic.requiresOwner) + let context = try #require(TransactionLockContext.current(fixture.store)) + #expect( + Set(context.resources.map { $0.identity.basename }) == ["config.toml", "opencode.jsonc"]) + }, { _ = Issue.record("expected pending native resources") }) + #expect(try FileSnapshot.read(at: fixture.root) == before) + var entered = false + #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { + try fixture.store.withLock(footprint: [.cursorMCPUser]) { entered = true } + } + #expect(!entered) + try fixture.store.withLock(footprint: [.codexMCPUser, .openCodeMCPUserJSONC]) { + for route in [NativeTargetRoute.codexMCPUser, .openCodeMCPUserJSONC] { + let target = try fixture.store.nativeTarget(for: route) + let receipt = try fixture.store.materializationReceipt(for: target) + if point == "journal.finalized" { + #expect(receipt != nil) + } else { + #expect(!FileManager.default.fileExists(atPath: target.url.path)) + #expect(receipt == nil) + } + } + } + } +} + +private struct NativeRouteBindings: RuntimeBindingProvider { + func value(for binding: String, environment: RuntimeEnvironment) throws -> Data { + Data(binding.utf8) + } +} + +private final class NativeRouteFixture { + let root: URL + let config: URL + let store: StateStore + init() throws { + root = try temporaryDirectory() + config = root.appendingPathComponent("configured") + do { + try FileManager.default.createDirectory(at: config, withIntermediateDirectories: true) + try FileManager.default.createDirectory( + at: root.appendingPathComponent("home"), withIntermediateDirectories: true) + try FileManager.default.createDirectory( + at: root.appendingPathComponent("other-home"), withIntermediateDirectories: true) + try FileManager.default.createDirectory( + at: root.appendingPathComponent("old-data"), withIntermediateDirectories: true) + try Data("ordinary before".utf8).write(to: root.appendingPathComponent("old-data/AGENTS.md")) + store = StateStore( + scope: .project, + environment: RuntimeEnvironment( + projectDirectory: root, homeDirectory: root.appendingPathComponent("home"), + environment: [ + "CLAUDE_CONFIG_DIR": config.path, "CODEX_HOME": config.path, + "GEMINI_CLI_HOME": config.path, "OPENCODE_CONFIG_DIR": config.path, + ])) + } catch { + removeTemporaryDirectory(root) + throw error + } + } + deinit { removeTemporaryDirectory(root) } + @discardableResult + func recordSkill(name: String, agent: AgentID) throws -> ResolvedLedger { + let store = self.store + var ledger = ResolvedLedger() + ledger.sources["fixture"] = LedgerSource(kind: .local, revision: "live") + ledger.components["skill"] = LedgerComponent( + declaringSource: "fixture", source: "fixture", root: ".", kind: "skills", + name: name, + payload: .init(object: [:]), conditions: [], recipients: [agent], chatGPT: false, + resources: []) + ledger.deployments = [ + LedgerDeployment( + id: "deployment", + target: .init(kind: .registered, root: "skills-" + agent.rawValue, path: name), + route: "agents/skill@1", owners: ["skill"], recipients: [agent], ownership: .generated, + expectedHash: "sha256:" + FileHash.sha256Hex(data: Data("old".utf8)), created: true) + ] + ledger.lowerings = [ + LockedLowering( + id: "lowering", format: "agents/skill@1", inputs: ["skill"], resources: [], + deployments: ["deployment"], layout: .init(object: [:]), platform: "macos", artifacts: []) + ] + try FileManager.default.createDirectory(at: store.directory, withIntermediateDirectories: true) + try ResolvedLedgerCodec.encode(ledger, limits: .standard).write(to: store.resolvedURL) + return ledger + } + static func journal(in store: StateStore) throws -> TransactionJournal { + try FileTransaction.readJournal( + Data(contentsOf: store.directory.appendingPathComponent(TransactionJournal.fileName))) + } +} + +extension Optional where Wrapped == TransactionLockContext { + fileprivate func requiredResourceForRoute(_ route: NativeTargetRoute) throws -> SharedResource { + try #require(self).resource(for: route) + } +} + +extension RegisteredNativeTargetTests { + private static var componentFiles: [NativeTargetRoute] { + var result: [NativeTargetRoute] = [ + .claudeSettingsProject, .claudeSettingsUser, + .codexHooksProject, .codexHooksUser, .cursorHooksProject, .cursorHooksUser, + .geminiIgnoreProject, .cursorIgnoreProject, + ] + for member in [ + NativeTargetRoute.Member.claudeCommand, .claudeAgent, .codexAgent, + .geminiCommand, .geminiAgent, .cursorCommand, .cursorAgent, + ] { + for scope in [InstallScope.project, .user] { + if let route = try? NativeTargetRoute.named(member, scope: scope, name: "example") { + result.append(route) + } + } + } + return result + } + + @Test(arguments: componentFiles) + func componentFilesRetainPrivateGenerationOnOrdinarySiblingEdit(_ route: NativeTargetRoute) throws + { + let fixture = try NativeRouteFixture() + let store = StateStore( + scope: route.shared ? .user : .project, environment: fixture.store.environment) + try store.withLock(footprint: [route]) { + let target = try store.nativeTarget(for: route) + let transaction = FileTransaction(store: store) + try transaction.replacePrivate( + store.preparePrivateMaterialization(target), provider: NativeRouteBindings() + ) { + _ in Data("bound region; unmanaged sibling".utf8) + } + try transaction.commit() + let before = try #require(try store.materializationReceipt(for: target)) + let ordinary = FileTransaction(store: store) + try ordinary.replace(target.url, with: .data(Data("bound region; edited sibling".utf8))) + try ordinary.commit() + let after = try #require(try store.materializationReceipt(for: target)) + #expect(before.generation != after.generation) + _ = try DirectoryHandle(at: target.url.deletingLastPathComponent()).requirePrivateAccess( + target.url.lastPathComponent) + } + try store.withReadLock(footprint: [route]) { + let target = try store.nativeTarget(for: route) + let receipt = try store.materializationReceipt(for: target) + #expect(receipt != nil) + } + } + + @Test func componentRouteBoundariesAndPureFreshHomePreview() throws { + let fixture = try NativeRouteFixture() + var environment = fixture.store.environment + environment.homeDirectory = fixture.root.appendingPathComponent("fresh-home") + environment.environment = [:] + let store = StateStore(scope: .user, environment: environment) + let routes = try Set([ + NativeTargetRoute.named(.claudeCommand, scope: .user, name: "team/check"), + .named(.geminiExtension, scope: .user, name: "example"), + .named(.cursorLocalPlugin, scope: .user, name: "example"), + ]) + let before = try FileSnapshot.read(at: fixture.root) + try store.withReadLock(footprint: routes) { + for route in routes { + #expect(try store.nativeTargetIdentity(for: route) == nil) + let target = try store.nativeTarget(for: route) + #expect(target.url.path.hasPrefix(environment.homeDirectory.path + "/")) + #expect(try store.materializationReceipt(for: target) == nil) + } + } + #expect(try FileSnapshot.read(at: fixture.root) == before) + for name in [ + "", ".", "..", "../escape", "/escape", "a//b", "a/../b", "a\\b", ".agents-native", + "a/.agents-native/b", ".agents-temporary", + ] { + #expect(throws: CoreError.self) { + try NativeTargetRoute.named(.claudeCommand, scope: .user, name: name) + } + } + #expect(throws: CoreError.self) { + try NativeTargetRoute.named(.cursorCommand, scope: .user, name: "example") + } + #expect(throws: CoreError.self) { + try NativeTargetRoute.named(.geminiExtension, scope: .project, name: "example") + } + #expect(throws: CoreError.self) { try fixture.store.nativeTarget(for: .claudeSettingsUser) } + let beforeRefusal = try FileSnapshot.read(at: fixture.root) + #expect(throws: CoreError.self) { + try fixture.store.withLock(footprint: [.claudeSettingsUser]) { + _ = Issue.record("wrong-scope request must be refused before callback") + } + } + #expect(try FileSnapshot.read(at: fixture.root) == beforeRefusal) + var collidingEnvironment = fixture.store.environment + collidingEnvironment.environment["CLAUDE_CONFIG_DIR"] = + fixture.root.appendingPathComponent(".claude").path + let colliding = StateStore(scope: .project, environment: collidingEnvironment) + let collidingRoute = try NativeTargetRoute.named(.claudeAgent, scope: .project, name: "example") + let collidingTarget = try colliding.nativeTarget(for: collidingRoute) + #expect(collidingTarget.path == collidingRoute.root + "/" + collidingRoute.basename) + #expect(try FileSnapshot.read(at: fixture.root) == beforeRefusal) + #expect(throws: CoreError.self) { + try colliding.withLock { + try FileTransaction(store: colliding).replace(collidingTarget.url, with: .data(Data())) + } + } + #expect(!FileManager.default.fileExists(atPath: collidingTarget.url.path)) + let linkParent = fixture.config.appendingPathComponent("commands") + try FileManager.default.createSymbolicLink(at: linkParent, withDestinationURL: fixture.root) + let user = StateStore(scope: .user, environment: fixture.store.environment) + #expect(throws: CoreError.self) { + try user.nativeTarget(for: .named(.claudeCommand, scope: .user, name: "escape")) + } + #expect(NativeTargetRoute.claudeSettingsUser.knownReaders == [.claudeCode, .cursor]) + let fileRoute = try NativeTargetRoute.file( + .claudeCommand, scope: .user, relativePath: "team/check.md") + let namedRoute = try NativeTargetRoute.named(.claudeCommand, scope: .user, name: "team/check") + #expect(fileRoute == namedRoute) + #expect(throws: CoreError.self) { + try NativeTargetRoute.file(.claudeCommand, scope: .user, relativePath: "team/check.toml") + } + } + + @Test func aliasedComponentKindsShareIdentityAndSensitiveReceiptAcrossHomes() throws { + let fixture = try NativeRouteFixture() + var environment = fixture.store.environment + environment.environment["GEMINI_CLI_HOME"] = fixture.root.path + environment.environment["CLAUDE_CONFIG_DIR"] = + fixture.root.appendingPathComponent(".gemini").path + let a = StateStore(scope: .user, environment: environment) + environment.homeDirectory = fixture.root.appendingPathComponent("other-home") + let b = StateStore(scope: .project, environment: environment) + let routes: Set = [.claudeSettingsUser, .geminiMCPUser, .cursorHooksUser] + var identity: NativeTargetIdentity? + try a.withLock(footprint: routes) { + let first = try a.nativeTarget(for: .claudeSettingsUser) + let second = try a.nativeTarget(for: .geminiMCPUser) + #expect(first.path == second.path) + identity = try a.nativeTargetIdentity(for: .claudeSettingsUser) + #expect(identity == (try a.nativeTargetIdentity(for: .geminiMCPUser))) + #expect(identity != (try a.nativeTargetIdentity(for: .cursorHooksUser))) + let transaction = FileTransaction(store: a) + try transaction.replacePrivate( + a.preparePrivateMaterialization(first), provider: NativeRouteBindings() + ) { _ in Data("bound; sibling".utf8) } + try transaction.commit() + } + try b.withLock(footprint: [.geminiMCPUser]) { + let target = try b.nativeTarget(for: .geminiMCPUser) + #expect(identity == (try b.nativeTargetIdentity(for: .geminiMCPUser))) + let previous = try #require(try b.materializationReceipt(for: target)) + let transaction = FileTransaction(store: b) + try transaction.replace(target.url, with: .data(Data("bound; changed sibling".utf8))) + try transaction.commit() + #expect(try b.materializationReceipt(for: target)?.generation != previous.generation) + } + try a.withReadLock(footprint: [.claudeSettingsUser]) { + let target = try a.nativeTarget(for: .claudeSettingsUser) + let receipt = try a.materializationReceipt(for: target) + #expect(receipt != nil) + } + } +} + +extension RegisteredNativeTargetTests { + @Test(arguments: ["shared.1.reservation.halfWritten", "entry.0.applied", "journal.finalized"]) + func namedFilesWithEqualBasenamesRecoverThroughTheirClosedRoots(_ point: String) throws { + let fixture = try NativeRouteFixture() + let routes = try [ + NativeTargetRoute.named(.claudeAgent, scope: .user, name: "example"), + .named(.cursorAgent, scope: .user, name: "example"), + ] + let store = StateStore(scope: .user, environment: fixture.store.environment) + let child = try stateTestProcess( + root: fixture.root, + arguments: [ + "shared-install", point, "--native-routes", routes.map(\.rawValue).joined(separator: ","), + "--shared-config", fixture.config.path, "--scope", "user", + ]) + defer { terminateProcess(child) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: child, root: fixture.root) + terminateProcess(child) + let before = try FileSnapshot.read(at: fixture.root) + try store.withReadLock( + onPendingRecovery: { + let diagnosis = FileTransaction.recoveryDiagnostic(store: store) + #expect(!diagnosis.requiresOwner) + }, { _ = Issue.record("expected pending named targets") }) + #expect(try FileSnapshot.read(at: fixture.root) == before) + #expect(throws: CoreError.transactionRecovered(store.directory.path)) { try store.withLock {} } + try store.withReadLock(footprint: Set(routes)) { + for route in routes { + let target = try store.nativeTarget(for: route) + let receipt = try store.materializationReceipt(for: target) + #expect((receipt != nil) == (point == "journal.finalized")) + } + } + } + + @Test(arguments: [ + NativeTargetRoute.Member.claudeSkillPlugin, .cursorLocalPlugin, .geminiExtension, + ]) + func registeredBundleContainersPublishAndDeleteWithoutInstallerAuthority( + _ member: NativeTargetRoute.Member + ) throws { + let fixture = try NativeRouteFixture() + let store = StateStore(scope: .user, environment: fixture.store.environment) + let route = try NativeTargetRoute.named(member, scope: .user, name: "example") + let payload = fixture.root.appendingPathComponent("bundle") + try FileManager.default.createDirectory(at: payload, withIntermediateDirectories: true) + try Data("native manifest fixture".utf8).write( + to: payload.appendingPathComponent("manifest.json")) + try store.withLock(footprint: [route]) { + let target = try store.nativeTarget(for: route) + #expect(throws: CoreError.self) { + let invalid = FileTransaction(store: store) + try invalid.replace(target.url, with: .data(Data("wrong kind".utf8))) + } + let transaction = FileTransaction(store: store) + try transaction.replace(target.url, with: .copy(payload)) + try transaction.commit() + #expect( + try Data(contentsOf: target.url.appendingPathComponent("manifest.json")) + == Data("native manifest fixture".utf8)) + #expect(throws: CoreError.self) { + let outside = fixture.root.appendingPathComponent("outside-native-root") + try FileTransaction(store: store).replace(outside, with: .copy(payload)) + } + let removal = FileTransaction(store: store) + try removal.delete(target.url) + try removal.commit() + #expect(!FileManager.default.fileExists(atPath: target.url.path)) + } + } +} + +extension RegisteredNativeTargetTests { + @Test func projectAliasesPreserveWholeFileSensitivityAcrossComponentKinds() throws { + let fixture = try NativeRouteFixture() + let store = fixture.store + let claude = try NativeTargetRoute.named(.claudeAgent, scope: .project, name: "example") + let cursor = try NativeTargetRoute.named(.cursorAgent, scope: .project, name: "example") + try FileManager.default.createDirectory( + at: fixture.root.appendingPathComponent(".claude"), withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink( + at: fixture.root.appendingPathComponent(".cursor"), + withDestinationURL: fixture.root.appendingPathComponent(".claude")) + try store.withLock(footprint: [claude, cursor]) { + let a = try store.nativeTarget(for: claude) + let b = try store.nativeTarget(for: cursor) + #expect(a.path == b.path) + let transaction = FileTransaction(store: store) + try transaction.replacePrivate( + store.preparePrivateMaterialization(a), provider: NativeRouteBindings() + ) { _ in Data("private sibling; first region".utf8) } + try transaction.commit() + } + try store.withLock(footprint: [cursor]) { + let target = try store.nativeTarget(for: cursor) + let before = try #require(try store.materializationReceipt(for: target)) + let transaction = FileTransaction(store: store) + try transaction.replace(target.url, with: .data(Data("private sibling; changed region".utf8))) + try transaction.commit() + #expect(try store.materializationReceipt(for: target)?.generation != before.generation) + } + try store.withReadLock(footprint: [claude]) { + let target = try store.nativeTarget(for: claude) + let receipt = try store.materializationReceipt(for: target) + #expect(receipt != nil) + } + } +} + +extension RegisteredNativeTargetTests { + @Test func crossFamilyProjectAliasCannotBypassPrivateUserAgent() throws { + let fixture = try NativeRouteFixture() + let user = StateStore(scope: .user, environment: fixture.store.environment) + let userRoute = try NativeTargetRoute.named(.cursorAgent, scope: .user, name: "example") + var targetURL: URL! + var receiptURL: URL! + try user.withLock(footprint: [userRoute]) { + let target = try user.nativeTarget(for: userRoute) + targetURL = target.url + let transaction = FileTransaction(store: user) + try transaction.replacePrivate( + user.preparePrivateMaterialization(target), provider: NativeRouteBindings() + ) { + _ in Data("private user agent".utf8) + } + try transaction.commit() + receiptURL = try user.materializationReceipts(for: target.path).url + } + let receipt = try Data(contentsOf: receiptURL) + try FileManager.default.createSymbolicLink( + at: fixture.root.appendingPathComponent(".claude"), + withDestinationURL: user.environment.homeDirectory.appendingPathComponent(".cursor")) + let projectRoute = try NativeTargetRoute.named(.claudeAgent, scope: .project, name: "example") + #expect(throws: CoreError.self) { + try fixture.store.withLock(footprint: [projectRoute]) { + let target = try fixture.store.nativeTarget(for: projectRoute) + let transaction = FileTransaction(store: fixture.store) + try transaction.replace(target.url, with: .data(Data("ordinary project edit".utf8))) + try transaction.commit() + } + } + #expect(try Data(contentsOf: targetURL) == Data("private user agent".utf8)) + #expect(try Data(contentsOf: receiptURL) == receipt) + try user.withReadLock(footprint: [userRoute]) { + let target = try user.nativeTarget(for: userRoute) + let privateReceipt = try user.materializationReceipt(for: target) + #expect(privateReceipt != nil) + } + } + + @Test func nestedProjectAliasCannotBypassPrivateUserCommand() throws { + let fixture = try NativeRouteFixture() + let user = StateStore(scope: .user, environment: fixture.store.environment) + let userRoute = try NativeTargetRoute.named(.claudeCommand, scope: .user, name: "team/example") + var targetURL: URL! + var receiptURL: URL! + try user.withLock(footprint: [userRoute]) { + let target = try user.nativeTarget(for: userRoute) + targetURL = target.url + let transaction = FileTransaction(store: user) + try transaction.replacePrivate( + user.preparePrivateMaterialization(target), provider: NativeRouteBindings() + ) { + _ in Data("private user agent".utf8) + } + try transaction.commit() + receiptURL = try user.materializationReceipts(for: target.path).url + } + let receipt = try Data(contentsOf: receiptURL) + try FileManager.default.createSymbolicLink( + at: fixture.root.appendingPathComponent(".claude"), + withDestinationURL: user.environment.homeDirectory.appendingPathComponent(".claude")) + let projectRoute = try NativeTargetRoute.named( + .claudeCommand, scope: .project, name: "team/example") + #expect(throws: CoreError.self) { + try fixture.store.withLock(footprint: [projectRoute]) { + let target = try fixture.store.nativeTarget(for: projectRoute) + let transaction = FileTransaction(store: fixture.store) + try transaction.replace(target.url, with: .data(Data("ordinary project edit".utf8))) + try transaction.commit() + } + } + #expect(try Data(contentsOf: targetURL) == Data("private user agent".utf8)) + #expect(try Data(contentsOf: receiptURL) == receipt) + try user.withReadLock(footprint: [userRoute]) { + let target = try user.nativeTarget(for: userRoute) + let privateReceipt = try user.materializationReceipt(for: target) + #expect(privateReceipt != nil) + } + } + + @Test(arguments: [InstallScope.project, .user]) + func namedLoaderAliasRedirectStopsPublication(_ scope: InstallScope) throws { + let fixture = try NativeRouteFixture() + let a = fixture.root.appendingPathComponent("loader-a") + let b = fixture.root.appendingPathComponent("loader-b") + for url in [a, b] { + try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) + } + let alias = fixture.root.appendingPathComponent(scope == .project ? ".claude" : "loader-alias") + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: a) + var environment = fixture.store.environment + if scope == .user { environment.environment["CLAUDE_CONFIG_DIR"] = alias.path } + let store = StateStore(scope: scope, environment: environment) + let route = try NativeTargetRoute.named(.claudeAgent, scope: scope, name: "example") + #expect(throws: CoreError.self) { + try store.withLock(footprint: [route]) { + let target = try store.nativeTarget(for: route) + let transaction = FileTransaction(store: store) { point in + if point == "stage.0.writeCreated" { + try FileManager.default.removeItem(at: alias) + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: b) + } + } + try transaction.replace(target.url, with: .data(Data("stale authority".utf8))) + try transaction.commit() + } + } + for url in [a, b] { + #expect( + !FileManager.default.fileExists( + atPath: url.appendingPathComponent("agents/example.md").path)) + } + try FileManager.default.removeItem(at: alias) + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: a) + if FileManager.default.fileExists( + atPath: store.directory.appendingPathComponent("transaction.json").path) + { + #expect(throws: CoreError.transactionRecovered(store.directory.path)) { + try store.withLock {} + } + } + } + + @Test(arguments: [false, true]) + func preparedNativeOutputMustRetainRegisteredKind(_ container: Bool) throws { + let fixture = try NativeRouteFixture() + let route = try NativeTargetRoute.named( + container ? .claudeSkillPlugin : .claudeAgent, scope: .project, name: "example") + try fixture.store.withLock(footprint: [route]) { + let target = try fixture.store.nativeTarget(for: route) + try FileManager.default.createDirectory( + at: target.url.deletingLastPathComponent(), withIntermediateDirectories: true) + if container { + try FileManager.default.createDirectory(at: target.url, withIntermediateDirectories: false) + try Data("existing member".utf8).write(to: target.url.appendingPathComponent("member")) + } else { + try Data("existing native file".utf8).write(to: target.url) + } + let before = try FileSnapshot.read(at: target.url) + let transaction = FileTransaction(store: fixture.store) + try transaction.replace( + target.url, + with: .prepared { work in + let output = work.appendingPathComponent("output") + if container { + try Data("wrong kind".utf8).write(to: output) + } else { + try FileManager.default.createDirectory(at: output, withIntermediateDirectories: false) + } + return output + }) + #expect(throws: CoreError.self) { try transaction.commit() } + #expect(try FileSnapshot.read(at: target.url) == before) + } + } + + @Test(arguments: ["AGENTS", "GEMINI"]) + func admittedNativeInstructionBasenameKeepsItsNativeReceipt(_ name: String) throws { + let fixture = try NativeRouteFixture() + // An unrelated user command alias does not authorize or restrict this project agent. + try FileManager.default.createSymbolicLink( + at: fixture.config.appendingPathComponent("commands"), withDestinationURL: fixture.root) + let route = try NativeTargetRoute.named(.claudeAgent, scope: .project, name: name) + try fixture.store.withLock(footprint: [route]) { + let target = try fixture.store.nativeTarget(for: route) + #expect(try TransactionPaths(store: fixture.store).path(for: target.url) == target.path) + let transaction = FileTransaction(store: fixture.store) + try transaction.replacePrivate( + fixture.store.preparePrivateMaterialization(target), provider: NativeRouteBindings() + ) { + _ in Data("native private sibling".utf8) + } + try transaction.commit() + let before = try #require(try fixture.store.materializationReceipt(for: target)) + let edit = FileTransaction(store: fixture.store) + try edit.replace(target.url, with: .data(Data("native private sibling; edit".utf8))) + try edit.commit() + #expect( + try fixture.store.materializationReceipt(for: target)?.generation != before.generation) + } + try fixture.store.withReadLock { + let instruction = fixture.root.appendingPathComponent("notes/" + name + ".md") + let path = try TransactionPaths(store: fixture.store).path(for: instruction) + #expect(path == "instructions-project/notes/" + name + ".md") + } + } +} diff --git a/Tests/AgentsCoreTests/RequirementSemanticsTests.swift b/Tests/AgentsCoreTests/RequirementSemanticsTests.swift new file mode 100644 index 0000000..ab41317 --- /dev/null +++ b/Tests/AgentsCoreTests/RequirementSemanticsTests.swift @@ -0,0 +1,259 @@ +import Foundation +import Testing + +@testable import AgentsCore + +@Suite("Requirement semantics") +struct RequirementSemanticsTests { + @Test(arguments: [ + ( + SourceRequirement.range(from: "v1.2.0+lower", to: "2.0.0+upper"), + SourceRequirement.upToNextMajor(from: "1.2.0") + ), + (.range(from: "1.2.0-beta+lower", to: "1.3.0+upper"), .upToNextMinor(from: "v1.2.0-beta")), + (.exact(" V1.2.3+build "), .exact("1.2.3+build")), + (.branch("main"), .branch("main")), (.revision("abc"), .revision("abc")), + ]) + func selectionsCompareSemanticValues(_ legacy: SourceRequirement, _ modern: SourceRequirement) + throws + { + #expect(legacy.declarationEquivalent(to: modern)) + let decoded = try JSONDecoder().decode( + SourceRequirement.self, from: JSONEncoder().encode(legacy)) + #expect(decoded == legacy) + #expect(try decoded.canonicalized().declarationEquivalent(to: modern)) + } + + @Test func absenceExactMetadataPrereleasesAndDifferentRangesStayDistinct() { + for (left, right) in [ + (SourceRequirement.exact("1.2.3+one"), SourceRequirement.exact("1.2.3+two")), + (.upToNextMajor(from: "1.2.0-beta"), .upToNextMajor(from: "1.2.0")), + (.upToNextMajor(from: "1.2.0"), .upToNextMinor(from: "1.2.0")), + (.branch("main"), .revision("main")), + ] { #expect(!left.declarationEquivalent(to: right)) } + #expect(LockedSource(kind: .local) != LockedSource(kind: .local, requirement: .branch("main"))) + } + + @Test func argumentSelectorsAcceptEqualBoundsAndRejectDifferentIntent() throws { + let environment = RuntimeEnvironment(environment: [:]) + let declaration = Declaration(sources: ["s": SourceDeclaration(kind: .local, location: "local")] + ) + let selected = try SourceArgument("s@from:1.2.0").selection( + in: declaration, requirement: .range(from: "v1.2.0+meta", to: "2.0.0"), path: nil, + environment: environment) + #expect(selected.requirement == .upToNextMajor(from: "1.2.0")) + #expect(selected.requirement?.declarationEquivalent(to: .upToNextMajor(from: "1.2.0")) == true) + #expect(throws: CoreError.self) { + try SourceArgument("s@minor:1.2.0").selection( + in: declaration, requirement: .range(from: "1.2.0", to: "2.0.0"), path: nil, + environment: environment) + } + } + + @Test func descriptorComparisonUsesIdentityRootAndSemanticRequirementWithoutRewritingReads() + throws + { + let bytes = Data( + #"{"kind":"git","url":"https://EXAMPLE.org:2222/team.git/","path":"skills","requirement":{"from":"v1.2.0","to":"2.0.0+meta"}}"# + .utf8) + let old = try JSONDecoder().decode(LockedSource.self, from: bytes) + let new = LockedSource( + kind: .git, url: "ssh://user@example.org:2222/team", + requirement: .upToNextMajor(from: "1.2.0"), path: "skills") + #expect(old == new) + var equivalentRoot = new + equivalentRoot.path = "./skills/" + #expect(old == equivalentRoot) + #expect(LockedSource(kind: .local) == LockedSource(kind: .local, path: ".")) + #expect(old.requirement == .range(from: "v1.2.0", to: "2.0.0+meta")) + var changed = new + changed.path = "instructions" + #expect(old != changed) + changed = new + changed.url = "https://example.org:2223/team" + #expect(old != changed) + #expect( + LockedSource(kind: .local, requirement: .range(from: "v1.2.0", to: "1.3.0")).requirement + == .upToNextMinor(from: "1.2.0")) + } + + @Test func fullLedgerComparisonPreservesEquivalentRequirementBytes() throws { + var ledger = ResolvedLedger() + ledger.sources["source"] = LedgerSource( + kind: .git, transport: "https://intranet/team.git", + revision: String(repeating: "a", count: 40)) + ledger.sourceUses = [ + .init(source: "source", root: ".", requirement: .range(from: "v1.2.0", to: "2.0.0+meta")) + ] + let bytes = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + var next = ledger + next.sourceUses[0].requirement = .upToNextMajor(from: "1.2.0") + #expect(try ResolvedLedgerCodec.replacement(next, existing: bytes, limits: .standard) == nil) + next.sourceUses[0].requirement = .upToNextMinor(from: "1.2.0") + let changed = try #require( + try ResolvedLedgerCodec.replacement(next, existing: bytes, limits: .standard)) + #expect(try ResolvedLedgerCodec.decode(changed, limits: .standard) == next) + } + + @Test func resolutionSessionsReuseEqualRequirementsAndCacheKeysKeepExactPins() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let repo = root.appendingPathComponent("repo") + try FileManager.default.createDirectory(at: repo, withIntermediateDirectories: true) + try Data("old".utf8).write(to: repo.appendingPathComponent("content")) + try initGitRepo(repo) + func git(_ args: [String]) throws { + _ = try ProcessRunner.run("/usr/bin/env", arguments: ["git", "-C", repo.path] + args) + } + try git(["tag", "1.2.0"]) + let store = StateStore( + scope: .project, + environment: RuntimeEnvironment(projectDirectory: root, homeDirectory: root, environment: [:]) + ) + let session = try SourceResolutionSession(store: store) + var source = SourceDeclaration( + kind: .local, location: repo.path, requirement: .range(from: "v1.2.0+lower", to: "2.0.0+meta") + ) + let first = try session.withSnapshot(source) { ($0, $1) } + try Data("new".utf8).write(to: repo.appendingPathComponent("content")) + try git(["commit", "-am", "new"]) + try git(["tag", "1.3.0"]) + source.requirement = .upToNextMajor(from: "1.2.0") + let second = try session.withSnapshot(source) { ($0, $1) } + #expect(first.0 == second.0 && first.1 == second.1) + #expect( + try String(contentsOf: second.1.appendingPathComponent("content"), encoding: .utf8) == "old") + let cache = SourceCache(store: store) + let newer = try cache.resolve(source) + #expect(newer != first.0) + let id = try source.identity(environment: store.environment) + let oldDescriptor = try JSONDecoder().decode( + LockedSource.self, + from: Data(#"{"kind":"local","requirement":{"from":"v1.2.0","to":"2.0.0"}}"#.utf8)) + let newDescriptor = LockedSource(kind: .local, requirement: source.requirement) + let before = try cache.materialize( + sourceID: id, source: oldDescriptor, revision: first.0.revision) + let after = try cache.materialize( + sourceID: id, source: newDescriptor, revision: first.0.revision) + #expect(before == after) + #expect( + try String(contentsOf: after.appendingPathComponent("content"), encoding: .utf8) == "old") + } +} + +extension RequirementSemanticsTests { + @Test(arguments: [ + ( + SourceRequirement.range(from: "v1.2.0+lower", to: "2.0.0+upper"), + SourceRequirement.upToNextMajor(from: "1.2.0") + ), + (.range(from: "1.2.0-beta+lower", to: "1.3.0+upper"), .upToNextMinor(from: "v1.2.0-beta")), + (.exact(" V1.2.3+build "), .exact("1.2.3+build")), + ]) + func sourceAndGroupRequirementsPreserveOriginalLayout( + _ original: SourceRequirement, _ equivalent: SourceRequirement + ) throws { + var ledger = ResolvedLedger() + ledger.sources["source"] = .init( + kind: .git, transport: "https://intranet/team.git", + revision: String(repeating: "a", count: 40)) + ledger.sourceUses = [.init(source: "source", root: ".", requirement: original)] + ledger.groups = [ + .init( + id: 0, source: "source", root: ".", name: "export", requirement: original, + manifestHash: "sha256:" + String(repeating: "a", count: 64), children: []) + ] + let encoded = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + let originalBytes = try JSONSerialization.data( + withJSONObject: JSONSerialization.jsonObject(with: encoded), + options: [.prettyPrinted, .sortedKeys]) + var next = ledger + next.sourceUses[0].requirement = equivalent + next.groups[0].requirement = equivalent + #expect( + try ResolvedLedgerCodec.replacement(next, existing: originalBytes, limits: .standard) == nil) + #expect( + try ResolvedLedgerCodec.decode(originalBytes, limits: .standard).groups[0].requirement + == original) + next.groups[0].requirement = .branch("different") + #expect( + try ResolvedLedgerCodec.replacement(next, existing: originalBytes, limits: .standard) != nil) + } + + @Test func equivalentRequirementsDoNotMaskByteExactNativeOrRefChanges() throws { + var ledger = ResolvedLedger() + ledger.sources["source"] = .init( + kind: .git, transport: "https://intranet/team.git", + revision: String(repeating: "a", count: 40)) + ledger.sourceUses = [ + .init(source: "source", root: ".", requirement: .range(from: "v1.2.0", to: "2.0.0+meta")) + ] + ledger.lowerings = [ + .init( + id: "native", format: "test/value@1", inputs: [], resources: [], deployments: [], + layout: .init("é"), platform: "macos", artifacts: []) + ] + let original = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + var next = ledger + next.sourceUses[0].requirement = .upToNextMajor(from: "1.2.0") + next.lowerings[0].layout = .init("e\u{301}") + #expect(try ResolvedLedgerCodec.replacement(next, existing: original, limits: .standard) != nil) + for (before, after) in [ + (LedgerValue("1.0", kind: .decimal), LedgerValue("1.00", kind: .decimal)), + (LedgerValue(), LedgerValue(object: [:])), + ( + LedgerValue(object: [ + "requirement": .init(object: ["from": .init("v1.2.0"), "to": .init("2.0.0+meta")]) + ]), + LedgerValue(object: ["requirement": .init(object: ["from": .init("1.2.0")])]) + ), + ] { + ledger.lowerings[0].layout = before + let valueBytes = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + next = ledger + next.sourceUses[0].requirement = .upToNextMajor(from: "1.2.0") + next.lowerings[0].layout = after + #expect( + try ResolvedLedgerCodec.replacement(next, existing: valueBytes, limits: .standard) != nil) + } + ledger.sourceUses[0].requirement = .exact("1.2.3+one") + let exactBytes = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + next = ledger + next.sourceUses[0].requirement = .exact("1.2.3+two") + #expect( + try ResolvedLedgerCodec.replacement(next, existing: exactBytes, limits: .standard) != nil) + for requirement in [SourceRequirement.branch("é"), .revision("é")] { + ledger.sourceUses[0].requirement = requirement + let refBytes = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + next = ledger + if case .branch = requirement { + next.sourceUses[0].requirement = .branch("e\u{301}") + } else { + next.sourceUses[0].requirement = .revision("e\u{301}") + } + #expect( + try ResolvedLedgerCodec.replacement(next, existing: refBytes, limits: .standard) != nil) + } + } +} + +extension RequirementSemanticsTests { + @Test func equivalentRequirementsStillRespectCandidateWireBudget() throws { + var ledger = ResolvedLedger() + ledger.sources["source"] = .init( + kind: .git, transport: "https://intranet/team.git", + revision: String(repeating: "a", count: 40)) + ledger.sourceUses = [ + .init(source: "source", root: ".", requirement: .upToNextMajor(from: "1.2.0")) + ] + let bytes = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + var next = ledger + next.sourceUses[0].requirement = .range( + from: "1.2.0", to: "2.0.0+" + String(repeating: "metadata", count: 20)) + var limits = LedgerLimits.standard + limits.encodedBytes = bytes.count + #expect(throws: (any Error).self) { + try ResolvedLedgerCodec.replacement(next, existing: bytes, limits: limits) + } + } +} diff --git a/Tests/AgentsCoreTests/SharedTargetTests.swift b/Tests/AgentsCoreTests/SharedTargetTests.swift new file mode 100644 index 0000000..afb4cf9 --- /dev/null +++ b/Tests/AgentsCoreTests/SharedTargetTests.swift @@ -0,0 +1,1079 @@ +import CPlatform +import Foundation +import StateTestSupport +import Synchronization +import Testing + +@testable import AgentsCore + +@Suite("Shared native physical targets") +struct SharedTargetTests { + @Test func localAndUserWritersKeepOnePrivateGenerationAcrossScopesAndAliases() throws { + let fixture = try SharedFixture() + let provider = SharedBindings() + var stale: PreparedPrivateMaterialization? + try fixture.a.withLock(footprint: [.claudeMCPLocal]) { + let target = try fixture.a.nativeTarget(for: .claudeMCPLocal) + let prepared = try fixture.a.preparePrivateMaterialization(target) + let transaction = FileTransaction(store: fixture.a) + try transaction.replacePrivate(prepared, bindings: ["secret"], provider: provider) { + try $0.value(for: "secret") + } + try transaction.commit() + stale = try fixture.a.preparePrivateMaterialization(target) + } + let first = try #require(stale) + let key = try fixture.identity(fixture.a) + var generations = [first.receiptGeneration] + for (store, route, bytes) in [ + (fixture.b, NativeTargetRoute.claudeMCPLocal, "secret sibling; B region"), + (fixture.user, NativeTargetRoute.claudeMCPUser, "secret sibling; B region; user region"), + (fixture.a, NativeTargetRoute.claudeMCPLocal, "secret sibling; user region"), + ] { + var privateBeforeWrite = false + try store.withLock(footprint: [route]) { + let target = try store.nativeTarget(for: route) + let before = try store.preparePrivateMaterialization( + target, requiringReceiptForExistingTarget: true) + #expect(before.receiptGeneration == generations.last!) + let transaction = FileTransaction(store: store) { point in + if point == "stage.0.writeCreated" { + let journal = try fixture.journal(store) + let container = target.url.deletingLastPathComponent().appendingPathComponent( + journal.containers[0].name) + let directory = try DirectoryHandle(at: container) + _ = try directory.requirePrivateAccess("entry.0.exchanged") + #expect(try directory.read("entry.0.exchanged").isEmpty) + privateBeforeWrite = true + } + } + try transaction.replace(target.url, with: .data(Data(bytes.utf8))) + try transaction.commit() + let after = try store.preparePrivateMaterialization( + target, requiringReceiptForExistingTarget: true) + #expect(after.receiptGeneration != before.receiptGeneration) + generations.append(after.receiptGeneration) + #expect(try Data(contentsOf: target.url) == Data(bytes.utf8)) + #expect(try TransactionLockContext.current(store).requiredResource().identity == key) + } + #expect(privateBeforeWrite) + #expect(try store.materializationReceipts().records.targets.isEmpty) + } + #expect(provider.calls == 1) + try fixture.a.withLock(footprint: [.claudeMCPLocal]) { + #expect(throws: CoreError.self) { try first.evidence.validate() } + #expect(throws: CoreError.self) { + try fixture.a.preparePrivateMaterialization( + first.target, expecting: first.receiptGeneration) + } + } + } + + @Test func registeredProjectRouteIsLocalAndSharedRequestsRequireAdmission() throws { + let fixture = try SharedFixture() + let target = try fixture.a.nativeTarget(for: .claudeMCPLocal) + try fixture.a.withLock { + let transaction = FileTransaction(store: fixture.a) + #expect(throws: CoreError.self) { try transaction.replace(target.url, with: .data(Data())) } + } + #expect( + !FileManager.default.fileExists( + atPath: fixture.config.appendingPathComponent(SharedResource.metadataName).path)) + try fixture.a.withLock(footprint: [.claudeMCPProject]) { + #expect(TransactionLockContext.current(fixture.a)?.resources.isEmpty == true) + let project = try fixture.a.nativeTarget(for: .claudeMCPProject) + let transaction = FileTransaction(store: fixture.a) + try transaction.replace(project.url, with: .data(Data("project only".utf8))) + #expect(throws: CoreError.self) { + try transaction.replace( + fixture.config.appendingPathComponent("other.json"), with: .data(Data())) + } + try transaction.commit() + } + #expect( + !FileManager.default.fileExists( + atPath: fixture.config.appendingPathComponent(SharedResource.metadataName).path)) + } + + @Test func externalSiblingOrAccessChangesCannotRefreshSharedReceipts() throws { + let fixture = try SharedFixture() + try fixture.install() + let before = try Data(contentsOf: fixture.receiptURL()) + try Data("external trust change".utf8).write(to: fixture.target) + #expect(throws: CoreError.self) { + try fixture.b.withLock(footprint: [.claudeMCPLocal]) { + let transaction = FileTransaction(store: fixture.b) + try transaction.replace(fixture.target, with: .data(Data("replacement".utf8))) + } + } + #expect(try Data(contentsOf: fixture.receiptURL()) == before) + #expect(try Data(contentsOf: fixture.target) == Data("external trust change".utf8)) + } + + @Test(arguments: [false, true]) + func ordinaryRecreationOfAnAbsentTargetRemovesItsSensitiveReceipt(_ rollback: Bool) throws { + let fixture = try SharedFixture() + try fixture.install() + let receiptURL = try fixture.receiptURL() + let receipt = try Data(contentsOf: receiptURL) + try FileManager.default.removeItem(at: fixture.target) + try fixture.b.withLock(footprint: [.claudeMCPLocal]) { + let transaction = FileTransaction(store: fixture.b) { point in + if rollback, point == "entry.1.applied" { + throw CoreError.invalidState("injected receipt publication failure") + } + } + try transaction.replace(fixture.target, with: .data(Data("ordinary recreation".utf8))) + if rollback { + #expect(throws: CoreError.self) { try transaction.commit() } + #expect(!FileManager.default.fileExists(atPath: fixture.target.path)) + #expect(try Data(contentsOf: receiptURL) == receipt) + let retry = FileTransaction(store: fixture.b) + try retry.replace(fixture.target, with: .data(Data("ordinary recreation".utf8))) + try retry.commit() + } else { + try transaction.commit() + } + } + #expect(!FileManager.default.fileExists(atPath: receiptURL.path)) + try fixture.user.withReadLock(footprint: [.claudeMCPUser]) { + let target = try fixture.user.nativeTarget(for: .claudeMCPUser) + #expect(try fixture.user.materializationReceipt(for: target) == nil) + #expect(try Data(contentsOf: target.url) == Data("ordinary recreation".utf8)) + } + try fixture.a.withLock(footprint: [.claudeMCPLocal]) { + let transaction = FileTransaction(store: fixture.a) + try transaction.replace(fixture.target, with: .data(Data("ordinary next edit".utf8))) + try transaction.commit() + } + #expect(try Data(contentsOf: fixture.target) == Data("ordinary next edit".utf8)) + #expect(!FileManager.default.fileExists(atPath: receiptURL.path)) + } + + @Test(arguments: ["target", "ancestor"]) + func sharedPreparedWriteRejectsChangedAccess(_ changed: String) throws { + let fixture = try SharedFixture() + try fixture.install() + let targetBytes = try Data(contentsOf: fixture.target) + let receiptURL = try fixture.receiptURL() + let receipt = try Data(contentsOf: receiptURL) + let changedURL = changed == "target" ? fixture.target : fixture.config + var original = stat() + try #require(stat(changedURL.path, &original) == 0) + defer { _ = chmod(changedURL.path, original.st_mode & 0o7777) } + try fixture.b.withLock(footprint: [.claudeMCPLocal]) { + let target = try fixture.b.nativeTarget(for: .claudeMCPLocal) + let prepared = try fixture.b.preparePrivateMaterialization( + target, requiringReceiptForExistingTarget: true) + let transaction = FileTransaction(store: fixture.b) + try transaction.replace( + target.url, with: .data(Data("secret sibling; changed region".utf8)), + expecting: prepared.evidence) + let externalMode: mode_t = changed == "target" ? 0o644 : 0o777 + try #require(chmod(changedURL.path, externalMode) == 0) + #expect(throws: CoreError.self) { try transaction.commit() } + var actual = stat() + try #require(stat(changedURL.path, &actual) == 0) + #expect(actual.st_mode & 0o7777 == externalMode) + #expect(try Data(contentsOf: fixture.target) == targetBytes) + #expect(try Data(contentsOf: receiptURL) == receipt) + } + } + + @Test(arguments: [ + "journal.preparing.created.written", "journal.preparing.created.renamed", + "shared.0.reservation.created", + "shared.0.reservation.halfWritten", "shared.0.reservation.written", + "shared.0.reservation.published", "shared.0.reservation.synced", "shared.ready", + "stage.0.writeCreated", "publish.0.exchanged", "entry.0.applied", "entry.2.applied", + "journal.committed", "disposal.0.removed", "journal.finalized", + "shared.0.reservation.removed", "journal.unlinked", + ]) + func sharedCrashWindowsRecoverOneGeneration(_ point: String) throws { + let fixture = try SharedFixture() + try fixture.install() + let old = try Data(contentsOf: fixture.target) + let oldReceipt = try Data(contentsOf: fixture.receiptURL()) + let child = try stateTestProcess(root: fixture.root, arguments: ["shared-edit", point]) + defer { terminateProcess(child) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: child, root: fixture.root) + terminateProcess(child) + let observed = + point == "journal.preparing.created.written" + ? fixture.a.directory.appendingPathComponent("transaction.new") + : fixture.root.appendingPathComponent("last-journal") + let journal = try StateStore.decode( + Data(contentsOf: observed), + as: TransactionJournal.self) + let committed = journal.phase == .committed + if point != "shared.0.reservation.removed" && point != "journal.unlinked" + && point != "journal.preparing.created.renamed" + && point != "journal.preparing.created.written" + { + #expect(throws: CoreError.self) { + try fixture.b.withLock(footprint: [.claudeMCPLocal]) {} + } + } + do { try fixture.a.withLock {} } catch CoreError.transactionRecovered {} + #expect( + try Data(contentsOf: fixture.target) + == (committed ? Data("secret sibling; edited region".utf8) : old)) + if !committed { #expect(try Data(contentsOf: fixture.receiptURL()) == oldReceipt) } + try fixture.b.withLock(footprint: [.claudeMCPLocal]) { + let target = try fixture.b.nativeTarget(for: .claudeMCPLocal) + #expect(try fixture.b.materializationReceipt(for: target) != nil) + } + #expect( + !FileManager.default.fileExists( + atPath: fixture.a.directory.appendingPathComponent("transaction.json").path)) + #expect( + try DirectoryHandle(at: fixture.receiptURL().deletingLastPathComponent()).names().sorted() + == ["lock", "receipt"]) + } + + @Test(arguments: [false, true]) + func finalizedCleanupAndDiagnosisNeverReconstructOldData(_ rolledBack: Bool) throws { + let fixture = try SharedFixture() + try fixture.install() + let command = rolledBack ? "entry.0.applied" : "shared.0.reservation.removed" + let child = try stateTestProcess(root: fixture.root, arguments: ["shared-edit", command]) + defer { terminateProcess(child) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: child, root: fixture.root) + terminateProcess(child) + if rolledBack { + try FileManager.default.removeItem(at: fixture.root.appendingPathComponent("ready")) + let recovery = try stateTestProcess( + root: fixture.root, arguments: ["shared-recover", "shared.0.reservation.removed"]) + defer { terminateProcess(recovery) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: recovery, root: fixture.root) + terminateProcess(recovery) + } + let journal = try fixture.journal(fixture.a) + #expect(journal.finalized) + #expect(journal.phase == (rolledBack ? .rolledBack : .committed)) + try fixture.b.withLock(footprint: [.claudeMCPLocal]) { + let transaction = FileTransaction(store: fixture.b) + try transaction.replace( + fixture.target, with: .data(Data("secret sibling; later B generation".utf8))) + try transaction.commit() + } + try FileManager.default.removeItem(at: fixture.root.appendingPathComponent("old-data")) + let target = try FileSnapshot.read(at: fixture.target) + let receipt = try Data(contentsOf: fixture.receiptURL()) + let journalBytes = try Data( + contentsOf: fixture.a.directory.appendingPathComponent("transaction.json")) + try fixture.a.withReadLock( + onPendingRecovery: { + let diagnostic = FileTransaction.recoveryDiagnostic(store: fixture.a) + #expect(!diagnostic.requiresOwner) + #expect(diagnostic.message.contains(rolledBack ? "rolledBack" : "committed")) + }, { _ = Issue.record("finalized journal must remain pending for inspection") }) + #expect( + try Data(contentsOf: fixture.a.directory.appendingPathComponent("transaction.json")) + == journalBytes) + let outcome = TransactionOutcome() + outcome.journalID = journal.id + do { try fixture.a.withLock(outcome: outcome) {} } catch CoreError.transactionRecovered {} + #expect(outcome.disposition == (rolledBack ? .unchanged : .committed)) + #expect(try FileSnapshot.read(at: fixture.target) == target) + #expect(try Data(contentsOf: fixture.receiptURL()) == receipt) + #expect( + !FileManager.default.fileExists(atPath: fixture.root.appendingPathComponent("old-data").path)) + } + @Test func aliasedCallersWaitOnTheSamePhysicalLockBeforeScopeEntry() throws { + let fixture = try SharedFixture() + let holder = try stateTestProcess( + root: fixture.root, arguments: ["shared-lock", "shared.locked"]) + defer { terminateProcess(holder) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: holder, root: fixture.root) + let other = fixture.b.environment.projectDirectory + let waiter = try stateTestProcess( + root: other, + arguments: [ + "shared-lock", "shared.0.lock.contended", "--shared-config", + fixture.root.appendingPathComponent("config-alias").path, + ]) + defer { terminateProcess(waiter) } + try ProcessWait.marker(other.appendingPathComponent("ready"), child: waiter, root: other) + #expect(!FileManager.default.fileExists(atPath: fixture.b.directory.path)) + terminateProcess(waiter) + terminateProcess(holder) + try fixture.b.withLock(footprint: [.claudeMCPLocal, .claudeMCPUser]) { + let local = try fixture.b.nativeTarget(for: .claudeMCPLocal) + let user = try fixture.b.nativeTarget(for: .claudeMCPUser) + #expect(local.path == user.path) + #expect(local.url == user.url) + } + } + + @Test(arguments: [false, true]) + func aliasedWritersSerializeAcrossReplacementAndBothMakeProgress(_ reverse: Bool) throws { + let fixture = try SharedFixture() + try fixture.install() + let other = fixture.b.environment.projectDirectory + try FileManager.default.createDirectory( + at: other.appendingPathComponent("old-data"), withIntermediateDirectories: true) + try Data("ordinary before".utf8).write(to: other.appendingPathComponent("old-data/AGENTS.md")) + let firstRoot = reverse ? other : fixture.root + let secondRoot = reverse ? fixture.root : other + let firstConfig = reverse ? fixture.root.appendingPathComponent("config-alias") : fixture.config + let secondConfig = + reverse ? fixture.config : fixture.root.appendingPathComponent("config-alias") + let holder = try stateTestProcess( + root: firstRoot, + arguments: ["shared-edit", "publish.0.exchanged", "--shared-config", firstConfig.path]) + defer { terminateProcess(holder) } + try ProcessWait.marker( + firstRoot.appendingPathComponent("ready"), child: holder, root: firstRoot) + try ProcessWait.stopped(holder, root: firstRoot) + let published = try Data(contentsOf: fixture.target) + #expect(published == Data("secret sibling; edited region".utf8)) + let waiter = try stateTestProcess( + root: secondRoot, + arguments: ["shared-edit", "shared.0.lock.contended", "--shared-config", secondConfig.path]) + defer { terminateProcess(waiter) } + try ProcessWait.marker( + secondRoot.appendingPathComponent("ready"), child: waiter, root: secondRoot) + try ProcessWait.stopped(waiter, root: secondRoot) + #expect(try Data(contentsOf: fixture.target) == published) + try #require(kill(holder.processIdentifier, SIGCONT) == 0) + try ProcessWait.exit(holder, root: firstRoot) + #expect(holder.terminationStatus == 0) + let firstGeneration = try fixture.a.withReadLock(footprint: [.claudeMCPLocal]) { + let target = try fixture.a.nativeTarget(for: .claudeMCPLocal) + let receipt = try fixture.a.materializationReceipt(for: target) + return try #require(receipt).generation + } + try #require(kill(waiter.processIdentifier, SIGCONT) == 0) + try ProcessWait.exit(waiter, root: secondRoot) + #expect(waiter.terminationStatus == 0) + try fixture.a.withLock(footprint: [.claudeMCPLocal]) { + let target = try fixture.a.nativeTarget(for: .claudeMCPLocal) + let after = try fixture.a.preparePrivateMaterialization( + target, requiringReceiptForExistingTarget: true) + #expect(after.receiptGeneration != firstGeneration) + #expect(try Data(contentsOf: target.url) == published) + } + } + + @Test(arguments: [false, true]) + func pendingFootprintReadmitsBeforeCallbackOrProvider(_ multipleResources: Bool) throws { + let fixture = try SharedFixture() + try fixture.install() + let original = try Data(contentsOf: fixture.target) + let receipt = try Data(contentsOf: fixture.receiptURL()) + let marker = fixture.root.appendingPathComponent("ready") + let nextStop = fixture.root.appendingPathComponent("stop-at") + let journal = fixture.a.directory.appendingPathComponent("transaction.json") + let extra = multipleResources ? ["--native-routes", "claude.mcp.local,codex.mcp.user"] : [] + let holder = try stateTestProcess( + root: fixture.root, arguments: ["shared-readmission-writer", "shared.beforeJournal"] + extra) + defer { terminateProcess(holder) } + try ProcessWait.marker(marker, child: holder, root: fixture.root) + try ProcessWait.stopped(holder, root: fixture.root) + #expect(!FileManager.default.fileExists(atPath: journal.path)) + try FileManager.default.removeItem(at: marker) + let waiter = try stateTestProcess( + root: fixture.root, arguments: ["shared-admission-wait", "scope-contention"] + extra) + defer { terminateProcess(waiter) } + try ProcessWait.marker(marker, child: waiter, root: fixture.root) + try ProcessWait.stopped(waiter, root: fixture.root) + let contention = try String(contentsOf: marker, encoding: .utf8) + #expect(contention.hasPrefix("scope.lock.") && contention.hasSuffix(".contended")) + #expect(!FileManager.default.fileExists(atPath: journal.path)) + try FileManager.default.removeItem(at: marker) + try Data("entry.0.applied".utf8).write(to: nextStop) + try #require(kill(holder.processIdentifier, SIGCONT) == 0) + try ProcessWait.marker(marker, child: holder, root: fixture.root) + try ProcessWait.stopped(holder, root: fixture.root) + #expect(FileManager.default.fileExists(atPath: journal.path)) + #expect(try Data(contentsOf: fixture.target) != original) + terminateProcess(holder) + + let other = fixture.b.environment.projectDirectory + let lock = try fixture.receiptURL().deletingLastPathComponent().appendingPathComponent("lock") + let blocker = try stateTestProcess( + root: other, arguments: ["shared-hold-lock", "shared.rawLocked", "--lock-path", lock.path]) + defer { terminateProcess(blocker) } + try ProcessWait.marker(other.appendingPathComponent("ready"), child: blocker, root: other) + try ProcessWait.stopped(blocker, root: other) + try FileManager.default.removeItem(at: marker) + let pending = try fixture.journal(fixture.a) + let claude = try SharedResource(store: fixture.b, create: false).identity + let index = try #require(pending.footprint.firstIndex(of: claude)) + let sharedContention = "shared.\(index).lock.contended" + if multipleResources { #expect(pending.footprint.contains { $0.basename == "config.toml" }) } + try Data(sharedContention.utf8).write(to: nextStop) + try #require(kill(waiter.processIdentifier, SIGCONT) == 0) + try ProcessWait.marker(marker, child: waiter, root: fixture.root) + try ProcessWait.stopped(waiter, root: fixture.root) + #expect(try String(contentsOf: marker, encoding: .utf8) == sharedContention) + #expect(FileManager.default.fileExists(atPath: journal.path)) + #expect( + !FileManager.default.fileExists( + atPath: fixture.root.appendingPathComponent("admission-body").path)) + #expect( + !FileManager.default.fileExists( + atPath: fixture.root.appendingPathComponent("provider-called").path)) + try #require(kill(blocker.processIdentifier, SIGCONT) == 0) + try ProcessWait.exit(blocker, root: other) + #expect(blocker.terminationStatus == 0) + try #require(kill(waiter.processIdentifier, SIGCONT) == 0) + try ProcessWait.exit(waiter, root: fixture.root) + #expect(waiter.terminationStatus == 0) + #expect( + FileManager.default.fileExists( + atPath: fixture.root.appendingPathComponent("admission-recovered").path)) + #expect( + !FileManager.default.fileExists( + atPath: fixture.root.appendingPathComponent("admission-body").path)) + #expect( + !FileManager.default.fileExists( + atPath: fixture.root.appendingPathComponent("provider-called").path)) + #expect(!FileManager.default.fileExists(atPath: journal.path)) + #expect(try Data(contentsOf: fixture.target) == original) + #expect(try Data(contentsOf: fixture.receiptURL()) == receipt) + + let provider = SharedBindings() + var callbacks = 0 + try fixture.a.withLock(footprint: [.claudeMCPLocal]) { + callbacks += 1 + let target = try fixture.a.nativeTarget(for: .claudeMCPLocal) + let prepared = try fixture.a.preparePrivateMaterialization( + target, requiringReceiptForExistingTarget: true) + let transaction = FileTransaction(store: fixture.a) + try transaction.replacePrivate(prepared, bindings: ["secret"], provider: provider) { + try $0.value(for: "secret") + } + try transaction.commit() + } + #expect(callbacks == 1 && provider.calls == 1) + } + + @Test(arguments: ["shared-skill-recover", "shared-watch-recover", "shared-instruction-recover"]) + func ordinaryMutationEntrypointsRecoverPendingSharedFootprints(_ command: String) throws { + let fixture = try SharedFixture() + try fixture.install() + let old = try Data(contentsOf: fixture.target) + let oldReceipt = try Data(contentsOf: fixture.receiptURL()) + let child = try stateTestProcess( + root: fixture.root, arguments: ["shared-edit", "entry.0.applied"]) + defer { terminateProcess(child) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: child, root: fixture.root) + terminateProcess(child) + let before = try FileSnapshot.read(at: fixture.config) + #expect(throws: CoreError.self) { try fixture.a.loadResolved() } + #expect(try FileSnapshot.read(at: fixture.config) == before) + let recovery = try stateTestProcess(root: fixture.root, arguments: [command, "never"]) + defer { terminateProcess(recovery) } + try ProcessWait.exit(recovery, root: fixture.root) + #expect(recovery.terminationStatus == 0) + #expect(try Data(contentsOf: fixture.target) == old) + #expect(try Data(contentsOf: fixture.receiptURL()) == oldReceipt) + } + + @Test(arguments: [false, true]) + func wholeFileDeletionAndReceiptDeletionRecoverTogether(_ committed: Bool) throws { + let fixture = try SharedFixture() + try fixture.install() + let old = try Data(contentsOf: fixture.target) + let receiptURL = try fixture.receiptURL() + let oldReceipt = try Data(contentsOf: receiptURL) + let child = try stateTestProcess( + root: fixture.root, + arguments: ["shared-delete", committed ? "journal.committed" : "entry.0.applied"]) + defer { terminateProcess(child) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: child, root: fixture.root) + terminateProcess(child) + do { try fixture.a.withLock {} } catch CoreError.transactionRecovered {} + if committed { + #expect(!FileManager.default.fileExists(atPath: fixture.target.path)) + #expect(!FileManager.default.fileExists(atPath: receiptURL.path)) + } else { + #expect(try Data(contentsOf: fixture.target) == old) + #expect(try Data(contentsOf: receiptURL) == oldReceipt) + } + } + + @Test func finalizedOwnerCannotDeleteAnotherJournalsReservation() throws { + let fixture = try SharedFixture() + try fixture.install() + let child = try stateTestProcess( + root: fixture.root, arguments: ["shared-edit", "shared.0.reservation.removed"]) + defer { terminateProcess(child) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: child, root: fixture.root) + terminateProcess(child) + let other = fixture.b.environment.projectDirectory + let b = try stateTestProcess( + root: other, + arguments: ["shared-edit", "shared.ready", "--shared-config", fixture.config.path]) + defer { terminateProcess(b) } + try ProcessWait.marker(other.appendingPathComponent("ready"), child: b, root: other) + terminateProcess(b) + let reservationURL = try fixture.receiptURL().deletingLastPathComponent() + .appendingPathComponent("reservation") + let reservation = try Data(contentsOf: reservationURL) + let target = try FileSnapshot.read(at: fixture.target) + try FileManager.default.removeItem(at: fixture.root.appendingPathComponent("old-data")) + try fixture.a.withReadLock( + onPendingRecovery: { + #expect(!FileTransaction.recoveryDiagnostic(store: fixture.a).requiresOwner) + }, { _ = Issue.record("expected metadata cleanup diagnostic") }) + do { try fixture.a.withLock {} } catch CoreError.transactionRecovered {} + #expect(try Data(contentsOf: reservationURL) == reservation) + #expect(try FileSnapshot.read(at: fixture.target) == target) + do { try fixture.b.withLock {} } catch CoreError.transactionRecovered {} + } + + @Test func synchronousFailureRecoversWithinTheOriginalFootprint() throws { + let fixture = try SharedFixture() + try fixture.install() + let before = try Data(contentsOf: fixture.target) + let receipt = try Data(contentsOf: fixture.receiptURL()) + var callbacks = 0 + try fixture.a.withLock(footprint: [.claudeMCPLocal]) { + callbacks += 1 + let transaction = FileTransaction(store: fixture.a) { point in + if point == "publish.0.exchanged" { throw CoreError.invalidState("injected failure") } + } + try transaction.replace(fixture.target, with: .data(Data("secret sibling; change".utf8))) + #expect(throws: CoreError.self) { try transaction.commit() } + #expect(try TransactionLockContext.current(fixture.a).requiredResource().reservation() == nil) + let unsupported = FileTransaction(store: fixture.a) + var producers = 0 + #expect(throws: CoreError.self) { + try unsupported.replace( + fixture.target, + with: .prepared { url in + producers += 1 + return url + }) + } + #expect(producers == 0) + #expect(throws: CoreError.self) { + try fixture.b.withLock(footprint: [.claudeMCPUser]) { callbacks += 1 } + } + } + #expect(callbacks == 1) + #expect(try Data(contentsOf: fixture.target) == before) + #expect(try Data(contentsOf: fixture.receiptURL()) == receipt) + } + + @Test(arguments: [ + "collision", "symlink", "unknown-slot", "malformed-reservation", "missing-ready-reservation", + "unsafe-partial", + ]) + func unsafeCoordinationMetadataIsRetainedAndRefused(_ shape: String) throws { + let fixture = try SharedFixture() + if shape == "collision" || shape == "symlink" { + let url = fixture.config.appendingPathComponent(SharedResource.metadataName) + if shape == "collision" { + try Data().write(to: url) + } else { + try FileManager.default.createSymbolicLink( + at: url, withDestinationURL: fixture.b.environment.projectDirectory) + } + } else { + try fixture.install() + let metadata = try DirectoryHandle(at: fixture.receiptURL().deletingLastPathComponent()) + if shape == "missing-ready-reservation" || shape == "unsafe-partial" { + let child = try stateTestProcess( + root: fixture.root, + arguments: [ + "shared-edit", + shape == "unsafe-partial" ? "shared.0.reservation.halfWritten" : "shared.ready", + ]) + defer { terminateProcess(child) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: child, root: fixture.root) + terminateProcess(child) + if shape == "unsafe-partial" { + let journal = try fixture.journal(fixture.a) + let slot = metadata.url.appendingPathComponent(SharedResource.temporaryName(journal.id)) + try #require(chmod(slot.path, 0o644) == 0) + } else { + try metadata.remove("reservation") + } + } else { + let name = shape == "unknown-slot" ? "reservation-unknown.new" : "reservation" + let file = try metadata.createPrivateFile(name) + try file.write(Data("incomplete".utf8)) + } + } + let before = try FileSnapshot.read(at: fixture.config) + var callbacks = 0 + #expect(throws: CoreError.self) { + try fixture.a.withLock(footprint: [.claudeMCPLocal]) { callbacks += 1 } + } + #expect(callbacks == 0) + #expect(try FileSnapshot.read(at: fixture.config) == before) + } + + @Test func intentBeforeReservationCannotUndoALaterWritersGeneration() throws { + let fixture = try SharedFixture() + try fixture.install() + let child = try stateTestProcess( + root: fixture.root, arguments: ["shared-edit", "journal.preparing.created.renamed"]) + defer { terminateProcess(child) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: child, root: fixture.root) + terminateProcess(child) + try fixture.b.withLock(footprint: [.claudeMCPLocal]) { + let transaction = FileTransaction(store: fixture.b) + try transaction.replace( + fixture.target, with: .data(Data("secret sibling; later region".utf8))) + try transaction.commit() + } + let before = try FileSnapshot.read(at: fixture.target) + let receipt = try Data(contentsOf: fixture.receiptURL()) + let scope = try FileSnapshot.read(at: fixture.a.directory) + let config = try FileSnapshot.read(at: fixture.config) + try fixture.a.withReadLock( + onPendingRecovery: { + let diagnostic = FileTransaction.recoveryDiagnostic(store: fixture.a) + #expect(!diagnostic.requiresOwner) + #expect(diagnostic.message == TransactionRecoveryDiagnostic.pendingMessage) + }, { _ = Issue.record("expected pending reservation intent") }) + #expect(try FileSnapshot.read(at: fixture.a.directory) == scope) + #expect(try FileSnapshot.read(at: fixture.config) == config) + do { try fixture.a.withLock {} } catch CoreError.transactionRecovered {} + #expect(try FileSnapshot.read(at: fixture.target) == before) + #expect(try Data(contentsOf: fixture.receiptURL()) == receipt) + } + + @Test(arguments: [ + "journal.rolledBack.finalized.written", "journal.rolledBack.finalized.renamed", + "journal.finalized", + ]) + func interruptedRecoveryOfALoneReservationIntentIsRepeatable(_ point: String) throws { + let fixture = try SharedFixture() + try fixture.install() + let before = try Data(contentsOf: fixture.target) + let receipt = try Data(contentsOf: fixture.receiptURL()) + let child = try stateTestProcess( + root: fixture.root, arguments: ["shared-edit", "journal.preparing.created.written"]) + defer { terminateProcess(child) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: child, root: fixture.root) + terminateProcess(child) + try FileManager.default.removeItem(at: fixture.root.appendingPathComponent("ready")) + let recovery = try stateTestProcess(root: fixture.root, arguments: ["shared-recover", point]) + defer { terminateProcess(recovery) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: recovery, root: fixture.root) + terminateProcess(recovery) + try fixture.a.withReadLock( + onPendingRecovery: { + #expect(!FileTransaction.recoveryDiagnostic(store: fixture.a).requiresOwner) + }, { _ = Issue.record("expected pending cleanup") }) + do { try fixture.a.withLock {} } catch CoreError.transactionRecovered {} + #expect(try Data(contentsOf: fixture.target) == before) + #expect(try Data(contentsOf: fixture.receiptURL()) == receipt) + } + + @Test func authorizationAliasChangesInvalidateTheHeldPhysicalTarget() throws { + let fixture = try SharedFixture() + try fixture.install() + let before = try FileSnapshot.read(at: fixture.target) + let receipt = try Data(contentsOf: fixture.receiptURL()) + let other = fixture.root.appendingPathComponent("other-config") + try FileManager.default.createDirectory(at: other, withIntermediateDirectories: true) + try fixture.b.withLock(footprint: [.claudeMCPLocal]) { + let alias = fixture.root.appendingPathComponent("config-alias") + try FileManager.default.removeItem(at: alias) + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: other) + #expect(throws: CoreError.self) { try fixture.b.nativeTarget(for: .claudeMCPLocal) } + let transaction = FileTransaction(store: fixture.b) + #expect(throws: CoreError.self) { + try transaction.replace(other.appendingPathComponent(".claude.json"), with: .data(Data())) + } + } + #expect(try FileSnapshot.read(at: fixture.target) == before) + #expect(try Data(contentsOf: fixture.receiptURL()) == receipt) + #expect(try FileManager.default.contentsOfDirectory(atPath: other.path).isEmpty) + } + + @Test(arguments: ["footprint", "reservationsReady", "finalized", "metadata-target"]) + func missingCoordinationEvidenceAndForgedMetadataTargetsCannotReplay(_ field: String) throws { + let fixture = try SharedFixture() + try fixture.install() + let child = try stateTestProcess( + root: fixture.root, arguments: ["shared-edit", "shared.ready"]) + defer { terminateProcess(child) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: child, root: fixture.root) + terminateProcess(child) + let url = fixture.a.directory.appendingPathComponent("transaction.json") + var value = try #require( + JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? [String: Any]) + if field == "metadata-target" { + var entries = try #require(value["entries"] as? [[String: Any]]) + let index = try #require( + entries.firstIndex { + ($0["path"] as? String)?.hasPrefix(NativeTargetRoute.metadataRoot) == true + }) + entries[index]["path"] = NativeTargetRoute.metadataRoot + "/lock" + value["entries"] = entries + } else { + value.removeValue(forKey: field) + } + let bytes = try JSONSerialization.data(withJSONObject: value, options: [.sortedKeys]) + try bytes.write(to: url) + let target = try FileSnapshot.read(at: fixture.target) + let metadata = try FileSnapshot.read(at: fixture.receiptURL().deletingLastPathComponent()) + try fixture.a.withReadLock( + onPendingRecovery: { + #expect(FileTransaction.recoveryDiagnostic(store: fixture.a).requiresOwner) + }, { _ = Issue.record("invalid evidence must block inspection") }) + #expect(throws: CoreError.self) { try fixture.a.withLock {} } + #expect(try Data(contentsOf: url) == bytes) + #expect(try FileSnapshot.read(at: fixture.target) == target) + #expect(try FileSnapshot.read(at: fixture.receiptURL().deletingLastPathComponent()) == metadata) + } + + @Test func aForeignReservationReportsItsOwnerWithoutOpeningTheOwnerScope() throws { + let fixture = try SharedFixture() + try fixture.install() + let child = try stateTestProcess( + root: fixture.root, arguments: ["shared-edit", "shared.ready"]) + defer { terminateProcess(child) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: child, root: fixture.root) + terminateProcess(child) + let journal = try fixture.journal(fixture.a) + var message = "" + do { try fixture.b.withLock(footprint: [.claudeMCPLocal]) {} } catch CoreError.recoveryPending( + let value) + { message = value } + #expect(message.contains(fixture.a.directory.path)) + #expect(message.contains(journal.id.uuidString)) + #expect(!message.contains("secret sibling")) + #expect(try fixture.journal(fixture.a).id == journal.id) + } + + @Test func orphanedForeignReservationRemainsPending() throws { + let fixture = try SharedFixture() + try fixture.install() + let child = try stateTestProcess( + root: fixture.root, arguments: ["shared-edit", "shared.ready"]) + defer { terminateProcess(child) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: child, root: fixture.root) + terminateProcess(child) + let journal = try fixture.journal(fixture.a) + let journalURL = fixture.a.directory.appendingPathComponent("transaction.json") + let reservationURL = try fixture.receiptURL().deletingLastPathComponent() + .appendingPathComponent("reservation") + let reservation = try Data(contentsOf: reservationURL) + let target = try FileSnapshot.read(at: fixture.target) + try FileManager.default.removeItem(at: journalURL) + var calls = 0 + var message = "" + do { + try fixture.b.withLock(footprint: [.claudeMCPLocal]) { calls += 1 } + } catch CoreError.recoveryPending(let value) { + message = value + } + #expect(message.contains(fixture.a.directory.path)) + #expect(message.contains(journal.id.uuidString)) + #expect(calls == 0) + #expect(try Data(contentsOf: reservationURL) == reservation) + #expect(try FileSnapshot.read(at: fixture.target) == target) + #expect(!FileManager.default.fileExists(atPath: journalURL.path)) + } + + @Test(arguments: [false, true], [false, true]) + func readOnlyAdmissionRechecksSuccessfulAndFailedUnlockedSharedReads( + _ metadataExists: Bool, _ throwFirst: Bool + ) throws { + let fixture = try SharedFixture() + if metadataExists { _ = try SharedResource(store: fixture.a, create: true) } + let writer = fixture.a + var attempts = 0 + let result = try fixture.b.withReadLock(footprint: [.claudeMCPLocal]) { + attempts += 1 + let target = try fixture.b.nativeTarget(for: .claudeMCPLocal) + let receipt = try fixture.b.materializationReceipt(for: target) + if attempts == 1 { + #expect(receipt == nil) + let finished = DispatchSemaphore(value: 0) + Thread.detachNewThread { + defer { finished.signal() } + do { + try writer.withLock(footprint: [.claudeMCPLocal]) { + let target = try writer.nativeTarget(for: .claudeMCPLocal) + let transaction = FileTransaction(store: writer) + try transaction.replacePrivate( + try writer.preparePrivateMaterialization(target), provider: SharedBindings() + ) { _ in + Data("secret sibling; concurrently installed".utf8) + } + try transaction.commit() + } + } catch { Issue.record(error) } + } + try #require(finished.wait(timeout: .now() + 10) == .success) + if throwFirst { throw CoreError.invalidState("discarded unlocked inspection") } + } + return receipt != nil + } + #expect(attempts == 2) + #expect(result) + } + + @Test func aSharedTransactionCannotEscapeItsHeldContext() throws { + let fixture = try SharedFixture() + try fixture.install() + let before = try FileSnapshot.read(at: fixture.target) + let provider = SharedBindings() + var escaped: FileTransaction? + let missingRoot = AgentRegistry.installSkillsDirectory( + for: .claudeCode, scope: .project, environment: fixture.a.environment) + #expect(!FileManager.default.fileExists(atPath: missingRoot.path)) + try fixture.a.withLock(footprint: [.claudeMCPLocal]) { + let target = try fixture.a.nativeTarget(for: .claudeMCPLocal) + let transaction = FileTransaction(store: fixture.a) + try transaction.replace(missingRoot.appendingPathComponent("escaped"), with: .data(Data())) + try transaction.replacePrivate( + try fixture.a.preparePrivateMaterialization(target), bindings: ["secret"], + provider: provider + ) { try $0.value(for: "secret") } + escaped = transaction + } + #expect(throws: CoreError.self) { try escaped?.commit() } + #expect(provider.calls == 0) + #expect(!FileManager.default.fileExists(atPath: missingRoot.path)) + #expect(try FileSnapshot.read(at: fixture.target) == before) + #expect( + !FileManager.default.fileExists( + atPath: fixture.a.directory.appendingPathComponent("transaction.json").path)) + } + + @Test func recoveryCannotCreateANewCoordinationDomainFromAChangedRuntime() throws { + let fixture = try SharedFixture() + try fixture.install() + let child = try stateTestProcess( + root: fixture.root, arguments: ["shared-edit", "shared.ready"]) + defer { terminateProcess(child) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: child, root: fixture.root) + terminateProcess(child) + let wrong = fixture.root.appendingPathComponent("missing-config") + var environment = fixture.a.environment + environment.environment["CLAUDE_CONFIG_DIR"] = wrong.path + let relocated = StateStore(scope: .project, environment: environment) + let journal = try Data( + contentsOf: fixture.a.directory.appendingPathComponent("transaction.json")) + let target = try FileSnapshot.read(at: fixture.target) + #expect { try relocated.withLock {} } throws: { error in + guard case CoreError.invalidState(let message) = error else { return false } + return message.contains("original registered runtime context") + } + #expect(!FileManager.default.fileExists(atPath: wrong.path)) + #expect( + try Data(contentsOf: fixture.a.directory.appendingPathComponent("transaction.json")) + == journal) + #expect(try FileSnapshot.read(at: fixture.target) == target) + } + + @Test func finalizedCleanupRequiresAConsistentTerminalOutcome() throws { + let fixture = try SharedFixture() + try fixture.install() + let child = try stateTestProcess( + root: fixture.root, arguments: ["shared-edit", "shared.0.reservation.removed"]) + defer { terminateProcess(child) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: child, root: fixture.root) + terminateProcess(child) + var journal = try fixture.journal(fixture.a) + journal.entries[0].progress = .publishing + let bytes = try StateStore.encode(journal) + let url = fixture.a.directory.appendingPathComponent("transaction.json") + try bytes.write(to: url) + let target = try FileSnapshot.read(at: fixture.target) + try fixture.a.withReadLock( + onPendingRecovery: { + #expect(FileTransaction.recoveryDiagnostic(store: fixture.a).requiresOwner) + }, { _ = Issue.record("inconsistent terminal outcome must block inspection") }) + #expect(throws: CoreError.self) { try fixture.a.withLock {} } + #expect(try Data(contentsOf: url) == bytes) + #expect(try FileSnapshot.read(at: fixture.target) == target) + } + + @Test(arguments: ["scope", "lock", "coordination-lock"]) + func replacementOfTheHeldScopeOrLockStopsBeforeBindings(_ shape: String) throws { + let fixture = try SharedFixture() + try fixture.install() + let before = try FileSnapshot.read(at: fixture.target) + let provider = SharedBindings() + try fixture.a.withLock(footprint: [.claudeMCPLocal]) { + let target = try fixture.a.nativeTarget(for: .claudeMCPLocal) + let transaction = FileTransaction(store: fixture.a) + try transaction.replacePrivate( + try fixture.a.preparePrivateMaterialization(target), bindings: ["secret"], + provider: provider + ) { + try $0.value(for: "secret") + } + let original: URL + if shape == "scope" { + original = fixture.a.directory + } else if shape == "lock" { + original = fixture.a.directory.appendingPathComponent(".agents.lock") + } else { + original = try TransactionLockContext.current(fixture.a).requiredResource().metadata!.url + .appendingPathComponent("lock") + } + let retained = fixture.root.appendingPathComponent("retained-scope-lock") + try FileManager.default.moveItem(at: original, to: retained) + defer { + try? FileManager.default.removeItem(at: original) + try? FileManager.default.moveItem(at: retained, to: original) + } + if shape == "scope" { + try FileManager.default.createDirectory(at: original, withIntermediateDirectories: false) + } else { + try Data().write(to: original) + try #require(chmod(original.path, 0o600) == 0) + } + #expect(throws: CoreError.self) { try transaction.commit() } + #expect(provider.calls == 0) + } + #expect(try FileSnapshot.read(at: fixture.target) == before) + } + + @Test func aSharedLockReplacedDuringStagingStopsBeforeTheProvider() throws { + let fixture = try SharedFixture() + try fixture.install() + let before = try FileSnapshot.read(at: fixture.target) + let provider = SharedBindings() + try fixture.a.withLock(footprint: [.claudeMCPLocal]) { + let target = try fixture.a.nativeTarget(for: .claudeMCPLocal) + let metadata = try #require( + TransactionLockContext.current(fixture.a).requiredResource().metadata) + let lock = metadata.url.appendingPathComponent("lock") + let retained = fixture.root.appendingPathComponent("retained-coordination-lock") + var replaced = false + let transaction = FileTransaction(store: fixture.a) { point in + if point == "stage.0.writeCreated" { + try FileManager.default.moveItem(at: lock, to: retained) + try Data().write(to: lock) + try #require(chmod(lock.path, 0o600) == 0) + replaced = true + } + } + try transaction.replacePrivate( + try fixture.a.preparePrivateMaterialization(target), bindings: ["secret"], + provider: provider + ) { + try $0.value(for: "secret") + } + #expect(throws: CoreError.self) { try transaction.commit() } + #expect(replaced && provider.calls == 0) + try FileManager.default.removeItem(at: lock) + try FileManager.default.moveItem(at: retained, to: lock) + #expect(try FileTransaction.recover(store: fixture.a)) + } + #expect(try FileSnapshot.read(at: fixture.target) == before) + } + + @Test func readOnlyFootprintsCreateNoMetadataOrScopeLock() throws { + let fixture = try SharedFixture() + let before = try FileSnapshot.read(at: fixture.config) + try fixture.b.withReadLock(footprint: [.claudeMCPLocal]) { + let target = try fixture.b.nativeTarget(for: .claudeMCPLocal) + #expect(try fixture.b.materializationReceipt(for: target) == nil) + } + #expect(try FileSnapshot.read(at: fixture.config) == before) + #expect(!FileManager.default.fileExists(atPath: fixture.b.directory.path)) + } + +} + +private final class SharedBindings: RuntimeBindingProvider { + private let count = Mutex(0) + var calls: Int { count.withLock { $0 } } + func value(for binding: String, environment: RuntimeEnvironment) throws -> Data { + count.withLock { $0 += 1 } + return Data("secret sibling; initial region".utf8) + } +} + +private final class SharedFixture { + let base: TransactionFixture + var root: URL { base.root } + let a: StateStore + let b: StateStore + let user: StateStore + let config: URL + var target: URL { config.appendingPathComponent(".claude.json") } + + init() throws { + base = try TransactionFixture() + config = base.root.appendingPathComponent("configured-claude") + let other = base.root.appendingPathComponent("B") + let home = base.root.appendingPathComponent("other-home") + for url in [config, other, home, base.root.appendingPathComponent("old-data")] { + try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) + } + try Data("ordinary before".utf8).write( + to: base.root.appendingPathComponent("old-data/AGENTS.md")) + let alias = base.root.appendingPathComponent("config-alias") + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: config) + a = StateStore( + scope: .project, + environment: RuntimeEnvironment( + projectDirectory: base.root, + homeDirectory: base.root.appendingPathComponent("home"), + environment: ["CLAUDE_CONFIG_DIR": config.path])) + b = StateStore( + scope: .project, + environment: RuntimeEnvironment( + projectDirectory: other, + homeDirectory: home, environment: ["CLAUDE_CONFIG_DIR": alias.path])) + user = StateStore( + scope: .user, + environment: RuntimeEnvironment( + projectDirectory: other, + homeDirectory: config, environment: [:])) + } + + func install() throws { + try a.withLock(footprint: [.claudeMCPLocal]) { + let target = try a.nativeTarget(for: .claudeMCPLocal) + let transaction = FileTransaction(store: a) + try transaction.replacePrivate( + try a.preparePrivateMaterialization(target), provider: SharedBindings() + ) { _ in + Data("secret sibling; initial region".utf8) + } + try transaction.commit() + } + } + + func identity(_ store: StateStore) throws -> SharedResourceIdentity { + try store.withReadLock(footprint: [.claudeMCPUser]) { + try TransactionLockContext.current(store).requiredResource().identity + } + } + + func receiptURL() throws -> URL { + let identity = try SharedResource(store: a, create: false).identity + return config.appendingPathComponent(SharedResource.metadataName).appendingPathComponent( + identity.directoryName + ).appendingPathComponent("receipt") + } + + func journal(_ store: StateStore) throws -> TransactionJournal { + try StateStore.decode( + Data(contentsOf: store.directory.appendingPathComponent("transaction.json")), + as: TransactionJournal.self) + } +} diff --git a/Tests/AgentsCoreTests/SourceAccessSettingsEditorTests.swift b/Tests/AgentsCoreTests/SourceAccessSettingsEditorTests.swift new file mode 100644 index 0000000..04fc07e --- /dev/null +++ b/Tests/AgentsCoreTests/SourceAccessSettingsEditorTests.swift @@ -0,0 +1,195 @@ +import AgentsCore +import Foundation +import Testing + +struct SourceAccessSettingsEditorTests { + private static let direct = Data("version: 1\negress: directAllowed\n".utf8) + private static let proxy = Data("version: 1\negress: proxyOnly\n".utf8) + + @Test func absentReadRepairAndResetUseTheSameUserPath() throws { + let home = try temporaryDirectory() + defer { removeTemporaryDirectory(home) } + let environment = RuntimeEnvironment(environment: ["HOME": home.path]) + let empty = try SourceAccessSettingsEditor(environment: environment) + #expect(empty.url.path == home.appendingPathComponent(".agents/source-access.yaml").path) + #expect(empty.original == nil) + #expect(try empty.inspect() == nil) + try empty.save(empty.preview(nil)) + #expect(!FileManager.default.fileExists(atPath: empty.url.deletingLastPathComponent().path)) + + let proposal = try empty.preview(Self.proxy) + #expect(proposal.profile?.egress == .proxyOnly) + #expect(proposal.hasChanges) + #expect(!FileManager.default.fileExists(atPath: empty.url.path)) + try empty.save(proposal) + #expect(try Data(contentsOf: empty.url) == Self.proxy) + let attributes = try FileManager.default.attributesOfItem(atPath: empty.url.path) + #expect((attributes[.posixPermissions] as? NSNumber)?.intValue == 0o600) + + let malformed = Data("version: 1\negress: typo\n".utf8) + try malformed.write(to: empty.url, options: .atomic) + let broken = try SourceAccessSettingsEditor(environment: environment) + #expect(broken.original == malformed) + #expect(throws: SourceAccessSettingsError.self) { try broken.inspect() } + try broken.save(broken.preview(Self.direct)) + let repaired = try SourceAccessSettingsEditor(environment: environment) + #expect(try repaired.inspect()?.egress == .directAllowed) + #expect(try !repaired.preview(Self.direct).hasChanges) + + let oversized = Data(repeating: 0x20, count: 65_537) + try oversized.write(to: empty.url, options: .atomic) + let oversizedEditor = try SourceAccessSettingsEditor(environment: environment) + #expect(throws: SourceAccessSettingsError.self) { try oversizedEditor.inspect() } + let reset = try oversizedEditor.preview(nil) + #expect(reset.hasChanges) + try oversizedEditor.save(reset) + #expect(!FileManager.default.fileExists(atPath: empty.url.path)) + } + + @Test func simultaneousPreviewsCanOnlyPublishOneGeneration() async throws { + let home = try temporaryDirectory() + defer { removeTemporaryDirectory(home) } + let environment = RuntimeEnvironment(environment: ["HOME": home.path]) + let first = try SourceAccessSettingsEditor(environment: environment) + let second = try SourceAccessSettingsEditor(environment: environment) + let direct = try first.preview(Self.direct) + let proxy = try second.preview(Self.proxy) + let results = await withTaskGroup(of: Bool.self, returning: [Bool].self) { writers in + for (editor, proposal) in [(first, direct), (second, proxy)] { + writers.addTask { + do { + try editor.save(proposal) + return true + } catch SourceAccessSettingsError.changed { + return false + } catch { + Issue.record("Unexpected save error: \(error)") + return false + } + } + } + return await writers.reduce(into: []) { $0.append($1) } + } + #expect(results.filter { $0 }.count == 1) + let saved = try Data(contentsOf: first.url) + #expect(saved == Self.direct || saved == Self.proxy) + let reopened = try SourceAccessSettingsEditor(environment: environment) + let reset = try reopened.preview(nil) + + // Replacing the inode with identical bytes still invalidates a displayed edit. + try saved.write(to: first.url, options: .atomic) + #expect(throws: SourceAccessSettingsError.changed(first.url)) { + try reopened.save(reset) + } + #expect(try Data(contentsOf: first.url) == saved) + } + + @Test(arguments: [ + "profile link", "home link", "directory link", "hard link", "writable", + "writable directory", + ]) + func unsafeFileAndAncestryRefuseReadingAndSaving(_ shape: String) throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let realHome = root.appendingPathComponent("home") + let realDirectory = realHome.appendingPathComponent(".agents") + try FileManager.default.createDirectory(at: realHome, withIntermediateDirectories: false) + let external = root.appendingPathComponent("profile") + try Self.direct.write(to: external) + var home = realHome + if shape == "home link" { + home = root.appendingPathComponent("redirected-home") + try FileManager.default.createSymbolicLink(at: home, withDestinationURL: realHome) + } + if shape == "directory link" { + try FileManager.default.createSymbolicLink(at: realDirectory, withDestinationURL: root) + } else { + try FileManager.default.createDirectory(at: realDirectory, withIntermediateDirectories: false) + let file = realDirectory.appendingPathComponent("source-access.yaml") + if shape == "profile link" { + try FileManager.default.createSymbolicLink(at: file, withDestinationURL: external) + } else if shape == "hard link" { + try FileManager.default.linkItem(at: external, to: file) + } else { + try Self.direct.write(to: file) + if shape == "writable" { + try FileManager.default.setAttributes([.posixPermissions: 0o666], ofItemAtPath: file.path) + } else if shape == "writable directory" { + try FileManager.default.setAttributes( + [.posixPermissions: 0o777], ofItemAtPath: realDirectory.path) + } + } + } + let environment = RuntimeEnvironment(environment: ["HOME": home.path]) + #expect( + throws: SourceAccessSettingsError.unsafeLocation( + SourceAccessSettingsEditor.settingsURL(environment: environment)) + ) { + try SourceAccessSettingsEditor(environment: environment) + } + #expect(try Data(contentsOf: external) == Self.direct) + } + + @Test(arguments: [ + "", + "version: 1", + "version: 1\negress: auto", + "version: 1\negress: null", + "version: 1\negress: proxyOnly\negress: directAllowed", + "version: 1\negress: proxyOnly\n---\nversion: 1\negress: directAllowed", + "version: 1\negress: proxyOnly\nmirrors: [unexpected]", + "version: 1\negress: proxyOnly\nmirrors: [{source: {host: github.com}, base: 'http://mirror.invalid', flavor: github}]", + "version: 1\negress: proxyOnly\nmirrors: [{source: {host: github.com}, base: 'https://mirror.invalid/%2e%2e', flavor: github}]", + "version: 1\negress: proxyOnly\nmirrors: [{source: {host: github.com}, base: 'https://mirror.invalid', flavor: artifactory}]", + "version: 1\negress: directAllowed\nproviders: [{host: code.invalid, port: 65536, provider: github}]", + "version: 1\negress: directAllowed\nproviders: [{host: code.invalid, provider: gitea}]", + "version: 1\negress: directAllowed\nproviders: [{host: CODE.invalid, provider: github}, {host: code.invalid, port: 443, provider: gitlab}]", + "version: 1\negress: directAllowed\ncredentials: [{route: direct, host: github.com, token: SYNTHETIC_VALUE}]", + "version: 1\negress: directAllowed\ncredentials: [{route: direct, host: github.com, environmentVariable: '$PACKAGE_TOKEN'}]", + "version: 1\negress: directAllowed\ncredentials: [{route: direct, host: github.com, path: /team/repo.git, environmentVariable: FIRST}, {route: direct, host: github.com, path: /team/repo, environmentVariable: SECOND}]", + "version: 1\negress: directAllowed\ncredentials: [{route: direct, host: github.com, environmentVariable: PACKAGE_TOKEN, validationEndpoint: 'https://different.invalid/user'}]", + ]) + func ambiguousOrUnsupportedMetadataIsRejected(_ document: String) { + #expect(throws: SourceAccessSettingsError.self) { + try SourceAccessProfile.parse(Data(document.utf8)) + } + } + + @Test func inspectionExposesOnlyDeclaredMetadata() throws { + let profile = try SourceAccessProfile.parse( + Data( + """ + version: 1 + egress: directAllowed + providers: + - host: Code.INVALID + port: 8443 + provider: gitlab + mirrors: + - source: {host: code.invalid, port: 8443} + base: https://archives.invalid:9443/api-base + flavor: gitlab + supportsQualifiedGitLabRefs: true + requiresExactArchiveBytes: true + credentials: + - route: direct + host: code.invalid + port: 8443 + path: /org/repo.git + environmentVariable: SYNTHETIC_PACKAGE_TOKEN + exportable: true + validationEndpoint: https://code.invalid:8443/api/v4/user + """.utf8)) + let authority = try SourceAuthority(host: "code.invalid", port: 8443) + #expect(profile.providers.first?.authority == authority) + #expect(profile.providers.first?.provider == .gitlab) + #expect(profile.mirrors.first?.source == authority) + #expect(profile.mirrors.first?.supportsQualifiedGitLabRefs == true) + #expect(profile.mirrors.first?.requiresExactArchiveBytes == true) + let credential = try #require(profile.credentials.first) + #expect(credential.authority == authority) + #expect(credential.path == "/org/repo.git") + #expect(credential.environmentVariable == "SYNTHETIC_PACKAGE_TOKEN") + #expect(credential.exportable) + } +} diff --git a/Tests/AgentsCoreTests/SourceArgumentTests.swift b/Tests/AgentsCoreTests/SourceArgumentTests.swift index dbb33d8..9581134 100644 --- a/Tests/AgentsCoreTests/SourceArgumentTests.swift +++ b/Tests/AgentsCoreTests/SourceArgumentTests.swift @@ -7,7 +7,7 @@ import Testing struct SourceArgumentTests { private let environment = RuntimeEnvironment( projectDirectory: URL(fileURLWithPath: "/project"), - homeDirectory: URL(fileURLWithPath: "/home/test"), environment: [:]) + homeDirectory: URL(fileURLWithPath: "/home/test"), environment: [:], sourceAccess: .init()) @Test( arguments: zip( diff --git a/Tests/AgentsCoreTests/SourceCacheTests.swift b/Tests/AgentsCoreTests/SourceCacheTests.swift index f0122e9..9617be4 100644 --- a/Tests/AgentsCoreTests/SourceCacheTests.swift +++ b/Tests/AgentsCoreTests/SourceCacheTests.swift @@ -1,4 +1,6 @@ +import AgentsManifest import Foundation +import StateTestSupport import Testing @testable import AgentsCore @@ -37,15 +39,12 @@ struct SourceCacheTests { #expect( !FileManager.default.fileExists( atPath: cache.materializedURL(sourceID: id, revision: second.revision).path)) - let section = LockedSection( - name: "rules", source: id, revision: first.revision, path: "content", - hash: "sha256:" + String(repeating: "a", count: 64)) - try cache.prune( - referencedBy: ResolvedState( - sources: [id: locked], - instructions: LockedInstructions(chatgpt: ["prompt": LockedPrompt(sections: [section])]))) + var references = RetentionReferences() + references.git.insert(.init(source: id, revision: first.revision)) + references.sourceLocations[id] = repo.path + try prune(cache, references: references) #expect(FileManager.default.fileExists(atPath: tree.path)) - try cache.prune(referencedBy: ResolvedState()) + try prune(cache, references: RetentionReferences()) #expect(!FileManager.default.fileExists(atPath: tree.path)) } @@ -169,14 +168,10 @@ extension SourceCacheTests { try FileManager.default.createDirectory( at: link.deletingLastPathComponent(), withIntermediateDirectories: true) try FileManager.default.createSymbolicLink(at: link, withDestinationURL: external) - let state = ResolvedState( - sources: [id: LockedSource(kind: .local)], - skills: [ - "demo": LockedSkill( - source: id, revision: revision, path: ".", - hash: "sha256:" + String(repeating: "b", count: 64), installs: ["codex": .link]) - ]) - #expect(throws: CoreError.self) { try cache.prune(referencedBy: state) } + var references = RetentionReferences() + references.git.insert(.init(source: id, revision: revision)) + references.sourceLocations[id] = String(id.dropFirst(6)) + #expect(throws: CoreError.self) { try prune(cache, references: references) } #expect( try String(contentsOf: external.appendingPathComponent("unrelated"), encoding: .utf8) == "keep") @@ -193,13 +188,17 @@ extension SourceCacheTests { try FileManager.default.createDirectory( at: content.appendingPathComponent("nested"), withIntermediateDirectories: true) try Data("live".utf8).write(to: content.appendingPathComponent("nested/SKILL.md")) - let id = "local:" + content.path - let state = ResolvedState( - sources: [id: LockedSource(kind: .local)], - skills: ["live": LockedSkill(source: id, path: "nested", installs: ["codex": .edit])]) - try SourceCache(store: store).prune(referencedBy: state) + var references = RetentionReferences() + references.live = [content.appendingPathComponent("nested")] + try prune(SourceCache(store: store), references: references) #expect( FileManager.default.fileExists(atPath: content.appendingPathComponent("nested/SKILL.md").path) ) } + private func prune(_ cache: SourceCache, references: RetentionReferences) throws { + let transaction = FileTransaction(store: cache.store) + try cache.prune(references: references, transaction: transaction) + try transaction.commit() + } + } diff --git a/Tests/AgentsCoreTests/SourceRegressionTests.swift b/Tests/AgentsCoreTests/SourceRegressionTests.swift index 4f35ff3..bb40859 100644 --- a/Tests/AgentsCoreTests/SourceRegressionTests.swift +++ b/Tests/AgentsCoreTests/SourceRegressionTests.swift @@ -1,3 +1,4 @@ +import CPlatform import Foundation import Testing @@ -5,6 +6,98 @@ import Testing @Suite("Source regressions") struct SourceRegressionTests { + @Test func localSnapshotsPreserveAliasedTreesMetadataAndMemoizedIdentity() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let live = root.appendingPathComponent("source") + let nested = live.appendingPathComponent("nested") + try FileManager.default.createDirectory(at: nested, withIntermediateDirectories: true) + let file = nested.appendingPathComponent("executable") + let bytes = Data(repeating: 0xa5, count: 200_000) + try bytes.write(to: file) + let link = live.appendingPathComponent("link") + try FileManager.default.createSymbolicLink( + atPath: link.path, withDestinationPath: "nested/executable") + try FileManager.default.createSymbolicLink( + atPath: live.appendingPathComponent("dangling").path, withDestinationPath: "nested/missing") + for (url, mode): (URL, mode_t) in [ + (live, 0o750), (nested, 0o751), (file, 0o751), (link, 0o755), + ] { + try setFixtureMetadata(url, mode: mode, value: Data(url.lastPathComponent.utf8)) + } + let alias = root.appendingPathComponent("alias") + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: live) + let store = StateStore( + scope: .project, + environment: RuntimeEnvironment(projectDirectory: root, homeDirectory: root, environment: [:]) + ) + let source = SourceDeclaration(kind: .local, location: alias.path) + let session = try SourceResolutionSession(store: store) + defer { try? session.close() } + let snapshot = try session.localSnapshot(source) + #expect(snapshot.liveRoot == alias) + #expect(try Data(contentsOf: snapshot.resource("link")) == bytes) + #expect(try FileHash.folderHash(snapshot.root) == FileHash.folderHash(live)) + #expect(try FileHash.executableFlags(snapshot.root) == FileHash.executableFlags(live)) + for path in [".", "nested", "nested/executable", "link"] { + #expect( + try fixtureMetadata(snapshot.root.appendingPathComponent(path)) + == fixtureMetadata(live.appendingPathComponent(path))) + } + #expect( + try FileManager.default.destinationOfSymbolicLink( + atPath: snapshot.root.appendingPathComponent("link").path) == "nested/executable") + #expect( + try FileManager.default.destinationOfSymbolicLink( + atPath: snapshot.root.appendingPathComponent("dangling").path) == "nested/missing") + let repeated = try SourceResolutionSession.withTemporaryRead(store: store) { + try $0.localSnapshot(source).snapshot + } + #expect(repeated == snapshot.snapshot) + try Data("changed".utf8).write(to: file) + let memoized = try session.localSnapshot(source) + #expect(memoized.snapshot == snapshot.snapshot && memoized.root == snapshot.root) + #expect(try Data(contentsOf: memoized.resource("link")) == bytes) + let changed = try SourceResolutionSession.withTemporaryRead(store: store) { + try $0.localSnapshot(source).snapshot + } + #expect(changed != snapshot.snapshot) + let workspace = snapshot.root.deletingLastPathComponent() + try session.close() + #expect(!FileManager.default.fileExists(atPath: workspace.path)) + } + + @Test(arguments: ["unsupported", "escaping-link"]) + func localSnapshotRefusesUnsafeEntriesAndCleansPartialCopies(_ kind: String) throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let store = StateStore( + scope: .project, + environment: RuntimeEnvironment(projectDirectory: root, homeDirectory: root, environment: [:]) + ) + let live = root.appendingPathComponent("source") + try FileManager.default.createDirectory(at: live, withIntermediateDirectories: true) + let session = try SourceResolutionSession(store: store) + defer { try? session.close() } + let first = try session.localSnapshot(SourceDeclaration(kind: .local, location: live.path)) + let invalid = root.appendingPathComponent("invalid") + try FileManager.default.createDirectory(at: invalid, withIntermediateDirectories: true) + try Data("copied first".utf8).write(to: invalid.appendingPathComponent("a")) + if kind == "unsupported" { + try #require(mkfifo(invalid.appendingPathComponent("z").path, 0o600) == 0) + } else { + try FileManager.default.createSymbolicLink( + atPath: invalid.appendingPathComponent("z").path, withDestinationPath: "../source") + } + #expect(throws: CoreError.self) { + try session.localSnapshot(SourceDeclaration(kind: .local, location: invalid.path)) + } + let workspace = first.root.deletingLastPathComponent() + try session.close() + #expect(!FileManager.default.fileExists(atPath: workspace.path)) + #expect(FileManager.default.fileExists(atPath: live.path)) + } + @Test func parsesLocalPathsAndGitLabSubgroupsAndTrees() throws { let cwd = URL(fileURLWithPath: "/workspace/project") for (input, expected) in [ @@ -24,8 +117,11 @@ struct SourceRegressionTests { #expect(parsed.subpath == (suffix.hasSuffix("skills/demo") ? "skills/demo" : nil)) } } + let location = "https://gitlab.example.test/team/subgroup/repo/-/tree/release/skills" + let authority = try SourceAuthority(host: "gitlab.example.test") + #expect(try SourceParser.parse(location, sourceAccess: .init()).type == .wellKnown) let hosted = try SourceParser.parse( - "https://gitlab.example.test/team/subgroup/repo/-/tree/release/skills") + location, sourceAccess: .init(providers: [authority: .gitlab])) #expect(hosted.type == .git) #expect(hosted.requirement == .branch("release")) #expect(hosted.subpath == "skills") diff --git a/Tests/AgentsCoreTests/StateEncodingTests.swift b/Tests/AgentsCoreTests/StateEncodingTests.swift index caf5e23..3aedaa9 100644 --- a/Tests/AgentsCoreTests/StateEncodingTests.swift +++ b/Tests/AgentsCoreTests/StateEncodingTests.swift @@ -1,11 +1,13 @@ +import AgentsManifest import Foundation +import StateTestSupport import Testing @testable import AgentsCore @Suite("State JSON encoding") struct StateEncodingTests { - @Test(arguments: ["agents.json", "agents.resolved", "transaction.json"]) + @Test(arguments: ["agents.resolved", "transaction.json"]) func rejectsEncodedDocumentsWithoutChangingFiles(_ name: String) throws { let root = try temporaryDirectory() defer { removeTemporaryDirectory(root) } @@ -15,8 +17,6 @@ struct StateEncodingTests { let resolved = try Data(contentsOf: store.resolvedURL) let json: String switch name { - case "agents.json": - json = #"{"sources":{"same":{"local":"/a"},"same":{"local":"/b"}}}"# case "agents.resolved": json = String(decoding: resolved, as: UTF8.self) default: let directory = try #require(try store.openDirectoryIfPresent()) @@ -36,20 +36,12 @@ struct StateEncodingTests { for data in encodings { let url = store.directory.appendingPathComponent(name) try data.write(to: url) - #expect(throws: (any Error).self) { - if name == "agents.json" { - _ = try store.loadDeclaration() - } else { - _ = try store.loadResolved() - } - } + #expect(throws: (any Error).self) { _ = try store.loadResolved() } #expect(throws: (any Error).self) { try store.save(declaration: Declaration(), resolved: ResolvedState()) } #expect(try Data(contentsOf: url) == data) - if name != "agents.json" { - #expect(try Data(contentsOf: store.declarationURL) == declaration) - } + #expect(try Data(contentsOf: store.declarationURL) == declaration) if name != "agents.resolved" { #expect(try Data(contentsOf: store.resolvedURL) == resolved) } } } diff --git a/Tests/AgentsCoreTests/StateInspectionTests.swift b/Tests/AgentsCoreTests/StateInspectionTests.swift index 966949f..1c1fb25 100644 --- a/Tests/AgentsCoreTests/StateInspectionTests.swift +++ b/Tests/AgentsCoreTests/StateInspectionTests.swift @@ -1,7 +1,11 @@ -import AgentsCore +import AgentsManifest import Foundation +import StateTestSupport +import Synchronization import Testing +@testable import AgentsCore + @Suite("State inspection concurrency") struct StateInspectionTests { @Test(arguments: [false, true]) @@ -20,10 +24,24 @@ struct StateInspectionTests { let result = try store.withReadLock( onPendingRecovery: { diagnostics += 1 + let finished = DispatchSemaphore(value: 0) + let writer = Mutex<(recovery: Result, save: Result)?>(nil) + Thread.detachNewThread { + let recovery = Result { + try store.save(declaration: Declaration(agents: [.cursor]), resolved: ResolvedState()) + } + let save = Result { + try store.save(declaration: Declaration(agents: [.cursor]), resolved: ResolvedState()) + } + writer.withLock { $0 = (recovery, save) } + finished.signal() + } + finished.wait() + let outcome = try #require(writer.withLock { $0 }) #expect(throws: CoreError.transactionRecovered(store.directory.path)) { - try store.save(declaration: Declaration(agents: [.cursor]), resolved: ResolvedState()) + try outcome.recovery.get() } - try store.save(declaration: Declaration(agents: [.cursor]), resolved: ResolvedState()) + try outcome.save.get() if callbackThrows { throw CoreError.invalidState("pending inspection") } return "pending" }, @@ -81,14 +99,14 @@ struct StateInspectionTests { atPath: fixture.store.directory.appendingPathComponent(".agents.lock").path)) var reads = 0 var interruptedState: String? - let pending = CoreError.invalidState("transaction recovery is required before inspection") - #expect(throws: pending) { + #expect(throws: pendingRecovery) { try fixture.store.withReadLock { reads += 1 let child = try stateTestProcess( - root: fixture.root, arguments: ["watch-add", "replace.1.renamed"]) - try fixture.kill(child, at: "replace.1.renamed") + root: fixture.root, + arguments: ["watch-add", TransactionCheckpoint.publication(1, .created).name]) + try fixture.kill(child, at: TransactionCheckpoint.publication(1, .created).name) let declaration = try fixture.store.readDeclaration() let watch = try fixture.store.readWatch() try #require(declaration.watch == ["source"]) diff --git a/Tests/AgentsCoreTests/StateModelTests.swift b/Tests/AgentsCoreTests/StateModelTests.swift index 5dc05c5..7300271 100644 --- a/Tests/AgentsCoreTests/StateModelTests.swift +++ b/Tests/AgentsCoreTests/StateModelTests.swift @@ -1,4 +1,6 @@ +import AgentsManifest import Foundation +import StateTestSupport import Testing @testable import AgentsCore @@ -91,15 +93,20 @@ struct StateModelTests { "CLAUDE.md": LockedTarget( agents: [.claudeCode], import: "AGENTS.md", blockHash: digest, created: false), ])) - try store.save(declaration: declaration, resolved: lock) + try store.save(declaration: declaration, ledger: ledgerFixture(lock)) let first = try Data(contentsOf: store.resolvedURL) let firstDeclaration = try Data(contentsOf: store.declarationURL) - try store.save(declaration: declaration, resolved: lock) + try store.save(declaration: declaration, ledger: ledgerFixture(lock)) #expect(try Data(contentsOf: store.resolvedURL) == first) #expect(try Data(contentsOf: store.declarationURL) == firstDeclaration) - #expect(try store.loadDeclaration() == declaration) + // The document spells the Git location as a URL; the projection keeps its meaning. + #expect( + ManifestProjection.equivalent( + try store.loadDeclaration(), declaration, environment: environment)) #expect(try store.loadResolved() == lock) - #expect(String(decoding: first, as: UTF8.self).contains("\"from\": \"1.0.0\"")) + #expect( + try store.loadLedger().sourceUses.contains { $0.requirement == .upToNextMajor(from: "1.0.0") } + ) } @Test func rejectsCorruptionWithoutReplacingFiles() throws { @@ -141,23 +148,10 @@ struct StateModelTests { StateStore(scope: .user, environment: environment).resolvedURL.path == "/home/test/.agents/agents.resolved") } - - @Test(arguments: [ - #"{"git":"github.com/a/b","local":"/a"}"#, - #"{"git":"github.com/a/b","from":"1.0.0","exact":"2.0.0"}"#, #"{"local":"/a","to":"2.0.0"}"#, - ]) - func rejectsAmbiguousSources(_ json: String) { - #expect(throws: (any Error).self) { - try JSONDecoder().decode(SourceDeclaration.self, from: Data(json.utf8)) - } - } } extension StateModelTests { @Test(arguments: [ - #"{"sources":{"same":{"local":"/a"},"same":{"local":"/b"}}}"#, - #"{"sources":{"same":{"local":"/a"},"sa\u006de":{"local":"/b"}}}"#, - #"{"sources":{},"skills":{"demo":{"select":"all"},"demo":{"select":[]}}}"#, #"{"version":1,"sources":{},"skills":{"demo":{},"demo":{}},"instructions":{"sections":[],"chatgpt":{},"targets":{}}}"#, #"{"version":1,"sources":{},"skills":{"demo":{"source":"local:/a","installs":{"codex":"link","codex":"copy"}}},"instructions":{"sections":[],"chatgpt":{},"targets":{}}}"#, ]) @@ -166,32 +160,104 @@ extension StateModelTests { defer { removeTemporaryDirectory(root) } let store = StateStore(scope: .project, environment: RuntimeEnvironment(projectDirectory: root)) try store.save(declaration: Declaration(), resolved: ResolvedState()) - let url = json.contains("version") ? store.resolvedURL : store.declarationURL - try Data(json.utf8).write(to: url) + try Data(json.utf8).write(to: store.resolvedURL) let beforeDeclaration = try Data(contentsOf: store.declarationURL) let beforeLock = try Data(contentsOf: store.resolvedURL) - #expect(throws: CoreError.self) { - if url == store.resolvedURL { - _ = try store.loadResolved() - } else { - _ = try store.loadDeclaration() - } - } + #expect(throws: CoreError.self) { _ = try store.loadResolved() } #expect(throws: CoreError.self) { try store.save(declaration: Declaration(), resolved: ResolvedState()) } #expect(try Data(contentsOf: store.declarationURL) == beforeDeclaration) #expect(try Data(contentsOf: store.resolvedURL) == beforeLock) } +} - @Test func rejectsUnknownFieldsInsteadOfDiscardingIntent() throws { - let root = try temporaryDirectory() - defer { removeTemporaryDirectory(root) } - let store = StateStore(scope: .project, environment: RuntimeEnvironment(projectDirectory: root)) - try store.save(declaration: Declaration(), resolved: ResolvedState()) - let bytes = Data(#"{"sources":{},"unexpected":{"intent":true}}"#.utf8) - try bytes.write(to: store.declarationURL) - #expect(throws: CoreError.self) { try store.loadDeclaration() } - #expect(try Data(contentsOf: store.declarationURL) == bytes) +private func ledgerFixture(_ model: ResolvedState) throws -> ResolvedLedger { + var ledger = ResolvedLedger() + func source(_ identity: String, revision: String?, version: String?) -> String { + let record = model.sources[identity]! + let id = identity + ":" + (revision ?? "live") + ":" + (version ?? "") + ledger.sources[id] = LedgerSource( + kind: record.kind, transport: record.url, + location: record.kind == .local + ? .init(kind: .absolute, path: String(identity.dropFirst(6))) : nil, + revision: revision ?? "live", version: version) + ledger.sourceUses.append( + .init(source: id, root: record.path ?? ".", requirement: record.requirement)) + return id + } + func occurrence(_ id: String, source: String) { + ledger.occurrences.append( + .init( + declaringSource: source, manifestPath: ".agent/agents.yaml", id: ledger.occurrences.count, + component: id, dependencies: [source], condition: .init(DeclarationCondition()), + recipients: ledger.components[id]!.recipients, consumerEditable: true)) + } + for (name, skill) in model.skills { + let sid = source(skill.source, revision: skill.revision, version: skill.version) + let rid = "skill:" + name + ledger.resources[rid] = .init( + kind: .git, source: sid, path: skill.path!, hash: skill.hash!, + entries: [.init(path: ".", kind: .directory, executable: false)]) + ledger.components[rid] = .init( + declaringSource: sid, source: sid, root: ".", kind: "skills", name: name, + revision: skill.revision, version: skill.version, + payload: .init(object: ["mode": .init(skill.installs.values.first!.rawValue)]), + conditions: [], recipients: skill.installs.keys.compactMap(AgentID.init(rawValue:)), + chatGPT: false, resources: [rid]) + occurrence(rid, source: sid) + } + var sectionOwners: [String] = [] + func section(_ record: LockedSection, prompt: String? = nil, append: String? = nil) { + let sid = source(record.source, revision: record.revision, version: record.version) + let id = "section:" + String(ledger.components.count) + let rid = id + ":resource" + ledger.resources[rid] = .init( + kind: .git, source: sid, path: record.path, hash: record.hash, + entries: [.init(path: ".", kind: .file, executable: false, byteCount: 0)]) + var payload = ["name": LedgerValue(record.name), "sourceHash": .init(record.hash)] + payload["prompt"] = prompt.map { .init($0) } + var resources = [rid] + if let append { + let aid = id + ":append" + ledger.resources[aid] = .init( + kind: .git, source: sid, path: append, hash: record.hash, + entries: [.init(path: ".", kind: .file, executable: false, byteCount: 0)]) + resources.append(aid) + } + ledger.components[id] = .init( + declaringSource: sid, source: sid, root: ".", kind: "instructions", name: record.name, + revision: record.revision, version: record.version, payload: .init(object: payload), + conditions: [], + recipients: prompt == nil ? [.codex, .claudeCode] : [], chatGPT: prompt != nil, + resources: resources) + occurrence(id, source: sid) + if prompt == nil { sectionOwners.append(id) } + } + for item in model.instructions.sections { section(item) } + for (name, prompt) in model.instructions.chatgpt { + for item in prompt.sections { section(item, prompt: name, append: prompt.append) } + } + #if os(macOS) + let platform = "macos" + #else + let platform = "linux" + #endif + for (path, target) in model.instructions.targets { + let id = "target:" + path + let route = target.import == nil ? "agents/instructions@1" : "agents/claude-import@1" + ledger.deployments.append( + .init( + id: id, target: .init(kind: .registered, root: "project", path: path), route: route, + owners: sectionOwners, + recipients: target.agents, ownership: target.import == nil ? .generated : .importBlock, + expectedHash: target.blockHash, + created: target.created, importReference: target.import, headingOffset: target.headingOffset + )) + ledger.lowerings.append( + .init( + id: id, format: route, inputs: sectionOwners, resources: [], deployments: [id], + layout: .init(), platform: platform, artifacts: [])) } + return ledger } diff --git a/Tests/AgentsCoreTests/StatePublicationTests.swift b/Tests/AgentsCoreTests/StatePublicationTests.swift new file mode 100644 index 0000000..a40ab61 --- /dev/null +++ b/Tests/AgentsCoreTests/StatePublicationTests.swift @@ -0,0 +1,322 @@ +import AgentsManifest +import CPlatform +import Foundation +import StateTestSupport +import Testing + +@testable import AgentsCore + +/// Domain operations whose single journal creates the declaration with the state beside it. +/// Killing them or their recovery at any recorded point leaves either no scope state or the +/// complete new generation, with declaration, lock, watch state and targets in agreement. +@Suite("State operation publication") +struct StatePublicationTests { + @Test(arguments: StateOperationMatrix.publications) + func killedOperationRecoversOneGeneration(_ fault: StateOperationFault) throws { + try fault.checkSetup() + let fixture = try StateOperationFixture(fault.operation) + terminateProcess(try fixture.pause(fault.operation.command, at: fault.point)) + try fixture.recover() + try fixture.check(committed: fault.committed) + } + + @Test(arguments: StateOperationMatrix.recoveries) + func recoveryCanBeKilledAtEachStageAndRepeated(_ fault: StateOperationFault) throws { + try fault.checkSetup() + let fixture = try StateOperationFixture(fault.operation) + terminateProcess(try fixture.pause(fault.operation.command, at: fault.seed!)) + terminateProcess(try fixture.pause("publication-recover", at: fault.point)) + try fixture.recover() + try fixture.check(committed: fault.committed) + } + + /// A writer waiting for the scope lock prepares from the generation the holder committed, so + /// neither declaration change is lost. + @Test func serializedWritersKeepBothDeclarationChanges() throws { + let fixture = try StateOperationFixture(.watchAdd) + let watch = try fixture.pause("watch-add", at: "watch.mirror.fetched") + defer { terminateProcess(watch) } + let skill = try fixture.launch("skill-add", at: "never") + defer { terminateProcess(skill) } + Thread.sleep(forTimeInterval: 0.2) + #expect(skill.isRunning) + try FileManager.default.removeItem(at: fixture.root.appendingPathComponent("ready")) + kill(watch.processIdentifier, SIGCONT) + for child in [watch, skill] { + try ProcessWait.exit(child, root: fixture.root) + #expect(child.terminationStatus == 0) + } + let declaration = try fixture.store.loadDeclaration() + #expect(declaration.sources.keys.sorted() == ["source"]) + #expect(declaration.watch == ["source"]) + #expect((try declaration.skills)?["source"]?.select == .names(["demo"])) + #expect(try fixture.store.loadResolved().skills.keys.sorted() == ["demo"]) + #expect(try fixture.store.loadWatch().sources.count == 1) + } +} + +enum StateOperation: String, CaseIterable, Sendable { + /// A first skill add creates the declaration, the lock and an installation target. + case freshSkillAdd + /// A first watch subscription creates the declaration and watch state. + case watchAdd + + var command: String { self == .freshSkillAdd ? "skill-add" : "watch-add" } + + /// Journal entries in request order; the declaration is created by entry `declaration`. + var entries: Int { self == .freshSkillAdd ? 3 : 2 } + var declaration: Int { self == .freshSkillAdd ? 1 : 0 } + + /// Recovery starts from sealed staging, a published declaration, every applied entry, the + /// committed marker and terminal disposal. + var recoverySeeds: [RecoverySeed] { + [ + RecoverySeed(point: TransactionCheckpoint.progress(entries - 1, .ready).name), + RecoverySeed( + point: TransactionCheckpoint.publication(declaration, .created).name, renamed: true), + RecoverySeed( + point: TransactionCheckpoint.progress(entries - 1, .applied).name, renamed: true), + RecoverySeed( + point: TransactionCheckpoint.persisted(.committed, .terminal, .renamed).name, + committed: true), + RecoverySeed(point: TransactionCheckpoint.disposalIntent.name, committed: true), + ] + } + + func requiredRecoveryPoints(from seed: RecoverySeed) -> Set { + var points = [ + TransactionCheckpoint.journalSynced.name, TransactionCheckpoint.journalRemoved.name, + ] + if !seed.committed { + points.append(TransactionCheckpoint.persisted(.rolledBack, .terminal, .renamed).name) + } + if seed.renamed { + points.append(TransactionCheckpoint.restoration(declaration, .withdrawn).name) + } + return Set(points) + } +} + +struct StateOperationFault: Sendable, CustomTestStringConvertible { + let operation: StateOperation + let point: String + var committed = false + var seed: String? + var setupFailure: String? + var testDescription: String { + "\(operation.rawValue), \(seed.map { "from \($0), " } ?? "")\(point)" + } + func checkSetup() throws { + if let setupFailure { + throw CoreError.invalidState("checkpoint recording failed: " + setupFailure) + } + } +} + +/// Kill points recorded from real traces. By default each operation is killed at +/// representative points, and its recovery at durable steps from each seeded interruption; +/// `AGENTS_PUBLICATION_MATRIX=full` kills at every recorded point. +enum StateOperationMatrix { + static let complete = ProcessInfo.processInfo.environment["AGENTS_PUBLICATION_MATRIX"] == "full" + static let publications = record(recovery: false) + static let recoveries = record(recovery: true) + + /// Every recovery seed, the first durable intent, the last synced publication, container + /// removal, and for watch subscriptions the acknowledged fetch and the ref reconciliation + /// that follows the commit. + private static func representativePublication(_ operation: StateOperation) -> Set { + var points = + operation.recoverySeeds.map(\.point) + [ + TransactionCheckpoint.progress(0, .publishing).name, + TransactionCheckpoint.publication(operation.entries - 1, .synced).name, + TransactionCheckpoint.phase(.committed).name, + TransactionCheckpoint.containerRemoved(0).name, + ] + if operation == .watchAdd { + points += ["watch.mirror.fetched", "watch.references.pending", "watch.references.0.synced"] + } + return Set(points) + } + + /// The observed-journal barrier, each durable recovery write, each creation's withdrawal and + /// its barrier, disposal and the ref reconciliation that follows recovery. + private static func representativeRecovery(_ operation: StateOperation) -> Set { + var points: [TransactionCheckpoint] = [.journalSynced, .containerRemoved(0), .journalRemoved] + for phase in [TransactionJournal.Phase.applying, .committed, .rolledBack] { + points += [.persisted(phase, .terminal, .renamed), .persisted(phase, .disposing, .renamed)] + for index in 0.. [StateOperationFault] { + var cases: [StateOperationFault] = [] + let commitMarker = TransactionCheckpoint.persisted(.committed, .terminal, .renamed).name + for operation in StateOperation.allCases { + let selected = + recovery ? representativeRecovery(operation) : representativePublication(operation) + let seeds: [RecoverySeed?] = recovery ? operation.recoverySeeds.map { $0 } : [nil] + for seed in seeds { + do { + let fixture = try StateOperationFixture(operation) + if let seed { terminateProcess(try fixture.pause(operation.command, at: seed.point)) } + let command = recovery ? "publication-recover" : operation.command + let child = try fixture.launch(command, at: "never") + defer { terminateProcess(child) } + try ProcessWait.exit(child, root: fixture.root) + guard child.terminationStatus == 0 else { + throw CoreError.invalidState("checkpoint recorder exited \(child.terminationStatus)") + } + let trace = try fixture.trace(child) + guard !trace.isEmpty, Set(trace).count == trace.count else { + throw CoreError.invalidState("checkpoint names are empty or repeated") + } + let required = + seed.map(operation.requiredRecoveryPoints(from:)) + ?? representativePublication(operation) + if !required.isSubset(of: trace) { + throw CoreError.invalidState( + "representative points were not recorded: \(required.subtracting(trace).sorted())") + } + var committed = seed?.committed ?? false + for point in trace { + if point == commitMarker { committed = true } + guard complete || selected.contains(point) else { continue } + cases.append( + StateOperationFault( + operation: operation, point: point, committed: committed, seed: seed?.point)) + } + } catch { + cases.append( + StateOperationFault( + operation: operation, point: "recording", seed: seed?.point, + setupFailure: String(describing: error))) + } + } + } + return cases + } +} + +final class StateOperationFixture { + let operation: StateOperation + let root: URL + let source: URL + let store: StateStore + let target: URL + + init(_ operation: StateOperation) throws { + self.operation = operation + root = try temporaryDirectory() + source = root.appendingPathComponent("source") + store = StateStore( + scope: .project, + environment: RuntimeEnvironment( + projectDirectory: root, homeDirectory: root.appendingPathComponent("home"), + environment: ["CLAUDE_CONFIG_DIR": root.appendingPathComponent("configured-claude").path] + )) + target = AgentRegistry.installSkillsDirectory( + for: .codex, scope: .project, environment: store.environment + ).appendingPathComponent("demo") + do { + let skill = source.appendingPathComponent("skills/demo") + try FileManager.default.createDirectory(at: skill, withIntermediateDirectories: true) + try Data("---\nname: demo\ndescription: Fixture skill.\n---\nBody\n".utf8).write( + to: skill.appendingPathComponent("SKILL.md")) + try initGitRepo(source) + } catch { + removeTemporaryDirectory(root) + throw error + } + } + + deinit { removeTemporaryDirectory(root) } + + func launch(_ command: String, at point: String) throws -> Process { + try stateTestProcess(root: root, arguments: [command, point]) + } + + func pause(_ command: String, at point: String) throws -> Process { + let marker = root.appendingPathComponent( + command == "publication-recover" ? "recovery-ready" : "ready") + try? FileManager.default.removeItem(at: marker) + let child = try launch(command, at: point) + do { + try ProcessWait.marker(marker, child: child, root: root) + try ProcessWait.stopped(child, root: root) + return child + } catch { + terminateProcess(child) + throw error + } + } + + func trace(_ child: Process) throws -> [String] { + try String( + contentsOf: root.appendingPathComponent("checkpoint-\(child.processIdentifier).log"), + encoding: .utf8 + ).split(separator: "\n").map(String.init) + } + + /// Recovers as the next writer would; repeating it finds nothing left to recover. + func recover() throws { + do { try store.withLock {} } catch CoreError.transactionRecovered {} + try store.withLock {} + } + + func check(committed: Bool) throws { + #expect(try store.openDirectoryIfPresent()?.info(TransactionJournal.fileName) == nil) + #expect(try store.openDirectoryIfPresent()?.info("watch-refs.pending") == nil) + let declaration = try store.loadDeclaration() + let lock = try store.loadResolved() + let watch = try store.loadWatch() + let present = { (url: URL) in FileManager.default.fileExists(atPath: url.path) } + guard committed else { + for url in [store.declarationURL, store.resolvedURL, store.watchURL] { + #expect(!present(url)) + } + #expect((try? FileManager.default.destinationOfSymbolicLink(atPath: target.path)) == nil) + #expect(declaration == Declaration()) + return + } + let id = try SourceDeclaration(kind: .local, location: source.path).identity( + environment: store.environment) + #expect(declaration.sources.keys.sorted() == ["source"]) + #expect(try declaration.sources["source"]?.identity(environment: store.environment) == id) + switch operation { + case .freshSkillAdd: + #expect( + (try declaration.skills) == [ + "source": SkillDeclaration(select: .names(["demo"]), agents: [.codex], mode: .edit) + ]) + #expect(declaration.watch == nil) + #expect(lock.skills["demo"]?.source == id) + #expect(lock.skills["demo"]?.installs == ["codex": .edit]) + #expect(lock.sources[id] == LockedSource(kind: .local)) + #expect( + target.resolvingSymlinksInPath().path + == source.appendingPathComponent("skills/demo").resolvingSymlinksInPath().path) + #expect(!present(store.watchURL)) + case .watchAdd: + #expect((try declaration.skills) == nil) + #expect(declaration.watch == ["source"]) + #expect(watch.sources[id]?.seen == .revision(try gitHead(source))) + #expect(lock == ResolvedState()) + #expect(!present(store.resolvedURL)) + } + let parents = [store.directory, target.deletingLastPathComponent()] + for parent in parents where present(parent) { + #expect( + try !FileManager.default.contentsOfDirectory(atPath: parent.path).contains { + $0.hasPrefix(".agents-") + }) + } + } +} diff --git a/Tests/AgentsCoreTests/StateTransactionTests.swift b/Tests/AgentsCoreTests/StateTransactionTests.swift index bd52944..512b94c 100644 --- a/Tests/AgentsCoreTests/StateTransactionTests.swift +++ b/Tests/AgentsCoreTests/StateTransactionTests.swift @@ -1,5 +1,7 @@ -import Darwin +import AgentsManifest +import CPlatform import Foundation +import StateTestSupport import Testing @testable import AgentsCore @@ -13,15 +15,17 @@ struct StateTransactionTests { let moved = fixture.root.appendingPathComponent("displaced-cache") try fixture.store.withLock { let transaction = FileTransaction(store: fixture.store) { step in - if step == "journal.committed.renamed" { + if step == TransactionCheckpoint.persisted(.committed, .terminal, .renamed).name { try FileManager.default.moveItem(at: parent, to: moved) throw CoreError.invalidState("cache cleanup interrupted") } } try transaction.replace( parent.appendingPathComponent("pruned"), - content: fixture.root.appendingPathComponent("new")) - #expect(throws: CoreError.self) { try transaction.commit() } + with: .copy(fixture.root.appendingPathComponent("new"))) + #expect(throws: CoreError.invalidState("cache cleanup interrupted")) { + try transaction.commit() + } #expect( FileManager.default.fileExists( atPath: @@ -39,17 +43,17 @@ struct StateTransactionTests { var checkpoints: [String] = [] do { let fixture = try TransactionFixture() - try fixture.commit { - if !$0.contains(fixture.root.lastPathComponent) { checkpoints.append($0) } - } + try fixture.commit { checkpoints.append($0) } } - #expect(checkpoints.contains("journal.committed")) + #expect(checkpoints.contains(TransactionCheckpoint.phase(.committed).name)) for failure in Set(checkpoints).sorted() { let fixture = try TransactionFixture() var committed = false - #expect(throws: CoreError.self) { + #expect(throws: CoreError.invalidState("injected failure")) { try fixture.commit { step in - if step == "journal.committed.renamed" { committed = true } + if step == TransactionCheckpoint.persisted(.committed, .terminal, .renamed).name { + committed = true + } if step == failure { throw CoreError.invalidState("injected failure") } } } @@ -61,41 +65,43 @@ struct StateTransactionTests { } @Test(arguments: [ - "journal.preparing", "journal.preparing.renamed", "stage.0", "stage.4", "journal.applying", - "replace.0", - "replace.1", "replace.2", - "replace.3", "replace.4", "replace.5", "replace.5.renamed", "replace.0.renamed", - "journal.applying.renamed", - "journal.committed.renamed", "journal.committed", "cleanup.0", + TransactionCheckpoint.phase(.preparing).name, + TransactionCheckpoint.persisted(.preparing, .created, .renamed).name, + TransactionCheckpoint.progress(0, .ready).name, TransactionCheckpoint.progress(4, .ready).name, + TransactionCheckpoint.progress(0, .publishing).name, + TransactionCheckpoint.progress(0, .applied).name, + TransactionCheckpoint.progress(1, .applied).name, + TransactionCheckpoint.progress(2, .applied).name, + TransactionCheckpoint.progress(3, .applied).name, + TransactionCheckpoint.progress(4, .applied).name, + TransactionCheckpoint.progress(5, .applied).name, + TransactionCheckpoint.publication(5, .exchanged).name, + TransactionCheckpoint.publication(0, .exchanged).name, + TransactionCheckpoint.persisted(.applying, .entry(0, .publishing), .renamed).name, + TransactionCheckpoint.persisted(.committed, .terminal, .renamed).name, + TransactionCheckpoint.phase(.committed).name, TransactionCheckpoint.containerRemoved(0).name, ]) - func killedWriterRecoversOnNextStateRead(_ step: String) throws { + func killedWriterIsReportedToReadersAndRecoveredByTheNextWriter(_ step: String) throws { let fixture = try TransactionFixture() let child = try stateTestProcess(root: fixture.root, arguments: ["crash", step]) - defer { - if child.isRunning { - kill(child.processIdentifier, SIGKILL) - child.waitUntilExit() - } - } - let deadline = Date().addingTimeInterval(10) - while !FileManager.default.fileExists( - atPath: fixture.root.appendingPathComponent("ready").path), Date() < deadline, child.isRunning - { - Thread.sleep(forTimeInterval: 0.01) - } - #expect( - FileManager.default.fileExists(atPath: fixture.root.appendingPathComponent("ready").path)) + defer { terminateProcess(child) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: child, root: fixture.root) // At every interruption point the replaced installation still has a directory entry. #expect( FileManager.default.fileExists( atPath: fixture.root.appendingPathComponent(".agents/skills/target/SKILL.md").path)) - kill(child.processIdentifier, SIGKILL) - child.waitUntilExit() + terminateProcess(child) #expect(child.terminationReason == .uncaughtSignal) + #expect(throws: pendingRecovery) { try fixture.store.loadResolved() } #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { - _ = try fixture.store.loadResolved() + try fixture.store.withLock {} } - try fixture.check(committed: step.hasPrefix("journal.committed") || step == "cleanup.0") + let committed = [ + TransactionCheckpoint.persisted(.committed, .terminal, .renamed), + .phase(.committed), .containerRemoved(0), + ].map(\.name) + try fixture.check(committed: committed.contains(step)) } @Test func serializesSeparateWriterProcesses() throws { @@ -104,7 +110,7 @@ struct StateTransactionTests { try stateTestProcess(root: fixture.root, arguments: ["writer", "writer-\($0)"]) } for child in children { - child.waitUntilExit() + try ProcessWait.exit(child, root: fixture.root) #expect(child.terminationStatus == 0) } #expect(try fixture.store.loadDeclaration().sources.count == 20) @@ -139,28 +145,30 @@ final class TransactionFixture { deinit { removeTemporaryDirectory(root) } func commit(checkpoint: @escaping (String) throws -> Void) throws { try store.withLock { + var ledger = ResolvedLedger() + ledger.sources["local:/new"] = LedgerSource(kind: .local, revision: "live") let transaction = FileTransaction(store: store, checkpoint: checkpoint) try transaction.replace( root.appendingPathComponent(".agents/skills/target"), - content: root.appendingPathComponent("new")) - try transaction.replace( - store.declarationURL, content: nil, data: StateStore.encode(Declaration(agents: [.codex]))) + with: .copy(root.appendingPathComponent("new"))) try transaction.replace( - store.resolvedURL, content: nil, - data: StateStore.encode(ResolvedState(sources: ["local:/new": LockedSource(kind: .local)]))) + store.declarationURL, with: .data(manifestText("defaultAgents: [\"codex\"]\n"))) try transaction.replace( - root.appendingPathComponent(".agent/cache/artifact-content/pruned"), content: nil) + store.resolvedURL, + with: .data( + StateStore.encode(ledger))) + try transaction.delete(root.appendingPathComponent(".agent/cache/artifact-content/pruned")) try transaction.replace( root.appendingPathComponent(".claude/skills/created"), - content: root.appendingPathComponent("new"), - link: true) + with: .link(root.appendingPathComponent("new"))) try transaction.replace( - root.appendingPathComponent("AGENTS.md"), content: nil, - data: Data("new instructions".utf8)) + root.appendingPathComponent("AGENTS.md"), with: .data(Data("new instructions".utf8))) try transaction.commit() } } + /// Recovers as the next writer would, then compares the selected generation. func check(committed: Bool) throws { + do { try store.withLock {} } catch CoreError.transactionRecovered {} #expect( try Data(contentsOf: root.appendingPathComponent("AGENTS.md")) == Data((committed ? "new instructions" : "old instructions").utf8)) @@ -169,7 +177,7 @@ final class TransactionFixture { contentsOf: root.appendingPathComponent(".agents/skills/target/SKILL.md"), encoding: .utf8) == (committed ? "new" : "target")) #expect(try store.loadDeclaration().agents == (committed ? [.codex] : nil)) - #expect(try store.loadResolved().sources.isEmpty == !committed) + #expect(try store.loadLedger().sources.isEmpty == !committed) #expect( FileManager.default.fileExists( atPath: root.appendingPathComponent(".claude/skills/created/SKILL.md").path) == committed) @@ -190,7 +198,7 @@ extension StateTransactionTests { let staging = store.directory.appendingPathComponent("transaction.new") try Data("partial journal".utf8).write(to: staging) #expect(throws: CoreError.transactionRecovered(store.directory.path)) { - try store.loadDeclaration() + try store.withLock {} } #expect(try Data(contentsOf: store.resolvedURL) == before) #expect(!FileManager.default.fileExists(atPath: staging.path)) @@ -208,7 +216,19 @@ extension StateTransactionTests { let before = try Data(contentsOf: store.resolvedURL) let journal = store.directory.appendingPathComponent("transaction.json") try Data(json.utf8).write(to: journal) - #expect(throws: (any Error).self) { try store.loadResolved() } + #expect { try store.loadResolved() } throws: { error in + guard case CoreError.recoveryPending(let message) = error else { return false } + return message.hasPrefix(TransactionRecoveryDiagnostic.conflictMessage) + } + #expect { try store.withLock {} } throws: { error in + if json == "{broken" { + return error as? CoreError == .invalidState("invalid ledger JSON") + } + return error as? CoreError + == .invalidState( + "transaction journal was written by another version; recover it with the version that wrote it (journal version: missing)" + ) + } #expect(try Data(contentsOf: store.resolvedURL) == before) #expect(try Data(contentsOf: journal) == Data(json.utf8)) } @@ -216,29 +236,19 @@ extension StateTransactionTests { extension StateTransactionTests { private func waitFor(_ marker: String, root: URL, child: Process) throws { - let deadline = Date().addingTimeInterval(10) - while !FileManager.default.fileExists(atPath: root.appendingPathComponent(marker).path), - Date() < deadline, child.isRunning - { - Thread.sleep(forTimeInterval: 0.01) - } - try #require(FileManager.default.fileExists(atPath: root.appendingPathComponent(marker).path)) + try ProcessWait.marker(root.appendingPathComponent(marker), child: child, root: root) } private func abandon( - _ fixture: TransactionFixture, at step: String = "replace.2", scope: InstallScope = .project + _ fixture: TransactionFixture, + at step: String = TransactionCheckpoint.progress(2, .applied).name, + scope: InstallScope = .project ) throws { let child = try stateTestProcess( - root: fixture.root, arguments: ["crash", step, scope.rawValue]) - defer { - if child.isRunning { - kill(child.processIdentifier, SIGKILL) - child.waitUntilExit() - } - } + root: fixture.root, arguments: ["crash", step, "--scope", scope.rawValue]) + defer { terminateProcess(child) } try waitFor("ready", root: fixture.root, child: child) - kill(child.processIdentifier, SIGKILL) - child.waitUntilExit() + terminateProcess(child) } @Test(arguments: [InstallScope.project, .user]) @@ -255,33 +265,32 @@ extension StateTransactionTests { let target = AgentRegistry.installSkillsDirectory( for: .claudeCode, scope: scope, environment: environment ).appendingPathComponent("created") - try abandon(fixture, at: "replace.4", scope: scope) + try abandon(fixture, at: TransactionCheckpoint.progress(4, .applied).name, scope: scope) try #require(FileManager.default.fileExists(atPath: target.path)) let recovery = try stateTestProcess( - root: fixture.root, arguments: ["recover", "restore.4.remove.unlinked", scope.rawValue]) - defer { - if recovery.isRunning { - kill(recovery.processIdentifier, SIGKILL) - recovery.waitUntilExit() - } - } + root: fixture.root, + arguments: [ + "recover", TransactionCheckpoint.restoration(4, .withdrawn).name, "--scope", + scope.rawValue, + ]) + defer { terminateProcess(recovery) } try waitFor("recovery-ready", root: fixture.root, child: recovery) #expect(try DirectoryHandle(at: target.deletingLastPathComponent()).info("created") == nil) - kill(recovery.processIdentifier, SIGKILL) - recovery.waitUntilExit() + terminateProcess(recovery) #expect(recovery.terminationReason == .uncaughtSignal) var steps: [String] = [] - try FileLock.withLock(at: store.directory.appendingPathComponent(".agents.lock")) { - let recovered = try FileTransaction.recover(store: store) { steps.append($0) } - #expect(recovered) - } - #expect(!steps.contains("restore.4.remove.unlinked")) - let synced = try #require(steps.firstIndex(of: "restore.4.remove.synced")) - let terminal = try #require(steps.firstIndex(of: "journal.rolledBack.renamed")) - let cleanup = try #require(steps.firstIndex(of: "journal.terminalSynced")) - #expect(synced < terminal && terminal < cleanup) + #expect(throws: CoreError.transactionRecovered(store.directory.path)) { + try store.withLock(checkpoint: { steps.append($0) }, {}) + } + #expect(!steps.contains(TransactionCheckpoint.restoration(4, .withdrawn).name)) + let synced = try #require( + steps.firstIndex(of: TransactionCheckpoint.restoration(4, .synced).name)) + let terminal = try #require( + steps.firstIndex(of: TransactionCheckpoint.persisted(.rolledBack, .terminal, .renamed).name)) + let disposal = try #require(steps.firstIndex(of: TransactionCheckpoint.disposalIntent.name)) + #expect(synced < terminal && terminal < disposal) #expect(try Data(contentsOf: store.declarationURL) == declaration) #expect(try Data(contentsOf: store.resolvedURL) == resolved) #expect(try Data(contentsOf: fixture.store.resolvedURL) == projectState) @@ -290,67 +299,62 @@ extension StateTransactionTests { #expect( !FileManager.default.fileExists( atPath: store.directory.appendingPathComponent("transaction.json").path)) - #expect( - try FileManager.default.contentsOfDirectory(atPath: target.deletingLastPathComponent().path) - .isEmpty) + let remaining = try FileManager.default.contentsOfDirectory( + atPath: target.deletingLastPathComponent().path) + #expect(remaining == (scope == .user ? [SharedResource.metadataName] : [])) + if scope == .user { + let route = try NativeTargetRoute.named(.claudeSkillPlugin, scope: scope, name: "created") + try store.withReadLock(footprint: [route]) { + let reservation = try TransactionLockContext.current(store).requiredResource().reservation() + #expect(reservation == nil) + } + } } @Test(arguments: [ - "restore.2.renamed", "restore.0", "journal.rolledBack.renamed", "journal.terminalSynced", - "cleanup.0", + TransactionCheckpoint.restoration(2, .exchanged).name, + TransactionCheckpoint.progress(0, .restored).name, + TransactionCheckpoint.persisted(.rolledBack, .terminal, .renamed).name, + TransactionCheckpoint.phase(.rolledBack).name, + TransactionCheckpoint.containerRemoved(0).name, ]) func interruptedRecoverySerializesCompetingReader(_ point: String) throws { let fixture = try TransactionFixture() try abandon(fixture) let recovery = try stateTestProcess(root: fixture.root, arguments: ["recover", point]) - defer { - if recovery.isRunning { - kill(recovery.processIdentifier, SIGKILL) - recovery.waitUntilExit() - } - } + defer { terminateProcess(recovery) } try waitFor("recovery-ready", root: fixture.root, child: recovery) let reader = try stateTestProcess(root: fixture.root, arguments: ["read", ""]) - defer { - if reader.isRunning { - kill(reader.processIdentifier, SIGKILL) - reader.waitUntilExit() - } - } + defer { terminateProcess(reader) } try waitFor("reader-started", root: fixture.root, child: reader) Thread.sleep(forTimeInterval: 0.05) #expect( !FileManager.default.fileExists( atPath: fixture.root.appendingPathComponent("reader-finished").path)) - kill(recovery.processIdentifier, SIGKILL) - recovery.waitUntilExit() + terminateProcess(recovery) try waitFor("reader-finished", root: fixture.root, child: reader) - reader.waitUntilExit() + try ProcessWait.exit(reader, root: fixture.root) #expect(reader.terminationStatus == 0) try fixture.check(committed: false) } - @Test(arguments: ["journal.terminalSynced", "cleanup.0"]) + @Test(arguments: [ + TransactionCheckpoint.journalSynced.name, TransactionCheckpoint.containerRemoved(0).name, + ]) func committedRecoverySyncsObservedMarkerBeforeCleanup(_ point: String) throws { let fixture = try TransactionFixture() - try abandon(fixture, at: "journal.committed.renamed") + try abandon(fixture, at: TransactionCheckpoint.persisted(.committed, .terminal, .renamed).name) let recovery = try stateTestProcess(root: fixture.root, arguments: ["recover", point]) - defer { - if recovery.isRunning { - kill(recovery.processIdentifier, SIGKILL) - recovery.waitUntilExit() - } - } + defer { terminateProcess(recovery) } try waitFor("recovery-ready", root: fixture.root, child: recovery) - if point == "journal.terminalSynced" { + if point == TransactionCheckpoint.journalSynced.name { let names = try FileManager.default.contentsOfDirectory( atPath: fixture.root.appendingPathComponent(".agents/skills").path) - #expect(names.contains { $0.hasSuffix(".old") }) + #expect(names.contains { $0.hasPrefix(".agents-") }) } - kill(recovery.processIdentifier, SIGKILL) - recovery.waitUntilExit() + terminateProcess(recovery) #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { - try fixture.store.loadResolved() + try fixture.store.withLock {} } try fixture.check(committed: true) } @@ -360,13 +364,13 @@ extension StateTransactionTests { try abandon(fixture) let journalURL = fixture.store.directory.appendingPathComponent("transaction.json") let original = try Data(contentsOf: journalURL) - let before = try FileHash.folderHash(fixture.root) + let before = try FileSnapshot.read(at: fixture.root) let victim = fixture.root.appendingPathComponent("Documents/victim") try FileManager.default.createDirectory(at: victim, withIntermediateDirectories: true) try Data("keep".utf8).write(to: victim.appendingPathComponent("sentinel")) let maliciousPaths = [ victim.path, "file://" + victim.path, "state/../../Documents/victim", "state/cache/../victim", - "state/agents.json/child", "codex/../victim", "codex/other/child", "unknown/victim", + "state/agents.yaml/child", "codex/../victim", "codex/other/child", "unknown/victim", "state/cache/artifact-content/../../victim", ] for path in maliciousPaths { @@ -376,30 +380,45 @@ extension StateTransactionTests { json["entries"] = entries let bytes = try JSONSerialization.data(withJSONObject: json, options: [.sortedKeys]) try bytes.write(to: journalURL) - let snapshot = try FileHash.folderHash(fixture.root) - #expect(throws: (any Error).self) { try fixture.store.loadResolved() } - #expect(try FileHash.folderHash(fixture.root) == snapshot) + let snapshot = try FileSnapshot.read(at: fixture.root) + let expected: CoreError + if path.contains("..") || path.hasPrefix("/") || path.hasPrefix("file://") { + expected = .invalidState("invalid scope-relative transaction path") + } else if path.hasPrefix("state/") { + expected = .unsafePath("unmanaged state transaction path") + } else { + expected = .unsafePath("unmanaged installation transaction path") + } + #expect(throws: expected) { try fixture.store.withLock {} } + #expect(try FileSnapshot.read(at: fixture.root) == snapshot) } var directories = try #require(JSONSerialization.jsonObject(with: original) as? [String: Any]) directories["directories"] = [victim.absoluteString] try JSONSerialization.data(withJSONObject: directories).write(to: journalURL) - let directorySnapshot = try FileHash.folderHash(fixture.root) - #expect(throws: (any Error).self) { try fixture.store.loadResolved() } - #expect(try FileHash.folderHash(fixture.root) == directorySnapshot) + let directorySnapshot = try FileSnapshot.read(at: fixture.root) + #expect { try fixture.store.withLock {} } throws: { error in + guard case CoreError.invalidState(let reason) = error else { return false } + return reason.contains("unknown state field: directories") + } + #expect(try FileSnapshot.read(at: fixture.root) == directorySnapshot) // The absolute-parent counterexample is rejected as a foreign schema, too. let forged = #"{"id":"00000000-0000-0000-0000-000000000000","phase":"applying","entries":[{"parent":""# + victim.deletingLastPathComponent().absoluteString + #"","name":"victim","existed":false,"replacement":false}],"directories":[]}"# try Data(forged.utf8).write(to: journalURL) - #expect(throws: (any Error).self) { try fixture.store.loadResolved() } + #expect( + throws: CoreError.invalidState( + "transaction journal was written by another version; recover it with the version that wrote it (journal version: missing)" + ) + ) { try fixture.store.withLock {} } #expect( try String(contentsOf: victim.appendingPathComponent("sentinel"), encoding: .utf8) == "keep") try FileManager.default.removeItem(at: victim.deletingLastPathComponent()) try original.write(to: journalURL) - #expect(try FileHash.folderHash(fixture.root) == before) + #expect(try FileSnapshot.read(at: fixture.root) == before) #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { - try fixture.store.loadResolved() + try fixture.store.withLock {} } } @@ -410,17 +429,22 @@ extension StateTransactionTests { try FileManager.default.createDirectory(at: pin, withIntermediateDirectories: true) try Data("keep".utf8).write(to: pin.appendingPathComponent("sentinel")) let url = fixture.store.directory.appendingPathComponent("transaction.json") - var journal = try #require( - JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? [String: Any]) - var entries = try #require(journal["entries"] as? [[String: Any]]) + var journal = try StateStore.decode(Data(contentsOf: url), as: TransactionJournal.self) for path in ["state/cache/materialized/source", "state/cache/materialized/source/pin"] { - entries.append(["path": path, "existed": false, "replacement": false]) + let target = fixture.store.directory.appendingPathComponent(String(path.dropFirst(6))) + let parent = try DirectoryHandle(at: target.deletingLastPathComponent()) + journal.entries.append( + .init( + path: path, action: .delete, preimage: try FileSnapshot.read(at: target), + parentIdentity: try parent.identity, container: 0, progress: .ready)) } - journal["entries"] = entries - try JSONSerialization.data(withJSONObject: journal).write(to: url) - let before = try FileHash.folderHash(fixture.root) - #expect(throws: (any Error).self) { try fixture.store.loadResolved() } - #expect(try FileHash.folderHash(fixture.root) == before) + try StateStore.encode(journal).write(to: url) + let before = try FileSnapshot.read(at: fixture.root) + #expect { try fixture.store.withLock {} } throws: { error in + guard case CoreError.invalidState(let reason) = error else { return false } + return reason.contains("state/cache/materialized/source/pin: overlapping destinations") + } + #expect(try FileSnapshot.read(at: fixture.root) == before) } @Test func rejectsCopiedJournalWithoutTouchingEitherLocation() throws { @@ -430,22 +454,22 @@ extension StateTransactionTests { defer { removeTemporaryDirectory(container) } let copy = container.appendingPathComponent("copy") try FileManager.default.copyItem(at: fixture.root, to: copy) - let originalHash = try FileHash.folderHash(fixture.root) - let copyHash = try FileHash.folderHash(copy) + let originalHash = try FileSnapshot.read(at: fixture.root) + let copyHash = try FileSnapshot.read(at: copy) let store = StateStore(scope: .project, environment: RuntimeEnvironment(projectDirectory: copy)) - #expect(throws: (any Error).self) { try store.loadDeclaration() } - #expect(try FileHash.folderHash(fixture.root) == originalHash) - #expect(try FileHash.folderHash(copy) == copyHash) + #expect(throws: CoreError.self) { try store.withLock {} } + #expect(try FileSnapshot.read(at: fixture.root) == originalHash) + #expect(try FileSnapshot.read(at: copy) == copyHash) } - @Test(arguments: ["journal", "scratch", "cache", "agent"]) + @Test(arguments: ["journal", "incompleteJournal", "cache", "agent"]) func rejectsSymlinkedRecoveryPaths(_ component: String) throws { let fixture = try TransactionFixture() try abandon(fixture) let original: URL switch component { case "journal": original = fixture.store.directory.appendingPathComponent("transaction.json") - case "scratch": + case "incompleteJournal": original = fixture.store.directory.appendingPathComponent("transaction.new") try Data("incomplete".utf8).write(to: original) case "cache": original = fixture.store.cacheDirectory.appendingPathComponent("artifact-content") @@ -454,9 +478,17 @@ extension StateTransactionTests { let external = fixture.root.appendingPathComponent("external") try FileManager.default.moveItem(at: original, to: external) try FileManager.default.createSymbolicLink(at: original, withDestinationURL: external) - let snapshot = try FileHash.folderHash(fixture.root) - #expect(throws: (any Error).self) { try fixture.store.loadResolved() } - #expect(try FileHash.folderHash(fixture.root) == snapshot) + let snapshot = try FileSnapshot.read(at: fixture.root) + #expect { try fixture.store.withLock {} } throws: { error in + if component == "agent" { + return error as? CoreError == .invalidState("transaction root identity changed") + } + guard case CoreError.unsafePath(let reason) = error else { return false } + return reason.contains( + component == "journal" || component == "incompleteJournal" + ? "cannot open file" : "unsafe directory") + } + #expect(try FileSnapshot.read(at: fixture.root) == snapshot) } @Test func journalEncodingAndDuplicateKeysCannotBypassRecoveryValidation() throws { @@ -476,16 +508,21 @@ extension StateTransactionTests { ] for bytes in encodings { try bytes.write(to: url) - let snapshot = try FileHash.folderHash(fixture.root) - #expect(throws: (any Error).self) { try fixture.store.loadResolved() } - #expect(try FileHash.folderHash(fixture.root) == snapshot) + let snapshot = try FileSnapshot.read(at: fixture.root) + #expect { try fixture.store.withLock {} } throws: { error in + guard case CoreError.invalidState = error else { return false } + return true + } + #expect(try FileSnapshot.read(at: fixture.root) == snapshot) } } try Data(duplicate.utf8).write(to: url) - #expect(throws: (any Error).self) { try fixture.store.loadResolved() } + #expect(throws: CoreError.invalidState("duplicate ledger key")) { + try fixture.store.withLock {} + } try original.write(to: url) #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { - try fixture.store.loadResolved() + try fixture.store.withLock {} } try fixture.check(committed: false) } @@ -496,38 +533,57 @@ extension StateTransactionTests { try FileManager.default.createDirectory( at: root.appendingPathComponent(".claude/skills"), withIntermediateDirectories: true) let child = try stateTestProcess( - root: root, arguments: ["create-scope", "directory.created..agent"]) - defer { - if child.isRunning { - kill(child.processIdentifier, SIGKILL) - child.waitUntilExit() - } - } + root: root, arguments: ["create-scope", FileLock.ancestryCheckpoint(.created(depth: 0))]) + defer { terminateProcess(child) } try waitFor("ready", root: root, child: child) #expect( !FileManager.default.fileExists(atPath: root.appendingPathComponent("lock-acquired").path)) - kill(child.processIdentifier, SIGKILL) - child.waitUntilExit() + terminateProcess(child) + // The interrupted creator's entry receives a parent barrier like every existing component. + let scope = root.appendingPathComponent(".agent") + let barriers = SynchronizationCount() var steps: [String] = [] - try FileLock.withLock( - at: root.appendingPathComponent(".agent/.agents.lock"), checkpoint: { steps.append($0) }, - { - #expect(steps.contains("directory.synced..agent")) + try DirectoryHandle.$synchronizationObserver.withValue( + DirectoryHandle.SynchronizationObserver(didSynchronize: { barriers.add() }), + operation: { + try FileLock.withLock( + at: scope.appendingPathComponent(".agents.lock"), checkpoint: { steps.append($0) }, + { + #expect(barriers.value == scope.resolvingSymlinksInPath().pathComponents.count - 1) + }) }) + #expect(steps.isEmpty) let new = root.appendingPathComponent("new/ancestry/.agents") - steps = [] try FileLock.withLock( at: new.appendingPathComponent(".agents.lock"), checkpoint: { steps.append($0) }, { - for name in ["new", "ancestry", ".agents"] { - let created = try #require(steps.firstIndex(of: "directory.created.\(name)")) - let synced = try #require(steps.firstIndex(of: "directory.synced.\(name)")) + for depth in 0...2 { + let created = try #require( + steps.firstIndex(of: FileLock.ancestryCheckpoint(.created(depth: depth)))) + let synced = try #require( + steps.firstIndex(of: FileLock.ancestryCheckpoint(.synced(depth: depth)))) #expect(created < synced) } + #expect(steps.count == 6) }) } } +private final class SynchronizationCount: @unchecked Sendable { + private let lock = NSLock() + private var count = 0 + var value: Int { + lock.lock() + defer { lock.unlock() } + return count + } + func add() { + lock.lock() + defer { lock.unlock() } + count += 1 + } +} + extension StateTransactionTests { @Test func userRecoveryBindsConfiguredTargetsAndPreservesProjectState() throws { let fixture = try TransactionFixture() @@ -546,10 +602,11 @@ extension StateTransactionTests { try Data("original".utf8).write(to: target.appendingPathComponent("SKILL.md")) } let before = try Data(contentsOf: store.resolvedURL) - #expect(throws: CoreError.self) { - try store.withLock { + let route = try NativeTargetRoute.named(.claudeSkillPlugin, scope: .user, name: "demo") + #expect(throws: CoreError.invalidState("interrupted user write")) { + try store.withLock(footprint: [route]) { let transaction = FileTransaction(store: store) { step in - if step == "replace.3.renamed" { + if step == TransactionCheckpoint.publication(3, .exchanged).name { let journal = try String( contentsOf: store.directory.appendingPathComponent("transaction.json"), encoding: .utf8) @@ -558,15 +615,13 @@ extension StateTransactionTests { } } for target in targets { - try transaction.replace(target, content: fixture.root.appendingPathComponent("new")) + try transaction.replace(target, with: .copy(fixture.root.appendingPathComponent("new"))) } try transaction.replace( - store.declarationURL, content: nil, data: StateStore.encode(Declaration(agents: [.codex])) - ) - try transaction.replace( - store.resolvedURL, content: nil, - data: StateStore.encode( - ResolvedState(sources: ["local:/new": LockedSource(kind: .local)]))) + store.declarationURL, with: .data(manifestText("defaultAgents: [\"codex\"]\n"))) + var ledger = ResolvedLedger() + ledger.sources["local:/new"] = LedgerSource(kind: .local, revision: "live") + try transaction.replace(store.resolvedURL, with: .data(StateStore.encode(ledger))) try transaction.commit() } } @@ -580,3 +635,284 @@ extension StateTransactionTests { #expect(try store.loadDeclaration().agents == nil) } } + +extension StateTransactionTests { + @Test(arguments: [false, true]) + func observedProjectCannotBeRecreatedOrReplacedBeforeAdmission(_ replace: Bool) throws { + let parent = try temporaryDirectory() + defer { removeTemporaryDirectory(parent) } + let project = parent.appendingPathComponent("project") + let moved = parent.appendingPathComponent("moved") + try FileManager.default.createDirectory(at: project, withIntermediateDirectories: false) + let store = StateStore( + scope: .project, environment: RuntimeEnvironment(projectDirectory: project)) + let before = try FileSnapshot.read(at: parent) + let observed = try store.captureExistingProjectRoot() + #expect(try FileSnapshot.read(at: parent) == before) + try FileManager.default.moveItem(at: project, to: moved) + if replace { + try FileManager.default.createDirectory(at: project, withIntermediateDirectories: false) + } + #expect(throws: (any Error).self) { + try store.withLock(existingRoot: observed) { Issue.record("stale root admitted") } + } + #expect(!FileManager.default.fileExists(atPath: project.appendingPathComponent(".agent").path)) + #expect(!FileManager.default.fileExists(atPath: moved.appendingPathComponent(".agent").path)) + #expect(FileManager.default.fileExists(atPath: project.path) == replace) + } + + @Test(arguments: [false, true]) + func observedProjectMovementStopsPublication(_ replace: Bool) throws { + let parent = try temporaryDirectory() + defer { removeTemporaryDirectory(parent) } + let project = parent.appendingPathComponent("project") + let moved = parent.appendingPathComponent("moved") + try FileManager.default.createDirectory(at: project, withIntermediateDirectories: false) + let target = project.appendingPathComponent("AGENTS.md") + try Data("preimage".utf8).write(to: target) + let store = StateStore( + scope: .project, environment: RuntimeEnvironment(projectDirectory: project)) + let observed = try store.captureExistingProjectRoot() + let outcome = TransactionOutcome() + #expect(throws: (any Error).self) { + try store.withLock(outcome: outcome, existingRoot: observed) { + let transaction = FileTransaction(store: store, outcome: outcome) { point in + if point == TransactionCheckpoint.publication(0, .validated).name { + try FileManager.default.moveItem(at: project, to: moved) + if replace { + try FileManager.default.createDirectory( + at: project, withIntermediateDirectories: false) + } + } + } + try transaction.replace(target, with: .data(Data("replacement".utf8))) + try transaction.commit() + } + } + #expect( + try Data(contentsOf: moved.appendingPathComponent("AGENTS.md")) == Data("preimage".utf8)) + #expect( + !FileManager.default.fileExists(atPath: project.appendingPathComponent("AGENTS.md").path)) + #expect(FileManager.default.fileExists(atPath: project.path) == replace) + #expect(outcome.publicationStarted && outcome.recoveryPending) + #expect(outcome.disposition == .recoveryRequired) + if replace { try FileManager.default.removeItem(at: project) } + try FileManager.default.moveItem(at: moved, to: project) + #expect(throws: CoreError.transactionRecovered(store.directory.path)) { try store.withLock {} } + #expect(try Data(contentsOf: target) == Data("preimage".utf8)) + } + + @Test(arguments: [false, true]) + func terminalEvidenceSurvivesFailedDisposalRecovery(_ committed: Bool) throws { + let fixture = try TransactionFixture() + let parent = fixture.root.appendingPathComponent(".agents/skills") + let displaced = fixture.root.appendingPathComponent("displaced-skills") + let outcome = TransactionOutcome() + let stop = + committed + ? TransactionCheckpoint.phase(.committed).name + : TransactionCheckpoint.progress(0, .applied).name + #expect(throws: CoreError.invalidState("interrupted transaction")) { + try fixture.store.withLock(outcome: outcome) { + let transaction = FileTransaction(store: fixture.store, outcome: outcome) { point in + if point == stop { + try FileManager.default.moveItem(at: parent, to: displaced) + throw CoreError.invalidState("interrupted transaction") + } + } + try transaction.replace( + parent.appendingPathComponent("target"), + with: .copy(fixture.root.appendingPathComponent("new"))) + try transaction.commit() + } + } + #expect(outcome.publicationStarted && outcome.recoveryPending) + #expect(outcome.disposition == (committed ? .committed : .recoveryRequired)) + #expect(outcome.terminal == (committed ? .committed : nil)) + #expect( + try Data(contentsOf: displaced.appendingPathComponent("target/SKILL.md")) == Data("new".utf8)) + #expect( + FileManager.default.fileExists( + atPath: fixture.store.directory.appendingPathComponent(TransactionJournal.fileName).path)) + let nextOperation = TransactionOutcome() + #expect(throws: (any Error).self) { + try fixture.store.withLock(outcome: nextOperation) { + Issue.record("pending recovery admitted a new operation") + } + } + #expect(!nextOperation.publicationStarted && nextOperation.terminal == nil) + #expect(nextOperation.disposition == .recoveryRequired && nextOperation.recoveryPending) + try FileManager.default.moveItem(at: displaced, to: parent) + #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { + try fixture.store.withLock(outcome: outcome) {} + } + #expect(outcome.terminal == (committed ? .committed : .rolledBack)) + #expect(!outcome.recoveryPending) + #expect( + try Data(contentsOf: parent.appendingPathComponent("target/SKILL.md")) + == Data((committed ? "new" : "target").utf8)) + } + + @Test func stagingRollbackDoesNotClaimPublication() throws { + let fixture = try TransactionFixture() + let outcome = TransactionOutcome() + try fixture.store.withLock(outcome: outcome) { + let transaction = FileTransaction(store: fixture.store, outcome: outcome) { point in + if point == TransactionCheckpoint.stage(0, .constructed).name { + throw CoreError.invalidState("stop staging") + } + } + try transaction.replace( + fixture.root.appendingPathComponent("AGENTS.md"), with: .data(Data("new".utf8))) + #expect(throws: CoreError.invalidState("stop staging")) { try transaction.commit() } + } + #expect(!outcome.publicationStarted && !outcome.recoveryPending) + #expect(outcome.terminal == .rolledBack && outcome.disposition == .unchanged) + #expect( + try Data(contentsOf: fixture.root.appendingPathComponent("AGENTS.md")) + == Data("old instructions".utf8)) + } +} + +extension StateTransactionTests { + @Test(arguments: [false, true]) + func localSkillInitializationUsesTheSameJournalAtAnExistingAnchor(_ named: Bool) throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let store = StateStore(scope: .project, environment: RuntimeEnvironment(projectDirectory: root)) + let before = try FileSnapshot.read(at: root) + let observation = try store.captureExistingProjectRoot() + let target = try store.skillInitializationTarget(named: named ? "new-skill" : nil) + #expect(try FileSnapshot.read(at: root) == before) + let outcome = TransactionOutcome() + try store.withLock(outcome: outcome, existingRoot: observation) { + #expect(throws: CoreError.self) { + try FileTransaction(store: store).replace(target.file, with: .data(Data("unadmitted".utf8))) + } + let transaction = FileTransaction(store: store, outcome: outcome) + try transaction.initializeSkill(target, bytes: Data("skill template".utf8)) + try transaction.commit() + } + #expect(outcome.terminal == .committed && !outcome.recoveryPending) + #expect(try Data(contentsOf: target.file) == Data("skill template".utf8)) + #expect(throws: CoreError.self) { + try store.skillInitializationTarget(named: named ? "new-skill" : nil) + } + for name in ["../escape", ".", "a/b", "UPPER"] { + #expect(throws: CoreError.self) { try store.skillInitializationTarget(named: name) } + } + } + + @Test func localSkillInitializationRollbackRetainsTheRecordedAbsence() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let store = StateStore(scope: .project, environment: RuntimeEnvironment(projectDirectory: root)) + let observed = try store.captureExistingProjectRoot() + let target = try store.skillInitializationTarget(named: "new-skill") + let outcome = TransactionOutcome() + try store.withLock(outcome: outcome, existingRoot: observed) { + let transaction = FileTransaction(store: store, outcome: outcome) { point in + if point == TransactionCheckpoint.publication(0, .created).name { + throw CoreError.invalidState("skill publication interrupted") + } + } + try transaction.initializeSkill(target, bytes: Data("template".utf8)) + #expect(throws: CoreError.invalidState("skill publication interrupted")) { + try transaction.commit() + } + } + #expect( + outcome.publicationStarted && outcome.terminal == .rolledBack && !outcome.recoveryPending) + #expect(!FileManager.default.fileExists(atPath: target.file.path)) + #expect( + !FileManager.default.fileExists( + atPath: store.directory.appendingPathComponent(TransactionJournal.fileName).path)) + } +} + +extension StateTransactionTests { + @Test func localSkillInitializationCannotFollowAChildLink() throws { + let parent = try temporaryDirectory() + defer { removeTemporaryDirectory(parent) } + let root = parent.appendingPathComponent("project") + let outside = parent.appendingPathComponent("outside") + for directory in [root, outside] { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false) + } + try FileManager.default.createSymbolicLink( + at: root.appendingPathComponent("linked"), withDestinationURL: outside) + let store = StateStore(scope: .project, environment: RuntimeEnvironment(projectDirectory: root)) + let observed = try store.captureExistingProjectRoot() + let target = try store.skillInitializationTarget(named: "linked") + #expect(throws: (any Error).self) { + try store.withLock(existingRoot: observed) { + let transaction = FileTransaction(store: store) + try transaction.initializeSkill(target, bytes: Data("template".utf8)) + try transaction.commit() + } + } + #expect( + !FileManager.default.fileExists(atPath: outside.appendingPathComponent("SKILL.md").path)) + } +} + +extension StateTransactionTests { + @Test func explicitlySelectedLocalDirectoryRetainsItsExactSpelling() throws { + let parent = try temporaryDirectory() + defer { removeTemporaryDirectory(parent) } + let store = StateStore( + scope: .project, environment: RuntimeEnvironment(projectDirectory: parent)) + let observed = try store.captureExistingProjectRoot() + let target = try store.skillInitializationTarget(inChildDirectory: "Selected Skill") + try store.withLock(existingRoot: observed) { + let transaction = FileTransaction(store: store) + try transaction.initializeSkill(target, bytes: Data("template".utf8)) + try transaction.commit() + } + #expect(target.file.deletingLastPathComponent().lastPathComponent == "Selected Skill") + #expect(try Data(contentsOf: target.file) == Data("template".utf8)) + for name in ["", ".", "..", "../outside", "a/b", "a\\b"] { + #expect(throws: CoreError.self) { + try store.skillInitializationTarget(inChildDirectory: name) + } + } + } +} + +extension StateTransactionTests { + @Test func durableRollbackTerminalSurvivesLossOfScopeReachability() throws { + let fixture = try TransactionFixture() + let moved = fixture.root.deletingLastPathComponent().appendingPathComponent( + fixture.root.lastPathComponent + "-moved") + defer { removeTemporaryDirectory(moved) } + let observed = try fixture.store.captureExistingProjectRoot() + let outcome = TransactionOutcome() + #expect(throws: CoreError.invalidState("stop publication")) { + try fixture.store.withLock(outcome: outcome, existingRoot: observed) { + let transaction = FileTransaction(store: fixture.store, outcome: outcome) { point in + if point == TransactionCheckpoint.publication(0, .exchanged).name { + throw CoreError.invalidState("stop publication") + } + if point == "recovery." + TransactionCheckpoint.phase(.rolledBack).name { + try FileManager.default.moveItem(at: fixture.root, to: moved) + throw CoreError.invalidState("scope moved after durable rollback") + } + } + try transaction.replace( + fixture.root.appendingPathComponent("AGENTS.md"), with: .data(Data("replacement".utf8))) + try transaction.commit() + } + } + #expect( + outcome.publicationStarted && outcome.terminal == .rolledBack && outcome.recoveryPending) + #expect( + try Data(contentsOf: moved.appendingPathComponent("AGENTS.md")) + == Data("old instructions".utf8)) + #expect(!FileManager.default.fileExists(atPath: fixture.root.path)) + try FileManager.default.moveItem(at: moved, to: fixture.root) + #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { + try fixture.store.withLock(outcome: outcome) {} + } + #expect(outcome.terminal == .rolledBack && !outcome.recoveryPending) + } +} diff --git a/Tests/AgentsCoreTests/TransactionCostTests.swift b/Tests/AgentsCoreTests/TransactionCostTests.swift new file mode 100644 index 0000000..7e48c7c --- /dev/null +++ b/Tests/AgentsCoreTests/TransactionCostTests.swift @@ -0,0 +1,181 @@ +import AgentsManifest +import Foundation +import StateTestSupport +import Testing + +@testable import AgentsCore + +@Suite("Transaction I/O cost") +struct TransactionCostTests { + enum SharedMetadataDrift: CaseIterable { + case siblingReplacement, siblingRemoval, siblingPermissions, baseReplacement + } + + @Test(arguments: SharedMetadataDrift.allCases) + func sharedMetadataValidationRejectsDriftBetweenPasses(_ drift: SharedMetadataDrift) throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let loader = root.appendingPathComponent("generated-claude") + let store = StateStore( + scope: .user, + environment: RuntimeEnvironment( + projectDirectory: root, homeDirectory: root, + environment: ["CLAUDE_CONFIG_DIR": loader.path])) + let resources = try ["first", "second"].map { name in + let route = try NativeTargetRoute.named(.claudeSkillPlugin, scope: .user, name: name) + return try SharedResource(store: store, route: route, create: true) + } + try SharedResource.validateAll(resources) + let sibling = try #require(resources[1].metadata).url + defer { + if drift == .siblingPermissions { + try? FileManager.default.setAttributes( + [.posixPermissions: 0o700], ofItemAtPath: sibling.path) + } + } + let displaced = root.appendingPathComponent("displaced") + switch drift { + case .siblingReplacement, .siblingRemoval: + try FileManager.default.moveItem(at: sibling, to: displaced) + if drift == .siblingReplacement { + try FileManager.default.createDirectory( + at: sibling, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700]) + } + case .siblingPermissions: + try FileManager.default.setAttributes([.posixPermissions: 0o500], ofItemAtPath: sibling.path) + case .baseReplacement: + let base = sibling.deletingLastPathComponent() + try FileManager.default.moveItem(at: base, to: displaced) + try FileManager.default.createDirectory( + at: base, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700]) + for resource in resources { + let metadata = try #require(resource.metadata) + try FileManager.default.moveItem( + at: displaced.appendingPathComponent(metadata.url.lastPathComponent), to: metadata.url) + } + } + if drift != .baseReplacement { try SharedResource.validateAll([resources[0]]) } + #expect(throws: CoreError.self) { try SharedResource.validateAll(resources) } + } + + @Test func mixedInstallationBatchKeepsEachTargetUnderItsRegisteredRoot() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let home = root.appendingPathComponent("home") + let loader = root.appendingPathComponent("claude") + let physical = root.appendingPathComponent("physical-claude") + try FileManager.default.createDirectory(at: physical, withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink(at: loader, withDestinationURL: physical) + let source = root.appendingPathComponent("source") + try FileManager.default.createDirectory(at: source, withIntermediateDirectories: true) + let bytes = Data("generated skill\n".utf8) + try bytes.write(to: source.appendingPathComponent("SKILL.md")) + let store = StateStore( + scope: .user, + environment: RuntimeEnvironment( + projectDirectory: root, homeDirectory: home, + environment: ["CLAUDE_CONFIG_DIR": loader.path])) + try store.save(declaration: Declaration(), resolved: ResolvedState()) + let agents = + Array(repeating: AgentID.codex, count: 16) + + Array(repeating: AgentID.claudeCode, count: 8) + let targets = try agents.enumerated().map { + try store.skillInstallationTarget(for: $0.element, named: "generated-\($0.offset)") + } + try store.withLock(installations: targets) { + let transaction = FileTransaction(store: store) + for target in targets { try transaction.replaceSkill(target, with: .link(source)) } + try transaction.commit() + } + for target in targets { + let installed = try #require(try FileSnapshot.read(at: target.url)) + #expect(installed.isSymbolicLink) + #expect(try Data(contentsOf: target.url.appendingPathComponent("SKILL.md")) == bytes) + let expected = + target.agent == .claudeCode + ? physical.appendingPathComponent("skills") : home.appendingPathComponent(".agents/skills") + #expect(target.url.deletingLastPathComponent().path == expected.path) + } + #expect( + !FileManager.default.fileExists( + atPath: store.directory.appendingPathComponent("transaction.json").path)) + } + + @Test func coincidentInstallationParentsRetainBothLoaderChecks() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let original = root.appendingPathComponent(".agents") + let redirected = root.appendingPathComponent("redirected") + let alias = root.appendingPathComponent(".claude") + for parent in [original, redirected] { + try FileManager.default.createDirectory( + at: parent.appendingPathComponent("skills"), withIntermediateDirectories: true) + } + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: original) + let source = root.appendingPathComponent("source") + try FileManager.default.createDirectory(at: source, withIntermediateDirectories: true) + try Data("generated skill\n".utf8).write(to: source.appendingPathComponent("SKILL.md")) + let store = StateStore( + scope: .project, + environment: RuntimeEnvironment( + projectDirectory: root, homeDirectory: root.appendingPathComponent("home"), environment: [:] + )) + try store.save(declaration: Declaration(), resolved: ResolvedState()) + let codex = try store.skillInstallationTarget(for: .codex, named: "codex-skill") + let claude = try store.skillInstallationTarget(for: .claudeCode, named: "claude-skill") + #expect(try #require(codex.parentIdentity) == claude.parentIdentity) + var moved = false + #expect(throws: CoreError.self) { + try store.withLock(installations: [codex, claude]) { + let transaction = FileTransaction(store: store) { point in + if point == TransactionCheckpoint.phase(.preparing).name { + try FileManager.default.removeItem(at: alias) + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: redirected) + moved = true + } + } + try transaction.replaceSkill(codex, with: .link(source)) + try transaction.replaceSkill(claude, with: .link(source)) + try transaction.commit() + } + } + #expect(moved) + for parent in [original, redirected] { + for target in [codex, claude] { + let url = parent.appendingPathComponent("skills").appendingPathComponent(target.name) + #expect(try FileSnapshot.read(at: url) == nil) + } + } + let journal = store.directory.appendingPathComponent("transaction.json") + #expect(FileManager.default.fileExists(atPath: journal.path)) + try FileManager.default.removeItem(at: alias) + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: original) + #expect(throws: CoreError.transactionRecovered(store.directory.path)) { try store.withLock {} } + #expect(!FileManager.default.fileExists(atPath: journal.path)) + for parent in [original, redirected] { + #expect(try FileManager.default.contentsOfDirectory(atPath: parent.path + "/skills").isEmpty) + } + } + + @Test func containersOnOneDeviceShareOneProbe() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let store = StateStore( + scope: .project, + environment: RuntimeEnvironment(projectDirectory: root, homeDirectory: root, environment: [:]) + ) + try store.save(declaration: Declaration(), resolved: ResolvedState()) + var steps: [String] = [] + try store.withLock { + let transaction = FileTransaction(store: store) { steps.append($0) } + try transaction.replace( + root.appendingPathComponent("AGENTS.md"), with: .data(Data("after".utf8))) + try transaction.replace( + store.declarationURL, with: .data(manifestText("defaultAgents: [\"codex\"]\n"))) + try transaction.commit() + } + #expect(steps.contains(TransactionCheckpoint.containerCreated(1).name)) + #expect(steps.contains(TransactionCheckpoint.probe(0, .verified).name)) + #expect(!steps.contains(TransactionCheckpoint.probe(1, .firstCreated).name)) + } +} diff --git a/Tests/AgentsCoreTests/TransactionMetadataTests.swift b/Tests/AgentsCoreTests/TransactionMetadataTests.swift index 65bb776..caa2f5d 100644 --- a/Tests/AgentsCoreTests/TransactionMetadataTests.swift +++ b/Tests/AgentsCoreTests/TransactionMetadataTests.swift @@ -1,12 +1,16 @@ -import Darwin +import CPlatform import Foundation +import StateTestSupport import Testing @testable import AgentsCore @Suite("Transaction metadata") struct TransactionMetadataTests { - @Test(arguments: ["complete", "journal.applying", "replace.1", "journal.committed"]) + @Test(arguments: [ + "complete", TransactionCheckpoint.progress(0, .publishing).name, + TransactionCheckpoint.progress(1, .applied).name, TransactionCheckpoint.phase(.committed).name, + ]) func dataReplacementPreservesPermissionsACLsAndExtendedAttributes(_ point: String) throws { let fixture = try TransactionFixture() let target = fixture.root.appendingPathComponent("AGENTS.md") @@ -14,15 +18,7 @@ struct TransactionMetadataTests { try Data("owner content".utf8).write(to: target) let files = [target, fixture.store.declarationURL, fixture.store.resolvedURL] for (file, mode) in zip(files, [0o644, 0o440, 0o600]) { - let value = Data("owner metadata".utf8) - try #require( - value.withUnsafeBytes { - setxattr(file.path, "org.agents.tests", $0.baseAddress, $0.count, 0, XATTR_NOFOLLOW) - } == 0) - try ProcessRunner.run( - "/bin/chmod", - arguments: ["+a", "everyone allow readattr,readextattr,readsecurity", file.path]) - try #require(chmod(file.path, mode_t(mode)) == 0) + try setFixtureMetadata(file, mode: mode_t(mode), value: Data("owner metadata".utf8)) } let before = try files.map(metadata) let original = try files.map { try Data(contentsOf: $0) } @@ -32,15 +28,15 @@ struct TransactionMetadataTests { if step == point { throw CoreError.invalidState("injected failure") } } for file in files + [created] { - try transaction.replace(file, content: nil, data: replacement) + try transaction.replace(file, with: .data(replacement)) } if point == "complete" { try transaction.commit() } else { - #expect(throws: CoreError.self) { try transaction.commit() } + #expect(throws: CoreError.invalidState("injected failure")) { try transaction.commit() } } } - let committed = point == "complete" || point == "journal.committed" + let committed = point == "complete" || point == TransactionCheckpoint.phase(.committed).name #expect(try files.map(metadata) == before) #expect( try files.map { try Data(contentsOf: $0) } @@ -55,10 +51,13 @@ struct TransactionMetadataTests { try expectRecoveryMaterialRemoved(fixture) } - @Test(arguments: ["complete", "journal.committed", "cleanup.0"]) + @Test(arguments: [ + "complete", TransactionCheckpoint.phase(.committed).name, + TransactionCheckpoint.containerRemoved(0).name, + ]) func committedCleanupDiscardsReadOnlyDirectories(_ point: String) throws { let fixture = try TransactionFixture() - defer { makeWritableForTeardown(fixture.root) } + defer { makeDirectoriesWritable(fixture.root) } let target = fixture.root.appendingPathComponent(".agents/skills/target") let source = fixture.root.appendingPathComponent("new") let targets = try makeReadOnlyTree(target) @@ -73,7 +72,7 @@ struct TransactionMetadataTests { } else { try interrupt(fixture, command: "crash", at: point) #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { - try fixture.store.loadResolved() + try fixture.store.withLock {} } } @@ -84,10 +83,14 @@ struct TransactionMetadataTests { try expectRecoveryMaterialRemoved(fixture) } - @Test(arguments: ["restore.3.renamed", "restore.0.renamed", "journal.rolledBack.renamed"]) + @Test(arguments: [ + TransactionCheckpoint.restoration(3, .returned).name, + TransactionCheckpoint.restoration(0, .exchanged).name, + TransactionCheckpoint.persisted(.rolledBack, .terminal, .renamed).name, + ]) func interruptedRollbackPreservesReadOnlyMetadata(_ point: String) throws { let fixture = try TransactionFixture() - defer { makeWritableForTeardown(fixture.root) } + defer { makeDirectoriesWritable(fixture.root) } let target = fixture.root.appendingPathComponent(".agents/skills/target") let pruned = fixture.store.cacheDirectory.appendingPathComponent("artifact-content/pruned") let originals = try makeReadOnlyTree(target) + makeReadOnlyTree(pruned) @@ -97,10 +100,10 @@ struct TransactionMetadataTests { let declaration = try Data(contentsOf: fixture.store.declarationURL) let resolved = try Data(contentsOf: fixture.store.resolvedURL) - try interrupt(fixture, command: "crash", at: "replace.4") + try interrupt(fixture, command: "crash", at: TransactionCheckpoint.progress(4, .applied).name) try interrupt(fixture, command: "recover", at: point) #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { - try fixture.store.loadResolved() + try fixture.store.withLock {} } try fixture.check(committed: false) @@ -111,7 +114,11 @@ struct TransactionMetadataTests { try expectRecoveryMaterialRemoved(fixture) } - @Test(arguments: ["journal.applying", "replace.0", "replace.2"]) + @Test(arguments: [ + TransactionCheckpoint.progress(0, .publishing).name, + TransactionCheckpoint.progress(0, .applied).name, + TransactionCheckpoint.progress(2, .applied).name, + ]) func rollbackPreservesPermissionsACLsAndExtendedAttributes(_ point: String) throws { let fixture = try TransactionFixture() let target = fixture.root.appendingPathComponent(".agents/skills/target") @@ -122,21 +129,12 @@ struct TransactionMetadataTests { try FileManager.default.createSymbolicLink(atPath: link.path, withDestinationPath: "SKILL.md") let urls = [target, file, nested, link] for (url, mode) in zip(urls, [0o750, 0o666, 0o775, 0o751]) { - #expect(lchmod(url.path, mode_t(mode)) == 0) - let value = Data("metadata:\(url.lastPathComponent)".utf8) - let result = value.withUnsafeBytes { - setxattr(url.path, "org.agents.tests", $0.baseAddress, $0.count, 0, XATTR_NOFOLLOW) - } - #expect(result == 0) - if url != link { - try ProcessRunner.run( - "/bin/chmod", - arguments: ["+a", "everyone allow readattr,readextattr,readsecurity", url.path]) - } + try setFixtureMetadata( + url, mode: mode_t(mode), value: Data("metadata:\(url.lastPathComponent)".utf8)) } let before = try urls.map(metadata) let bytes = try FileHash.folderHash(target) - #expect(throws: CoreError.self) { + #expect(throws: CoreError.invalidState("injected failure")) { try fixture.commit { step in if step == point { throw CoreError.invalidState("injected failure") } } @@ -146,12 +144,6 @@ struct TransactionMetadataTests { try fixture.check(committed: false) } - private struct Metadata: Equatable { - var mode: mode_t - var acl: String - var attribute: Data - } - private func makeReadOnlyTree(_ root: URL) throws -> [URL] { let nested = root.appendingPathComponent("nested") try FileManager.default.createDirectory(at: nested, withIntermediateDirectories: true) @@ -161,38 +153,18 @@ struct TransactionMetadataTests { try FileManager.default.createSymbolicLink(atPath: link.path, withDestinationPath: "SKILL.md") let urls = [root, root.appendingPathComponent("SKILL.md"), nested, file, link] for (url, mode) in zip(urls, [0o555, 0o444, 0o555, 0o444, 0o751]) { - let value = Data("preserved metadata".utf8) - try #require( - value.withUnsafeBytes { - setxattr(url.path, "org.agents.tests", $0.baseAddress, $0.count, 0, XATTR_NOFOLLOW) - } == 0) - if url != link { - try ProcessRunner.run( - "/bin/chmod", - arguments: ["+a", "everyone allow readattr,readextattr,readsecurity", url.path]) - } - try #require(lchmod(url.path, mode_t(mode)) == 0) + try setFixtureMetadata(url, mode: mode_t(mode), value: Data("preserved metadata".utf8)) } return urls } private func interrupt(_ fixture: TransactionFixture, command: String, at point: String) throws { let child = try stateTestProcess(root: fixture.root, arguments: [command, point]) - defer { - if child.isRunning { - kill(child.processIdentifier, SIGKILL) - child.waitUntilExit() - } - } + defer { terminateProcess(child) } let marker = fixture.root.appendingPathComponent( command == "recover" ? "recovery-ready" : "ready") - let deadline = Date().addingTimeInterval(10) - while !FileManager.default.fileExists(atPath: marker.path), Date() < deadline, child.isRunning { - Thread.sleep(forTimeInterval: 0.01) - } - try #require(FileManager.default.fileExists(atPath: marker.path)) - kill(child.processIdentifier, SIGKILL) - child.waitUntilExit() + try ProcessWait.marker(marker, child: child, root: fixture.root) + terminateProcess(child) #expect(child.terminationReason == .uncaughtSignal) } @@ -208,38 +180,7 @@ struct TransactionMetadataTests { }) } - private func makeWritableForTeardown(_ root: URL) { - guard let entries = FileManager.default.enumerator(at: root, includingPropertiesForKeys: nil) - else { - return - } - for case let entry as URL in entries { - var info = stat() - if lstat(entry.path, &info) == 0, info.st_mode & S_IFMT == S_IFDIR { - _ = chmod(entry.path, (info.st_mode & 0o7777) | S_IRWXU) - } - } - } - - private func metadata(_ url: URL) throws -> Metadata { - var info = stat() - try #require(lstat(url.path, &info) == 0) - let size = getxattr(url.path, "org.agents.tests", nil, 0, 0, XATTR_NOFOLLOW) - try #require(size >= 0) - var data = Data(count: size) - let count = data.withUnsafeMutableBytes { - getxattr(url.path, "org.agents.tests", $0.baseAddress, $0.count, 0, XATTR_NOFOLLOW) - } - try #require(count == size) - var text = "" - if info.st_mode & S_IFMT != S_IFLNK { - let acl = try #require(acl_get_file(url.path, ACL_TYPE_EXTENDED)) - defer { acl_free(UnsafeMutableRawPointer(acl)) } - if let value = acl_to_text(acl, nil) { - text = String(cString: value) - acl_free(value) - } - } - return Metadata(mode: info.st_mode, acl: text, attribute: data) + private func metadata(_ url: URL) throws -> FixtureMetadata { + try fixtureMetadata(url) } } diff --git a/Tests/AgentsCoreTests/WatchDurabilityTests.swift b/Tests/AgentsCoreTests/WatchDurabilityTests.swift index b651a3e..b54983f 100644 --- a/Tests/AgentsCoreTests/WatchDurabilityTests.swift +++ b/Tests/AgentsCoreTests/WatchDurabilityTests.swift @@ -1,8 +1,11 @@ -import AgentsCore -import Darwin +import AgentsManifest +import CPlatform import Foundation +import StateTestSupport import Testing +@testable import AgentsCore + @Suite("Watch Git durability") struct WatchDurabilityTests { @Test( @@ -10,8 +13,10 @@ struct WatchDurabilityTests { [ "watch.mirror.fetched", "watch.references.pending", "watch.objects.synced", "watch.ref.updated", "watch.ref.synced", - "watch.mirror.synced", "journal.applying", "replace.0.renamed", - "journal.committed.renamed", "journal.committed", "journal.removed", + "watch.mirror.synced", TransactionCheckpoint.progress(0, .publishing).name, + TransactionCheckpoint.publication(0, .exchanged).name, + TransactionCheckpoint.persisted(.committed, .terminal, .renamed).name, + TransactionCheckpoint.phase(.committed).name, TransactionCheckpoint.journalRemoved.name, ]) func interruptedAcknowledgmentRetainsTheRecoveredBaseline(_ advancing: Bool, _ step: String) throws @@ -27,7 +32,10 @@ struct WatchDurabilityTests { let child = try stateTestProcess( root: fixture.root, arguments: [advancing ? "watch-seen" : "watch-add", step]) try fixture.kill(child, at: step) - let committed = step.hasPrefix("journal.committed") || step == "journal.removed" + let committed = [ + TransactionCheckpoint.persisted(.committed, .terminal, .renamed), .phase(.committed), + .journalRemoved, + ].map(\.name).contains(step) let state = try fixture.recoveredWatch() let expected = committed ? current : advancing ? first : nil #expect(state.sources[fixture.id]?.seen == expected.map(WatchSeen.revision)) @@ -106,7 +114,7 @@ struct WatchDurabilityTests { let before = try fixture.stateBytes() let watch = WatchOperations( discoverSkills: { _ in [] }, - fetchArtifacts: { _ in throw CoreError.unsupported("Git fixture") }, + fetchArtifacts: { _ in throw CoreError.unsupported("Git fixture") }, declarations: .manifest, checkpoint: { step in if step == "watch.ref.updated" { throw CoreError.invalidState("injected durability failure") @@ -163,7 +171,7 @@ final class WatchGitFixture { try store.save( declaration: Declaration(sources: [ "source": SourceDeclaration(kind: .local, location: repo.path) - ]), resolved: ResolvedState()) + ]), ledger: ResolvedLedger()) } catch { try? FileManager.default.removeItem(at: root) throw error @@ -208,10 +216,10 @@ final class WatchGitFixture { } } + /// Recovers as the next mutating command would, then reads the watch state. func recoveredWatch() throws -> WatchState { - do { return try store.loadWatch() } catch CoreError.transactionRecovered { - return try store.loadWatch() - } + do { try store.withLock {} } catch CoreError.transactionRecovered {} + return try store.loadWatch() } func cachedInstruction(_ revision: String) throws -> String { @@ -229,21 +237,13 @@ final class WatchGitFixture { } func kill(_ child: Process, at step: String) throws { - defer { - if child.isRunning { - Darwin.kill(child.processIdentifier, SIGKILL) - child.waitUntilExit() - } - } + defer { terminateProcess(child) } let marker = root.appendingPathComponent("ready") - let deadline = Date().addingTimeInterval(30) - while !FileManager.default.fileExists(atPath: marker.path), child.isRunning, Date() < deadline { - Thread.sleep(forTimeInterval: 0.01) - } - try #require(FileManager.default.fileExists(atPath: marker.path), "did not reach \(step)") - #expect(try String(contentsOf: marker, encoding: .utf8) == step) - Darwin.kill(child.processIdentifier, SIGKILL) - child.waitUntilExit() + try ProcessWait.marker(marker, child: child, root: root) + try ProcessWait.stopped(child, root: root) + let observed = try String(contentsOf: marker, encoding: .utf8) + #expect(observed == step) + terminateProcess(child) try FileManager.default.removeItem(at: marker) } } diff --git a/Tests/AgentsCoreTests/WatchGitLockTests.swift b/Tests/AgentsCoreTests/WatchGitLockTests.swift index 6ec0d28..d12875d 100644 --- a/Tests/AgentsCoreTests/WatchGitLockTests.swift +++ b/Tests/AgentsCoreTests/WatchGitLockTests.swift @@ -1,6 +1,7 @@ import AgentsCore -import Darwin +import CPlatform import Foundation +import StateTestSupport import Testing @Suite("Watch Git lock recovery") @@ -39,13 +40,13 @@ struct WatchGitLockTests { defer { // Freeze the scope owner before killing its Git children, so error handling // cannot race the assertions about abandoned locks. - if writer.isRunning { Darwin.kill(writer.processIdentifier, SIGSTOP) } + if writer.isRunning { CPlatform.kill(writer.processIdentifier, SIGSTOP) } if let text = try? String(contentsOf: ready, encoding: .utf8) { for pid in text.split(whereSeparator: \.isWhitespace).compactMap({ Int32($0) }) { - Darwin.kill(pid, SIGKILL) + CPlatform.kill(pid, SIGKILL) } } - terminate(writer) + terminateProcess(writer) } try waitFor(ready, process: writer) var locks = [ @@ -55,30 +56,31 @@ struct WatchGitLockTests { if packed { locks.append(fixture.mirror.appendingPathComponent("packed-refs.new")) } for lock in locks { try #require(FileManager.default.fileExists(atPath: lock.path)) } let reader = try stateTestProcess(root: fixture.root, arguments: ["read", ""]) - defer { terminate(reader) } + defer { terminateProcess(reader) } try waitFor(fixture.root.appendingPathComponent("reader-started"), process: reader) Thread.sleep(forTimeInterval: 0.05) #expect( !FileManager.default.fileExists( atPath: fixture.root.appendingPathComponent("reader-finished").path)) for lock in locks { #expect(FileManager.default.fileExists(atPath: lock.path)) } - terminate(reader) - Darwin.kill(writer.processIdentifier, SIGSTOP) + terminateProcess(reader) + CPlatform.kill(writer.processIdentifier, SIGSTOP) let pids = try String(contentsOf: ready, encoding: .utf8) .split(whereSeparator: \.isWhitespace).compactMap { Int32($0) } try #require(pids.count == 2) - for pid in pids { Darwin.kill(pid, SIGKILL) } - terminate(writer) + for pid in pids { CPlatform.kill(pid, SIGKILL) } + terminateProcess(writer) try FileManager.default.removeItem(at: ready) try FileManager.default.removeItem(at: hook) for lock in locks { #expect(FileManager.default.fileExists(atPath: lock.path)) } // Pruning the disappeared upstream branch would need the abandoned packed-refs lock. try fixture.rewrite("later") let before = try FileHash.folderHash(fixture.store.directory) - let pending = CoreError.invalidState("transaction recovery is required before inspection") - #expect(throws: pending) { try fixture.watch.status(environment: fixture.environment) } + #expect(throws: pendingRecovery) { try fixture.watch.status(environment: fixture.environment) } #expect(try FileHash.folderHash(fixture.store.directory) == before) - #expect(throws: pending) { try fixture.watch.diff("source", environment: fixture.environment) } + #expect(throws: pendingRecovery) { + try fixture.watch.diff("source", environment: fixture.environment) + } #expect(try FileHash.folderHash(fixture.store.directory) == before) let committed = try fixture.stateBytes() @@ -87,8 +89,8 @@ struct WatchGitLockTests { } for lock in additional { try Data("abandoned".utf8).write(to: lock) } let recovery = try stateTestProcess( - root: fixture.root, arguments: ["watch-recover", "watch.git-lock.unlinked"]) - try fixture.kill(recovery, at: "watch.git-lock.unlinked") + root: fixture.root, arguments: ["watch-recover", "watch.git-lock.0.0.unlinked"]) + try fixture.kill(recovery, at: "watch.git-lock.0.0.unlinked") #expect( try fixture.recoveredWatch().sources[fixture.id]?.seen == (removing ? nil : .revision(replacement))) @@ -124,7 +126,7 @@ struct WatchGitLockTests { try #require(mkfifo(unsafe.path, 0o600) == 0) } let before = try fixture.stateBytes() - #expect(throws: CoreError.self) { try fixture.store.loadWatch() } + #expect(throws: CoreError.self) { try fixture.store.withLock {} } #expect(try fixture.stateBytes() == before) #expect(try Data(contentsOf: safe) == original) #expect(try Data(contentsOf: external) == original) @@ -151,18 +153,6 @@ struct WatchGitLockTests { } private func waitFor(_ marker: URL, process: Process) throws { - let deadline = Date().addingTimeInterval(30) - while !FileManager.default.fileExists(atPath: marker.path), process.isRunning, Date() < deadline - { - Thread.sleep(forTimeInterval: 0.01) - } - try #require(FileManager.default.fileExists(atPath: marker.path)) - } - - private func terminate(_ process: Process) { - if process.isRunning { - Darwin.kill(process.processIdentifier, SIGKILL) - process.waitUntilExit() - } + try ProcessWait.marker(marker, child: process, root: marker.deletingLastPathComponent()) } } diff --git a/Tests/AgentsCoreTests/WatchInspectionTests.swift b/Tests/AgentsCoreTests/WatchInspectionTests.swift index 078be13..df50225 100644 --- a/Tests/AgentsCoreTests/WatchInspectionTests.swift +++ b/Tests/AgentsCoreTests/WatchInspectionTests.swift @@ -1,10 +1,15 @@ -import AgentsCore +import AgentsManifest import Foundation import Testing +@testable import AgentsCore + @Suite("Read-only watch inspection") struct WatchInspectionTests { - @Test(arguments: ["replace.0.renamed", "journal.committed"]) + @Test(arguments: [ + TransactionCheckpoint.publication(0, .exchanged).name, + TransactionCheckpoint.phase(.committed).name, + ]) func pendingTransactionLeavesStateUnchanged(_ step: String) throws { let fixture = try WatchGitFixture() try fixture.watch.add("source", environment: fixture.environment) @@ -16,15 +21,16 @@ struct WatchInspectionTests { FileManager.default.fileExists( atPath: fixture.store.directory.appendingPathComponent("transaction.json").path)) let before = try FileHash.folderHash(fixture.store.directory) - let pending = CoreError.invalidState("transaction recovery is required before inspection") - #expect(throws: pending) { try fixture.watch.status(environment: fixture.environment) } + #expect(throws: pendingRecovery) { try fixture.watch.status(environment: fixture.environment) } #expect(try FileHash.folderHash(fixture.store.directory) == before) - #expect(throws: pending) { try fixture.watch.diff("source", environment: fixture.environment) } + #expect(throws: pendingRecovery) { + try fixture.watch.diff("source", environment: fixture.environment) + } #expect(try FileHash.folderHash(fixture.store.directory) == before) } - @Test(arguments: ["journal.removed", "watch.references.deleted"]) + @Test(arguments: [TransactionCheckpoint.journalRemoved.name, "watch.references.0.0.deleted"]) func pendingRefCleanupLeavesStateUnchanged(_ step: String) throws { let fixture = try WatchGitFixture() let first = try fixture.head() @@ -40,15 +46,17 @@ struct WatchInspectionTests { try #require( FileManager.default.fileExists( atPath: fixture.store.directory.appendingPathComponent("watch-refs.pending").path)) - let refs: Set = step == "journal.removed" ? [first, committed] : [committed] + let refs: Set = + step == TransactionCheckpoint.journalRemoved.name ? [first, committed] : [committed] try #require(try fixture.watchRefs() == refs) try fixture.rewrite("later") let before = try FileHash.folderHash(fixture.store.directory) - let pending = CoreError.invalidState("transaction recovery is required before inspection") - #expect(throws: pending) { try fixture.watch.status(environment: fixture.environment) } + #expect(throws: pendingRecovery) { try fixture.watch.status(environment: fixture.environment) } #expect(try FileHash.folderHash(fixture.store.directory) == before) - #expect(throws: pending) { try fixture.watch.diff("source", environment: fixture.environment) } + #expect(throws: pendingRecovery) { + try fixture.watch.diff("source", environment: fixture.environment) + } #expect(try FileHash.folderHash(fixture.store.directory) == before) #expect(try fixture.watchRefs() == refs) } @@ -69,6 +77,11 @@ struct WatchInspectionTests { discoverSkills: { _ in [] }, fetchArtifacts: { _ in throw CoreError.unsupported("no subscribed sources") }) + let inspection = try watch.inspectStatus(scope: scope, environment: environment) + #expect(inspection.statuses.isEmpty) + #expect( + Set(inspection.readLocations) + == Set([store.declarationURL, store.resolvedURL, store.watchURL])) #expect(try watch.status(scope: scope, environment: environment).isEmpty) #expect(try FileHash.folderHash(root) == before) #expect(throws: CoreError.notFound("source is not subscribed: ./source")) { diff --git a/Tests/AgentsCoreTests/WatchMirrorConcurrencyTests.swift b/Tests/AgentsCoreTests/WatchMirrorConcurrencyTests.swift index c7713e9..2135a26 100644 --- a/Tests/AgentsCoreTests/WatchMirrorConcurrencyTests.swift +++ b/Tests/AgentsCoreTests/WatchMirrorConcurrencyTests.swift @@ -1,5 +1,5 @@ import AgentsCore -import Darwin +import CPlatform import Foundation import Testing @@ -42,7 +42,7 @@ struct WatchMirrorConcurrencyTests { #expect(currentLocks == locks) // Recovery and re-acknowledgment must follow the surviving Git child's completion. - try finishProcesses([acknowledger], resuming: pause) + try finishProcesses([acknowledger], root: fixture.root, resuming: pause) #expect(try fixture.store.loadWatch().sources[fixture.id]?.seen == .revision(first)) #expect(try fixture.watchRefs() == [first]) #expect(try gitLocks(fixture).isEmpty) @@ -51,53 +51,48 @@ struct WatchMirrorConcurrencyTests { #expect(try fixture.cachedInstruction(first).contains("initial")) } - @Test(arguments: [false, true]) - func listingAndFirstWatchMutationShareMirrorLock(_ existingMirror: Bool) throws { + @Test func temporaryListingAndFirstSubscriptionCompleteWithoutSharedMirror() throws { let fixture = try WatchGitFixture() try FileManager.default.removeItem(at: fixture.store.directory) - let scopeLock = fixture.store.directory.appendingPathComponent(".agents.lock") + + let initial = try stateTestProcess(root: fixture.root, arguments: ["instruction-list", ""]) + defer { terminateProcess(initial) } + try finishProcesses([initial], root: fixture.root) + let listingResult = fixture.root.appendingPathComponent("listing-finished") + #expect(try String(contentsOf: listingResult, encoding: .utf8) == "rule") + #expect(!exists(fixture.store.directory)) + #expect(!exists(fixture.store.cacheDirectory)) + try FileManager.default.removeItem(at: listingResult) + let template = fixture.root.appendingPathComponent("template") - if existingMirror { - let listing = try stateTestProcess(root: fixture.root, arguments: ["instruction-list", ""]) - defer { terminateProcess(listing) } - try finishProcesses([listing]) - try #require(exists(fixture.mirror)) - try #require(!exists(scopeLock)) - try FileManager.default.removeItem( - at: fixture.root.appendingPathComponent("listing-finished")) - try Data("---\ndescription: Fixture instructions.\n---\n# Rule\nupdated\n".utf8).write( - to: fixture.repo.appendingPathComponent("instructions/rule.md")) - try fixture.git(["commit", "-am", "update"]) - } let pause = try GitTransactionPause( - root: fixture.root, - hooks: (existingMirror ? fixture.mirror : template).appendingPathComponent("hooks"), + root: fixture.root, hooks: template.appendingPathComponent("hooks"), condition: "[ \"${ref#refs/heads/}\" != \"$ref\" ]") defer { pause.terminate() } let listing = try stateTestProcess( root: fixture.root, arguments: ["instruction-list", ""], - environment: existingMirror ? [:] : ["GIT_TEMPLATE_DIR": template.path]) + environment: ["GIT_TEMPLATE_DIR": template.path]) defer { terminateProcess(listing) } try pause.wait() - try #require(!exists(scopeLock)) - let mirrorLock = fixture.store.cacheDirectory.appendingPathComponent("locks") - .appendingPathComponent(fixture.mirror.deletingPathExtension().lastPathComponent + ".lock") - try #require(exists(mirrorLock)) - let contention = try ProcessSignal(at: fixture.root.appendingPathComponent("writer-contended")) + #expect(listing.isRunning) + #expect(!exists(listingResult)) + #expect(!exists(fixture.store.directory)) + #expect(!exists(fixture.store.cacheDirectory)) let writer = try stateTestProcess(root: fixture.root, arguments: ["watch-subscribe", ""]) defer { terminateProcess(writer) } - #expect(try contention.receive() == "contended") - #expect(exists(scopeLock)) - #expect(writer.isRunning) - #expect(!exists(fixture.store.watchURL)) - #expect(!exists(fixture.root.appendingPathComponent("writer-finished"))) + try finishProcesses([writer], root: fixture.root) + #expect(listing.isRunning) + #expect(!exists(listingResult)) + #expect(exists(fixture.root.appendingPathComponent("writer-finished"))) + #expect(try fixture.store.loadWatch().sources[fixture.id]?.seen == .revision(fixture.head())) + #expect(try fixture.watchRefs() == [fixture.head()]) + #expect(try gitLocks(fixture).isEmpty) + let published = try FileHash.folderHash(fixture.store.directory) - try finishProcesses([listing, writer], resuming: pause) - #expect( - try String( - contentsOf: fixture.root.appendingPathComponent("listing-finished"), encoding: .utf8) - == "rule") + try finishProcesses([listing], root: fixture.root, resuming: pause) + #expect(try String(contentsOf: listingResult, encoding: .utf8) == "rule") + #expect(try FileHash.folderHash(fixture.store.directory) == published) #expect(try fixture.store.loadWatch().sources[fixture.id]?.seen == .revision(fixture.head())) #expect(try fixture.watchRefs() == [fixture.head()]) #expect(try gitLocks(fixture).isEmpty) diff --git a/Tests/AgentsCoreTests/WatchPreparationTests.swift b/Tests/AgentsCoreTests/WatchPreparationTests.swift new file mode 100644 index 0000000..93aebf6 --- /dev/null +++ b/Tests/AgentsCoreTests/WatchPreparationTests.swift @@ -0,0 +1,109 @@ +import AgentsManifest +import Foundation +import Testing + +@testable import AgentsCore + +/// Watch writes take their journal preimages and lock baseline before the Git acknowledgment, +/// which can be slow; editors that ignore the scope lock may change state meanwhile. +@Suite("Watch preparation evidence") +struct WatchPreparationTests { + /// A comment-only edit changes no declared intent but still invalidates the preparation. + @Test func declarationEditedDuringAcknowledgmentIsPreserved() throws { + let fixture = try WatchGitFixture() + let watchBefore = try FileSnapshot.read(at: fixture.store.watchURL) + let external = ExternalEdit() + let watch = fixture.operations { [store = fixture.store] in + let edited = try Data(contentsOf: store.declarationURL) + Data("// Edited.\n".utf8) + try edited.write(to: store.declarationURL) + external.snapshot = try FileSnapshot.read(at: store.declarationURL) + } + #expect { + try watch.add("source", environment: fixture.environment) + } throws: { error in + guard case CoreError.invalidState(let reason) = error else { return false } + return reason.contains("changed during preparation") + && reason.contains(fixture.store.declarationURL.lastPathComponent) + } + #expect(external.snapshot != nil) + #expect(try FileSnapshot.read(at: fixture.store.declarationURL) == external.snapshot) + #expect(try FileSnapshot.read(at: fixture.store.watchURL) == watchBefore) + } + + /// Control for the lock edit below: the unchanged lock lets the same seen prune the entry. + @Test func unchangedLockPrunesUnreferencedCache() throws { + let fixture = try WatchGitFixture() + try fixture.watch.add("source", environment: fixture.environment) + let unreferenced = try fixture.unreferencedCacheEntry() + try fixture.watch.seen("source", environment: fixture.environment) + #expect(try FileSnapshot.read(at: unreferenced) == nil) + } + + @Test func lockEditedDuringAcknowledgmentPreventsPruning() throws { + let fixture = try WatchGitFixture() + try fixture.watch.add("source", environment: fixture.environment) + let unreferenced = try fixture.unreferencedCacheEntry() + let cached = try FileSnapshot.read(at: unreferenced) + let declaration = try FileSnapshot.read(at: fixture.store.declarationURL) + let watchBefore = try FileSnapshot.read(at: fixture.store.watchURL) + var ledger = try fixture.store.loadLedger() + ledger.sources["external"] = LedgerSource( + kind: .local, location: .init(kind: .absolute, path: "/edited"), revision: "live") + let edited = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + let external = ExternalEdit() + let watch = fixture.operations { [store = fixture.store] in + try edited.write(to: store.resolvedURL) + external.snapshot = try FileSnapshot.read(at: store.resolvedURL) + } + #expect { + try watch.seen("source", environment: fixture.environment) + } throws: { error in + guard case CoreError.invalidState(let reason) = error else { return false } + return reason.contains("changed during preparation") + && reason.contains(fixture.store.resolvedURL.lastPathComponent) + } + #expect(external.snapshot != nil) + #expect(try FileSnapshot.read(at: fixture.store.resolvedURL) == external.snapshot) + #expect(try FileSnapshot.read(at: unreferenced) == cached) + #expect(try FileSnapshot.read(at: fixture.store.declarationURL) == declaration) + #expect(try FileSnapshot.read(at: fixture.store.watchURL) == watchBefore) + } +} + +private final class ExternalEdit: @unchecked Sendable { + private let lock = NSLock() + private var value: FileSnapshot? + var snapshot: FileSnapshot? { + get { + lock.lock() + defer { lock.unlock() } + return value + } + set { + lock.lock() + defer { lock.unlock() } + value = newValue + } + } +} + +extension WatchGitFixture { + /// Runs `edit` after each Git fetch of an acknowledgment, before the scope journal is written. + fileprivate func operations(edit: @escaping @Sendable () throws -> Void) -> WatchOperations { + WatchOperations( + discoverSkills: { _ in [] }, + fetchArtifacts: { _ in throw CoreError.unsupported("Git fixture") }, declarations: .manifest, + checkpoint: { step in + if step == "watch.mirror.fetched" { try edit() } + }) + } + + /// An artifact tree that neither the lock nor watch state references. + fileprivate func unreferencedCacheEntry() throws -> URL { + let entry = store.cacheDirectory.appendingPathComponent( + "artifact-content/" + String(repeating: "a", count: 64)) + try FileManager.default.createDirectory(at: entry, withIntermediateDirectories: true) + try Data("unreferenced".utf8).write(to: entry.appendingPathComponent("SKILL.md")) + return entry + } +} diff --git a/Tests/AgentsCoreTests/WatchReferenceTests.swift b/Tests/AgentsCoreTests/WatchReferenceTests.swift index 3735a04..f1bba43 100644 --- a/Tests/AgentsCoreTests/WatchReferenceTests.swift +++ b/Tests/AgentsCoreTests/WatchReferenceTests.swift @@ -1,12 +1,13 @@ -import AgentsCore import Foundation import Testing +@testable import AgentsCore + @Suite("Watch Git ref retention") struct WatchReferenceTests { @Test( arguments: [false, true], - ["watch.references.deleted", "watch.references.synced", "watch.references.cleared"]) + ["watch.references.0.0.deleted", "watch.references.0.synced", "watch.references.cleared"]) func interruptedCleanupUsesCommittedBaselines(_ removing: Bool, _ step: String) throws { let fixture = try WatchGitFixture() let first = try fixture.head() @@ -48,12 +49,13 @@ struct WatchReferenceTests { try fixture.rewrite("replacement") let replacement = try fixture.head() let writer = try stateTestProcess( - root: fixture.root, arguments: ["watch-seen", "replace.0.renamed"]) - try fixture.kill(writer, at: "replace.0.renamed") + root: fixture.root, + arguments: ["watch-seen", TransactionCheckpoint.publication(0, .exchanged).name]) + try fixture.kill(writer, at: TransactionCheckpoint.publication(0, .exchanged).name) #expect(try fixture.watchRefs() == [first, replacement]) let recovery = try stateTestProcess( - root: fixture.root, arguments: ["watch-recover", "watch.references.deleted"]) - try fixture.kill(recovery, at: "watch.references.deleted") + root: fixture.root, arguments: ["watch-recover", "watch.references.0.0.deleted"]) + try fixture.kill(recovery, at: "watch.references.0.0.deleted") #expect(try fixture.recoveredWatch().sources[fixture.id]?.seen == .revision(first)) #expect(try fixture.stateBytes() == before) #expect(try fixture.watchRefs() == [first]) @@ -74,7 +76,7 @@ struct WatchReferenceTests { try fixture.kill(child, at: "watch.mirror.synced") let corrupt = Data("invalid watch state".utf8) try corrupt.write(to: fixture.store.watchURL) - #expect(throws: CoreError.self) { try fixture.store.loadWatch() } + #expect(throws: CoreError.self) { try fixture.store.withLock {} } #expect(try Data(contentsOf: fixture.store.watchURL) == corrupt) #expect(try fixture.watchRefs() == [first, replacement]) #expect( diff --git a/Tests/AgentsCoreTests/WatchSourceTests.swift b/Tests/AgentsCoreTests/WatchSourceTests.swift new file mode 100644 index 0000000..766e234 --- /dev/null +++ b/Tests/AgentsCoreTests/WatchSourceTests.swift @@ -0,0 +1,139 @@ +import AgentsManifest +import Foundation +import StateTestSupport +import Testing + +@testable import AgentsCore + +@Suite("Watch source selection") +struct WatchSourceTests { + @Test(arguments: ["alias", "identity", "location"]) + func addSelectsTheRequestedRootOfASharedRepository(_ input: String) throws { + let fixture = try WatchGitFixture() + try fixture.store.save( + declaration: Declaration(sources: [ + "a": SourceDeclaration(kind: .local, location: fixture.repo.path, path: "."), + "b": SourceDeclaration(kind: .local, location: fixture.repo.path, path: "second"), + ]), ledger: ResolvedLedger()) + let sources = try fixture.store.loadDeclaration().sources + let location = + input == "alias" + ? "b" : (input == "identity" ? fixture.id : fixture.repo.path) + "@path:second" + let added = try fixture.watch.add(location, environment: fixture.environment) + #expect(added.alias == "b" && added.sourceID == fixture.id) + + let second = fixture.repo.appendingPathComponent("second/instructions") + try FileManager.default.createDirectory(at: second, withIntermediateDirectories: true) + try Data("---\ndescription: Second rule.\n---\n# Second\n".utf8) + .write(to: second.appendingPathComponent("second.md")) + try fixture.git(["add", "."]) + try fixture.git(["commit", "-m", "add second-root instructions"]) + + let declaration = try fixture.store.loadDeclaration() + #expect(declaration.sources == sources) + #expect(declaration.watch == ["b"]) + let status = try #require(fixture.watch.status(environment: fixture.environment).first) + #expect(status.alias == "b") + #expect(status.changes.map(\.name) == ["second"]) + } + + @Test(arguments: [InstallScope.project, .user]) + func addAcceptsDeclaredLocalIdentityAndPreservesSource(_ scope: InstallScope) throws { + let fixture = try WatchGitFixture() + let store = StateStore(scope: scope, environment: fixture.environment) + let source = SourceDeclaration( + kind: .local, location: "./source", requirement: .exact("1.0.0"), path: "instructions", + environment: SourceEnvironment( + projectDirectory: fixture.environment.projectDirectory, + homeDirectory: fixture.environment.homeDirectory)) + try store.save(declaration: Declaration(sources: ["source": source]), ledger: ResolvedLedger()) + let lock = try FileSnapshot.read(at: store.resolvedURL) + + let added = try fixture.watch.add( + fixture.id, scope: scope, environment: fixture.environment) + + #expect(added.alias == "source" && added.sourceID == fixture.id) + #expect(added.seen == .revision(try fixture.head())) + let declaration = try store.loadDeclaration() + #expect(declaration.sources == ["source": source]) + #expect(declaration.watch == ["source"]) + #expect(try store.loadWatch().sources[fixture.id]?.seen == added.seen) + #expect(try FileSnapshot.read(at: store.resolvedURL) == lock) + } + + @Test(arguments: ["alias", "identity", "location"]) + func selectorsReplaceDeclaredRequirementAndPath(_ input: String) throws { + let fixture = try WatchGitFixture() + let source = SourceDeclaration( + kind: .local, location: "./source", requirement: .exact("1.0.0"), path: "instructions", + environment: SourceEnvironment( + projectDirectory: fixture.environment.projectDirectory, + homeDirectory: fixture.environment.homeDirectory)) + try fixture.store.save( + declaration: Declaration(sources: ["source": source]), ledger: ResolvedLedger()) + let topic = try fixture.head() + try fixture.git(["branch", "topic"]) + try fixture.git(["commit", "--allow-empty", "-m", "advance default branch"]) + let location = + input == "alias" ? "source" : input == "identity" ? fixture.id : fixture.repo.path + + let added = try fixture.watch.add( + location + "@branch:topic@path:rules", requirement: .branch("topic"), path: "rules", + environment: fixture.environment) + + #expect(added.alias == "source" && added.sourceID == fixture.id) + #expect(added.seen == .revision(topic)) + #expect( + try fixture.store.loadDeclaration().sources == [ + "source": SourceDeclaration( + kind: .local, location: "./source", requirement: .branch("topic"), path: "rules", + environment: SourceEnvironment( + projectDirectory: fixture.environment.projectDirectory, + homeDirectory: fixture.environment.homeDirectory)) + ]) + } + + @Test(arguments: ["requirement", "path", "skill"]) + func invalidSelectorsForDeclaredIdentityStopBeforeGit(_ kind: String) throws { + let fixture = try WatchGitFixture() + let before = try fixture.stateBytes() + let selector = + kind == "requirement" ? "@branch:master" : kind == "path" ? "@path:rules" : "@skill:demo" + let reason = + kind == "requirement" + ? "the source selector and option give different requirements" + : kind == "path" + ? "the source selector and option give different paths" + : "@skill: selects skills; watch subscribes to whole sources" + + #expect(throws: CoreError.invalidSource(reason)) { + try fixture.watch.add( + fixture.id + selector, requirement: kind == "requirement" ? .branch("topic") : nil, + path: kind == "path" ? "other" : nil, environment: fixture.environment) + } + + #expect(try fixture.stateBytes() == before) + #expect(!FileManager.default.fileExists(atPath: fixture.mirror.path)) + } + + @Test func declaredIdentityIsPlannedBeforeGit() throws { + let fixture = try WatchGitFixture() + let before = try fixture.stateBytes() + struct PlanningFailed: Error {} + let watch = WatchOperations( + discoverSkills: { _ in [] }, + fetchArtifacts: { _ in throw CoreError.unsupported("Git fixture") }, + declarations: DeclarationAccess( + read: DeclarationAccess.manifest.read, + plan: { _, _, next, _ in + #expect(next.sources.count == 1 && next.watch == ["source"]) + throw PlanningFailed() + })) + + #expect(throws: PlanningFailed.self) { + try watch.add(fixture.id, environment: fixture.environment) + } + #expect(try fixture.stateBytes() == before) + #expect(!FileManager.default.fileExists(atPath: fixture.mirror.path)) + } +} diff --git a/Tests/AgentsCoreTests/WatchStateTests.swift b/Tests/AgentsCoreTests/WatchStateTests.swift index e4c5ea7..5d044e0 100644 --- a/Tests/AgentsCoreTests/WatchStateTests.swift +++ b/Tests/AgentsCoreTests/WatchStateTests.swift @@ -1,10 +1,42 @@ -import AgentsCore -import Darwin +import AgentsManifest +import CPlatform import Foundation +import StateTestSupport import Testing +@testable import AgentsCore + @Suite("Watch state") struct WatchStateTests { + @Test func existingDeclarationWatchReorderingPreservesBytesAndInode() throws { + let root = try temporaryDirectory() + defer { try? FileManager.default.removeItem(at: root) } + let store = StateStore( + scope: .project, + environment: RuntimeEnvironment( + projectDirectory: root, homeDirectory: root.appendingPathComponent("home"), environment: [:] + )) + try FileManager.default.createDirectory(at: store.directory, withIntermediateDirectories: true) + let text = """ + version: 1 + sources: {"web": {"url": "https://example.test/repo.git"}, "git": {"path": "missing"}} + watch: ["web", "git"] + """ + let bytes = Data(text.utf8) + try bytes.write(to: store.declarationURL) + let inode = try #require( + FileManager.default.attributesOfItem(atPath: store.declarationURL.path)[.systemFileNumber] + as? NSNumber) + var declaration = try store.loadDeclaration() + #expect(declaration.watch == ["web", "git"]) + declaration.watch = ["git", "web"] + try store.save(declaration: declaration, ledger: ResolvedLedger()) + #expect(try Data(contentsOf: store.declarationURL) == bytes) + #expect( + try FileManager.default.attributesOfItem(atPath: store.declarationURL.path)[.systemFileNumber] + as? NSNumber == inode) + } + @Test(arguments: [InstallScope.project, .user]) func storesSortedBaselinesAndPreservesWatchWhenSavingOtherState(_ scope: InstallScope) throws { let root = try temporaryDirectory() @@ -24,7 +56,7 @@ struct WatchStateTests { "git": SourceDeclaration(kind: .local, location: "/source"), "web": SourceDeclaration(kind: .wellKnown, location: "https://example.test"), ], watch: ["web", "git"]) - try store.save(declaration: declaration, resolved: ResolvedState(), watch: watch) + try store.save(declaration: declaration, ledger: ResolvedLedger(), watch: watch) let bytes = try Data(contentsOf: store.watchURL) #expect(try store.loadWatch() == watch) #expect(bytes.last == 10) @@ -33,9 +65,9 @@ struct WatchStateTests { try #require(text.range(of: "alpha")).lowerBound < #require(text.range(of: "zebra")).lowerBound) #expect(!text.contains("timestamp")) - try store.save(declaration: declaration, resolved: ResolvedState()) + try store.save(declaration: declaration, ledger: ResolvedLedger()) #expect(try Data(contentsOf: store.watchURL) == bytes) - try store.save(declaration: declaration, resolved: ResolvedState(), watch: watch) + try store.save(declaration: declaration, ledger: ResolvedLedger(), watch: watch) #expect(try Data(contentsOf: store.watchURL) == bytes) #expect(try store.loadDeclaration().watch == ["git", "web"]) } @@ -48,7 +80,7 @@ struct WatchStateTests { environment: RuntimeEnvironment( projectDirectory: root, homeDirectory: root.appendingPathComponent("home"), environment: [:] )) - try store.save(declaration: Declaration(), resolved: ResolvedState(), watch: WatchState()) + try store.save(declaration: Declaration(), ledger: ResolvedLedger(), watch: WatchState()) let declaration = try Data(contentsOf: store.declarationURL) let resolved = try Data(contentsOf: store.resolvedURL) let valid = #"{"version":1,"sources":{}}"# @@ -73,7 +105,7 @@ struct WatchStateTests { try data.write(to: store.watchURL) #expect(throws: (any Error).self) { try store.loadWatch() } #expect(throws: (any Error).self) { - try store.save(declaration: Declaration(), resolved: ResolvedState(), watch: WatchState()) + try store.save(declaration: Declaration(), ledger: ResolvedLedger(), watch: WatchState()) } #expect(try Data(contentsOf: store.watchURL) == data) #expect(try Data(contentsOf: store.declarationURL) == declaration) @@ -93,7 +125,7 @@ struct WatchStateTests { try Data("invalid".utf8).write(to: store.watchURL) let before = try FileHash.folderHash(root) #expect(throws: (any Error).self) { - try store.save(declaration: Declaration(), resolved: ResolvedState()) + try store.save(declaration: Declaration(), ledger: ResolvedLedger()) } #expect(try FileHash.folderHash(root) == before) } @@ -109,7 +141,11 @@ struct WatchStateTests { #expect(throws: CoreError.self) { try declaration.validate(environment: environment) } } - @Test(arguments: ["replace.0.renamed", "replace.1.renamed", "journal.committed", "cleanup.0"]) + @Test(arguments: [ + TransactionCheckpoint.publication(0, .exchanged).name, + TransactionCheckpoint.publication(1, .exchanged).name, + TransactionCheckpoint.phase(.committed).name, TransactionCheckpoint.containerRemoved(0).name, + ]) func interruptedWatchAndDeclarationRecoverTogether(_ checkpoint: String) throws { let root = try temporaryDirectory() defer { try? FileManager.default.removeItem(at: root) } @@ -121,25 +157,17 @@ struct WatchStateTests { let declaration = Declaration(sources: [ "source": SourceDeclaration(kind: .local, location: "/source") ]) - try store.save(declaration: declaration, resolved: ResolvedState(), watch: WatchState()) + try store.save(declaration: declaration, ledger: ResolvedLedger(), watch: WatchState()) let lockBytes = try Data(contentsOf: store.resolvedURL) let child = try stateTestProcess(root: root, arguments: ["watch-crash", checkpoint]) - defer { - if child.isRunning { - kill(child.processIdentifier, SIGKILL) - child.waitUntilExit() - } - } + defer { terminateProcess(child) } let marker = root.appendingPathComponent("ready") - let deadline = Date().addingTimeInterval(10) - while !FileManager.default.fileExists(atPath: marker.path), child.isRunning, Date() < deadline { - Thread.sleep(forTimeInterval: 0.01) - } - try #require(FileManager.default.fileExists(atPath: marker.path)) - kill(child.processIdentifier, SIGKILL) - child.waitUntilExit() - #expect(throws: CoreError.transactionRecovered(store.directory.path)) { try store.loadWatch() } - let committed = checkpoint == "journal.committed" || checkpoint == "cleanup.0" + try ProcessWait.marker(marker, child: child, root: root) + terminateProcess(child) + #expect(throws: CoreError.transactionRecovered(store.directory.path)) { try store.withLock {} } + let committed = + checkpoint == TransactionCheckpoint.phase(.committed).name + || checkpoint == TransactionCheckpoint.containerRemoved(0).name #expect(try store.loadDeclaration().watch == (committed ? ["source"] : nil)) #expect(try store.loadWatch().sources.isEmpty == !committed) #expect(try Data(contentsOf: store.resolvedURL) == lockBytes) diff --git a/Tests/AgentsInstructionsTests/DeclarationDocumentTests.swift b/Tests/AgentsInstructionsTests/DeclarationDocumentTests.swift new file mode 100644 index 0000000..cf45718 --- /dev/null +++ b/Tests/AgentsInstructionsTests/DeclarationDocumentTests.swift @@ -0,0 +1,113 @@ +import AgentsCore +import AgentsInstructions +import AgentsManifest +import AgentsUpdates +import Foundation +import Testing + +/// Instruction writes through the scope's `agents.yaml` declaration document. +@Suite("Instruction declaration documents") +struct DeclarationDocumentTests { + @Test func instructionEditsKeepCommentsAndUntouchedBytes() throws { + let fixture = try InstructionFixture() + try fixture.own("guide") + try fixture.own("style") + let declaration = fixture.store().declarationURL + let header = """ + # Project instructions. + version: 1 + components: + # Shared guidance first. + + """ + let closing = "\n" + try fixture.write( + header + " - {kind: instructions, sections: [{name: guide}], agents: [codex]}" + closing, + to: declaration) + _ = try InstructionOperations.updateInstalled(environment: fixture.environment, apply: true) + func text() throws -> String { + String(decoding: try Data(contentsOf: declaration), as: UTF8.self) + } + + try fixture.addOwn(names: ["style"]) + #expect(try text().hasPrefix(header)) + #expect(try fixture.store().loadDeclaration().instructions?.sections == ["guide", "style"]) + try InstructionOperations.remove(names: ["guide"], environment: fixture.environment) + #expect(try text().hasPrefix(header)) + _ = try InstructionOperations.updateInstalled( + agents: [.claudeCode, .codex], environment: fixture.environment, apply: true) + #expect( + try text() + == header + + " - {kind: instructions, sections: [{\"name\": \"style\"}], agents: [\"claude-code\", codex]}" + + closing) + #expect(try fixture.store().loadResolved().instructions.sections.map(\.name) == ["style"]) + } + + /// A declaration another writer creates after preparation is kept, and no lock or target is + /// published beside it. + @Test func externallyCreatedDeclarationIsKept() throws { + let fixture = try InstructionFixture() + try fixture.own("guide") + let store = fixture.store() + let external = Data( + "version: 1\n".utf8) + #expect(throws: CoreError.self) { + try InstructionOperations.add( + InstructionAddOptions(source: ".", names: ["guide"], environment: fixture.environment), + beforeApply: { _ in try external.write(to: store.declarationURL) }) + } + #expect(try Data(contentsOf: store.declarationURL) == external) + #expect(!FileManager.default.fileExists(atPath: store.resolvedURL.path)) + #expect( + !FileManager.default.fileExists( + atPath: fixture.project.appendingPathComponent("AGENTS.md").path)) + } + + /// Unsupported shared aliases fail before the callback and any write. + @Test func unsupportedSectionsStopBeforeTheCallback() throws { + let fixture = try InstructionFixture() + try fixture.own("guide") + try fixture.own("style") + _ = try InstructionOperations.updateInstalled(environment: fixture.environment, apply: true) + try fixture.write( + """ + version: 1 + components: [{kind: instructions, sections: &shared [{name: guide}], agents: [codex]}] + """, to: fixture.store().declarationURL) + let before = try fixture.snapshot() + var called = false + #expect { + try InstructionOperations.add( + InstructionAddOptions(source: ".", names: ["style"], environment: fixture.environment), + beforeApply: { _ in called = true }) + } throws: { error in + (error as? ManifestFailure)?.diagnostics.first?.code == "manifest.unsupported" + } + #expect(!called) + #expect(try fixture.snapshot() == before) + } + + /// A lock without its declaration stops instruction writes, including authoring a new file + /// while the scope lock already exists. + @Test func missingDeclarationStopsInstructionWrites() throws { + let fixture = try InstructionFixture() + try fixture.own("guide") + try fixture.addOwn(names: ["guide"]) + let store = fixture.store() + try FileManager.default.removeItem(at: store.declarationURL) + let before = try fixture.snapshot() + let missing = CoreError.missingDeclaration(store.declarationURL.path) + #expect(throws: missing) { + try InstructionOperations.initializeInstructions( + named: "style", environment: fixture.environment) + } + #expect(throws: missing) { + try InstructionOperations.updateInstalled(environment: fixture.environment, apply: true) + } + #expect(throws: missing) { + try InstructionOperations.listManaged(environment: fixture.environment) + } + #expect(try fixture.snapshot() == before) + } +} diff --git a/Tests/AgentsInstructionsTests/DoctorLifecycleTests.swift b/Tests/AgentsInstructionsTests/DoctorLifecycleTests.swift index b20303f..31af69c 100644 --- a/Tests/AgentsInstructionsTests/DoctorLifecycleTests.swift +++ b/Tests/AgentsInstructionsTests/DoctorLifecycleTests.swift @@ -1,5 +1,6 @@ import AgentsCore import AgentsInstructions +import AgentsUpdates import Foundation import Testing @@ -24,11 +25,11 @@ struct InstructionDoctorTests { let before = try fixture.snapshot() let report = try InstructionOperations.doctor( scope: pendingScope, environment: fixture.environment) - #expect(report.diagnostics.map(\.kind) == [.pendingRecovery]) + #expect(report.diagnostics.map(\.kind) == [.unresolvedTransaction]) #expect(report.diagnostics.first?.path == pending.directory) let healthy = try InstructionOperations.doctor( scope: healthyScope, environment: fixture.environment) - #expect(healthy.diagnostics.filter { $0.kind == .pendingRecovery }.count == 1) + #expect(healthy.diagnostics.filter { $0.kind == .unresolvedTransaction }.count == 1) #expect(healthy.diagnostics.contains { $0.kind == .missingTarget && $0.path == healthyFile }) #expect(!healthy.diagnostics.contains { $0.kind == .duplicateScope }) #expect(try fixture.snapshot() == before) @@ -180,7 +181,7 @@ struct InstructionDoctorTests { projectRoots: [fixture.project, empty, pending], environment: fixture.environment) #expect(reports.count == 3) #expect(reports[0].diagnostics.contains { $0.kind == .missingTarget }) - #expect(reports[2].diagnostics.map(\.kind) == [.pendingRecovery]) + #expect(reports[2].diagnostics.map(\.kind) == [.unresolvedTransaction]) #expect(try fixture.snapshot() == before) #expect(!FileManager.default.fileExists(atPath: empty.appendingPathComponent(".agent").path)) #expect( diff --git a/Tests/AgentsInstructionsTests/FileReadAccessTests.swift b/Tests/AgentsInstructionsTests/FileReadAccessTests.swift new file mode 100644 index 0000000..a97647a --- /dev/null +++ b/Tests/AgentsInstructionsTests/FileReadAccessTests.swift @@ -0,0 +1,96 @@ +import AgentsCore +import AgentsUpdates +import Foundation +import Testing + +@testable import AgentsInstructions + +@Suite( + "Instruction file read access", + .enabled(if: geteuid() != 0, "Permission-denial checks require an unprivileged user"), + .timeLimit(.minutes(1))) +struct InstructionFileReadAccessTests { + @Test func unreadableTargetReportsItsPath() throws { + let fixture = try InstructionFixture() + let file = fixture.project.appendingPathComponent("AGENTS.md") + try fixture.write("User content", to: file) + let before = try fixture.snapshot() + try withUnreadableFile(file) { + #expect(throws: accessError(file)) { try InstructionTargets.read(file) } + } + #expect(try fixture.snapshot() == before) + } + + @Test func unreadableOwnInstructionsReportTheirPath() throws { + let fixture = try InstructionFixture() + try fixture.own("guide") + let file = fixture.project.appendingPathComponent(".agent/instructions/guide.md") + let before = try fixture.snapshot() + try withUnreadableFile(file) { + #expect { + try InstructionOperations.listOwn(environment: fixture.environment) + } throws: { error in + guard case CoreError.invalidState(let message) = error else { return false } + let prefix = "permission denied: " + let suffix = "; check the directory's permissions and default ACL" + guard message.hasPrefix(prefix), message.hasSuffix(suffix) else { return false } + let path = String(message.dropFirst(prefix.count).dropLast(suffix.count)) + return URL(fileURLWithPath: path).resolvingSymlinksInPath() + == file.resolvingSymlinksInPath() + } + } + #expect(try fixture.snapshot() == before) + } + + @Test(arguments: ["config", "target"]) + func doctorReportsUnreadableFiles(_ kind: String) throws { + let fixture = try InstructionFixture() + let file = + kind == "config" + ? fixture.home.appendingPathComponent(".codex/config.toml") + : fixture.project.appendingPathComponent("AGENTS.md") + try fixture.write("", to: file) + let before = try fixture.snapshot() + try withUnreadableFile(file) { + let report = try InstructionOperations.doctor(environment: fixture.environment) + #expect( + report.diagnostics.contains { + $0.path == file && $0.message.contains(accessError(file).description) + }) + } + #expect(try fixture.snapshot() == before) + } + + @Test func doctorReportsAnUnreadableManagedTargetOnce() throws { + let fixture = try InstructionFixture() + try fixture.own("guide") + try fixture.addOwn(names: ["guide"], agents: [.codex]) + let file = fixture.project.appendingPathComponent("AGENTS.md") + try withUnreadableFile(file) { + let report = try InstructionOperations.doctor(environment: fixture.environment) + #expect(report.diagnostics.filter { $0.message.contains("permission denied: ") }.count == 1) + } + } +} + +private func accessError(_ file: URL) -> CoreError { + .invalidState( + "permission denied: \(file.path); check the directory's permissions and default ACL") +} + +private func withUnreadableFile(_ file: URL, _ body: () throws -> Void) throws { + let attributes = try FileManager.default.attributesOfItem(atPath: file.path) + let mode = try #require(attributes[.posixPermissions] as? NSNumber) + try FileManager.default.setAttributes([.posixPermissions: 0], ofItemAtPath: file.path) + defer { + do { + try FileManager.default.setAttributes([.posixPermissions: mode], ofItemAtPath: file.path) + } catch { Issue.record(error) } + } + for _ in 0..<2 { + try body() + let current = try FileManager.default.attributesOfItem(atPath: file.path) + #expect((current[.posixPermissions] as? NSNumber)?.intValue == 0) + #expect(current[.systemFileNumber] as? NSNumber == attributes[.systemFileNumber] as? NSNumber) + } +} diff --git a/Tests/AgentsInstructionsTests/LedgerCompatibilityTests.swift b/Tests/AgentsInstructionsTests/LedgerCompatibilityTests.swift new file mode 100644 index 0000000..e65d1d3 --- /dev/null +++ b/Tests/AgentsInstructionsTests/LedgerCompatibilityTests.swift @@ -0,0 +1,49 @@ +import AgentsCore +import AgentsInstructions +import Foundation +import Testing + +@Suite("Ledger instruction compatibility") +struct LedgerCompatibilityTests { + @Test func generatedAndImportRemovalKeepExistingOwnership() throws { + let generated = Data((Instructions.notice + "\n\n# Section\nBody\n").utf8) + let digest = try ResolvedLedgerCodec.digest("unused") + var deployment = LedgerDeployment( + id: "target", target: .init(kind: .registered, root: "project", path: "AGENTS.md"), + route: "agents/instructions@1", owners: ["section"], recipients: [.codex], + ownership: .generated, + expectedHash: digest, created: false) + // Use the production source renderer to obtain the whole-file expected hash. + let root = FileManager.default.temporaryDirectory.appendingPathComponent( + "ledger-compatibility-" + UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + let source = Data("---\ndescription: A section\n---\n# Section\nBody\n".utf8) + let rendered = try InstructionCompatibility.renderSections([source], ids: ["section"]) + #expect(rendered == generated) + // A tiny complete ledger gives the expected SHA-256 through the object identity. + let hash = try resourceHash(rendered, root: root) + deployment.expectedHash = hash + #expect(try InstructionCompatibility.obsolete(deployment, before: rendered) == nil) + #expect( + try InstructionCompatibility.obsolete(deployment, before: Data("drift".utf8)) + == Data("drift".utf8)) + #expect(try InstructionCompatibility.obsolete(deployment, before: nil) == nil) + deployment.ownership = .importBlock + deployment.importReference = "AGENTS.md" + deployment.created = true + let block = Data(ClaudeForwarding.renderBlock(for: .root).utf8) + #expect(try InstructionCompatibility.obsolete(deployment, before: block) == nil) + let custom = Data("# My instructions\n\n".utf8) + block + let after = try InstructionCompatibility.obsolete(deployment, before: custom) + #expect(after == Data("# My instructions\n".utf8)) + deployment.created = false + #expect(try InstructionCompatibility.obsolete(deployment, before: block) != nil) + } + + private func resourceHash(_ bytes: Data, root: URL) throws -> String { + let file = root.appendingPathComponent("rendered") + try bytes.write(to: file) + return try LedgerResources.capture(file, embed: false, limits: .standard).hash + } +} diff --git a/Tests/AgentsInstructionsTests/LifecycleFixture.swift b/Tests/AgentsInstructionsTests/LifecycleFixture.swift index a5e8720..e7f1f38 100644 --- a/Tests/AgentsInstructionsTests/LifecycleFixture.swift +++ b/Tests/AgentsInstructionsTests/LifecycleFixture.swift @@ -1,5 +1,6 @@ import AgentsCore import AgentsInstructions +import AgentsUpdates import Foundation import Testing diff --git a/Tests/AgentsInstructionsTests/LifecycleSafetyTests.swift b/Tests/AgentsInstructionsTests/LifecycleSafetyTests.swift index 2b8cba6..35d67e4 100644 --- a/Tests/AgentsInstructionsTests/LifecycleSafetyTests.swift +++ b/Tests/AgentsInstructionsTests/LifecycleSafetyTests.swift @@ -1,6 +1,10 @@ import AgentsCore import AgentsInstructions +import AgentsManifest +import AgentsSkills +import AgentsUpdates import Foundation +import StateTestSupport import Testing @Suite("Instruction lifecycle safety") @@ -10,10 +14,16 @@ struct InstructionLifecycleSafetyTests { try fixture.section("rules") try fixture.commit() try fixture.add(agents: [.codex, .geminiCLI]) - let original = try fixture.store().loadResolved() + let original = try fixture.store().loadLedger() var lock = original - lock.instructions.sections[0].revision = String(repeating: "a", count: 40) - try fixture.store().save(declaration: fixture.store().loadDeclaration(), resolved: lock) + let unavailable = String(repeating: "a", count: 40) + for id in lock.sources.keys where lock.sources[id]!.revision != "live" { + lock.sources[id]!.revision = unavailable + } + for id in lock.components.keys where lock.components[id]!.revision != nil { + lock.components[id]!.revision = unavailable + } + try fixture.store().save(declaration: fixture.store().loadDeclaration(), ledger: lock) try fixture.write("Custom target.\n", to: fixture.project.appendingPathComponent("AGENTS.md")) let before = try fixture.snapshot(fixture.project, excludingCache: true) #expect(throws: (any Error).self) { @@ -21,8 +31,10 @@ struct InstructionLifecycleSafetyTests { } #expect(try fixture.snapshot(fixture.project, excludingCache: true) == before) lock = original - lock.instructions.sections[0].hash = "sha256:" + String(repeating: "a", count: 64) - try fixture.store().save(declaration: fixture.store().loadDeclaration(), resolved: lock) + for id in lock.resources.keys { + lock.resources[id]!.hash = "sha256:" + String(repeating: "a", count: 64) + } + try fixture.store().save(declaration: fixture.store().loadDeclaration(), ledger: lock) #expect(throws: (any Error).self) { try InstructionOperations.installResolvedReport(environment: fixture.environment) } @@ -69,20 +81,23 @@ struct InstructionLifecycleSafetyTests { try fixture.section("two") try fixture.commit() try fixture.add(names: ["one"]) - var declaration = try fixture.store().loadDeclaration() - var lock = try fixture.store().loadResolved() + try fixture.write( + "---\nname: example\ndescription: Example\n---\nExample\n", + to: fixture.repo.appendingPathComponent("skills/example/SKILL.md")) + try fixture.commit() + _ = try SkillOperations.add( + AddOptions( + source: "rules", agents: [.claudeCode], skillNames: ["example"], + environment: fixture.environment)) + let declaration = try fixture.store().loadDeclaration() + let lock = try fixture.store().loadResolved() let previous = lock.instructions.sections[0] - declaration.skills = ["rules": SkillDeclaration(select: .names([]))] - lock.skills["example"] = LockedSkill( - source: previous.source, revision: previous.revision, - path: "skills/example", hash: previous.hash, installs: ["codex": .copy]) - try fixture.store().save(declaration: declaration, resolved: lock) try fixture.section("one", body: "Changed") try fixture.commit() try fixture.add(names: ["two"]) #expect(try fixture.store().loadResolved().instructions.sections[0] == previous) #expect(try fixture.store().loadResolved().skills == lock.skills) - #expect(try fixture.store().loadDeclaration().skills == declaration.skills) + #expect(try fixture.store().loadDeclaration().skills == (try declaration.skills)) #expect(try !fixture.text().contains("Changed")) } @@ -158,24 +173,54 @@ struct InstructionLifecycleSafetyTests { #expect(try String(contentsOf: outside, encoding: .utf8) == "Owner content.\n") } - @Test func promptAppendCannotEscapeScopeThroughSymlinks() throws { + @Test(arguments: [InstallScope.project, .user]) + func localPromptAppendUsesCurrentScopedContentOnlyAtExport(_ scope: InstallScope) throws { let fixture = try InstructionFixture() try fixture.section("rules") try fixture.commit() - try fixture.add() - var declaration = try fixture.store().loadDeclaration() - declaration.instructions?.chatgpt = [ - "prompt": PromptDeclaration(sections: ["rules:rules"], append: "custom.md") - ] - try fixture.store().save(declaration: declaration, resolved: fixture.store().loadResolved()) - _ = try InstructionOperations.updateInstalled(environment: fixture.environment, apply: true) + try fixture.add(scope: scope, agents: [.codex]) + let store = fixture.store(scope) + var declaration = try store.loadDeclaration() + try declaration.updateInstructions { + $0?.chatgpt = [ + "prompt": PromptDeclaration(sections: ["rules:rules"], append: "custom.md") + ] + } + try store.save(declaration: declaration, ledger: store.loadLedger()) + _ = try InstructionOperations.updateInstalled( + scope: scope, environment: fixture.environment, apply: true) + let lock = try Data(contentsOf: store.resolvedURL) + #expect(throws: (any Error).self) { + try InstructionOperations.renderChatGPT( + prompt: "prompt", scope: scope, environment: fixture.environment) + } + let root = scope == .project ? fixture.project : fixture.home + let other = scope == .project ? fixture.home : fixture.project + let append = root.appendingPathComponent("custom.md") + try fixture.write("Wrong scope.\n", to: other.appendingPathComponent("custom.md")) + try fixture.write("First custom text.\n", to: append) + let first = try InstructionOperations.renderChatGPT( + prompt: "prompt", scope: scope, environment: fixture.environment) + #expect(String(decoding: first, as: UTF8.self).hasSuffix("First custom text.\n")) + try fixture.write("Current custom text.\n", to: append) + try fixture.section("rules", body: "Changed upstream") + let current = try InstructionOperations.renderChatGPT( + prompt: "prompt", scope: scope, environment: fixture.environment) + let text = String(decoding: current, as: UTF8.self) + #expect(text.contains("Original") && text.hasSuffix("Current custom text.\n")) + #expect(!text.contains("Changed upstream") && !text.contains("Wrong scope")) + #expect(try Data(contentsOf: store.resolvedURL) == lock) + try FileManager.default.removeItem(at: append) let outside = fixture.root.appendingPathComponent("outside.md") try fixture.write("Owner content.\n", to: outside) - try FileManager.default.createSymbolicLink( - at: fixture.project.appendingPathComponent("custom.md"), withDestinationURL: outside) + try FileManager.default.createSymbolicLink(at: append, withDestinationURL: outside) #expect(throws: (any Error).self) { - try InstructionOperations.renderChatGPT(prompt: "prompt", environment: fixture.environment) + try InstructionOperations.renderChatGPT( + prompt: "prompt", scope: scope, environment: fixture.environment) } + _ = try InstructionOperations.installResolvedReport( + scope: scope, environment: fixture.environment) + #expect(try Data(contentsOf: store.resolvedURL) == lock) } @Test func sourceInstructionsDirectoryCannotBeATarget() throws { diff --git a/Tests/AgentsInstructionsTests/LifecycleTests.swift b/Tests/AgentsInstructionsTests/LifecycleTests.swift index b901843..0f0ddeb 100644 --- a/Tests/AgentsInstructionsTests/LifecycleTests.swift +++ b/Tests/AgentsInstructionsTests/LifecycleTests.swift @@ -1,6 +1,9 @@ import AgentsCore import AgentsInstructions +import AgentsManifest +import AgentsUpdates import Foundation +import StateTestSupport import Testing @Suite("Instruction lifecycle") @@ -62,8 +65,8 @@ struct InstructionLifecycleTests { try fixture.add(names: ["one", "two"], scope: .user, agents: [.cursor]) let store = fixture.store(.user) var declaration = try store.loadDeclaration() - declaration.instructions?.sections.reverse() - try store.save(declaration: declaration, resolved: store.loadResolved()) + try declaration.updateInstructions { $0?.sections.reverse() } + try store.save(declaration: declaration, ledger: store.loadLedger()) let report = try InstructionOperations.updateInstalled( scope: .user, environment: fixture.environment) #expect(report.sections.isEmpty && report.targets.isEmpty && report.changedPrompts.isEmpty) @@ -86,7 +89,7 @@ struct InstructionLifecycleTests { sources: ["rules": SourceDeclaration(kind: .local, location: fixture.repo.path)], instructions: InstructionsDeclaration( chatgpt: ["daily": PromptDeclaration(sections: ["rules:rules"])])), - resolved: ResolvedState()) + ledger: ResolvedLedger()) _ = try InstructionOperations.updateInstalled(environment: fixture.environment, apply: true) let original = try InstructionOperations.renderChatGPT( prompt: "daily", environment: fixture.environment) @@ -192,9 +195,12 @@ struct InstructionLifecycleTests { "CLAUDE_CONFIG_DIR": fixture.home.appendingPathComponent("claude-config").path, "XDG_CONFIG_HOME": config.path, ] - try fixture.add(scope: .user, agents: AgentID.allCases, environment: runtime) + try fixture.add( + scope: .user, agents: AgentID.allCases.filter { $0.supportsInstructions(in: .user) }, + environment: runtime) let lock = try fixture.store(.user, environment: runtime).loadResolved() - #expect(lock.instructions.targets.count == 3) + #expect(lock.instructions.targets.count == 4) + #expect(lock.instructions.targets.values.contains { $0.agents == [.antigravity] }) let common = try #require( lock.instructions.targets[config.appendingPathComponent("opencode/AGENTS.md").path]) #expect(Set(common.agents) == [.codex, .opencode]) @@ -213,13 +219,16 @@ struct InstructionLifecycleTests { try fixture.commit() try fixture.add(agents: [.codex, .geminiCLI]) var declaration = try fixture.store().loadDeclaration() - declaration.instructions?.chatgpt = [ - "daily": PromptDeclaration(sections: ["rules:one", "rules:two"], append: ".agent/custom.md"), - "stable": PromptDeclaration(sections: ["rules:two"]), - ] + try declaration.updateInstructions { + $0?.chatgpt = [ + "daily": PromptDeclaration( + sections: ["rules:one", "rules:two"], append: ".agent/custom.md"), + "stable": PromptDeclaration(sections: ["rules:two"]), + ] + } try fixture.write( "Custom prompt.\r\n", to: fixture.project.appendingPathComponent(".agent/custom.md")) - try fixture.store().save(declaration: declaration, resolved: fixture.store().loadResolved()) + try fixture.store().save(declaration: declaration, ledger: fixture.store().loadLedger()) _ = try InstructionOperations.updateInstalled(environment: fixture.environment, apply: true) let old = try fixture.snapshot(fixture.project, excludingCache: true) try fixture.section("one", body: "Changed") @@ -340,11 +349,11 @@ struct InstructionLifecycleTests { try InstructionOperations.doctor(environment: fixture.environment).diagnostics.contains { $0.kind == .uncommittedSource }) - #expect(throws: (any Error).self) { + #expect( try InstructionOperations.list( source: SourceDeclaration(kind: .local, location: fixture.home.path), - environment: fixture.environment) - } + environment: fixture.environment + ).isEmpty) } @Test func discoveryRejectsInvalidNamesSymbolicLinksAndDuplicates() throws { diff --git a/Tests/AgentsInstructionsTests/MappingReadLocationsTests.swift b/Tests/AgentsInstructionsTests/MappingReadLocationsTests.swift new file mode 100644 index 0000000..23998bb --- /dev/null +++ b/Tests/AgentsInstructionsTests/MappingReadLocationsTests.swift @@ -0,0 +1,288 @@ +import AgentsCore +import AgentsInstructions +import AgentsManifest +import AgentsUpdates +import Foundation +import StateTestSupport +import Testing + +@Suite("Instruction mapping read dependencies") +struct MappingReadLocationsTests { + @Test(arguments: [ + "base-absent", "metadata-absent", "lock-absent", "base-access", "metadata-access", + "lock-access", + ]) + func sharedRecoveryAdmissionRepairChangesStatusWithoutChangingScope(_ damage: String) throws { + let f = try InstructionFixture() + let config = f.root.appendingPathComponent("shared-config") + let home = f.project.appendingPathComponent("home") + for directory in [config, home] { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + } + let environment = RuntimeEnvironment( + projectDirectory: f.project, homeDirectory: home, + environment: ["CLAUDE_CONFIG_DIR": config.path]) + let store = StateStore(scope: .project, environment: environment) + try store.save(declaration: Declaration(), ledger: ResolvedLedger()) + try f.write("Before", to: f.project.appendingPathComponent("old-data/AGENTS.md")) + var binaryDirectory = Bundle(for: MappingTestBundle.self).bundleURL + while !FileManager.default.isExecutableFile( + atPath: binaryDirectory.appendingPathComponent("StateTestProcess").path), + binaryDirectory.path != "/" + { + binaryDirectory.deleteLastPathComponent() + } + let child = Process() + child.executableURL = binaryDirectory.appendingPathComponent("StateTestProcess") + child.arguments = [ + f.project.path, "shared-install", "shared.ready", "--shared-config", config.path, + ] + child.environment = ProcessInfo.processInfo.environment + try child.run() + defer { do { try ProcessWait.terminate(child) } catch { Issue.record(error) } } + try ProcessWait.marker(f.project.appendingPathComponent("ready"), child: child, root: f.project) + try ProcessWait.terminate(child) + func mapping() throws -> InstructionMapping { + try #require( + InstructionOperations.export(projectRoots: [f.project], environment: environment).last) + } + #expect(try mapping().status == .pendingRecovery) + let base = config.resolvingSymlinksInPath().appendingPathComponent(".agents-native") + let metadata = try #require( + FileManager.default.contentsOfDirectory( + at: base, includingPropertiesForKeys: nil + ).first) + let lock = metadata.appendingPathComponent("lock") + let externalPaths = Set( + [config, base, metadata, lock, URL(fileURLWithPath: "/")] + .map { $0.standardizedFileURL.path }) + let damaged = damage.hasPrefix("base") ? base : damage.hasPrefix("metadata") ? metadata : lock + let backup = f.root.appendingPathComponent("metadata-backup") + let scopeBefore = try f.snapshot(store.directory) + if damage.hasSuffix("absent") { + try FileManager.default.moveItem(at: damaged, to: backup) + } else { + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: damaged.path) + } + let beforeInspection = try f.snapshot() + let unavailable = try mapping() + guard case .unavailable = unavailable.status else { + Issue.record("Expected failed shared admission, got \(unavailable.status)") + return + } + #expect(unavailable.readDependencies.allSatisfy { if case .entry = $0 { true } else { false } }) + #expect( + Set(unavailable.readDependencies.map { $0.url.path }).isSuperset(of: externalPaths)) + #expect(try f.snapshot() == beforeInspection) + #expect(try f.snapshot(store.directory) == scopeBefore) + if damage.hasSuffix("absent") { + try FileManager.default.moveItem(at: backup, to: damaged) + } else { + try FileManager.default.setAttributes( + [.posixPermissions: damage == "lock-access" ? 0o600 : 0o700], + ofItemAtPath: damaged.path) + } + let repairedBeforeInspection = try f.snapshot() + let repaired = try mapping() + #expect(repaired.status == .pendingRecovery) + #expect(repaired.readDependencies.allSatisfy { if case .entry = $0 { true } else { false } }) + #expect( + Set(repaired.readDependencies.map { $0.url.path }).isSuperset(of: externalPaths)) + #expect(try f.snapshot(store.directory) == scopeBefore) + #expect(try f.snapshot() == repairedBeforeInspection) + } + + @Test func lockedMappingReadsMetadataWithoutContentDependencies() throws { + let f = try InstructionFixture() + try f.section("shared") + try f.commit() + try f.add(agents: [.codex]) + try f.own("own") + try f.addOwn(names: ["own"], agents: [.codex]) + let store = f.store() + var declaration = try store.loadDeclaration() + try declaration.updateInstructions { + $0?.chatgpt = [ + "daily": PromptDeclaration(sections: ["rules:shared", "own"], append: "append.md") + ] + } + try store.save(declaration: declaration, ledger: store.loadLedger()) + _ = try InstructionOperations.updateInstalled(environment: f.environment, apply: true) + let own = f.project.appendingPathComponent(".agent/instructions/own.md") + let target = f.project.appendingPathComponent("AGENTS.md") + for url in [own, target, store.cacheDirectory] { + try FileManager.default.removeItem(at: url) + } + let before = try f.snapshot() + let mapping = try #require( + InstructionOperations.export(projectRoots: [f.project], environment: f.environment).last) + #expect(mapping.status == .locked) + #expect(mapping.targets.flatMap(\.sections).map(\.name) == ["shared", "own"]) + #expect(mapping.prompts["daily"]?.map(\.name) == ["shared", "own"]) + #expect(mapping.unplaced.isEmpty) + expectStateLocations(mapping, store: store) + let paths = Set(mapping.readDependencies.map { $0.url.path }) + #expect(!paths.contains(own.path)) + #expect(!paths.contains(target.path)) + #expect(!paths.contains(f.project.appendingPathComponent("append.md").path)) + #expect(!paths.contains { $0.hasPrefix(store.cacheDirectory.path) }) + #expect(try f.snapshot() == before) + } + + @Test func missingScopesRetainAbsentLeavesWithoutCreatingState() throws { + let f = try InstructionFixture() + let before = try f.snapshot() + let mappings = InstructionOperations.export( + projectRoots: [f.project, f.project.appendingPathComponent(".")], environment: f.environment) + #expect(mappings.map(\.scope) == [.user, .project]) + for mapping in mappings { + #expect(mapping.status == .missingLock) + expectStateLocations(mapping, store: f.store(mapping.scope)) + #expect(!FileManager.default.fileExists(atPath: f.store(mapping.scope).directory.path)) + } + #expect(try f.snapshot() == before) + } + + @Test(arguments: ["transaction.json", "transaction.new", "watch-refs.pending"]) + func pendingRecoveryRetainsAdmissionLocations(_ marker: String) throws { + let f = try InstructionFixture() + let store = f.store() + try f.write("", to: store.directory.appendingPathComponent(marker)) + let before = try f.snapshot() + let mapping = try #require( + InstructionOperations.export(projectRoots: [f.project], environment: f.environment).last) + #expect(mapping.status == .pendingRecovery) + expectStateLocations(mapping, store: store) + #expect(mapping.targets.isEmpty) + #expect(try f.snapshot() == before) + } + + @Test(arguments: ["agents.yaml", "agents.resolved", "agents.watch", ".agents.lock"]) + func unavailableScopesRetainLocationsForRepair(_ name: String) throws { + let f = try InstructionFixture() + let store = f.store() + let file = store.directory.appendingPathComponent(name) + if name == ".agents.lock" { + try FileManager.default.createDirectory( + at: store.directory, withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink( + at: file, withDestinationURL: f.root.appendingPathComponent("absent-lock")) + } else { + try f.write("invalid", to: file) + } + let before = try f.snapshot() + let mapping = try #require( + InstructionOperations.export(projectRoots: [f.project], environment: f.environment).last) + guard case .unavailable(let message) = mapping.status else { + Issue.record("Expected unavailable scope, got \(mapping.status)") + return + } + if name == "agents.watch" || name == "agents.resolved" { + #expect(message.contains(store.declarationURL.path)) + } + expectStateLocations(mapping, store: store) + #expect(mapping.targets.isEmpty) + #expect(try f.snapshot() == before) + } + + @Test(arguments: [InstallScope.project, .user]) + func allowedRootAliasesRetainLogicalAndPhysicalEntries(_ scope: InstallScope) throws { + let f = try InstructionFixture() + let logical = f.root.appendingPathComponent("scope-alias") + let first = f.root.appendingPathComponent("physical-first").resolvingSymlinksInPath() + let second = f.root.appendingPathComponent("physical-second").resolvingSymlinksInPath() + for root in [first, second] { + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: false) + } + try FileManager.default.createSymbolicLink(at: logical, withDestinationURL: first) + var environment = f.environment + if scope == .project { + environment.projectDirectory = logical + } else { + environment.homeDirectory = logical + } + let stateName = scope == .project ? ".agent" : ".agents" + func mapping() throws -> InstructionMapping { + let values = InstructionOperations.export( + projectRoots: scope == .project ? [logical] : [], environment: environment) + return try #require(scope == .project ? values.last : values.first) + } + let absent = try mapping() + #expect(absent.status == .missingLock) + let expected = Set( + [ + logical, first, logical.appendingPathComponent(stateName), + first.appendingPathComponent(stateName), + first.appendingPathComponent(stateName + "/agents.resolved"), + ].map(\.path)) + #expect(Set(absent.readDependencies.map { $0.url.path }).isSuperset(of: expected)) + #expect(absent.readDependencies.allSatisfy { if case .entry = $0 { true } else { false } }) + let physicalMarker = first.appendingPathComponent(stateName + "/transaction.new") + try f.write("", to: physicalMarker) + let before = try f.snapshot() + let pending = try mapping() + #expect(pending.status == .pendingRecovery) + #expect(pending.readDependencies.map { $0.url.path }.contains(physicalMarker.path)) + #expect(try f.snapshot() == before) + try FileManager.default.removeItem(at: logical) + try FileManager.default.createSymbolicLink(at: logical, withDestinationURL: second) + let retargetedBefore = try f.snapshot() + let retargeted = try mapping() + #expect(retargeted.status == .missingLock) + #expect(retargeted.readDependencies.map { $0.url.path }.contains(logical.path)) + #expect(retargeted.readDependencies.map { $0.url.path }.contains(second.path)) + #expect(!retargeted.readDependencies.map { $0.url.path }.contains(first.path)) + #expect(try f.snapshot() == retargetedBefore) + } + + @Test(arguments: ["state", "lock"]) + func forbiddenLinksDoNotIntroduceTargetAuthority(_ kind: String) throws { + let f = try InstructionFixture() + let store = f.store() + let external = f.root.appendingPathComponent("forbidden-target") + if kind == "state" { + try FileManager.default.createDirectory(at: external, withIntermediateDirectories: false) + try FileManager.default.createSymbolicLink(at: store.directory, withDestinationURL: external) + } else { + try f.write("", to: external) + try FileManager.default.createDirectory( + at: store.directory, withIntermediateDirectories: false) + try FileManager.default.createSymbolicLink( + at: store.directory.appendingPathComponent(".agents.lock"), withDestinationURL: external) + } + let before = try f.snapshot() + let mapping = try #require( + InstructionOperations.export( + projectRoots: [f.project], environment: f.environment + ).last) + guard case .unavailable = mapping.status else { + Issue.record("Forbidden link was admitted") + return + } + #expect(!mapping.readDependencies.map { $0.url.path }.contains(external.path)) + #expect(mapping.readDependencies.allSatisfy { if case .entry = $0 { true } else { false } }) + #expect(try f.snapshot() == before) + } + + private func expectStateLocations(_ mapping: InstructionMapping, store: StateStore) { + let root = + store.scope == .project + ? store.environment.projectDirectory : store.environment.homeDirectory + let expected = Set( + [root, root.resolvingSymlinksInPath()].flatMap { root in + let state = root.appendingPathComponent(store.scope == .project ? ".agent" : ".agents") + let userConfiguration = + store.scope == .user ? [state.appendingPathComponent("agents.json")] : [] + return [root, state] + userConfiguration + + [ + "agents.yaml", "agents.resolved", "agents.watch", ".agents.lock", + "transaction.json", "transaction.new", "watch-refs.pending", + ].map { state.appendingPathComponent($0) } + }.map(\.path) + ).sorted() + #expect(mapping.readDependencies.map { $0.url.path } == expected) + #expect(mapping.readDependencies.allSatisfy { if case .entry = $0 { true } else { false } }) + } +} + +private final class MappingTestBundle: NSObject {} diff --git a/Tests/AgentsInstructionsTests/OwnershipAndPlacementTests.swift b/Tests/AgentsInstructionsTests/OwnershipAndPlacementTests.swift index f13f9f8..03a8e4a 100644 --- a/Tests/AgentsInstructionsTests/OwnershipAndPlacementTests.swift +++ b/Tests/AgentsInstructionsTests/OwnershipAndPlacementTests.swift @@ -1,5 +1,7 @@ import AgentsCore import AgentsInstructions +import AgentsManifest +import AgentsUpdates import Foundation import Testing @@ -156,8 +158,10 @@ struct OwnershipAndPlacementTests { let fixture = try InstructionFixture() try fixture.own("guide") try fixture.write( - "{\"instructions\": {\"sections\": [], \"chatgpt\": {\"weekly\": {\"sections\": [\"guide\"]}}}}\n", - to: fixture.store().declarationURL) + """ + version: 1 + components: [{"kind": "instructions", "chatgpt": {"weekly": {"sections": [{"name": "guide"}]}}}] + """, to: fixture.store().declarationURL) _ = try InstructionOperations.updateInstalled(environment: fixture.environment, apply: true) #expect( try fixture.store().loadResolved().instructions.chatgpt["weekly"]?.sections.map(\.name) @@ -212,3 +216,45 @@ struct OwnershipAndPlacementTests { #expect(user.targets.map { $0.sections.map(\.name) } == [["rules"]]) } } + +extension OwnershipAndPlacementTests { + @Test func removeBareNameFallsBackOnlyToAUniqueDeclaredSource() throws { + let fixture = try InstructionFixture() + try fixture.section("guide") + try fixture.commit() + try fixture.add(names: ["guide"]) + try InstructionOperations.remove(names: ["guide"], environment: fixture.environment) + #expect(try fixture.store().loadDeclaration().instructions?.sections == []) + #expect(try fixture.store().loadResolved().instructions.sections.isEmpty) + } + + @Test func ambiguousFallbackRefusesAndQualifiedReferencesPreserveOtherGuides() throws { + let fixture = try InstructionFixture() + try fixture.section("guide", heading: "# Shared Guide") + try fixture.commit() + try fixture.add(names: ["guide"]) + let store = fixture.store() + var declaration = try store.loadDeclaration() + declaration.sources["other"] = .init( + kind: .local, location: fixture.root.appendingPathComponent("unresolved-other").path) + try declaration.updateInstructions { $0?.sections.append("other:guide") } + try store.save(declaration: declaration, ledger: store.loadLedger()) + let before = try fixture.snapshot() + var called = false + #expect(throws: CoreError.notFound("instruction name is missing or ambiguous: guide")) { + try InstructionOperations.remove(names: ["guide"], environment: fixture.environment) { _ in + called = true + } + } + #expect(!called) + #expect(try fixture.snapshot() == before) + try declaration.updateInstructions { $0?.sections.removeAll { $0 == "other:guide" } } + declaration.sources["other"] = nil + try store.save(declaration: declaration, ledger: store.loadLedger()) + try fixture.own("guide", heading: "# Project Guide") + try fixture.addOwn(names: ["guide"]) + try InstructionOperations.remove(names: ["rules:guide"], environment: fixture.environment) + #expect(try store.loadDeclaration().instructions?.sections == ["guide"]) + #expect(try fixture.text() == generated(["# Project Guide\n\nOriginal"])) + } +} diff --git a/Tests/AgentsInstructionsTests/SourceDiagnosticTests.swift b/Tests/AgentsInstructionsTests/SourceDiagnosticTests.swift index dc496b0..ed0a9f2 100644 --- a/Tests/AgentsInstructionsTests/SourceDiagnosticTests.swift +++ b/Tests/AgentsInstructionsTests/SourceDiagnosticTests.swift @@ -1,6 +1,9 @@ import AgentsCore import AgentsInstructions +import AgentsManifest +import AgentsUpdates import Foundation +import StateTestSupport import Testing @Suite("Instruction source diagnostics") @@ -45,7 +48,7 @@ struct InstructionSourceDiagnosticTests { let object = try fixture.git(["rev-parse", "release"]) var declaration = try fixture.store().loadDeclaration() declaration.sources["rules"]?.requirement = .revision(object) - try fixture.store().save(declaration: declaration, resolved: fixture.store().loadResolved()) + try fixture.store().save(declaration: declaration, ledger: fixture.store().loadLedger()) let mirrors = fixture.store().cacheDirectory.appendingPathComponent("mirrors") if retainMirror { try fixture.section("prompt", body: "New branch content") @@ -80,7 +83,7 @@ struct InstructionSourceDiagnosticTests { } var declaration = try fixture.store().loadDeclaration() declaration.sources["rules"]?.requirement = .revision(object) - try fixture.store().save(declaration: declaration, resolved: fixture.store().loadResolved()) + try fixture.store().save(declaration: declaration, ledger: fixture.store().loadLedger()) let before = try fixture.snapshot() let report = try InstructionOperations.doctor(environment: fixture.environment) #expect( @@ -162,7 +165,7 @@ struct InstructionSourceDiagnosticTests { try install(fixture, kind: kind, requirement: .branch("main"), files: []) var declaration = try fixture.store().loadDeclaration() declaration.sources["rules"]?.requirement = .branch("missing") - try fixture.store().save(declaration: declaration, resolved: fixture.store().loadResolved()) + try fixture.store().save(declaration: declaration, ledger: fixture.store().loadLedger()) let before = try fixture.snapshot() let report = try InstructionOperations.doctor(environment: fixture.environment) let failure = try #require(report.diagnostics.first { $0.kind == .sourceResolutionFailed }) @@ -208,7 +211,7 @@ struct InstructionSourceDiagnosticTests { instructions: InstructionsDeclaration( sections: files.map { "rules:" + $0 }, chatgpt: ["daily": PromptDeclaration(sections: ["rules:prompt"])])), - resolved: ResolvedState()) + ledger: ResolvedLedger()) _ = try InstructionOperations.updateInstalled(environment: fixture.environment, apply: true) } } diff --git a/Tests/AgentsInstructionsTests/SourceShorthandTests.swift b/Tests/AgentsInstructionsTests/SourceShorthandTests.swift index daf7001..81aa224 100644 --- a/Tests/AgentsInstructionsTests/SourceShorthandTests.swift +++ b/Tests/AgentsInstructionsTests/SourceShorthandTests.swift @@ -1,5 +1,7 @@ import AgentsCore import AgentsInstructions +import AgentsManifest +import AgentsUpdates import Foundation import Testing @@ -14,7 +16,7 @@ struct InstructionSourceShorthandTests { InstructionAddOptions( source: fixture.repo.path + "@skill:rules", environment: fixture.environment)) } - try InstructionOperations.add( + _ = try InstructionOperations.add( InstructionAddOptions( source: fixture.repo.path + "@branch:main", names: ["rules"], agents: [.codex], environment: fixture.environment)) diff --git a/Tests/AgentsInstructionsTests/TargetLifecycleTests.swift b/Tests/AgentsInstructionsTests/TargetLifecycleTests.swift index 392fe1c..1c2bea4 100644 --- a/Tests/AgentsInstructionsTests/TargetLifecycleTests.swift +++ b/Tests/AgentsInstructionsTests/TargetLifecycleTests.swift @@ -1,10 +1,25 @@ import AgentsCore import AgentsInstructions +import AgentsManifest +import AgentsUpdates import Foundation import Testing @Suite("Own instructions and generated targets") struct TargetLifecycleTests { + @Test func doctorReportsAnOwnFileReplacedByADirectory() throws { + let fixture = try InstructionFixture() + try fixture.own("guide", heading: "# Project Guide") + try fixture.addOwn(names: ["guide"]) + let file = fixture.project.appendingPathComponent(".agent/instructions/guide.md") + try FileManager.default.removeItem(at: file) + try FileManager.default.createDirectory(at: file, withIntermediateDirectories: false) + #expect( + try InstructionOperations.doctor(environment: fixture.environment).diagnostics.contains { + $0.kind == .ownChanged + }) + } + @Test func ownInstructionsAreReadLiveAndRecordedByHash() throws { let fixture = try InstructionFixture() try fixture.section("shared") @@ -34,9 +49,9 @@ struct TargetLifecycleTests { try InstructionOperations.doctor(environment: fixture.environment).diagnostics.contains { $0.kind == .ownChanged }) - #expect(throws: InstructionError.ownChanged(name: "guide")) { - try InstructionOperations.installResolvedReport(environment: fixture.environment) - } + let locked = try fixture.bytes() + _ = try InstructionOperations.installResolvedReport(environment: fixture.environment) + #expect(try fixture.bytes() == locked) _ = try InstructionOperations.updateInstalled(environment: fixture.environment, apply: true) #expect(try fixture.text().contains("# Project Guide\n\nEdited")) #expect( @@ -45,30 +60,32 @@ struct TargetLifecycleTests { }) } - @Test func updateApplyWritesStateInTheStandardLayout() throws { + @Test func updateApplyKeepsAnUnchangedDeclarationAndLedgerAsWritten() throws { let fixture = try InstructionFixture() try fixture.own("guide") try fixture.addOwn(names: ["guide"], agents: [.codex]) let declarationFile = fixture.store().declarationURL let lockFile = fixture.store().resolvedURL - let declaration = try Data(contentsOf: declarationFile) - let lock = try Data(contentsOf: lockFile) - #expect( - String(decoding: declaration, as: UTF8.self) - == "{\n \"instructions\": {\n \"agents\": [\"codex\"],\n \"sections\": [\"guide\"]\n },\n \"sources\": {}\n}\n" - ) - let lockText = String(decoding: lock, as: UTF8.self) - #expect(lockText.contains("\"chatgpt\": {}") && lockText.contains("\"skills\": {}")) - #expect(!lockText.contains(" : ")) - // An earlier version wrote this content in Foundation's layout. - try StateStore.encode(fixture.store().loadDeclaration()).write(to: declarationFile) - try StateStore.encode(fixture.store().loadResolved()).write(to: lockFile) + let declaration = Data( + """ + # Project-owned layout. + version: 1 + components: + - kind: instructions # Keep this guidance. + sections: + - {name: guide} + agents: [codex] + """.utf8) + try declaration.write(to: declarationFile) + var existingLockBytes = try Data(contentsOf: lockFile) + existingLockBytes.append(Data("\n \n".utf8)) + try existingLockBytes.write(to: lockFile) _ = try InstructionOperations.updateInstalled(environment: fixture.environment, apply: true) #expect(try Data(contentsOf: declarationFile) == declaration) - #expect(try Data(contentsOf: lockFile) == lock) + #expect(try Data(contentsOf: lockFile) == existingLockBytes) _ = try InstructionOperations.updateInstalled(environment: fixture.environment, apply: true) #expect(try Data(contentsOf: declarationFile) == declaration) - #expect(try Data(contentsOf: lockFile) == lock) + #expect(try Data(contentsOf: lockFile) == existingLockBytes) } @Test func pathsPlaceSectionsInNestedTargets() throws { diff --git a/Tests/AgentsManifestTests/DeclarationProgressTests.swift b/Tests/AgentsManifestTests/DeclarationProgressTests.swift new file mode 100644 index 0000000..bbc347b --- /dev/null +++ b/Tests/AgentsManifestTests/DeclarationProgressTests.swift @@ -0,0 +1,72 @@ +import AgentsCore +import Foundation +import Testing + +@testable import AgentsManifest + +@Suite("Declaration edit progress") +struct DeclarationProgressTests { + @Test func flatSkillReplacementsKeepTheirInsertionAndRemovalProgressAcrossBatches() throws { + let old = (0..<100).map { "old\($0)" } + let replacement = (0..<100).map { "new\($0)" }.sorted(by: utf8Less) + let keep = (0..<2000).map { "keep\($0)" } + func literals(_ names: [String]) -> String { + names.map { "\"\($0)\"" }.joined(separator: ", ") + } + let body = """ + version: 1 + sources: {a: {path: a}, b: {path: b}} + components: + - {kind: skills, source: a, select: [\(literals(old))]} + - {kind: skills, source: b, select: [\(literals(keep))]} + """ + let previous = try projected(body) + var next = previous + try next.updateSkills { $0?["a"]?.select = .names(replacement) } + let bytes = try #require(try planned(previous, next, in: manifestHeader + body)) + let document = try DeclarationDocument(bytes: bytes, identity: DocumentIdentity("manifest")) + #expect( + document.declaration + == YAMLConstruction.root(next)) + let result = try ManifestProjection.declaration( + of: document, environment: projectionEnvironment) + #expect(try result.skills?["b"]?.select == .names(keep)) + #expect(try planned(result, next, in: String(decoding: bytes, as: UTF8.self)) == nil) + } + + @Test func sourceReorderingAndSkillReplacementProgressAcrossBatches() throws { + let old = (0..<100).map { "old\($0)" } + let replacement = (0..<100).map { "new\($0)" } + let keep = (0..<2000).map { "keep\($0)" } + func literals(_ names: [String]) -> String { + names.map { "\"\($0)\"" }.joined(separator: ", ") + } + let body = """ + version: 1 + sources: {b: {path: b}, a: {path: a}} + components: + - {kind: skills, source: a, select: [\(literals(old))]} + - {kind: skills, source: b, select: [\(literals(keep))]} + """ + let previous = try projected(body) + var next = previous + next.sourceDeclarations.reverse() + try next.updateSkills { $0?["a"]?.select = .names(replacement) } + try previous.validate(environment: projectionEnvironment) + try next.validate(environment: projectionEnvironment) + #expect(previous.sourceDeclarations.map(\.name) == ["b", "a"]) + #expect(next.sourceDeclarations.map(\.name) == ["a", "b"]) + #expect(try previous.skills?["a"]?.select == .names(old)) + #expect(try next.skills?["a"]?.select == .names(replacement)) + #expect(try next.skills?["b"]?.select == .names(keep)) + + let bytes = try #require(try planned(previous, next, in: manifestHeader + body)) + let document = try DeclarationDocument(bytes: bytes, identity: DocumentIdentity("manifest")) + #expect( + document.declaration + == YAMLConstruction.root(next)) + let result = try ManifestProjection.declaration( + of: document, environment: projectionEnvironment) + #expect(try planned(result, next, in: String(decoding: bytes, as: UTF8.self)) == nil) + } +} diff --git a/Tests/AgentsManifestTests/EditPlanTests.swift b/Tests/AgentsManifestTests/EditPlanTests.swift new file mode 100644 index 0000000..19e6040 --- /dev/null +++ b/Tests/AgentsManifestTests/EditPlanTests.swift @@ -0,0 +1,404 @@ +import AgentsCore +import Foundation +import Testing + +@testable import AgentsManifest + +func planned(_ previous: Declaration, _ next: Declaration, in text: String?) throws -> [UInt8]? { + try DeclarationEditPlan.bytes( + replacing: previous, with: next, in: text.map { Array($0.utf8) }, + identity: DocumentIdentity("manifest"), environment: projectionEnvironment) +} + +@Suite("Declaration edit planning") +struct EditPlanTests { + @Test func equivalentSpellingsAndWatchOrderPreserveEveryByte() throws { + let body = """ + # header + version: 1 + defaultAgents: [codex, claude-code] + sources: + g: {url: https://github.com/team/skills, requirement: {from: "1.2.0", to: "2.0.0"}} + l: {path: ./rules/, subpath: ./skills} # retained + components: [{kind: skills, source: g, select: [b, a], exclude: []}] + watch: [l, g] + """ + let previous = try projected(body) + var next = previous + next.agents = [.claudeCode, .codex] + next.sources["g"] = SourceDeclaration( + kind: .git, location: "https://GitHub.com/team/skills.git", + requirement: .upToNextMajor(from: "1.2.0")) + next.sources["l"] = SourceDeclaration( + kind: .local, location: "/work/project/rules", path: "skills") + try next.updateSkills { $0?["g"] = SkillDeclaration(select: .names(["a", "b"])) } + next.watch = ["g", "l"] + #expect(try planned(previous, next, in: body) == nil) + #expect(try planned(Declaration(), Declaration(), in: nil) == nil) + } + @Test func defaultRecipientsCanBeInsertedReplacedAndOmitted() throws { + var previous = try projected("version: 1\n") + var bytes = Array("version: 1\n".utf8) + for recipients: [AgentID]? in [[], [.codex, .claudeCode], nil] { + var next = previous + next.agents = recipients + bytes = try #require(try planned(previous, next, in: String(decoding: bytes, as: UTF8.self))) + #expect(try projected(String(decoding: bytes, as: UTF8.self)).agents == recipients) + previous = next + } + } + @Test func missingCollectionsAndLastElementRemovalKeepValidDocuments() throws { + let doc = try document("# header\r\nversion: 1\r\n") + let added = try doc.preparing([ + .insertComponent( + .instructions(InstructionsDeclaration(sections: ["guide"])), into: .root, at: .last) + ]) + let populated = try DeclarationDocument( + bytes: added.bytes, identity: DocumentIdentity("manifest")) + let removed = try populated.preparing([ + .removeComponent(#require(populated.node(at: "/components/0"))) + ]) + #expect( + try DeclarationDocument(bytes: removed.bytes, identity: DocumentIdentity("manifest")) + .declaration.components.isEmpty) + #expect(String(decoding: removed.bytes, as: UTF8.self).hasPrefix("# header\r\n")) + } + @Test func preparationRejectsOversizedIntentBeforeRendering() throws { + let doc = try document("version: 1\n") + expectManifestFailure("manifest.limit") { + try doc.preparing([ + .insertComponent( + .ignore(name: "large", patterns: [String(repeating: "x", count: 20_000_000)]), + into: .root, at: .first) + ]) + } + } + + @Test(arguments: ["", " ", "flow"], ["", "\n", "\r\n"]) + func removingSoleComponentKeepsMappingTriviaAndEOF(_ style: String, _ ending: String) throws { + let newline = ending == "\r\n" ? ending : "\n" + for nested in [false, true] { + for comments in [false, true] { + for sibling in [false, true] { + let owner = nested ? " " : "" + let indent = owner + (style == "flow" ? "" : style) + let prefix = + "# Preserve this comment\nversion: 1\nsources: {s: {path: ./keep}}\n" + + (nested ? "groups:\n local:\n" : "") + let field = owner + "components:" + let component = + "{kind: command, name: review, description: Review, prompt: Review sources., agents: [claude-code]}" + let retained = comments ? indent + "# entry\n" + indent + "# prompt\n" : "" + let collection: String + let empty: String + if style == "flow" { + collection = field + " [" + component + "]" + (comments ? " # field" : "") + empty = field + " []" + (comments ? " # field" : "") + } else { + let header = field + (comments ? " # field" : "") + "\n" + collection = + header + (comments ? indent + "# entry\n" : "") + + indent + "- kind: command\n" + indent + " name: review\n" + + indent + " description: Review\n" + indent + " prompt: Review sources." + + (comments ? " # prompt" : "") + "\n" + indent + " agents: [claude-code]" + empty = header + owner + " []" + (comments ? "\n" + retained.dropLast() : "") + } + let suffix = sibling ? "\n# unrelated tail\nwatch: []" : "" + let input = + (prefix + collection + suffix).replacingOccurrences(of: "\n", with: newline) + + ending + let expected = + (prefix + empty + suffix).replacingOccurrences(of: "\n", with: newline) + + ending + let doc = try document(input) + let pointer = nested ? "/groups/0/components/0" : "/components/0" + let change = try doc.preparing([.removeComponent(#require(doc.node(at: pointer)))]) + #expect(String(decoding: change.bytes, as: UTF8.self) == expected) + let result = try DeclarationDocument( + bytes: change.bytes, identity: DocumentIdentity("manifest")) + #expect(result.declaration == change.expectedDeclaration) + let previous = try projected(input) + var next = previous + if nested { + next.groups[0].components = [] + } else { + next.components = [] + } + #expect( + try ManifestProjection.declaration(of: result, environment: projectionEnvironment) + == next) + #expect(try planned(previous, next, in: input) == change.bytes) + #expect(try planned(next, next, in: expected) == nil) + } + } + } + } +} + +extension EditPlanTests { + @Test func blockAndFlowMovesCarryCommentsAcrossContainers() throws { + let doc = try document( + """ + version: 1 + components: + # owned entry + - kind: ignore + name: moving + patterns: [] # owned tail + groups: + target: + components: + - {kind: ignore, name: existing, patterns: []} + """) + let change = try doc.preparing([ + .moveComponent( + #require(doc.node(at: "/components/0")), into: .group(#require(doc.node(at: "/groups/0"))), + at: .last) + ]) + let result = try DeclarationDocument( + bytes: change.bytes, identity: DocumentIdentity("manifest")) + #expect(result.declaration.components.isEmpty) + #expect(result.declaration.groups[0]["components"]?.elements?.count == 2) + let text = String(decoding: change.bytes, as: UTF8.self) + #expect(text.contains("# owned entry\n - kind: ignore")) + #expect(text.contains("patterns: [] # owned tail")) + let flow = try document( + "version: 1\ncomponents: [{kind: ignore, name: moving, patterns: []}]\ngroups: {target: {}}\n" + ) + let moved = try flow.preparing([ + .moveComponent( + #require(flow.node(at: "/components/0")), + into: .group(#require(flow.node(at: "/groups/0"))), at: .first) + ]) + #expect( + try DeclarationDocument(bytes: moved.bytes, identity: DocumentIdentity("manifest")) + .declaration.groups[0]["components"]?.elements?.count == 1) + } + + @Test func sourceKindChangeRetainsInternalCommentsAndUnchangedFields() throws { + let body = + "version: 1\nsources:\n s:\n path: ./s # location\n # root comment\n subpath: rules\ncomponents: [{kind: skills, source: s, mode: edit}]\n" + let previous = try projected(body) + var next = previous + next.sourceDeclarations[0].source = SourceDeclaration( + kind: .git, location: "https://example.invalid/repo.git", path: "rules") + try next.updateSkills { $0?["s"]?.mode = .copy } + let bytes = try #require(try planned(previous, next, in: body)) + let text = String(decoding: bytes, as: UTF8.self) + #expect(text.contains("# root comment\n subpath: rules")) + #expect(text.contains("# location")) + #expect(try projected(text).components == next.components) + } + + @Test func unrelatedHandlesAndLiteralKindsAreRejectedWithoutTrapping() throws { + let doc = try document("version: 1\ncomponents: [{kind: ignore, name: i, patterns: []}]\n") + let scalar = try #require(doc.node(at: "/components/0/name")) + for edit in [ + ManifestEdit.setSkillSelection(scalar, .all), .moveComponent(scalar, into: .root, at: .first), + .setDictionaryEntry(scalar, key: "k", value: .string("v")), + ] { + expectManifestFailure("manifest.edit.readOnly") { try doc.preparing([edit]) } + } + } +} + +extension EditPlanTests { + @Test func blockScalarHeaderCommentsAndFollowingFieldsSurviveReplacement() throws { + let doc = try document( + "version: 1\ncomponents:\n - kind: subagent\n name: a\n description: d\n prompt: |- # owned header\n before\n model: keep\n# tail\n" + ) + let change = try doc.preparing([ + .replaceComponent( + #require(doc.node(at: "/components/0")), + with: .subagent(name: "a", description: "d", prompt: .literal("after"), model: "keep")) + ]) + let text = String(decoding: change.bytes, as: UTF8.self) + #expect(text.contains("# owned header\n model: keep\n# tail\n")) + #expect( + try DeclarationDocument(bytes: change.bytes, identity: DocumentIdentity("manifest")) + .declaration == change.expectedDeclaration) + } +} + +extension EditPlanTests { + @Test func promptKindChangesOwnTheWrapperAndRetainResourceLocations() throws { + var text = + "version: 1\nsources: {s: {path: ./s}}\ncomponents: [{kind: subagent, name: a, description: d, prompt: {file: {path: p.md}}, model: keep}] # tail\n" + let original = try document(text) + let prompt = try #require(original.sourceMap.locations(at: "/components/0/prompt").first?.span) + let path = try #require( + original.sourceMap.locations(at: "/components/0/prompt/path").first?.span) + #expect( + String(decoding: original.bytes[prompt.start.. DeclarationDocument { + try DeclarationDocument(bytes: Array(body.utf8), identity: DocumentIdentity("manifest")) +} + +@Suite("YAML frontend") +struct FrontEndTests { + @Test(arguments: ["yes", "on", "2026-11-15"]) + func coreStringsRemainStrings(_ text: String) throws { + let doc = try document( + "version: 1\ncomponents: [{kind: subagent, name: a, description: d, prompt: \(text)}]\n") + #expect(doc.declaration.components[0]["prompt"]?.record?["value"] == .string(text)) + } + @Test(arguments: ["&a []", "*a", "!!str x", "!!float 1", "{x: 1}"]) + func unsupportedOrdinaryValuesAreRejected(_ text: String) { + #expect(throws: ManifestFailure.self) { try document("version: 1\nwatch: \(text)\n") } + } + @Test(arguments: ["\u{85}", "\u{2028}", "\u{2029}"]) + func rawSeparatorsAreRejectedBeforeParsing(_ separator: String) { + expectManifestFailure("manifest.character") { try document("# \(separator)\nversion: 1\n") } + let prefix = "\u{FEFF}# 🙂 " + do { + _ = try document(prefix + separator + "\r\nversion: 1\r\n") + Issue.record("expected a raw separator failure") + } catch let failure as ManifestFailure { + #expect(failure.diagnostics[0].code == "manifest.character") + #expect(failure.diagnostics[0].span.start == prefix.utf8.count) + #expect(failure.diagnostics[0].span.column == prefix.utf8.count + 1) + } catch { + Issue.record(error) + } + } + @Test func escapedSeparatorsAndDecimalPayloadsRoundTrip() throws { + let body = #""" + version: 1 + components: + - kind: lspServer + name: test + run: {executable: unused} + languages: {'.swift': swift} + initializationOptions: + text: "\u0085\u2028\u2029" + decimal: !!float "1E+003" + integerLike: !!float "1" + negativeZero: !!float "-0" + '<<': {ordinary: true} + """# + let doc = try document(body) + let typed = try ManifestProjection.declaration(of: doc, environment: projectionEnvironment) + let bytes = try #require(try planned(Declaration(), typed, in: nil)) + #expect(try projected(String(decoding: bytes, as: UTF8.self)).components == typed.components) + let dumped = try ManifestDump(document: doc) + #expect(dumped.schemaVersion == 2 && dumped.format == "yaml" && dumped.manifestVersion == 1) + #expect(String(decoding: try dumped.encodedJSON(), as: UTF8.self).contains("1E+003")) + } + @Test func sourceMapUsesOrderedSemanticPointers() throws { + let body = + "version: 1\nsources: {b: {path: b}, a: {path: a}}\ngroups: {unused: {components: [{kind: ignore, name: i, patterns: []}]}}\n" + let doc = try document(body) + let name = try #require(doc.sourceMap.locations(at: "/sources/0/name").first) + #expect(String(decoding: doc.bytes[name.span.start.. DeclarationDocument { + try DeclarationDocument(bytes: Array(text.utf8), identity: yamlIdentity) +} + +private func yamlProjection(_ text: String) throws -> Declaration { + try ManifestProjection.declaration(of: yamlDocument(text), environment: yamlEnvironment) +} + +private func yamlPlan(_ before: Declaration, _ after: Declaration, _ text: String?) throws + -> [UInt8]? +{ + try DeclarationEditPlan.bytes( + replacing: before, with: after, in: text.map { Array($0.utf8) }, + identity: yamlIdentity, environment: yamlEnvironment) +} + +private func assertYAMLEdit( + _ input: String, _ target: Declaration, preserving segments: [String], + sourceLocation: SourceLocation = #_sourceLocation +) throws -> String { + let before = try yamlProjection(input) + let bytes = try #require(try yamlPlan(before, target, input), sourceLocation: sourceLocation) + let output = String(decoding: bytes, as: UTF8.self) + let actual = try yamlProjection(output) + #expect(actual == target, sourceLocation: sourceLocation) + for segment in segments { + #expect( + output.contains(segment), "missing unchanged bytes: \(segment)", + sourceLocation: sourceLocation) + } + #expect(try yamlPlan(actual, target, output) == nil, sourceLocation: sourceLocation) + return output +} + +@Suite("Independent YAML acceptance") +struct IndependentYAMLAcceptanceTests { + @Test func nativeValuesRoundTripWithoutLosingNumericIdentity() throws { + let values: [NativeValue] = [ + .integer(1), .decimal("1"), .decimal("9223372036854775808"), .decimal("-0"), + .decimal("1.00"), .decimal("1E+003"), .decimal("1.2345678901234567890123456789"), + .string("1"), .string("true"), .boolean(true), .null, + ] + let desired = Declaration(components: [ + .lspServer( + name: "server", run: ExecutableDeclaration(executable: "missing-program"), + languages: [".swift": "swift"], + initializationOptions: ["nested": .array(values), "<<": .object(["text": .string("1")])], + native: ["example/lsp@1": ["values": .object(["nested": .array(values)])]]), + .ignore(name: "second", patterns: ["private/**"]), + ]) + let bytes = try #require(try yamlPlan(Declaration(), desired, nil)) + let text = String(decoding: bytes, as: UTF8.self) + let actual = try yamlProjection(text) + #expect(actual == desired) + guard case .lspServer(_, _, let languages, let options, _, _, let native) = actual.components[0] + else { + Issue.record("expected LSP component") + return + } + #expect(languages == [".swift": "swift"]) + #expect(options["nested"] == .array(values)) + #expect(options["<<"] == .object(["text": .string("1")])) + #expect(native["example/lsp@1"]?["values"] == .object(["nested": .array(values)])) + #expect(actual.components[1] == .ignore(name: "second", patterns: ["private/**"])) + #expect(try yamlPlan(actual, desired, text) == nil) + } + + @Test(arguments: ["\u{0085}", "\u{2028}", "\u{2029}"]) + func rawLineSeparatorsAreRejectedAtTheirOriginalBytes(_ character: String) throws { + let templates = [ + "version: 1\ncomponents:\n - {kind: subagent, name: a, description: \"left@right\", prompt: ok}\n", + "version: 1\ncomponents:\n - {kind: subagent, name: a, description: 'left@right', prompt: ok}\n", + "version: 1\ncomponents:\n - {kind: subagent, name: a, description: left@right, prompt: ok}\n", + "version: 1\ncomponents:\n - kind: subagent\n name: a\n description: |-\n left@right\n prompt: ok\n", + "version: 1\n# left@right\n", + ] + for template in templates { + let input = template.replacingOccurrences(of: "@", with: character) + let prefix = try #require(input.range(of: character)).lowerBound + let start = input[..= prefix.utf8.count + suffix.utf8.count) + } + + @Test func flowFieldEditRetainsNeighboringComments() throws { + let input = """ + # Heading + version: 1 + components: [ {kind: ignore, name: first, patterns: [old]}, {kind: ignore, name: second, patterns: [keep]} ] # components + # Footer + """ + var target = try yamlProjection(input) + target.components[0] = .ignore(name: "first", patterns: ["new"]) + let output = try assertYAMLEdit( + input, target, + preserving: [ + "# Heading\nversion: 1\n", "{kind: ignore, name: second, patterns: [keep]} ] # components", + "\n# Footer", + ]) + let scalar = try #require(input.range(of: "old")) + let prefix = String(input[..= prefix.utf8.count + suffix.utf8.count) + } + + @Test func insertingIntoEmptyComponentsKeepsSurroundingSections() throws { + let input = """ + # Header + version: 1 + components: [] # empty components + groups: + unused: {} + # Tail + """ + var target = try yamlProjection(input) + target.components = [.ignore(name: "new", patterns: ["private/**"])] + _ = try assertYAMLEdit( + input, target, + preserving: [ + "# Header\nversion: 1\n", "# empty components", "groups:\n unused: {}\n# Tail", + ]) + } + + @Test func deletingComponentKeepsItsCommentAndUnrelatedSections() throws { + let input = """ + # Header + version: 1 + components: + # Retain this note. + - {kind: ignore, name: remove, patterns: [old]} + # Kept item. + - {kind: ignore, name: keep, patterns: [keep]} + groups: + unused: {} + # Tail + """ + var target = try yamlProjection(input) + target.components.removeFirst() + _ = try assertYAMLEdit( + input, target, + preserving: [ + "# Header\nversion: 1\n", "# Retain this note.", + "# Kept item.\n - {kind: ignore, name: keep, patterns: [keep]}", + "groups:\n unused: {}\n# Tail", + ]) + } + + @Test func movingBlockComponentsCarriesUniquelyOwnedComments() throws { + let input = """ + # Header + version: 1 + components: + # First item. + - {kind: ignore, name: first, patterns: [one]} # first tail + # Second item. + - {kind: ignore, name: second, patterns: [two]} # second tail + groups: + unused: {} + # Tail + """ + var target = try yamlProjection(input) + target.components.reverse() + let output = try assertYAMLEdit( + input, target, + preserving: [ + "# Header\nversion: 1\n", "groups:\n unused: {}\n# Tail", + "# First item.\n - {kind: ignore, name: first, patterns: [one]} # first tail", + "# Second item.\n - {kind: ignore, name: second, patterns: [two]} # second tail", + ]) + let first = try #require(output.range(of: "# First item.")) + let second = try #require(output.range(of: "# Second item.")) + #expect(second.lowerBound < first.lowerBound) + } + + @Test func flowComponentsSupportInsertionDeletionAndMove() throws { + let input = """ + # Flow header + version: 1 + components: [{kind: ignore, name: first, patterns: [one]}, {kind: ignore, name: second, patterns: [two]}] # flow items + groups: {unused: {}} + # Flow tail + """ + let kept = ["# Flow header\nversion: 1\n", "# flow items", "groups: {unused: {}}\n# Flow tail"] + var target = try yamlProjection(input) + target.components.insert(.ignore(name: "middle", patterns: ["three"]), at: 1) + let inserted = try assertYAMLEdit(input, target, preserving: kept) + target.components.removeFirst() + let deleted = try assertYAMLEdit(inserted, target, preserving: kept) + target.components.reverse() + _ = try assertYAMLEdit(deleted, target, preserving: kept) + } + + @Test func semanticNoOpPreservesBOMCRLFAndOmittedWatchBytes() throws { + let input = "\u{FEFF}# heading\r\nversion: 1\r\ncomponents: [] # untouched\r\n" + let previous = try yamlProjection(input) + var target = previous + target.watch = [] + #expect(try yamlPlan(previous, target, input) == nil) + #expect(try yamlDocument(input).bytes == Array(input.utf8)) + } + + @Test func inputByteLimitIncludesExactBoundary() throws { + let prefix = "version: 1\n#" + let limit = 2_097_152 + let boundary = prefix + String(repeating: "x", count: limit - prefix.utf8.count) + #expect(boundary.utf8.count == limit) + #expect(try yamlProjection(boundary) == Declaration()) + #expect(throws: ManifestFailure.self) { try yamlDocument(boundary + "x") } + } +} diff --git a/Tests/AgentsManifestTests/ManifestExpectations.swift b/Tests/AgentsManifestTests/ManifestExpectations.swift new file mode 100644 index 0000000..90e60b3 --- /dev/null +++ b/Tests/AgentsManifestTests/ManifestExpectations.swift @@ -0,0 +1,17 @@ +import Testing + +@testable import AgentsManifest + +func expectManifestFailure( + _ code: String, sourceLocation: SourceLocation = #_sourceLocation, + _ operation: () throws -> T +) { + do { + _ = try operation() + Issue.record("expected diagnostic \(code)", sourceLocation: sourceLocation) + } catch let failure as ManifestFailure { + #expect(failure.diagnostics.map(\.code) == [code], sourceLocation: sourceLocation) + } catch { + Issue.record(error, sourceLocation: sourceLocation) + } +} diff --git a/Tests/AgentsManifestTests/MappingFieldInsertionTests.swift b/Tests/AgentsManifestTests/MappingFieldInsertionTests.swift new file mode 100644 index 0000000..1184a3a --- /dev/null +++ b/Tests/AgentsManifestTests/MappingFieldInsertionTests.swift @@ -0,0 +1,98 @@ +import AgentsCore +import Foundation +import Testing + +@testable import AgentsManifest + +struct MappingFieldInsertionTests { + @Test(arguments: [false, true], ["\n", "\r\n"]) + func skillPathAlignsWithCompactMappingKeys(_ nested: Bool, _ newline: String) throws { + let owner = nested ? " " : "" + let prefix = + "# header\nversion: 1\ndefaultAgents: [codex]\nsources: {team: {path: ./source}}\n" + + (nested ? "groups:\n local:\n" : "") + let first = """ + \(owner)components: + \(owner) - kind: skills # component + \(owner) source: team + \(owner) select: [demo] + \(owner) mode: link # mode + """ + "\n" + let following = """ + \(owner) # following component + \(owner) - kind: instructions + \(owner) sections: [{name: style, source: team}] + # tail + """ + "\n" + let body = (prefix + first + following).replacingOccurrences(of: "\n", with: newline) + let doc = try document(body) + let pointer = nested ? "/groups/0/components/0" : "/components/0" + let edit = IREdit.set(pointer + "/path", .string(".")) + let patches = try YAMLPatches(document: doc).patches( + for: edit, expected: edit.applying(to: IRTree.root(doc.declaration))) + #expect(patches.count == 1) + #expect( + String(decoding: patches[0].replacement, as: UTF8.self) == owner + " \"path\": \".\"" + + newline) + let change = try doc.preparing([ + .replaceComponent( + #require(doc.node(at: pointer)), + with: .skills(source: "team", .init(select: .names(["demo"]), path: ".", mode: .link))) + ]) + let expected = (prefix + first + owner + " \"path\": \".\"\n" + following) + .replacingOccurrences(of: "\n", with: newline) + #expect(String(decoding: change.bytes, as: UTF8.self) == expected) + #expect(try document(expected).declaration == change.expectedDeclaration) + } + + @Test(arguments: [false, true]) + func executableSourcePreservesNestedBlockAndFlowMappings(_ flow: Bool) throws { + let transport = + flow + ? " transport: {kind: stdio, executable: ./tool} # transport\n" + : " transport:\n kind: stdio\n executable: ./tool # executable\n" + let prefix = + "version: 1\nsources: {team: {path: ./source}}\ncomponents:\n - kind: mcpServer\n name: server\n" + let tail = " - {kind: ignore, name: keep, patterns: []}\n" + let doc = try document(prefix + transport + tail) + let change = try doc.preparing([ + .replaceComponent( + #require(doc.node(at: "/components/0")), + with: .mcpServer( + name: "server", transport: .stdio(.init(executable: "./tool", executableSource: "team")))) + ]) + let expectedTransport = + flow + ? " transport: {kind: stdio, executable: ./tool, \"executableSource\": \"team\"} # transport\n" + : transport + " \"executableSource\": \"team\"\n" + #expect(String(decoding: change.bytes, as: UTF8.self) == prefix + expectedTransport + tail) + #expect( + try document(prefix + expectedTransport + tail).declaration == change.expectedDeclaration) + } + + @Test func flowSkillPathPreservesCommentsAndFollowingComponent() throws { + let body = + "version: 1\nsources: {team: {path: ./source}}\ncomponents:\n - {kind: skills, source: team, select: [demo], mode: link} # skill\n - {kind: ignore, name: keep, patterns: []}\n" + let doc = try document(body) + let change = try doc.preparing([ + .replaceComponent( + #require(doc.node(at: "/components/0")), + with: .skills(source: "team", .init(select: .names(["demo"]), path: ".", mode: .link))) + ]) + #expect( + String(decoding: change.bytes, as: UTF8.self) + == body.replacingOccurrences(of: "mode: link}", with: "mode: link, \"path\": \".\"}")) + } + + @Test(arguments: [false, true]) + func rootFieldInsertionPreservesByteOrderMark(_ explicitKey: Bool) throws { + let first = explicitKey ? "? version\r\n: 1" : "version: 1" + let body = "\u{FEFF}" + first + "\r\n# retained\r\n" + let doc = try document(body) + let change = try doc.preparing([.setDefaultAgents([.codex])]) + #expect( + String(decoding: change.bytes, as: UTF8.self) + == "\u{FEFF}" + first + "\r\n\"defaultAgents\": [\"codex\"]\r\n# retained\r\n") + } + +} diff --git a/Tests/AgentsManifestTests/NativeCoordinateTests.swift b/Tests/AgentsManifestTests/NativeCoordinateTests.swift new file mode 100644 index 0000000..52bccd7 --- /dev/null +++ b/Tests/AgentsManifestTests/NativeCoordinateTests.swift @@ -0,0 +1,71 @@ +import AgentsCore +import Foundation +import Testing + +@testable import AgentsManifest + +struct NativeCoordinateTests { + @Test func completeCoordinatesRoundTripAndRenameLosslessly() throws { + let body = """ + # retained header + version: 1 + sources: {s: {path: missing, subpath: bundle}} + components: + - {kind: skills, source: s, path: skills/helper, select: [helper]} + - {kind: mcpServer, name: server, transport: {kind: stdio, executable: ./server, executableSource: s, workingDirectory: {path: cwd, source: s}}} + - {kind: hook, name: check, event: sessionStart, run: {executable: ./server, executableSource: s}} + groups: + unused: + components: + - {kind: lspServer, name: language, run: {executable: bin/server, executableSource: s}, languages: {".swift": swift}} + # retained tail + """ + let previous = try projected(body) + let ir = YAMLConstruction.root(previous) + #expect(try projected(String(decoding: YAMLWriter.manifest(ir), as: UTF8.self)) == previous) + #expect(try planned(previous, previous, in: body) == nil) + let target = body.replacingOccurrences(of: "{s:", with: "{t:") + .replacingOccurrences(of: "source: s", with: "source: t") + .replacingOccurrences(of: "executableSource: s", with: "executableSource: t") + .replacingOccurrences(of: "skills/helper", with: "skills/other") + let next = try projected(target) + let output = String( + decoding: try #require(try planned(previous, next, in: body)), as: UTF8.self) + #expect(try projected(output) == next) + #expect(output.hasPrefix("# retained header\n") && output.hasSuffix("# retained tail")) + #expect(SkillDeclaration(select: .all).path == nil) + #expect(ExecutableDeclaration(executable: "tool").executableSource == nil) + } + + @Test func invalidCoordinatesAreRejectedByTypedAndManifestAdmission() throws { + let index = SourceDeclaration(kind: .wellKnown, location: "https://example.invalid/index.json") + let invalid = Declaration( + sources: ["s": index], + components: [ + .skills(source: "s", .init(select: .all, path: "skills")) + ]) + #expect(throws: (any Error).self) { try invalid.validate(environment: projectionEnvironment) } + for component in [ + "{kind: skills, source: s, path: ../outside}", + "{kind: mcpServer, name: server, transport: {kind: stdio, executable: tool, executableSource: s}}", + "{kind: hook, name: check, event: sessionStart, run: {executable: ./server, executableSource: missing}}", + ] { + #expect(throws: (any Error).self) { + try projected( + "version: 1\nsources: {s: {path: missing}}\ncomponents: [" + component + "]\n") + } + } + #expect(throws: (any Error).self) { + try projected( + "version: 1\nsources: {s: {index: https://example.invalid/index.json}}\ncomponents: [{kind: skills, source: s, path: skills}]\n" + ) + } + let ambient = Declaration( + sources: ["s": .init(kind: .local, location: "missing")], + components: [ + .mcpServer( + name: "server", transport: .stdio(.init(executable: "tool", executableSource: "s"))) + ]) + #expect(throws: (any Error).self) { try ambient.validate(environment: projectionEnvironment) } + } +} diff --git a/Tests/AgentsManifestTests/ProjectionTests.swift b/Tests/AgentsManifestTests/ProjectionTests.swift new file mode 100644 index 0000000..094e2e1 --- /dev/null +++ b/Tests/AgentsManifestTests/ProjectionTests.swift @@ -0,0 +1,63 @@ +import AgentsCore +import Foundation +import Testing + +@testable import AgentsManifest + +let projectionEnvironment = RuntimeEnvironment( + projectDirectory: URL(fileURLWithPath: "/work/project", isDirectory: true), + homeDirectory: URL(fileURLWithPath: "/work/home", isDirectory: true), environment: [:]) +func projected(_ body: String) throws -> Declaration { + try ManifestProjection.declaration(of: document(body), environment: projectionEnvironment) +} + +@Suite("Manifest projection") +struct ProjectionTests { + @Test func absentValuesStayDistinctFromExplicitEmptyValues() throws { + #expect(try projected("version: 1\n") == Declaration()) + let explicit = try projected( + "version: 1\ndefaultAgents: []\ncomponents: [{kind: instructions, agents: []}]\nwatch: []\n") + #expect(explicit.agents == []) + #expect((try explicit.instructions) == InstructionsDeclaration(agents: [])) + #expect(explicit.watch == nil) + let inherited = try projected("version: 1\ncomponents: [{kind: instructions}]\n") + #expect(inherited.agents == nil) + #expect((try inherited.instructions) == InstructionsDeclaration()) + #expect((try inherited.instructions)?.agents == nil) + } + @Test(arguments: [ + "groups: {g: {}}\nuses: [{group: g}]", + "components: [{kind: skills, source: s, condition: {agents: [codex]}}]", + "components: [{kind: skills, source: s, native: {'claude-code/skill@1': {x: 1}}}]", + "components: [{kind: instructions, condition: {scopes: [user]}}]", + "components: [{kind: instructions, sections: [{name: g, condition: {}}]}]", + "components: [{kind: instructions, chatgpt: {p: {sections: [], condition: {platforms: [linux]}}}}]", + "components: [{kind: instructions, chatgpt: {p: {sections: [{name: g, condition: {}}]}}}]", + "components: [{kind: ignore, name: i, patterns: []}]", + "components: [{kind: skills, source: s}, {kind: skills, source: s, select: [a]}]", + "components: [{kind: instructions}, {kind: instructions, sections: [{name: g}]}]", + "components: [{kind: skills, source: '.'}]", + ]) + func completeStructuresRemainSymbolic(_ fields: String) throws { + let doc = try document("version: 1\nsources: {s: {path: s}}\n" + fields + "\n") + let declaration = try ManifestProjection.declaration( + of: doc, environment: projectionEnvironment) + #expect(YAMLConstruction.root(declaration) == doc.declaration) + } + @Test func unusedGroupsAndExportsArePreserved() throws { + let declaration = try projected( + "version: 1\nexports: [review]\nsources: {s: {path: s}}\ngroups: {review: {components: [{kind: skills, source: s, condition: {agents: [codex]}}, {kind: ignore, name: i, patterns: [x]}], uses: [{group: nested}]}, nested: {components: [{kind: instructions, sections: [{name: g}]}]}}\n" + ) + #expect(declaration.exports == ["review"]) + #expect(declaration.groups.map(\.name) == ["review", "nested"]) + #expect(declaration.groups[0].components.count == 2) + #expect(declaration.groups[0].uses == [GroupUseDeclaration(name: "nested")]) + } + @Test func environmentDependentValidationFollowsProjection() throws { + let doc = try document( + "version: 1\nsources: {a: {path: '~/rules'}, b: {path: /work/home/rules}}\n") + #expect(throws: CoreError.self) { + try ManifestProjection.declaration(of: doc, environment: projectionEnvironment) + } + } +} diff --git a/Tests/AgentsManifestTests/ResourceTests.swift b/Tests/AgentsManifestTests/ResourceTests.swift new file mode 100644 index 0000000..056dc18 --- /dev/null +++ b/Tests/AgentsManifestTests/ResourceTests.swift @@ -0,0 +1,52 @@ +import AgentsCore +import Foundation +import Testing + +@testable import AgentsManifest + +@Suite("YAML parser resources") +struct ResourceTests { + @Test func parserStageWorkCancelsBeforeTheCSTGate() throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent( + "yaml-budget-" + UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { do { try FileManager.default.removeItem(at: directory) } catch { Issue.record(error) } } + let bytes = Array( + ("[" + Array(repeating: "x", count: 200_000).joined(separator: ",") + "]").utf8) + let result = try probe("wide-flow", bytes, semantics: true, in: directory) + #expect(result.report.status == "manifest.limit") + #expect(result.report.stage == .parser) + #expect(result.report.metrics.parserCallbacks == YAMLParser.callbackLimit + 1) + #expect(result.report.metrics.syntaxNodes == 0) + } + @Test func validScalarAtTheInputLimitIsAdmitted() throws { + let prefix = "version: 1\ncomponents: [{kind: subagent, name: a, description: d, prompt: '" + let suffix = "'}]\n" + let bytes = Array( + (prefix + + String( + repeating: "x", count: ManifestLimits.Input.bytes - prefix.utf8.count - suffix.utf8.count) + + suffix).utf8) + let document = try DeclarationDocument(bytes: bytes, identity: DocumentIdentity("manifest")) + #expect(document.bytes.count == ManifestLimits.Input.bytes) + #expect(document.declaration.components.count == 1) + } + @Test func wideAndDeepShapesFailWithAnEnforcedBudget() { + for text in [ + "[" + Array(repeating: "x", count: 200_000).joined(separator: ",") + "]", + String(repeating: "[", count: 256) + "x" + String(repeating: "]", count: 256), + ] { + expectManifestFailure("manifest.limit") { try document(text) } + } + } + @Test func inputAndContainerLimitsRemainIndependent() { + expectManifestFailure("manifest.limit") { + try document(String(repeating: "x", count: ManifestLimits.Input.bytes + 1)) + } + expectManifestFailure("manifest.limit") { + try document( + "version: 1\nwatch: [" + Array(repeating: "x", count: 10_001).joined(separator: ",") + "]\n" + ) + } + } +} diff --git a/Tests/AgentsManifestTests/SourceReplacementTests.swift b/Tests/AgentsManifestTests/SourceReplacementTests.swift new file mode 100644 index 0000000..e2960a8 --- /dev/null +++ b/Tests/AgentsManifestTests/SourceReplacementTests.swift @@ -0,0 +1,143 @@ +import AgentsCore +import Foundation +import Testing + +@testable import AgentsManifest + +struct SourceReplacementTests { + @Test func replacementRetargetsTypedReferencesAndPreservesOtherBytes() throws { + let body = """ + # source header + version: 1 + sources: + first: {path: first} + original: {path: original, subpath: original} # source comment + other: {path: other} + components: + - {kind: skills, source: original, path: original, select: [], mode: copy} + - {kind: instructions, sections: [{name: original, source: original}], chatgpt: {original: {sections: [{name: original, source: original}], append: original}}} + - {kind: mcpServer, name: original, transport: {kind: stdio, executable: ./original, executableSource: original, arguments: [original], workingDirectory: {path: original, source: other}}, native: {schema: {source: original, executableSource: original}}} + - {kind: hook, name: hook, event: sessionStart, run: {executable: ./original, executableSource: other, workingDirectory: {path: original, source: original}}} + - {kind: lspServer, name: language, run: {executable: ./original, executableSource: original}, languages: {".original": original}} + - {kind: command, name: command, description: original, prompt: {file: {path: original, source: original}}} + - {kind: subagent, name: agent, description: original, prompt: {file: {path: original, source: original}}} + - {kind: plugin, name: plugin, path: original, source: original} + groups: + unused: + components: + - {kind: skills, source: original, select: []} + - {kind: instructions, sections: [{name: original, source: original}], chatgpt: {p: {sections: [{name: original, source: original}]}}} + - {kind: command, name: unused, description: original, prompt: {file: {path: original, source: original}}} + uses: [{group: original, source: original}] + uses: [{group: original, source: original}, {group: unused, source: "."}] + watch: [original, other] + # tail + """ + let doc = try document(body) + let source = try #require(doc.node(at: "/sources/1")) + let change = try doc.preparing([ + .replaceSource( + source, + with: .init( + name: "renamed", source: .init(kind: .local, location: "new-location", path: "original"))) + ]) + let output = String(decoding: change.bytes, as: UTF8.self) + let next = try DeclarationDocument(bytes: change.bytes, identity: .init("manifest")) + let tree = IRTree.root(next.declaration) + for pointer in [ + "/components/0/source", "/components/1/sections/0/source", + "/components/1/chatGPT/0/sections/0/source", + "/components/2/transport/executableSource", "/components/3/run/workingDirectory/source", + "/components/4/run/executableSource", "/components/5/prompt/source", + "/components/6/prompt/source", "/components/7/source", + "/groups/0/components/0/source", "/groups/0/components/1/sections/0/source", + "/groups/0/components/1/chatGPT/0/sections/0/source", + "/groups/0/components/2/prompt/source", "/groups/0/uses/0/source", "/uses/0/source", + "/watch/0", + ] { #expect(IRTree.value(tree, at: pointer)?.string == "renamed") } + #expect(next.declaration.sources.map { $0["name"]?.string } == ["first", "renamed", "other"]) + #expect( + IRTree.value(tree, at: "/components/2/transport/workingDirectory/source")?.string == "other") + #expect(IRTree.value(tree, at: "/components/3/run/executableSource")?.string == "other") + #expect(IRTree.value(tree, at: "/uses/1/source")?.string == ".") + #expect(output.contains("native: {schema: {source: original, executableSource: original}}")) + #expect(output.contains("executable: ./original") && output.contains("arguments: [original]")) + #expect( + output.contains(#"languages: {".original": original}"#) && output.contains("append: original") + ) + #expect( + output.contains("# source comment") && output.hasPrefix("# source header\n") + && output.hasSuffix("# tail")) + #expect(doc.bytes == Array(body.utf8)) + } + + @Test func handlesNoopsCollisionsAndSourceKindsKeepExistingAdmission() throws { + let doc = try document( + "version: 1\nsources: {s: {path: old}, other: {path: other}}\ncomponents: [{kind: skills, source: s, mode: edit}]\n" + ) + let source = try #require(doc.node(at: "/sources/0")) + let same = NamedSourceDeclaration(name: "s", source: .init(kind: .local, location: "old")) + #expect(try doc.preparing([.replaceSource(source, with: same)]).patches.isEmpty) + let updated = try doc.preparing([ + .replaceSource(source, with: .init(name: "s", source: .init(kind: .local, location: "new"))) + ]) + #expect( + try DeclarationDocument(bytes: updated.bytes, identity: .init("manifest")).declaration + .sources[0]["path"]?.string == "new") + for name in ["other", "."] { + #expect(throws: (any Error).self) { + try doc.preparing([.replaceSource(source, with: .init(name: name, source: same.source))]) + } + } + #expect(throws: (any Error).self) { + try doc.preparing([ + .replaceSource( + source, + with: .init( + name: "s", source: .init(kind: .git, location: "https://example.invalid/repo.git"))) + ]) + } + #expect(throws: (any Error).self) { + try doc.preparing([.replaceSource(#require(doc.node(at: "/components/0")), with: same)]) + } + #expect(throws: (any Error).self) { + try doc.preparing([.removeSource(alias: "s"), .replaceSource(source, with: same)]) + } + let changed = try document("# changed\n" + String(decoding: doc.bytes, as: UTF8.self)) + #expect(throws: (any Error).self) { + try changed.preparing([.replaceSource(source, with: same)]) + } + #expect(throws: (any Error).self) { + try doc.preparing([ + .replaceSource(NodeID(digest: doc.digest, pointer: "/sources/99", syntax: 0), with: same) + ]) + } + let chained = try doc.preparing([ + .replaceSource(source, with: .init(name: "temporary", source: same.source)), + .replaceSource(source, with: .init(name: "final", source: same.source)), + ]) + #expect( + try DeclarationDocument(bytes: chained.bytes, identity: .init("manifest")).declaration + .components[0]["source"]?.string == "final") + } + + @Test func replacementComposesAcrossBatchesAndRemapsOriginalHandles() throws { + let uses = (0..<105).map { "{group: g\($0), source: original}" }.joined(separator: ", ") + let doc = try document( + "version: 1\nsources: {first: {path: first}, original: {path: original}}\nuses: [" + uses + + "]\nwatch: [original]\n") + let source = try #require(doc.node(at: "/sources/1")) + let reference = try #require(doc.node(at: "/uses/104")) + let change = try doc.preparing([ + .removeSource(alias: "first"), + .replaceSource( + source, with: .init(name: "renamed", source: .init(kind: .local, location: "new"))), + .removeGroupReference(reference), + ]) + let result = try DeclarationDocument(bytes: change.bytes, identity: .init("manifest")) + #expect(result.declaration.uses.count == 104) + #expect(result.declaration.uses.allSatisfy { $0["source"]?.string == "renamed" }) + #expect(result.declaration.watch == ["renamed"]) + #expect(result.declaration.sources.first?["name"]?.string == "renamed") + } +} diff --git a/Tests/AgentsManifestTests/Watchdog.swift b/Tests/AgentsManifestTests/Watchdog.swift new file mode 100644 index 0000000..0031663 --- /dev/null +++ b/Tests/AgentsManifestTests/Watchdog.swift @@ -0,0 +1,142 @@ +import AgentsCore +import Foundation +import ManifestTestSupport +import Testing + +@testable import AgentsManifest + +struct ProbeResult: Codable { + let name: String + let configuration: String + let watchdogSeconds: Double + let wallSeconds: Double + let report: ProbeReport +} + +private final class ManifestTestBundle {} + +func testProcessURL() throws -> URL { + var directory = Bundle(for: ManifestTestBundle.self).bundleURL + for _ in 0..<6 { + let candidate = directory.appendingPathComponent("ManifestTestProcess") + if FileManager.default.isExecutableFile(atPath: candidate.path) { return candidate } + directory.deleteLastPathComponent() + } + throw CocoaError(.fileNoSuchFile) +} + +func probe( + _ name: String, _ bytes: [UInt8], semantics: Bool = false, extraArguments: [String] = [], + in directory: URL +) throws + -> ProbeResult +{ + let input = directory.appendingPathComponent("input.yaml") + let output = directory.appendingPathComponent("output.json") + let errors = directory.appendingPathComponent("stderr.txt") + try Data(bytes).write(to: input) + FileManager.default.createFile(atPath: output.path, contents: nil) + FileManager.default.createFile(atPath: errors.path, contents: nil) + let stdout = try FileHandle(forWritingTo: output) + let stderr = try FileHandle(forWritingTo: errors) + defer { + try? stdout.close() + try? stderr.close() + } + let process = Process() + process.executableURL = try testProcessURL() + process.arguments = [input.path] + (semantics ? ["--semantics"] : []) + extraArguments + process.standardOutput = stdout + process.standardError = stderr + let clock = ContinuousClock() + let start = clock.now + try process.run() + // The timer starts before launch and remains active through child exit and teardown. + while process.isRunning && start.duration(to: clock.now) < .seconds(probeWatchdogSeconds) { + Thread.sleep(forTimeInterval: 0.002) + } + let timedOut = process.isRunning + if timedOut { + process.interrupt() + process.terminate() + } + if timedOut { + #if canImport(Darwin) + _ = Darwin.kill(process.processIdentifier, SIGKILL) + #else + _ = Glibc.kill(process.processIdentifier, SIGKILL) + #endif + } + process.waitUntilExit() + let duration = start.duration(to: clock.now).components + let elapsed = Double(duration.seconds) + Double(duration.attoseconds) / 1e18 + let errorText = (try? String(contentsOf: errors, encoding: .utf8)) ?? "" + try #require( + !timedOut, + "\(name) [\(probeConfiguration)] exceeded \(probeWatchdogSeconds) seconds: \(elapsed); \(errorText)" + ) + try #require( + process.terminationReason == .exit && process.terminationStatus == 0, + "\(name) crashed or signaled: \(process.terminationStatus); \(errorText)") + #expect(elapsed < probeWatchdogSeconds, "\(name): launch-to-exit deadline") + let report = try JSONDecoder().decode(ProbeReport.self, from: Data(contentsOf: output)) + #expect(report.configuration == probeConfiguration, "\(name): child build configuration") + // A loose runaway-process guard, not a platform-specific memory promise. 512 MiB + // leaves room for the Swift runtime, the YAML parsers and bounded source/IR copies; + // it is well above the contract's 2 MiB input, 16 MiB values and 32 MiB encoding caps. + #expect( + report.peakMemoryBytes < 512 * 1_024 * 1_024, "\(name): peak memory \(report.peakMemoryBytes)") + #expect(report.status != "unexpected", "\(report.message)") + if report.stage == .admission { #expect(report.metrics.parserCalls == 0) } + if report.status == "accepted" { + #expect(report.operation == .frontEnd) + #expect(report.stage == .teardown) + #expect(report.metrics.parserCalls == 1) + #expect(report.metrics.syntaxNodes <= ManifestLimits.Syntax.nodes) + } + return ProbeResult( + name: name, configuration: probeConfiguration, watchdogSeconds: probeWatchdogSeconds, + wallSeconds: elapsed, report: report) +} + +func temporaryManifestDirectory() throws -> URL { + let url = FileManager.default.temporaryDirectory.appendingPathComponent( + "manifest-tests-" + UUID().uuidString) + try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) + return url +} + +func recordProbeResults(_ results: [ProbeResult], name: String) throws { + let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent() + .deletingLastPathComponent().deletingLastPathComponent() + let evidenceRoot = + ProcessInfo.processInfo.environment["MANIFEST_TEST_EVIDENCE"].map { + URL(fileURLWithPath: $0) + } ?? root.appendingPathComponent(".build/manifest-test-evidence") + let directory = evidenceRoot.appendingPathComponent(probeConfiguration) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + let encoder = JSONEncoder() + encoder.outputFormatting = [.prettyPrinted, .sortedKeys] + let path = directory.appendingPathComponent(name + ".json") + try encoder.encode(results).write(to: path) + let compiler = try ProcessRunner.run("/usr/bin/env", arguments: ["swift", "--version"]) + struct Runner: Encodable { + let configuration: String + let watchdogSeconds: Double + let operatingSystem: String + let compiler: String + } + let runner = Runner( + configuration: probeConfiguration, watchdogSeconds: probeWatchdogSeconds, + operatingSystem: ProcessInfo.processInfo.operatingSystemVersionString, compiler: compiler.stdout + ) + try encoder.encode(runner).write( + to: directory.appendingPathComponent(name + "-runner.json")) + print("MANIFEST_EVIDENCE \(path.path)") +} + +#if canImport(Darwin) + import Darwin +#else + import Glibc +#endif diff --git a/Tests/AgentsManifestTests/YAMLReaderTests.swift b/Tests/AgentsManifestTests/YAMLReaderTests.swift new file mode 100644 index 0000000..d29809d --- /dev/null +++ b/Tests/AgentsManifestTests/YAMLReaderTests.swift @@ -0,0 +1,49 @@ +import AgentsCore +import AgentsManifest +import Testing + +struct YAMLReaderTests { + @Test func readerRetainsOrderedDataAndYAML12ScalarIdentity() throws { + let reader = try YAMLReader( + bytes: Array( + "name: on\r\nquoted: 'true'\r\nflag: true\r\nnumber: 0x10\r\né: [one, two]\r\n".utf8), + identity: .init("producer.yml")) + let pairs = try #require(reader.root.pairs) + #expect(pairs.map { $0.key.text } == ["name", "quoted", "flag", "number", "é"]) + #expect(pairs[0].value.scalar?.text == "on") + #expect(pairs[0].value.scalar?.quoted == false) + #expect(pairs[1].value.scalar?.text == "true") + #expect(pairs[1].value.scalar?.quoted == true) + #expect(YAMLScalar.classify("on") == .string) + #expect(YAMLScalar.classify("true") == .boolean) + #expect(YAMLScalar.integer("0x10") == 16) + #expect(pairs[4].value.items?.compactMap(\.text) == ["one", "two"]) + let span = reader.span(of: pairs[4].value) + #expect(span.document == .init("producer.yml")) + #expect(span.line == 5) + #expect(span.column == 5) + #expect( + Array("name: on\r\nquoted: 'true'\r\nflag: true\r\nnumber: 0x10\r\né: ".utf8).count + == span.start) + } + + @Test(arguments: [ + "token: secret-sentinel\n\"\\u0074oken\": secret-sentinel\n", + "token: secret-sentinel\ntoken: secret-sentinel\n", + "token: &secret-sentinel value\nother: *secret-sentinel\n", + "token: !secret-sentinel value\n", + "true: secret-sentinel\n", + ]) + func readerRefusesUnsupportedOrAmbiguousDataWithValueFreeLocatedFailure(_ text: String) throws { + do { + _ = try YAMLReader(bytes: Array(text.utf8), identity: .init("chosen.yml")) + Issue.record("Expected YAML admission failure") + } catch let failure as YAMLReadFailure { + #expect(failure.span.document == .init("chosen.yml")) + #expect(failure.span.line >= 1) + #expect(failure.span.start <= text.utf8.count) + #expect(!String(reflecting: failure).contains("secret-sentinel")) + #expect(failure.description == "YAML input is not admitted.") + } + } +} diff --git a/Tests/AgentsSkillsTests/ArchiveSafetyTests.swift b/Tests/AgentsSkillsTests/ArchiveSafetyTests.swift index 4094927..64f5039 100644 --- a/Tests/AgentsSkillsTests/ArchiveSafetyTests.swift +++ b/Tests/AgentsSkillsTests/ArchiveSafetyTests.swift @@ -1,3 +1,4 @@ +import AgentsUpdates import Foundation import Testing @@ -16,7 +17,7 @@ struct ArchiveSafetyTests { try fixture.commit() _ = try fixture.add(mode: .copy) let before = try fixture.stateAndTargetBytes() - let archive = zip(entries: [ + let archive = zipArchive(entries: [ ("SKILL.md", Data("---\nname: zip-skill\ndescription: Test\n---".utf8), 0o100644), ( path, path.hasSuffix("/") ? Data() : Data("payload".utf8), @@ -36,10 +37,7 @@ struct ArchiveSafetyTests { ? "subpath must be relative: \(path)" : "subpath contains path traversal segment: \(path)" ) #expect(throws: expected) { - try SkillOperations.add( - AddOptions( - source: "https://zip.test", agents: [.codex], all: true, environment: fixture.environment), - provider: provider) + _ = try provider.fetchAllSkills(from: "https://zip.test") } #expect(try fixture.stateAndTargetBytes() == before) } @@ -64,7 +62,7 @@ struct ArchiveSafetyTests { @Test func generatedZipFixtureIsAValidArchive() throws { let fixture = try SkillFixture() let skill = Data("---\nname: demo\ndescription: Test\n---".utf8) - let data = zip(entries: [("SKILL.md", skill, 0o100644)]) + let data = zipArchive(entries: [("SKILL.md", skill, 0o100644)]) let provider = WellKnownProvider { _ in data } let artifact = LockedArtifact( type: .archive, url: "https://archive.test/skill.zip", @@ -72,49 +70,4 @@ struct ArchiveSafetyTests { let restored = try provider.restore(artifact, cache: SourceCache(store: fixture.store())) #expect(restored.files["SKILL.md"] == skill) } - - private func zip(entries: [(String, Data, UInt32)]) -> Data { - var local = Data() - var central = Data() - func number(_ value: T, to data: inout Data) { - var little = value.littleEndian - withUnsafeBytes(of: &little) { data.append(contentsOf: $0) } - } - for (path, content, mode) in entries { - let name = Data(path.utf8) - let offset = UInt32(local.count) - var crc: UInt32 = 0xffff_ffff - for byte in content { - crc ^= UInt32(byte) - for _ in 0..<8 { crc = (crc >> 1) ^ (crc & 1 == 0 ? 0 : 0xedb8_8320) } - } - crc ^= 0xffff_ffff - number(UInt32(0x0403_4b50), to: &local) - for value: UInt16 in [20, 0, 0, 0, 0] { number(value, to: &local) } - for value in [crc, UInt32(content.count), UInt32(content.count)] { number(value, to: &local) } - number(UInt16(name.count), to: &local) - number(UInt16(0), to: &local) - local.append(name) - local.append(content) - number(UInt32(0x0201_4b50), to: ¢ral) - for value: UInt16 in [0x0314, 20, 0, 0, 0, 0] { number(value, to: ¢ral) } - for value in [crc, UInt32(content.count), UInt32(content.count)] { - number(value, to: ¢ral) - } - for value: UInt16 in [UInt16(name.count), 0, 0, 0, 0] { number(value, to: ¢ral) } - number(mode << 16, to: ¢ral) - number(offset, to: ¢ral) - central.append(name) - } - let offset = UInt32(local.count) - local.append(central) - number(UInt32(0x0605_4b50), to: &local) - for value: UInt16 in [0, 0, UInt16(entries.count), UInt16(entries.count)] { - number(value, to: &local) - } - number(UInt32(central.count), to: &local) - number(offset, to: &local) - number(UInt16(0), to: &local) - return local - } } diff --git a/Tests/AgentsSkillsTests/ArchiveTestSupport.swift b/Tests/AgentsSkillsTests/ArchiveTestSupport.swift new file mode 100644 index 0000000..1ae3d2f --- /dev/null +++ b/Tests/AgentsSkillsTests/ArchiveTestSupport.swift @@ -0,0 +1,46 @@ +import Foundation + +func zipArchive(entries: [(String, Data, UInt32)]) -> Data { + var local = Data() + var central = Data() + func number(_ value: T, to data: inout Data) { + var little = value.littleEndian + withUnsafeBytes(of: &little) { data.append(contentsOf: $0) } + } + for (path, content, mode) in entries { + let name = Data(path.utf8) + let offset = UInt32(local.count) + var crc: UInt32 = 0xffff_ffff + for byte in content { + crc ^= UInt32(byte) + for _ in 0..<8 { crc = (crc >> 1) ^ (crc & 1 == 0 ? 0 : 0xedb8_8320) } + } + crc ^= 0xffff_ffff + number(UInt32(0x0403_4b50), to: &local) + for value: UInt16 in [20, 0, 0, 0, 0] { number(value, to: &local) } + for value in [crc, UInt32(content.count), UInt32(content.count)] { number(value, to: &local) } + number(UInt16(name.count), to: &local) + number(UInt16(0), to: &local) + local.append(name) + local.append(content) + number(UInt32(0x0201_4b50), to: ¢ral) + for value: UInt16 in [0x0314, 20, 0, 0, 0, 0] { number(value, to: ¢ral) } + for value in [crc, UInt32(content.count), UInt32(content.count)] { + number(value, to: ¢ral) + } + for value: UInt16 in [UInt16(name.count), 0, 0, 0, 0] { number(value, to: ¢ral) } + number(mode << 16, to: ¢ral) + number(offset, to: ¢ral) + central.append(name) + } + let offset = UInt32(local.count) + local.append(central) + number(UInt32(0x0605_4b50), to: &local) + for value: UInt16 in [0, 0, UInt16(entries.count), UInt16(entries.count)] { + number(value, to: &local) + } + number(UInt32(central.count), to: &local) + number(offset, to: &local) + number(UInt16(0), to: &local) + return local +} diff --git a/Tests/AgentsSkillsTests/AutomaticSelectionTests.swift b/Tests/AgentsSkillsTests/AutomaticSelectionTests.swift index dc0eab5..c302839 100644 --- a/Tests/AgentsSkillsTests/AutomaticSelectionTests.swift +++ b/Tests/AgentsSkillsTests/AutomaticSelectionTests.swift @@ -1,6 +1,8 @@ import AgentsCore -import Darwin +import AgentsManifest +import CPlatform import Foundation +import StateTestSupport import Testing @Suite("Automatic add selection") @@ -15,11 +17,10 @@ struct AutomaticSelectionTests { to: instructions.appendingPathComponent("demo.md")) try fixture.commit() let store = fixture.store() - try FileManager.default.createDirectory(at: store.directory, withIntermediateDirectories: true) var declaration = Declaration(sources: [ "source": SourceDeclaration(kind: .local, location: fixture.repo.path) ]) - try StateStore.encode(declaration).write(to: store.declarationURL) + try store.writeDeclaration(declaration) let root = fixture.environment.projectDirectory let resume = root.appendingPathComponent("resume-discovery") @@ -31,10 +32,7 @@ struct AutomaticSelectionTests { defer { // Release the Git wrapper even if fixture preparation fails. _ = "\n".withCString { write(descriptor, $0, 1) } - if child.isRunning { - kill(child.processIdentifier, SIGKILL) - child.waitUntilExit() - } + terminateProcess(child) } try wait(for: child) { FileManager.default.fileExists(atPath: root.appendingPathComponent("discovery-ready").path) @@ -47,11 +45,15 @@ struct AutomaticSelectionTests { let replacement = fixture.root.appendingPathComponent("replacement-source") try ProcessRunner.run( "/usr/bin/git", arguments: ["clone", "--no-local", fixture.repo.path, replacement.path]) + for (key, value) in [("maintenance.auto", "false"), ("gc.auto", "0")] { + try ProcessRunner.run( + "/usr/bin/git", arguments: ["-C", replacement.path, "config", key, value]) + } declaration.sources["source"] = SourceDeclaration(kind: .local, location: replacement.path) - try store.save(declaration: declaration, resolved: ResolvedState()) + try store.save(declaration: declaration, ledger: ResolvedLedger()) } else if change == "removed-source" { declaration.sources.removeValue(forKey: "source") - try store.save(declaration: declaration, resolved: ResolvedState()) + try store.save(declaration: declaration, ledger: ResolvedLedger()) } else { if kind == "skill" { let name = change == "rename" ? "replacement" : "demo" @@ -130,7 +132,6 @@ struct AutomaticSelectionTests { ).write(to: git) try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: git.path) var directory = Bundle(for: AutomaticSelectionTestBundle.self).bundleURL - .deletingLastPathComponent() while !FileManager.default.isExecutableFile( atPath: directory.appendingPathComponent("StateTestProcess").path), directory.path != "/" { @@ -148,9 +149,9 @@ struct AutomaticSelectionTests { } private func wait(for process: Process, until ready: () -> Bool) throws { - let deadline = Date().addingTimeInterval(20) - while !ready(), process.isRunning, Date() < deadline { Thread.sleep(forTimeInterval: 0.01) } - try #require(ready()) + try ProcessWait.condition( + process, root: URL(fileURLWithPath: process.arguments![0]), + description: "automatic selection handshake", ready: ready) } } diff --git a/Tests/AgentsSkillsTests/CoreTestSupport.swift b/Tests/AgentsSkillsTests/CoreTestSupport.swift index 2195c9c..de0d2c1 100644 --- a/Tests/AgentsSkillsTests/CoreTestSupport.swift +++ b/Tests/AgentsSkillsTests/CoreTestSupport.swift @@ -1,4 +1,6 @@ +import AgentsManifest import Foundation +import StateTestSupport import Testing @testable import AgentsCore @@ -20,6 +22,11 @@ func removeTemporaryDirectory(_ directory: URL) { } } +/// A child that survives the termination deadline fails the test instead of blocking the run. +func terminateProcess(_ process: Process) { + do { try ProcessWait.terminate(process) } catch { Issue.record(error) } +} + func initGitRepo(_ repo: URL) throws { try ProcessRunner.run( "/usr/bin/env", arguments: ["git", "init", "--initial-branch=master", repo.path]) @@ -42,3 +49,14 @@ func gitHead(_ repo: URL) throws -> String { .stdout .trimmingCharacters(in: .whitespacesAndNewlines) } + +extension StateStore { + /// Writes the document that a first write of `declaration` creates, without a lock, watch + /// state or scope lock. + func writeDeclaration(_ declaration: Declaration) throws { + let change = try planDeclaration( + declaration, replacing: Declaration(), prepared: StatePrecondition(store: self)) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + try (change?.bytes ?? manifestText()).write(to: declarationURL) + } +} diff --git a/Tests/AgentsSkillsTests/DefaultResolutionTests.swift b/Tests/AgentsSkillsTests/DefaultResolutionTests.swift index 9748a50..5c2f2ad 100644 --- a/Tests/AgentsSkillsTests/DefaultResolutionTests.swift +++ b/Tests/AgentsSkillsTests/DefaultResolutionTests.swift @@ -1,4 +1,7 @@ +import AgentsManifest +import AgentsUpdates import Foundation +import StateTestSupport import Testing @testable import AgentsCore @@ -51,7 +54,7 @@ struct DefaultResolutionTests { let declaration = Declaration(sources: [ "upstream": SourceDeclaration(kind: .git, location: "file://localhost" + fixture.repo.path) ]) - try fixture.store().save(declaration: declaration, resolved: ResolvedState()) + try fixture.store().save(declaration: declaration, ledger: ResolvedLedger()) _ = try SkillOperations.add( AddOptions( source: "upstream", agents: [.codex], skillNames: ["pinned"], @@ -65,14 +68,14 @@ struct DefaultResolutionTests { #expect(FileManager.default.fileExists(atPath: mirror.path)) var unqualified = try fixture.store().loadDeclaration() unqualified.sources["upstream"]?.requirement = nil - try fixture.store().save(declaration: unqualified, resolved: fixture.store().loadResolved()) + try fixture.store().save(declaration: unqualified, ledger: fixture.store().loadLedger()) func expectDefault(_ name: String, revision: String, version: String?, body: String) throws { let cold = RuntimeEnvironment( projectDirectory: fixture.root.appendingPathComponent("cold-\(name)"), homeDirectory: fixture.environment.homeDirectory, environment: [:]) let coldStore = StateStore(scope: .project, environment: cold) - try coldStore.save(declaration: declaration, resolved: ResolvedState()) + try coldStore.save(declaration: declaration, ledger: ResolvedLedger()) #expect(!FileManager.default.fileExists(atPath: coldStore.cacheDirectory.path)) let warm = try SkillOperations.add( AddOptions( diff --git a/Tests/AgentsSkillsTests/DiscoveryBehaviorTests.swift b/Tests/AgentsSkillsTests/DiscoveryBehaviorTests.swift index 3216cc2..5364698 100644 --- a/Tests/AgentsSkillsTests/DiscoveryBehaviorTests.swift +++ b/Tests/AgentsSkillsTests/DiscoveryBehaviorTests.swift @@ -1,4 +1,7 @@ +import AgentsManifest +import AgentsUpdates import Foundation +import StateTestSupport import Testing @testable import AgentsCore @@ -6,6 +9,17 @@ import Testing @Suite("Skill Discovery") struct SkillDiscoveryTests { + @Test(arguments: ["marketplace.json", "plugin.json"]) + func pluginMetadataThatIsADirectoryDoesNotStopDiscovery(_ name: String) throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + try writeDiscoverySkill(root.appendingPathComponent("skills/source"), name: "source") + try FileManager.default.createDirectory( + at: root.appendingPathComponent(".claude-plugin/" + name), + withIntermediateDirectories: true) + #expect(try Discovery.discover(in: root).map(\.name) == ["source"]) + } + @Test func discoversSkillsWithUndecodableResolvedHint() throws { let root = try temporaryDirectory() defer { removeTemporaryDirectory(root) } @@ -91,21 +105,16 @@ struct SkillDiscoveryTests { let locked = try temporaryDirectory() defer { removeTemporaryDirectory(locked) } + let upstream = try temporaryDirectory() + defer { removeTemporaryDirectory(upstream) } try writeDiscoverySkill( - locked.appendingPathComponent(".agents/skills/installed-skill"), name: "installed-skill") + upstream.appendingPathComponent("installed-skill"), name: "installed-skill") try writeDiscoverySkill( locked.appendingPathComponent("skills/source-skill"), name: "source-skill") - let store = StateStore( - scope: .project, environment: RuntimeEnvironment(projectDirectory: locked)) - let id = "local:" + locked.path - try store.save( - declaration: Declaration(), - resolved: ResolvedState( - sources: [id: LockedSource(kind: .local)], - skills: [ - "installed-skill": LockedSkill( - source: id, path: ".agents/skills/installed-skill", installs: ["codex": .edit]) - ])) + _ = try SkillOperations.add( + AddOptions( + source: upstream.path, + agents: [.codex], mode: .edit, environment: RuntimeEnvironment(projectDirectory: locked))) #expect(try Discovery.discover(in: locked).map(\.name) == ["source-skill"]) } diff --git a/Tests/AgentsSkillsTests/FileReadAccessTests.swift b/Tests/AgentsSkillsTests/FileReadAccessTests.swift new file mode 100644 index 0000000..dd34b16 --- /dev/null +++ b/Tests/AgentsSkillsTests/FileReadAccessTests.swift @@ -0,0 +1,76 @@ +import AgentsCore +import CPlatform +import Foundation +import Testing + +@testable import AgentsSkills + +@Suite( + "Skill file read access", + .enabled(if: geteuid() != 0, "Permission-denial checks require an unprivileged user"), + .timeLimit(.minutes(1))) +struct SkillFileReadAccessTests { + @Test func unreadableCachedArtifactStopsRestoreWithoutFetching() throws { + let fixture = try SkillFixture() + let store = fixture.store() + let cache = SourceCache(store: store) + let bytes = Data("---\nname: demo\ndescription: Test skill\n---\n".utf8) + let digest = "sha256:" + FileHash.sha256Hex(data: bytes) + let cached = try store.withLock { try cache.storeArtifact(bytes, digest: digest) } + let artifact = LockedArtifact( + type: .skillMD, url: "https://example.test/SKILL.md", digest: digest) + let provider = WellKnownProvider { _ in + Issue.record("An unreadable cached artifact must not trigger a fetch") + return bytes + } + try withUnreadableFile(cached) { + _ = try provider.restore(artifact, cache: cache) + } + #expect(try Data(contentsOf: cached) == bytes) + } + + @Test func unreadableSkillFileStopsInspectionAndDiscovery() throws { + let fixture = try SkillFixture() + try fixture.skill("demo", body: "Original") + let directory = fixture.repo.appendingPathComponent("skills/demo") + let file = directory.appendingPathComponent("SKILL.md") + try withUnreadableFile(file) { _ = try SkillLifecycle.entries(directory) } + try withUnreadableFile(file) { _ = try Discovery.parseSkill(at: file) } + } + + @Test(arguments: ["marketplace.json", "plugin.json"]) + func unreadablePluginMetadataStopsDiscovery(_ name: String) throws { + let fixture = try SkillFixture() + try fixture.skill("demo", body: "Original") + let directory = fixture.repo.appendingPathComponent(".claude-plugin") + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false) + let file = directory.appendingPathComponent(name) + try Data("{}".utf8).write(to: file) + try withUnreadableFile(file) { _ = try Discovery.discover(in: fixture.repo) } + } +} + +private func withUnreadableFile(_ file: URL, _ body: () throws -> Void) throws { + let bytes = try Data(contentsOf: file) + var original = stat() + try #require(lstat(file.path, &original) == 0) + try #require(chmod(file.path, 0) == 0) + defer { chmod(file.path, original.st_mode & 0o777) } + for _ in 0..<2 { + #expect { + try body() + } throws: { error in + guard case CoreError.invalidState(let message) = error else { return false } + let prefix = "permission denied: " + let suffix = "; check the directory's permissions and default ACL" + guard message.hasPrefix(prefix), message.hasSuffix(suffix) else { return false } + let path = String(message.dropFirst(prefix.count).dropLast(suffix.count)) + return URL(fileURLWithPath: path).resolvingSymlinksInPath() == file.resolvingSymlinksInPath() + } + var current = stat() + try #require(lstat(file.path, ¤t) == 0) + #expect(current.st_mode & 0o777 == 0 && current.st_ino == original.st_ino) + } + try #require(chmod(file.path, original.st_mode & 0o777) == 0) + #expect(try Data(contentsOf: file) == bytes) +} diff --git a/Tests/AgentsSkillsTests/IndexedArtifactLifecycleTests.swift b/Tests/AgentsSkillsTests/IndexedArtifactLifecycleTests.swift new file mode 100644 index 0000000..fd025f2 --- /dev/null +++ b/Tests/AgentsSkillsTests/IndexedArtifactLifecycleTests.swift @@ -0,0 +1,303 @@ +import AgentsCore +import AgentsManifest +import AgentsSkills +import AgentsUpdates +import Foundation +import StateTestSupport +import Testing + +@Suite("Indexed artifact lifecycle", .serialized) +struct IndexedArtifactLifecycleTests { + @Test(arguments: [InstallMode.copy, .link], [false, true]) + func publicLifecycleUsesVerifiedIndexAndColdLockedResources( + _ mode: InstallMode, archive: Bool + ) throws { + let fixture = try SkillFixture() + let web = fixture.root.appendingPathComponent("web") + try FileManager.default.createDirectory(at: web, withIntermediateDirectories: true) + let server = try ArtifactHTTPServer(root: web) + defer { server.stop() } + func publish(_ body: String, validDigest: Bool = true) throws { + let bytes = Data("---\nname: indexed\ndescription: Indexed fixture\n---\n\(body)\n".utf8) + let payload = + archive + ? zipArchive(entries: [ + ("SKILL.md", bytes, 0o100644), + ("references/context.md", Data(("Context: " + body).utf8), 0o100644), + ]) : bytes + let file = archive ? "/skill.zip" : "/SKILL.md" + let kind = archive ? "archive" : "skill-md" + try payload.write(to: web.appendingPathComponent(String(file.dropFirst()))) + let digest = + validDigest ? FileHash.sha256Hex(data: payload) : String(repeating: "0", count: 64) + let index = web.appendingPathComponent(".well-known/agent-skills/index.json") + try FileManager.default.createDirectory( + at: index.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data( + "{\"$schema\":\"https://schemas.agentskills.io/discovery/0.2.0/schema.json\",\"skills\":[{\"name\":\"indexed\",\"type\":\"\(kind)\",\"description\":\"Indexed fixture\",\"url\":\"\(file)\",\"digest\":\"sha256:\(digest)\"}]}" + .utf8 + ).write(to: index) + } + try publish("Original") + _ = try SkillOperations.add( + AddOptions( + source: server.url, alias: "indexed", agents: [.codex], mode: mode, all: true, + environment: fixture.environment)) + let store = fixture.store() + #expect(try store.loadLedger().resources.values.contains { $0.kind == .artifact }) + #expect( + try SkillOperations.listManaged(environment: fixture.environment).map(\.name) == ["indexed"]) + let watch = SkillOperations.watchOperations() + try watch.add("indexed", environment: fixture.environment) + let original = try Data(contentsOf: store.resolvedURL) + try publish("Current") + let before = try FileHash.folderHash(fixture.environment.projectDirectory) + let preview = try SkillOperations.updateInstalled(environment: fixture.environment) + #expect(try watch.status(environment: fixture.environment).first?.changes.isEmpty == false) + #expect(preview.contains { $0.changed }) + #expect(try FileHash.folderHash(fixture.environment.projectDirectory) == before) + #expect(try Data(contentsOf: store.resolvedURL) == original) + _ = try SkillOperations.updateInstalled(environment: fixture.environment, apply: true) + #expect(try fixture.body(fixture.target("indexed")).contains("Current")) + let current = try Data(contentsOf: store.resolvedURL) + try watch.seen("indexed", environment: fixture.environment) + try watch.remove("indexed", environment: fixture.environment) + #expect(try Data(contentsOf: store.resolvedURL) == current) + try publish("Unverified", validDigest: false) + let valid = try FileHash.folderHash(fixture.environment.projectDirectory) + #expect(throws: (any Error).self) { + try SkillOperations.updateInstalled(environment: fixture.environment, apply: true) + } + #expect(try FileHash.folderHash(fixture.environment.projectDirectory) == valid) + try publish("Current") + server.stop() + try FileManager.default.removeItem(at: fixture.target("indexed")) + try FileManager.default.removeItem(at: store.cacheDirectory) + _ = try SkillOperations.installResolvedReport(environment: fixture.environment) + #expect(try Data(contentsOf: store.resolvedURL) == current) + #expect(try fixture.body(fixture.target("indexed")).contains("Current")) + if archive { + #expect( + try String( + contentsOf: fixture.target("indexed").appendingPathComponent("references/context.md"), + encoding: .utf8) == "Context: Current") + } + #expect( + try SkillOperations.listManaged(environment: fixture.environment).allSatisfy { + $0.isInstalled + }) + // An empty selection must remove the last indexed member without contacting its origin. + #expect(throws: Never.self) { + try SkillOperations.remove(skillNames: ["indexed"], environment: fixture.environment) + } + #expect(try store.loadLedger().components.values.allSatisfy { $0.kind != "skills" }) + #expect(!FileManager.default.fileExists(atPath: fixture.target("indexed").path)) + } + + @Test func namedUpdatePreservesAnUnselectedIndexedArtifact() throws { + let fixture = try SkillFixture() + let web = fixture.root.appendingPathComponent("web") + try FileManager.default.createDirectory(at: web, withIntermediateDirectories: true) + let server = try ArtifactHTTPServer(root: web) + defer { server.stop() } + func publish(_ body: String) throws { + var entries: [[String: String]] = [] + for name in ["one", "two"] { + let bytes = Data("---\nname: \(name)\ndescription: Indexed fixture\n---\n\(body)\n".utf8) + try bytes.write(to: web.appendingPathComponent(name + ".md")) + entries.append([ + "name": name, "description": "Indexed fixture", "type": "skill-md", + "url": "/" + name + ".md", "digest": "sha256:" + FileHash.sha256Hex(data: bytes), + ]) + } + let index = web.appendingPathComponent(".well-known/agent-skills/index.json") + try FileManager.default.createDirectory( + at: index.deletingLastPathComponent(), withIntermediateDirectories: true) + try JSONSerialization.data(withJSONObject: [ + "$schema": "https://schemas.agentskills.io/discovery/0.2.0/schema.json", "skills": entries, + ]).write(to: index) + } + try publish("Original") + _ = try SkillOperations.add( + AddOptions( + source: server.url, alias: "indexed", agents: [.codex], mode: .copy, all: true, + environment: fixture.environment)) + let previous = try #require(fixture.store().loadResolved().skills["two"]) + try publish("Current") + _ = try SkillOperations.updateInstalled( + environment: fixture.environment, skillNames: ["one"], apply: true) + #expect(try fixture.store().loadResolved().skills["two"] == previous) + #expect(try fixture.body(fixture.target("two")).contains("Original")) + #expect(try fixture.body(fixture.target("one")).contains("Current")) + } + +} + +/// Serves fixture bytes to the production HTTP loader; no source-provided program is executed. +private final class ArtifactHTTPServer { + private let process = Process() + private let output = Pipe() + let url: String + + init(root: URL, redirect: String? = nil) throws { + process.executableURL = URL(fileURLWithPath: "/usr/bin/perl") + process.arguments = [ + "-e", + #""" + use IO::Socket::INET; + alarm 120; + my ($root, $redirect) = @ARGV; + my $server = IO::Socket::INET->new(LocalAddr => '127.0.0.1', LocalPort => 0, Listen => 8, Proto => 'tcp') or die $!; + $| = 1; print $server->sockport, "\n"; + while (my $client = $server->accept()) { + my $request = <$client>; + my ($path) = $request =~ m{^GET (/[^ ]*) HTTP/}; + while (my $line = <$client>) { last if $line eq "\r\n"; } + if (defined($path) && $path eq '/redirect.md' && length($redirect)) { + print $client "HTTP/1.1 302 Found\r\nLocation: $redirect\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"; + close $client; next; + } + my $bytes = ''; + my $status = '404 Not Found'; + if (defined($path) && $path !~ /\.\./ && open(my $file, '<', "$root$path")) { + binmode $file; local $/; $bytes = <$file>; close $file; $status = '200 OK'; + } + print $client "HTTP/1.1 $status\r\nContent-Length: ", length($bytes), "\r\nConnection: close\r\n\r\n", $bytes; + close $client; + } + """#, root.path, redirect ?? "", + ] + process.standardOutput = output + try process.run() + output.fileHandleForWriting.closeFile() + var bytes = Data() + while let byte = try output.fileHandleForReading.read(upToCount: 1), !byte.isEmpty { + if byte == Data([10]) { break } + bytes.append(byte) + } + guard let port = Int(String(decoding: bytes, as: UTF8.self)) else { + if process.isRunning { process.terminate() } + process.waitUntilExit() + try? output.fileHandleForReading.close() + throw CoreError.invalidState("fixture HTTP listener did not start") + } + url = "http://127.0.0.1:\(port)" + } + + func stop() { + if process.isRunning { terminateProcess(process) } + try? output.fileHandleForReading.close() + } +} + +extension IndexedArtifactLifecycleTests { + @Test func acknowledgmentRevalidatesTheDisplayedArtifactDigests() throws { + let fixture = try SkillFixture() + let web = fixture.root.appendingPathComponent("watch-web") + try FileManager.default.createDirectory(at: web, withIntermediateDirectories: true) + let server = try ArtifactHTTPServer(root: web) + defer { server.stop() } + func publish(_ body: String) throws { + let bytes = Data("---\nname: watched\ndescription: Watch\n---\n\(body)\n".utf8) + try bytes.write(to: web.appendingPathComponent("watched.md")) + let index = web.appendingPathComponent(".well-known/agent-skills/index.json") + try FileManager.default.createDirectory( + at: index.deletingLastPathComponent(), withIntermediateDirectories: true) + try JSONSerialization.data(withJSONObject: [ + "$schema": "https://schemas.agentskills.io/discovery/0.2.0/schema.json", + "skills": [ + [ + "name": "watched", "description": "Watch", "type": "skill-md", "url": "/watched.md", + "digest": "sha256:" + FileHash.sha256Hex(data: bytes), + ] + ], + ]).write(to: index) + } + try publish("original") + let watch = SkillOperations.watchOperations() + _ = try watch.add(server.url, alias: "watched", environment: fixture.environment) + let displayed = try #require(watch.status(environment: fixture.environment).first) + let baseline = try Data(contentsOf: fixture.store().watchURL) + try publish("advanced") + #expect(throws: (any Error).self) { + try watch.seen(displayed, environment: fixture.environment) + } + #expect(try Data(contentsOf: fixture.store().watchURL) == baseline) + let current = try #require(watch.status(environment: fixture.environment).first) + _ = try watch.seen(current, environment: fixture.environment) + #expect(try fixture.store().loadWatch().sources[current.sourceID]?.seen == current.current) + #expect(try fixture.store().loadLedger().components.isEmpty) + } +} + +extension IndexedArtifactLifecycleTests { + @Test func sourcePolicyEnforcesIndexAndDownstreamArtifactOrigins() throws { + let fixture = try SkillFixture() + let indexRoot = fixture.root.appendingPathComponent("index") + let artifactRoot = fixture.root.appendingPathComponent("downstream") + try FileManager.default.createDirectory(at: indexRoot, withIntermediateDirectories: true) + try FileManager.default.createDirectory(at: artifactRoot, withIntermediateDirectories: true) + let artifact = try ArtifactHTTPServer(root: artifactRoot) + defer { artifact.stop() } + let index = try ArtifactHTTPServer(root: indexRoot, redirect: artifact.url + "/SKILL.md") + defer { index.stop() } + let payload = Data("---\nname: indexed\ndescription: Policy fixture\n---\nContent.\n".utf8) + try payload.write(to: artifactRoot.appendingPathComponent("SKILL.md")) + let listing = indexRoot.appendingPathComponent(".well-known/agent-skills/index.json") + try FileManager.default.createDirectory( + at: listing.deletingLastPathComponent(), withIntermediateDirectories: true) + func publish(artifactURL: String) throws { + try JSONSerialization.data(withJSONObject: [ + "$schema": "https://schemas.agentskills.io/discovery/0.2.0/schema.json", + "skills": [ + [ + "name": "indexed", "description": "Policy fixture", "type": "skill-md", + "url": artifactURL, + "digest": "sha256:" + FileHash.sha256Hex(data: payload), + ] + ], + ]).write(to: listing) + } + try publish(artifactURL: artifact.url + "/SKILL.md") + let environment = fixture.environment + let policy = SourcePolicyOperations.policyURL(scope: .project, environment: environment) + try FileManager.default.createDirectory( + at: policy.deletingLastPathComponent(), withIntermediateDirectories: true) + let indexOnly = Data("version: 1\nallow: [{http: '\(index.url)'}]\n".utf8) + try indexOnly.write(to: policy) + let options = AddOptions( + source: index.url, alias: "index", agents: [.codex], mode: .copy, all: true, + environment: environment) + do { + _ = try SkillOperations.add(options) + Issue.record("A disallowed artifact was acquired") + } catch let failure as SourcePolicyFailure { + #expect(failure.violations.map(\.origin) == [try .http(artifact.url)]) + } + #expect(!FileManager.default.fileExists(atPath: fixture.store().resolvedURL.path)) + try Data("version: 1\nallow: [{http: '\(index.url)'}, {http: '\(artifact.url)'}]\n".utf8) + .write(to: policy) + try publish(artifactURL: index.url + "/redirect.md") + do { + _ = try SkillOperations.add(options) + Issue.record("An unrecorded redirect was acquired") + } catch { + #expect(String(describing: error).contains("cross-origin downloads")) + } + #expect(!FileManager.default.fileExists(atPath: fixture.store().resolvedURL.path)) + try publish(artifactURL: artifact.url + "/SKILL.md") + _ = try SkillOperations.add(options) + #expect(FileManager.default.fileExists(atPath: fixture.target("indexed").path)) + index.stop() + artifact.stop() + try indexOnly.write(to: policy) + try FileManager.default.removeItem(at: fixture.target("indexed")) + let audit = try SourcePolicyOperations.audit(environment: environment) + #expect(audit.violations.map(\.origin) == [try .http(artifact.url)]) + let before = try FileHash.folderHash(environment.projectDirectory) + #expect(throws: SourcePolicyFailure.self) { + try UpdateOperations.restore(environment: environment) + } + #expect(try FileHash.folderHash(environment.projectDirectory) == before) + } +} diff --git a/Tests/AgentsSkillsTests/InstallationSafetyTests.swift b/Tests/AgentsSkillsTests/InstallationSafetyTests.swift index fcbc126..cdc33e7 100644 --- a/Tests/AgentsSkillsTests/InstallationSafetyTests.swift +++ b/Tests/AgentsSkillsTests/InstallationSafetyTests.swift @@ -1,3 +1,4 @@ +import AgentsUpdates import Foundation import Testing diff --git a/Tests/AgentsSkillsTests/InstalledInventoryTests.swift b/Tests/AgentsSkillsTests/InstalledInventoryTests.swift index 03d4122..aed4e65 100644 --- a/Tests/AgentsSkillsTests/InstalledInventoryTests.swift +++ b/Tests/AgentsSkillsTests/InstalledInventoryTests.swift @@ -1,3 +1,5 @@ +import AgentsManifest +import AgentsUpdates import Foundation import Testing @@ -35,9 +37,16 @@ struct InstalledInventoryTests { to: universal.appendingPathComponent("invalid/SKILL.md")) let claude = AgentRegistry.installSkillsDirectory( for: .claudeCode, scope: scope, environment: environment) + try FileManager.default.createDirectory( + at: claude.deletingLastPathComponent(), withIntermediateDirectories: true) _ = try SkillOperations.initializeSkill(named: "claude-only", directory: claude) var expectedCodex = Set(["linked"]) if scope == .user { + for agent in [AgentID.codex, .opencode] { + let selected = AgentRegistry.userSkillsDirectory(for: agent, environment: environment) + try FileManager.default.createDirectory( + at: selected.deletingLastPathComponent(), withIntermediateDirectories: true) + } _ = try SkillOperations.initializeSkill( named: "codex-native", directory: AgentRegistry.userSkillsDirectory(for: .codex, environment: environment)) @@ -98,24 +107,31 @@ struct InstalledInventoryTests { let file = corruptDeclaration ? store.declarationURL : store.resolvedURL let bytes = Data("{corrupt".utf8) try bytes.write(to: file) - #expect(throws: CoreError.self) { try fixture.add(mode: mode, scope: scope) } - #expect(throws: CoreError.self) { - try SkillOperations.listManaged(scope: scope, environment: fixture.environment) + // Declaration diagnostics come from the manifest front end; a corrupt lock is a state error. + func expectFailure(_ body: () throws -> Void) { + if corruptDeclaration { + #expect(throws: ManifestFailure.self, performing: body) + } else { + #expect(throws: CoreError.self, performing: body) + } + } + expectFailure { _ = try fixture.add(mode: mode, scope: scope) } + expectFailure { + _ = try SkillOperations.listManaged(scope: scope, environment: fixture.environment) } - #expect(throws: CoreError.self) { - try SkillOperations.listInstalled(scope: scope, environment: fixture.environment) + expectFailure { + _ = try SkillOperations.listInstalled(scope: scope, environment: fixture.environment) } - #expect(throws: CoreError.self) { - try SkillOperations.removableSkillNames(scope: scope, environment: fixture.environment) + expectFailure { + _ = try SkillOperations.removableSkillNames(scope: scope, environment: fixture.environment) } - #expect(throws: CoreError.self) { - try SkillOperations.doctor(scope: scope, environment: fixture.environment) + expectFailure { + _ = try SkillOperations.doctor(scope: scope, environment: fixture.environment) } #expect(try Data(contentsOf: file) == bytes) #expect( - try FileManager.default.contentsOfDirectory(atPath: store.directory.path) == [ - file.lastPathComponent - ]) + try Set(FileManager.default.contentsOfDirectory(atPath: store.directory.path)) + == Set([file.lastPathComponent])) #expect(!FileManager.default.fileExists(atPath: store.cacheDirectory.path)) #expect( !FileManager.default.fileExists( diff --git a/Tests/AgentsSkillsTests/LifecycleRegressionTests.swift b/Tests/AgentsSkillsTests/LifecycleRegressionTests.swift index 5d38385..f9c6cd4 100644 --- a/Tests/AgentsSkillsTests/LifecycleRegressionTests.swift +++ b/Tests/AgentsSkillsTests/LifecycleRegressionTests.swift @@ -1,4 +1,7 @@ +import AgentsManifest +import AgentsUpdates import Foundation +import StateTestSupport import Testing @testable import AgentsCore @@ -44,8 +47,8 @@ struct LifecycleRegressionTests { source: fixture.repo.path, alias: "fixture", agents: [.codex, .claudeCode], mode: .copy, environment: fixture.environment)) var declaration = try fixture.store().loadDeclaration() - declaration.skills?["fixture"]?.agents = [.codex] - try fixture.store().save(declaration: declaration, resolved: fixture.store().loadResolved()) + try declaration.updateSkills { $0?["fixture"]?.agents = [.codex] } + try fixture.store().save(declaration: declaration, ledger: fixture.store().loadLedger()) let target = fixture.target("demo") try FileManager.default.createDirectory( at: target.appendingPathComponent("empty"), withIntermediateDirectories: true) @@ -101,8 +104,10 @@ struct LifecycleRegressionTests { try fixture.commit() _ = try fixture.add(mode: .copy) var declaration = try fixture.store().loadDeclaration() - declaration.skills?["fixture"]?.overrides = ["demo": SkillOverride(mode: .edit)] - try fixture.store().save(declaration: declaration, resolved: fixture.store().loadResolved()) + try declaration.updateSkills { + $0?["fixture"]?.overrides = ["demo": SkillOverride(mode: .edit)] + } + try fixture.store().save(declaration: declaration, ledger: fixture.store().loadLedger()) _ = try SkillOperations.updateInstalled(environment: fixture.environment, apply: true) try FileManager.default.removeItem(at: fixture.repo.appendingPathComponent("skills/demo")) #expect(throws: CoreError.self) { @@ -118,7 +123,7 @@ struct LifecycleRegressionTests { let fixture = try SkillFixture() try fixture.skill("demo", body: "A") try fixture.commit() - try fixture.store().save(declaration: Declaration(agents: [.codex]), resolved: ResolvedState()) + try fixture.store().save(declaration: Declaration(agents: [.codex]), ledger: ResolvedLedger()) _ = try SkillOperations.add( AddOptions( source: fixture.repo.path, agents: [.codex, .claudeCode], environment: fixture.environment)) @@ -162,3 +167,30 @@ extension LifecycleRegressionTests { .status == .missing) } } + +extension LifecycleRegressionTests { + @Test func namedUpdatePreservesUnselectedCanonicalIdentityAndExactPin() throws { + let fixture = try SkillFixture() + try fixture.skill("example", body: "A") + try fixture.skill("selected", body: "A") + let file = fixture.repo.appendingPathComponent("skills/example/SKILL.md") + try Data("---\nname: Example Skill\ndescription: Example\n---\nOriginal".utf8).write(to: file) + try fixture.commit() + _ = try fixture.add(mode: .copy) + let original = try #require(fixture.store().loadResolved().skills["example-skill"]) + try Data("---\nname: Example Skill\ndescription: Example\n---\nChanged".utf8).write(to: file) + try fixture.skill("selected", body: "B") + try fixture.commit() + _ = try SkillOperations.updateInstalled( + environment: fixture.environment, skillNames: ["selected"], apply: true) + let lock = try fixture.store().loadResolved() + #expect(lock.skills["example-skill"] == original) + #expect(lock.skills["selected"]?.revision == (try fixture.head())) + #expect(try fixture.body(fixture.target("example-skill")).hasSuffix("Original")) + #expect(try fixture.body(fixture.target("selected")).contains("B")) + let ledger = try fixture.store().loadLedger() + #expect( + ledger.components.values.filter { $0.kind == "skills" }.compactMap(\.revision).contains( + original.revision!)) + } +} diff --git a/Tests/AgentsSkillsTests/LockedArtifactLifecycleTests.swift b/Tests/AgentsSkillsTests/LockedArtifactLifecycleTests.swift deleted file mode 100644 index 9790231..0000000 --- a/Tests/AgentsSkillsTests/LockedArtifactLifecycleTests.swift +++ /dev/null @@ -1,229 +0,0 @@ -import AgentsCore -import Darwin -import Foundation -import Testing - -@testable import AgentsSkills - -@Suite("Locked artifacts") -struct LockedArtifactLifecycleTests { - @Test func automaticSelectionRediscoversContentUnderTheWriterLock() throws { - let fixture = try SkillFixture() - let store = fixture.store() - let lock = store.directory.appendingPathComponent(".agents.lock") - let observations = fixture.root.appendingPathComponent("discovery-phases") - let content = "---\nname: demo\ndescription: Test skill\n---\n" - let provider = WellKnownProvider { _ in - let applying = FileManager.default.fileExists(atPath: lock.path) - let before = (try? Data(contentsOf: observations)) ?? Data() - try (before + Data((applying ? "apply\n" : "inspect\n").utf8)).write(to: observations) - return Data((content + (applying ? "Current\n" : "Previous\n")).utf8) - } - let outcome = try SkillOperations.add( - AddOptions( - source: "https://example.test/demo/SKILL.md", agents: [.codex], mode: .copy, - environment: fixture.environment), provider: provider) - #expect(outcome.installed.map(\.skill) == ["demo"]) - #expect(try Data(contentsOf: observations) == Data("inspect\napply\n".utf8)) - #expect(try fixture.body(fixture.target("demo")) == content + "Current\n") - #expect(try store.loadResolved().skills["demo"]?.artifact != nil) - } - - @Test(arguments: [false, true]) - func restoresWithoutIndexAndVerifiesDigests(_ filesArtifact: Bool) throws { - let fixture = try SkillFixture() - let content = Data("---\nname: demo\ndescription: Test skill\n---\nA\n".utf8) - let digest = "sha256:" + FileHash.sha256Hex(data: content) - let base = "https://example.test" - let artifactURL = base + "/demo/SKILL.md" - let fileURL = base + "/.well-known/agent-skills/demo/SKILL.md" - let index = - filesArtifact - ? Data(#"{"skills":[{"name":"demo","description":"Test skill","files":["SKILL.md"]}]}"#.utf8) - : Data( - "{\"$schema\":\"https://schemas.agentskills.io/discovery/0.2.0/schema.json\",\"skills\":[{\"name\":\"demo\",\"description\":\"Test skill\",\"type\":\"skill-md\",\"url\":\"\(artifactURL)\",\"digest\":\"\(digest)\"}]}" - .utf8) - let provider = WellKnownProvider { url in - if url.path.hasSuffix("index.json") { return index } - if [artifactURL, fileURL].contains(url.absoluteString) { return content } - throw CoreError.notFound("URL") - } - _ = try SkillOperations.add( - AddOptions( - source: base, agents: [.codex], mode: .copy, all: true, environment: fixture.environment), - provider: provider) - let locked = try fixture.store().loadResolved() - let artifact = try #require(locked.skills["demo"]?.artifact) - #expect(artifact.type == (filesArtifact ? .files : .skillMD)) - if filesArtifact { - #expect(artifact.files?.first?.url == fileURL) - #expect(artifact.files?.first?.digest == digest) - } - let lockBytes = try Data(contentsOf: fixture.store().resolvedURL) - try FileManager.default.removeItem(at: fixture.store().cacheDirectory) - try FileManager.default.removeItem(at: fixture.target("demo")) - let restore = WellKnownProvider { url in - guard [artifactURL, fileURL].contains(url.absoluteString) else { - throw CoreError.invalidState("restore consulted index") - } - return content - } - _ = try SkillOperations.install( - scope: .project, environment: fixture.environment, provider: restore) - #expect( - try Data(contentsOf: fixture.target("demo").appendingPathComponent("SKILL.md")) == content) - #expect(try Data(contentsOf: fixture.store().resolvedURL) == lockBytes) - try FileManager.default.removeItem(at: fixture.store().cacheDirectory) - let before = try fixture.stateAndTargetBytes() - let mismatch = WellKnownProvider { _ in Data("different content".utf8) } - #expect(throws: (any Error).self) { - try SkillOperations.install( - scope: .project, environment: fixture.environment, provider: mismatch) - } - #expect(try fixture.stateAndTargetBytes() == before) - } - - @Test func cachedArtifactCorruptionStopsRestore() throws { - let fixture = try SkillFixture() - let content = Data("---\nname: demo\ndescription: Test skill\n---\nA\n".utf8) - let url = "https://example.test/demo/SKILL.md" - let provider = WellKnownProvider { _ in content } - _ = try SkillOperations.add( - AddOptions(source: url, agents: [.codex], mode: .copy, environment: fixture.environment), - provider: provider) - let locked = try fixture.store().loadResolved() - let digest = try #require(locked.skills["demo"]?.artifact?.digest) - let cached = try SourceCache(store: fixture.store()).artifactURL(digest: digest) - try Data("corrupt".utf8).write(to: cached) - let before = try fixture.stateAndTargetBytes() - #expect(throws: (any Error).self) { - try SkillOperations.install( - scope: .project, environment: fixture.environment, provider: provider) - } - #expect(try fixture.stateAndTargetBytes() == before) - } -} - -extension LockedArtifactLifecycleTests { - @Test func namedUpdateFetchesOnlySelectedArtifactAndAllFollowsEmptyIndex() throws { - let fixture = try SkillFixture() - let first = Data("---\nname: one\ndescription: Test\n---\nA\n".utf8) - let second = Data("---\nname: two\ndescription: Test\n---\nA\n".utf8) - let index = Data( - #"{"skills":[{"name":"one","description":"Test","files":["SKILL.md"]},{"name":"two","description":"Test","files":["SKILL.md"]}]}"# - .utf8) - let provider = WellKnownProvider { url in - if url.path.hasSuffix("index.json") { return index } - return url.path.contains("/one/") ? first : second - } - _ = try SkillOperations.add( - AddOptions( - source: "https://example.test", agents: [.codex], all: true, - environment: fixture.environment), provider: provider) - let old = try fixture.store().loadResolved().skills["two"] - let changed = Data("---\nname: one\ndescription: Test\n---\nB\n".utf8) - let selectedOnly = WellKnownProvider { url in - if url.path.hasSuffix("index.json") { return index } - guard url.path.contains("/one/") else { - throw CoreError.invalidState("unselected artifact fetched") - } - return changed - } - let updated = try SkillOperations.update( - scope: .project, environment: fixture.environment, skillNames: ["one"], apply: true, - provider: selectedOnly) - #expect(updated.allSatisfy { $0.oldVersion == nil && $0.newVersion == nil }) - #expect(try fixture.store().loadResolved().skills["two"] == old) - let empty = WellKnownProvider { _ in Data(#"{"skills":[]}"#.utf8) } - _ = try SkillOperations.update( - scope: .project, environment: fixture.environment, skillNames: [], apply: true, - provider: empty) - #expect(try fixture.store().loadResolved().skills.isEmpty) - } -} - -extension LockedArtifactLifecycleTests { - @Test func restoresArchiveLockAfterInterruptedExpansionPublication() throws { - let fixture = try SkillFixture() - let project = fixture.environment.projectDirectory - let expanded = project.appendingPathComponent("new") - try FileManager.default.createDirectory(at: expanded, withIntermediateDirectories: true) - let markdown = Data("---\nname: demo\ndescription: Test skill\n---\narchive content\n".utf8) - try markdown.write(to: expanded.appendingPathComponent("SKILL.md")) - try Data("reference".utf8).write(to: expanded.appendingPathComponent("z-reference.md")) - let archive = fixture.root.appendingPathComponent("demo.tar.gz") - try ProcessRunner.run( - "/usr/bin/env", arguments: ["tar", "-czf", archive.path, "-C", expanded.path, "."]) - let bytes = try Data(contentsOf: archive) - let digest = "sha256:" + FileHash.sha256Hex(data: bytes) - let base = "https://example.test" - let url = base + "/demo.tar.gz" - let index = try JSONSerialization.data(withJSONObject: [ - "$schema": "https://schemas.agentskills.io/discovery/0.2.0/schema.json", - "skills": [ - [ - "name": "demo", "description": "Test skill", "type": "archive", "url": url, - "digest": digest, - ] - ], - ]) - _ = try SkillOperations.add( - AddOptions(source: base, agents: [.codex], all: true, environment: fixture.environment), - provider: WellKnownProvider { $0.path.hasSuffix("index.json") ? index : bytes }) - let store = fixture.store() - let lock = try Data(contentsOf: store.resolvedURL) - try FileManager.default.removeItem(at: store.cacheDirectory) - try FileManager.default.removeItem(at: fixture.target("demo")) - let child = try artifactTestProcess(root: project) - defer { - if child.isRunning { - kill(child.processIdentifier, SIGKILL) - child.waitUntilExit() - } - } - let marker = project.appendingPathComponent("ready") - let deadline = Date().addingTimeInterval(10) - while !FileManager.default.fileExists(atPath: marker.path), child.isRunning, Date() < deadline { - Thread.sleep(forTimeInterval: 0.01) - } - try #require(FileManager.default.fileExists(atPath: marker.path)) - let final = store.cacheDirectory.appendingPathComponent( - "artifact-content/" + digest.dropFirst(7)) - #expect(!FileManager.default.fileExists(atPath: final.path)) - kill(child.processIdentifier, SIGKILL) - child.waitUntilExit() - let restore = WellKnownProvider { - guard $0.absoluteString == url else { - throw CoreError.invalidState("restore consulted index") - } - return bytes - } - #expect(throws: CoreError.transactionRecovered(store.directory.path)) { - try SkillOperations.install( - scope: .project, environment: fixture.environment, provider: restore) - } - _ = try SkillOperations.install( - scope: .project, environment: fixture.environment, provider: restore) - #expect(try FileHash.folderHash(fixture.target("demo")) == FileHash.folderHash(expanded)) - #expect(try Data(contentsOf: store.resolvedURL) == lock) - #expect( - try FileManager.default.contentsOfDirectory(atPath: final.deletingLastPathComponent().path) - == [final.lastPathComponent]) - } - - private func artifactTestProcess(root: URL) throws -> Process { - var directory = Bundle(for: ArtifactTestBundle.self).bundleURL.deletingLastPathComponent() - while !FileManager.default.isExecutableFile( - atPath: directory.appendingPathComponent("StateTestProcess").path), directory.path != "/" - { - directory.deleteLastPathComponent() - } - let process = Process() - process.executableURL = directory.appendingPathComponent("StateTestProcess") - process.arguments = [root.path, "cache-content", "stage.0.copy.entry"] - try process.run() - return process - } -} - -private final class ArtifactTestBundle: NSObject {} diff --git a/Tests/AgentsSkillsTests/ManifestLifecycleTests.swift b/Tests/AgentsSkillsTests/ManifestLifecycleTests.swift new file mode 100644 index 0000000..4de43e4 --- /dev/null +++ b/Tests/AgentsSkillsTests/ManifestLifecycleTests.swift @@ -0,0 +1,278 @@ +import AgentsManifest +import AgentsSkills +import AgentsUpdates +import CPlatform +import Foundation +import StateTestSupport +import Testing + +@testable import AgentsCore + +/// Skill and watch writes through the scope's `agents.yaml` declaration document. +@Suite("Skill declaration documents") +struct ManifestLifecycleTests { + @Test func freshAddCreatesTheCanonicalDeclarationInTheLockJournal() throws { + let fixture = try SkillFixture() + try fixture.skill("demo", body: "A") + try fixture.commit() + let store = fixture.store() + let entries = JournalEntries() + _ = try SkillOperations.add( + AddOptions( + source: fixture.repo.path, alias: "fixture", agents: [.codex], mode: .copy, all: true, + environment: fixture.environment), + checkpoint: { point in + guard point == TransactionCheckpoint.progress(0, .ready).name else { return } + let journal = try StateStore.decode( + Data(contentsOf: store.directory.appendingPathComponent(TransactionJournal.fileName)), + as: TransactionJournal.self) + entries.value = journal.entries + }) + #expect( + Set(["codex/demo", "state/agents.yaml", "state/agents.resolved"]).isSubset( + of: Set(entries.value.map(\.path)))) + #expect(entries.value.allSatisfy { $0.preimage == nil }) + #expect( + String(decoding: try Data(contentsOf: store.declarationURL), as: UTF8.self) == """ + version: 1 + sources: + "fixture": {"path": "\(fixture.repo.path)"} + components: + - {"kind": "skills", "source": "fixture", "select": "all", "exclude": [], "mode": "copy", "overrides": {}, "agents": ["codex"], "native": {}} + + """) + #expect(try store.loadResolved().skills["demo"]?.installs == ["codex": .copy]) + } + + @Test func skillAndWatchEditsKeepCommentsAndUntouchedBytes() throws { + let fixture = try SkillFixture() + try fixture.skill("demo", body: "A") + try fixture.skill("other", body: "B") + try fixture.commit() + let store = fixture.store() + let header = """ + # Team skills, reviewed weekly. + version: 1 + sources: + # The fixture repository. + fixture: {path: "\(fixture.repo.path)"} + + """ + try FileManager.default.createDirectory(at: store.directory, withIntermediateDirectories: true) + try Data( + (header + + "components:\n # Everything the fixture publishes.\n - {kind: skills, source: fixture, agents: [codex]}\n") + .utf8 + ).write(to: store.declarationURL) + _ = try SkillOperations.updateInstalled(environment: fixture.environment, apply: true) + #expect(try store.loadResolved().skills.keys.sorted() == ["demo", "other"]) + func text() throws -> String { + String(decoding: try Data(contentsOf: store.declarationURL), as: UTF8.self) + } + func expectUntouched() throws { + let current = try text() + #expect(current.hasPrefix(header)) + #expect(current.contains(" # Everything the fixture publishes.\n")) + } + + try SkillOperations.remove(skillNames: ["demo"], environment: fixture.environment) + try expectUntouched() + #expect(try store.loadDeclaration().skills?["fixture"]?.exclude == ["demo"]) + #expect(try store.loadResolved().skills.keys.sorted() == ["other"]) + + _ = try SkillOperations.add( + AddOptions( + source: "fixture", agents: [.codex], skillNames: ["demo"], environment: fixture.environment) + ) + try expectUntouched() + #expect(try store.loadDeclaration().skills?["fixture"]?.exclude == nil) + + let watch = SkillOperations.watchOperations() + try watch.add("fixture", environment: fixture.environment) + try expectUntouched() + #expect(try store.loadDeclaration().watch == ["fixture"]) + try watch.remove("fixture", environment: fixture.environment) + try expectUntouched() + // Only the component fields and the watch field were edited. + let final = try text() + #expect( + final.hasPrefix( + header + + "components:\n # Everything the fixture publishes.\n - {kind: skills, source: fixture, agents: [codex]" + )) + #expect(final.hasSuffix("\"watch\": []\n")) + let declaration = try store.loadDeclaration() + #expect(declaration.watch == nil) + #expect((try declaration.skills)?["fixture"]?.select == .all) + #expect((try declaration.skills)?["fixture"]?.exclude == nil) + #expect(try store.loadResolved().skills.keys.sorted() == ["demo", "other"]) + } + + @Test func unchangedUpdateKeepsTheDeclarationFile() throws { + let fixture = try SkillFixture() + try fixture.skill("demo", body: "A") + try fixture.commit() + _ = try fixture.add(mode: .copy) + let declaration = fixture.store().declarationURL + let before = try FileStatus(declaration) + let results = try SkillOperations.updateInstalled(environment: fixture.environment, apply: true) + #expect(results.allSatisfy { !$0.changed }) + let after = try FileStatus(declaration) + #expect(after == before) + } + + /// A comment-only edit during the callback changes no declared intent but still invalidates + /// the preparation. + @Test func commentEditBeforeApplyRejectsTheUpdate() throws { + let fixture = try SkillFixture() + try fixture.skill("demo", body: "A") + try fixture.commit() + _ = try fixture.add(mode: .copy) + try fixture.skill("demo", body: "B") + try fixture.commit() + let store = fixture.store() + let lock = try Data(contentsOf: store.resolvedURL) + let target = try fixture.body(fixture.target("demo")) + var edited = Data() + #expect { + try SkillOperations.updateInstalled( + environment: fixture.environment, apply: true, + beforeApply: { _ in + edited = try Data(contentsOf: store.declarationURL) + Data("# Reviewed.\n".utf8) + try edited.write(to: store.declarationURL) + }) + } throws: { error in + guard case CoreError.invalidState(let reason) = error else { return false } + return reason.contains("changed during preparation") + } + #expect(try Data(contentsOf: store.declarationURL) == edited) + #expect(try Data(contentsOf: store.resolvedURL) == lock) + #expect(try fixture.body(fixture.target("demo")) == target) + } + + /// Unsupported shared aliases stop before retaining content or touching targets. + @Test func unsupportedSelectionStopsAnAddBeforeRetention() throws { + let fixture = try SkillFixture() + try fixture.skill("demo", body: "A") + try fixture.skill("other", body: "B") + try fixture.commit() + _ = try fixture.add(mode: .copy) + let store = fixture.store() + let declaration = Data( + """ + version: 1 + sources: {"fixture": {"path": "\(fixture.repo.path)"}} + components: [{"kind": "skills", "source": "fixture", "select": &picked [demo], "mode": "copy", "agents": ["codex"]}] + """.utf8) + try declaration.write(to: store.declarationURL) + let before = try snapshot(fixture.environment.projectDirectory) + #expect { + try SkillOperations.add( + AddOptions( + source: "fixture", agents: [.codex], skillNames: ["other"], mode: .copy, + environment: fixture.environment)) + } throws: { error in + (error as? ManifestFailure)?.diagnostics.first?.code == "manifest.unsupported" + } + #expect(try snapshot(fixture.environment.projectDirectory) == before) + #expect(try Data(contentsOf: store.declarationURL) == declaration) + } + + @Test func fullDeclarationSurvivesSkillAndWatchWrites() throws { + let fixture = try SkillFixture() + try fixture.skill("demo", body: "A") + try fixture.commit() + let store = fixture.store() + try FileManager.default.createDirectory(at: store.directory, withIntermediateDirectories: true) + let declaration = Data( + """ + # All declaration families remain owned by this document. + version: 1 + sources: + fixture: {path: "\(fixture.repo.path)"} + unused: {path: ./not-present} + groups: + unused: {components: [{kind: skills, source: unused, select: [draft]}]} + components: + - {kind: skills, source: fixture, agents: [codex], mode: copy} + # A valid inactive declaration needs no native target. + - {kind: mcpServer, name: tools, agents: [], transport: {kind: stdio, executable: never-run}} + + """.utf8) + try declaration.write(to: store.declarationURL) + #expect(try SkillOperations.listManaged(environment: fixture.environment).isEmpty) + _ = try UpdateOperations.withPreparedUpdate(environment: fixture.environment) { try $0.apply() } + _ = try SkillOperations.updateInstalled(environment: fixture.environment, apply: true) + let ledger = try store.loadLedger() + #expect(ledger.version == 2) + #expect(ledger.components.values.contains { $0.kind == "mcpServer" && $0.recipients.isEmpty }) + #expect(try Data(contentsOf: store.declarationURL) == declaration) + try fixture.skill("other", body: "B") + try fixture.commit() + _ = try SkillOperations.add( + AddOptions( + source: "fixture", agents: [.codex], skillNames: ["other"], mode: .copy, + environment: fixture.environment)) + let watch = SkillOperations.watchOperations() + try watch.add("fixture", environment: fixture.environment) + let lock = try Data(contentsOf: store.resolvedURL) + let before = try snapshot(fixture.root) + #expect( + try SkillOperations.listManaged(environment: fixture.environment).map(\.name).sorted() == [ + "demo", "other", + ]) + _ = try SkillOperations.doctor(environment: fixture.environment) + _ = try watch.status(environment: fixture.environment) + #expect(try snapshot(fixture.root) == before) + try watch.remove("fixture", environment: fixture.environment) + #expect(try Data(contentsOf: store.resolvedURL) == lock) + let document = try #require(try store.loadManifest()) + #expect(document.declaration.groups.count == 1) + #expect(document.declaration.components.contains { $0.kind == "mcpServer" }) + #expect(try store.loadDeclaration().sources["unused"]?.location == "./not-present") + #expect( + String(decoding: document.bytes, as: UTF8.self).contains("# A valid inactive declaration")) + } + +} + +/// Checkpoint callbacks run synchronously in the calling test. +private final class JournalEntries: @unchecked Sendable { + var value: [TransactionJournal.Entry] = [] +} + +/// The inode and modification time a rewrite would change. +private struct FileStatus: Equatable { + let inode: UInt64 + let seconds: Int + let nanoseconds: Int + + init(_ url: URL) throws { + var info = stat() + guard lstat(url.path, &info) == 0 else { throw CoreError.notFound(url.path) } + inode = UInt64(info.st_ino) + #if canImport(Darwin) + seconds = info.st_mtimespec.tv_sec + nanoseconds = info.st_mtimespec.tv_nsec + #else + seconds = info.st_mtim.tv_sec + nanoseconds = info.st_mtim.tv_nsec + #endif + } +} + +private func snapshot(_ directory: URL) throws -> [String: Data] { + var result: [String: Data] = [:] + let entries = try #require(FileManager.default.enumerator(atPath: directory.path)) + for case let path as String in entries { + let url = directory.appendingPathComponent(path) + if let destination = try? FileManager.default.destinationOfSymbolicLink(atPath: url.path) { + result[path] = Data(("link:" + destination).utf8) + } else if (try? url.resourceValues(forKeys: [.isRegularFileKey]))?.isRegularFile == true { + result[path] = try Data(contentsOf: url) + } else { + result[path] = Data() + } + } + return result +} diff --git a/Tests/AgentsSkillsTests/NetworkingTests.swift b/Tests/AgentsSkillsTests/NetworkingTests.swift new file mode 100644 index 0000000..e927274 --- /dev/null +++ b/Tests/AgentsSkillsTests/NetworkingTests.swift @@ -0,0 +1,47 @@ +import Foundation +import Testing + +@testable import AgentsSkills + +@Suite("Artifact networking") +struct NetworkingTests { + @Test func defaultFetcherLoadsHTTPData() throws { + // Exercise the default loader: injected fetch closures cannot detect a + // missing FoundationNetworking linkage on Linux. The child alarm bounds I/O. + let script = """ + use IO::Socket::INET; + alarm 15; + my $server = IO::Socket::INET->new( + LocalAddr => '127.0.0.1', LocalPort => 0, Listen => 1, Proto => 'tcp' + ) or die $!; + $| = 1; + print $server->sockport, "\\n"; + my $client = $server->accept() or die $!; + while (my $line = <$client>) { last if $line eq "\\r\\n"; } + print $client "HTTP/1.1 200 OK\\r\\nContent-Length: 8\\r\\nConnection: close\\r\\n\\r\\nartifact"; + close $client; + """ + let process = Process() + let output = Pipe() + process.executableURL = URL(fileURLWithPath: "/usr/bin/perl") + process.arguments = ["-e", script] + process.standardOutput = output + try process.run() + output.fileHandleForWriting.closeFile() + defer { + if process.isRunning { process.terminate() } + process.waitUntilExit() + try? output.fileHandleForReading.close() + } + var bytes = Data() + while let byte = try output.fileHandleForReading.read(upToCount: 1), !byte.isEmpty { + if byte == Data([10]) { break } + bytes.append(byte) + } + let port = try #require(Int(String(decoding: bytes, as: UTF8.self))) + let url = try #require(URL(string: "http://127.0.0.1:\(port)/artifact")) + #expect(try WellKnownProvider().fetch(url) == Data("artifact".utf8)) + process.waitUntilExit() + #expect(process.terminationStatus == 0) + } +} diff --git a/Tests/AgentsSkillsTests/PublicLifecycleTests.swift b/Tests/AgentsSkillsTests/PublicLifecycleTests.swift index e2f48bf..489489a 100644 --- a/Tests/AgentsSkillsTests/PublicLifecycleTests.swift +++ b/Tests/AgentsSkillsTests/PublicLifecycleTests.swift @@ -1,6 +1,9 @@ import AgentsCore +import AgentsManifest import AgentsSkills +import AgentsUpdates import Foundation +import StateTestSupport import Testing @Suite("Public lifecycle API") @@ -14,8 +17,8 @@ struct PublicLifecycleTests { #expect(Set(added.installed.map(\.agent)) == [.codex, .claudeCode]) var declaration = try fixture.store().loadDeclaration() declaration.agents = [.cursor] - let lock = try fixture.store().loadResolved() - try fixture.store().save(declaration: declaration, resolved: lock) + let lock = try fixture.store().loadLedger() + try fixture.store().save(declaration: declaration, ledger: lock) for install in added.installed { try FileManager.default.removeItem(atPath: install.path) } let restored = try SkillOperations.installResolvedReport(environment: fixture.environment) #expect(Set(restored.installed.map(\.agent)) == [.codex, .claudeCode]) @@ -79,9 +82,15 @@ struct PublicLifecycleTests { try fixture.skill("two", body: "A") try fixture.commit() _ = try fixture.add(mode: .copy) - var lock = try fixture.store().loadResolved() - lock.skills["two"]?.revision = String(repeating: "a", count: 40) - try fixture.store().save(declaration: fixture.store().loadDeclaration(), resolved: lock) + var lock = try fixture.store().loadLedger() + let unavailable = String(repeating: "a", count: 40) + for id in lock.sources.keys where lock.sources[id]!.revision != "live" { + lock.sources[id]!.revision = unavailable + } + for id in lock.components.keys where lock.components[id]!.revision != nil { + lock.components[id]!.revision = unavailable + } + try fixture.store().save(declaration: fixture.store().loadDeclaration(), ledger: lock) try Data("custom".utf8).write(to: fixture.target("one").appendingPathComponent("SKILL.md")) let bytes = try Data(contentsOf: fixture.store().resolvedURL) #expect(throws: (any Error).self) { @@ -96,9 +105,21 @@ struct PublicLifecycleTests { try fixture.skill("demo", body: "A") try fixture.commit() _ = try fixture.add() - var lock = try fixture.store().loadResolved() - lock.skills["demo"]?.installs["cursor"] = .copy - try fixture.store().save(declaration: fixture.store().loadDeclaration(), resolved: lock) + var lock = try fixture.store().loadLedger() + var deployment = try #require(lock.deployments.first { $0.route == "agents/skill@1" }) + var lowering = try #require(lock.lowerings.first { $0.deployments.contains(deployment.id) }) + let id = deployment.id + ":cursor" + deployment.id = id + deployment.target.root = "skills-cursor" + deployment.recipients = [.cursor] + lowering.id = id + lowering.deployments = [id] + lowering.layout.object?["mode"] = .init("copy") + lowering.layout.object?["name"] = .init(id) + for index in lowering.artifacts.indices { lowering.artifacts[index].name = id } + lock.deployments.append(deployment) + lock.lowerings.append(lowering) + try fixture.store().save(declaration: fixture.store().loadDeclaration(), ledger: lock) let bytes = try fixture.stateAndTargetBytes() #expect(throws: (any Error).self) { try SkillOperations.installResolvedReport(environment: fixture.environment) @@ -106,6 +127,48 @@ struct PublicLifecycleTests { #expect(try fixture.stateAndTargetBytes() == bytes) } + @Test func removalFingerprintPreservesRemainingIndependentMembers() throws { + let fixture = try SkillFixture() + for name in ["demo", "keep-b", "keep-a"] { try fixture.skill(name, body: name) } + try fixture.commit() + _ = try fixture.add(mode: .copy) + let pin = try fixture.head() + let request = UpdateRequest(operation: .remove, kinds: [.skills], names: ["demo"]) + let first = try UpdateOperations.preview(request, environment: fixture.environment) + let second = try UpdateOperations.preview(request, environment: fixture.environment) + #expect(first.displayedFingerprint == second.displayedFingerprint) + _ = try UpdateOperations.withPreparedUpdate(request, environment: fixture.environment) { + try $0.apply(ifUnchangedFrom: first.displayedFingerprint) + } + let ledger = try fixture.store().loadLedger() + #expect( + Set(ledger.components.values.filter { $0.kind == "skills" }.map(\.name)) == [ + "keep-a", "keep-b", + ]) + #expect( + ledger.components.values.filter { $0.kind == "skills" }.allSatisfy { $0.revision == pin }) + #expect(try fixture.body(fixture.target("keep-a")).contains("keep-a")) + #expect(try fixture.body(fixture.target("keep-b")).contains("keep-b")) + #expect(!FileManager.default.fileExists(atPath: fixture.target("demo").path)) + } + + @Test func removalDoesNotDiscoverNewAllMembers() throws { + let fixture = try SkillFixture() + try fixture.skill("demo", body: "Original") + try fixture.commit() + _ = try fixture.add(mode: .copy) + try fixture.skill("new-member", body: "Current") + try fixture.commit() + try SkillOperations.remove(skillNames: ["demo"], environment: fixture.environment) + #expect(try fixture.store().loadResolved().skills.isEmpty) + #expect(!FileManager.default.fileExists(atPath: fixture.target("new-member").path)) + #expect(try fixture.store().loadDeclaration().skills?["fixture"]?.select == .all) + #expect(try fixture.store().loadDeclaration().skills?["fixture"]?.exclude == ["demo"]) + _ = try SkillOperations.updateInstalled(environment: fixture.environment, apply: true) + #expect(try fixture.store().loadResolved().skills.keys.sorted() == ["new-member"]) + #expect(try fixture.body(fixture.target("new-member")).contains("Current")) + } + @Test func emptyNamedSelectionDoesNotRequireSourceAccess() throws { let fixture = try SkillFixture() try fixture.skill("demo", body: "A") diff --git a/Tests/AgentsSkillsTests/ReadOnlyInspectionTests.swift b/Tests/AgentsSkillsTests/ReadOnlyInspectionTests.swift index 3f965da..a87fbeb 100644 --- a/Tests/AgentsSkillsTests/ReadOnlyInspectionTests.swift +++ b/Tests/AgentsSkillsTests/ReadOnlyInspectionTests.swift @@ -1,10 +1,15 @@ -import AgentsCore import AgentsInstructions +import AgentsManifest import AgentsSkills -import Darwin +import AgentsUpdates +import CPlatform import Foundation +import StateTestSupport +import Synchronization import Testing +@testable import AgentsCore + @Suite("Read-only skill inspection") struct ReadOnlyInspectionTests { @Test(arguments: [false, true], [false, true]) @@ -26,13 +31,24 @@ struct ReadOnlyInspectionTests { let skills = try store.readResolved().skills if reads == 1 { try #require(skills.isEmpty) - _ = try fixture.add(mode: .copy) + let options = AddOptions( + source: fixture.repo.path, alias: "fixture", agents: [.codex], mode: .copy, all: true, + environment: fixture.environment) + let finished = DispatchSemaphore(value: 0) + let writer = Mutex?>(nil) + Thread.detachNewThread { + let outcome = Result { _ = try SkillOperations.add(options) } + writer.withLock { $0 = outcome } + finished.signal() + } + finished.wait() + try #require(writer.withLock { $0 }).get() if bodyThrows { throw CoreError.invalidState("inconsistent inspection") } } else { let descriptor = open(lock.path, O_RDONLY | O_CLOEXEC) try #require(descriptor >= 0) defer { close(descriptor) } - let acquired = flock(descriptor, LOCK_EX | LOCK_NB) + let acquired = platform_flock(descriptor, LOCK_EX | LOCK_NB) let lockError = errno #expect(acquired == -1) #expect(lockError == EWOULDBLOCK) @@ -69,6 +85,33 @@ struct ReadOnlyInspectionTests { try inspectPendingTransaction(scope: .project, initialize: true) } + @Test func instructionDoctorsDiagnosePendingSharedRecoveryWithoutWriting() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let environment = RuntimeEnvironment( + projectDirectory: root, homeDirectory: root.appendingPathComponent("home"), + environment: ["CLAUDE_CONFIG_DIR": root.appendingPathComponent("configured-claude").path]) + for directory in [environment.homeDirectory, root.appendingPathComponent("old-data")] { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + } + try Data("ordinary before".utf8).write( + to: root.appendingPathComponent("old-data/AGENTS.md")) + let child = try interruptedTransaction( + root: root, scope: .project, command: "shared-install", checkpoint: "shared.ready") + defer { terminateProcess(child) } + try ProcessWait.marker(root.appendingPathComponent("ready"), child: child, root: root) + terminateProcess(child) + let before = try snapshot(root) + let pending = StateStore(scope: .project, environment: environment) + for scope in [InstallScope.project, .user] { + let report = try InstructionOperations.doctor(scope: scope, environment: environment) + #expect(report.diagnostics.map(\.kind) == [.pendingRecovery]) + #expect(report.diagnostics.first?.path == pending.directory) + #expect(report.diagnostics.first?.message == TransactionRecoveryDiagnostic.pendingMessage) + } + #expect(try snapshot(root) == before) + } + private func inspectPendingTransaction( scope: InstallScope, initialize: Bool ) throws { @@ -78,7 +121,7 @@ struct ReadOnlyInspectionTests { projectDirectory: root, homeDirectory: root.appendingPathComponent("home"), environment: ["CLAUDE_CONFIG_DIR": root.appendingPathComponent("configured-claude").path]) let store = StateStore(scope: scope, environment: environment) - try store.save(declaration: Declaration(), resolved: ResolvedState()) + try store.save(declaration: Declaration(), ledger: ResolvedLedger()) let target = AgentRegistry.installSkillsDirectory( for: .codex, scope: scope, environment: environment ).appendingPathComponent("target") @@ -96,20 +139,10 @@ struct ReadOnlyInspectionTests { at: instructions.deletingLastPathComponent(), withIntermediateDirectories: true) try Data("Original instructions\n".utf8).write(to: instructions) let child = try interruptedTransaction(root: root, scope: scope) - defer { - if child.isRunning { - kill(child.processIdentifier, SIGKILL) - child.waitUntilExit() - } - } + defer { terminateProcess(child) } let marker = root.appendingPathComponent("ready") - let deadline = Date().addingTimeInterval(10) - while !FileManager.default.fileExists(atPath: marker.path), child.isRunning, Date() < deadline { - Thread.sleep(forTimeInterval: 0.01) - } - try #require(FileManager.default.fileExists(atPath: marker.path)) - kill(child.processIdentifier, SIGKILL) - child.waitUntilExit() + try ProcessWait.marker(marker, child: child, root: root) + terminateProcess(child) #expect(!FileManager.default.fileExists(atPath: instructions.path)) #expect(try Data(contentsOf: created) == Data("New instructions\n".utf8)) #expect(try Data(contentsOf: target.appendingPathComponent("SKILL.md")) == Data("new".utf8)) @@ -150,14 +183,11 @@ struct ReadOnlyInspectionTests { } let store = fixture.store(scope) if existingDirectory { - try FileManager.default.createDirectory( - at: store.directory, withIntermediateDirectories: true) - try StateStore.encode( + try store.writeDeclaration( Declaration(sources: [ "relative": SourceDeclaration(kind: .local, location: "../source"), "remote": SourceDeclaration(kind: .git, location: "file://localhost" + fixture.repo.path), - ]) - ).write(to: store.declarationURL) + ])) } let before = try snapshot(fixture.root) let sources = @@ -217,7 +247,7 @@ struct ReadOnlyInspectionTests { try fixture.store().save( declaration: Declaration(sources: [ source: SourceDeclaration(kind: .git, location: "file://localhost" + fixture.repo.path) - ]), resolved: ResolvedState()) + ]), ledger: ResolvedLedger()) _ = try SkillOperations.add( AddOptions(source: source, agents: [.codex], all: true, environment: fixture.environment)) // A cached immutable pin remains inspectable when upstream no longer provides it. @@ -251,7 +281,7 @@ struct ReadOnlyInspectionTests { try fixture.store().save( declaration: Declaration( agents: [.codex], sources: ["fixture": source], - skills: ["fixture": SkillDeclaration(select: .all)]), resolved: ResolvedState()) + skills: ["fixture": SkillDeclaration(select: .all)]), ledger: ResolvedLedger()) _ = try SkillOperations.updateInstalled(environment: fixture.environment, apply: true) try fixture.skill("demo", body: "Upstream") try fixture.commit() @@ -275,7 +305,7 @@ struct ReadOnlyInspectionTests { if existingDirectory { try FileManager.default.createDirectory( at: store.directory, withIntermediateDirectories: true) - try StateStore.encode(Declaration()).write(to: store.declarationURL) + try manifestText().write(to: store.declarationURL) } let before = try snapshot(fixture.root) #expect( @@ -305,9 +335,8 @@ struct ReadOnlyInspectionTests { agents: [.codex], sources: ["fixture": source], skills: ["fixture": SkillDeclaration(select: .all)], instructions: InstructionsDeclaration(sections: ["fixture:rules"])), - resolved: ResolvedState()) - _ = try SkillOperations.updateInstalled(environment: fixture.environment, apply: true) - _ = try InstructionOperations.updateInstalled(environment: fixture.environment, apply: true) + ledger: ResolvedLedger()) + _ = try UpdateOperations.withPreparedUpdate(environment: fixture.environment) { try $0.apply() } let locks = fixture.store().cacheDirectory.appendingPathComponent("locks") let files = try FileManager.default.contentsOfDirectory( at: locks, includingPropertiesForKeys: nil) @@ -345,7 +374,7 @@ struct ReadOnlyInspectionTests { report.diagnostics.first?.message.contains("next command that changes this scope") == true) #expect(try snapshot(root) == before) - let pending = CoreError.invalidState("transaction recovery is required before inspection") + let pending = CoreError.recoveryPending(TransactionRecoveryDiagnostic.pendingMessage) #expect(throws: pending) { try SkillOperations.listManaged(scope: scope, environment: environment) } @@ -415,8 +444,11 @@ struct ReadOnlyInspectionTests { return result } - private func interruptedTransaction(root: URL, scope: InstallScope) throws -> Process { - var directory = Bundle(for: InspectionTestBundle.self).bundleURL.deletingLastPathComponent() + private func interruptedTransaction( + root: URL, scope: InstallScope, command: String = "inspection-transaction", + checkpoint: String = TransactionCheckpoint.progress(4, .applied).name + ) throws -> Process { + var directory = Bundle(for: InspectionTestBundle.self).bundleURL while !FileManager.default.isExecutableFile( atPath: directory.appendingPathComponent("StateTestProcess").path), directory.path != "/" { @@ -424,7 +456,10 @@ struct ReadOnlyInspectionTests { } let process = Process() process.executableURL = directory.appendingPathComponent("StateTestProcess") - process.arguments = [root.path, "inspection-transaction", "replace.4", scope.rawValue] + process.arguments = [ + root.path, command, checkpoint, + "--scope", scope.rawValue, + ] try process.run() return process } diff --git a/Tests/AgentsSkillsTests/RetainedLifecycleTests.swift b/Tests/AgentsSkillsTests/RetainedLifecycleTests.swift index 3da70f2..8f28cae 100644 --- a/Tests/AgentsSkillsTests/RetainedLifecycleTests.swift +++ b/Tests/AgentsSkillsTests/RetainedLifecycleTests.swift @@ -1,3 +1,5 @@ +import AgentsManifest +import AgentsUpdates import Foundation import Testing @@ -58,8 +60,9 @@ struct RetainedLifecycleTests { named: "internal", directory: fixture.repo.appendingPathComponent("skills")) try Data("---\nname: internal\ndescription: Internal\nmetadata:\n internal: true\n---".utf8) .write(to: internalDirectory.appendingPathComponent("SKILL.md")) - _ = try SkillOperations.initializeSkill( - named: "deep", directory: fixture.repo.appendingPathComponent("skills/level/level")) + let deepDirectory = fixture.repo.appendingPathComponent("skills/level/level") + try FileManager.default.createDirectory(at: deepDirectory, withIntermediateDirectories: true) + _ = try SkillOperations.initializeSkill(named: "deep", directory: deepDirectory) for value in ["", "false", "TRUE", "yes", "true", "1"] { var environment = fixture.environment environment.environment["INSTALL_INTERNAL_SKILLS"] = value @@ -149,30 +152,35 @@ struct RetainedLifecycleTests { if configureClaude { environment.environment["CLAUDE_CONFIG_DIR"] = claudeRoot.path } _ = try SkillOperations.add( AddOptions( - source: fixture.repo.path, agents: AgentID.allCases, scope: .user, environment: environment) + source: fixture.repo.path, agents: AgentRegistry.skillAgents, scope: .user, + environment: environment) ) let shared = fixture.target("demo", scope: .user) let claude = claudeRoot.appendingPathComponent("skills/demo") + let antigravity = environment.homeDirectory.appendingPathComponent(".gemini/config/skills/demo") #expect(try fixture.body(shared).contains("A")) #expect(try fixture.body(claude).contains("A")) + #expect(try fixture.body(antigravity).contains("A")) #expect( !(try FileManager.default.destinationOfSymbolicLink(atPath: shared.path)).hasPrefix("/")) let bytes = try Data(contentsOf: fixture.store(.user).resolvedURL) - for target in [shared, claude] { try FileManager.default.removeItem(at: target) } + for target in [shared, claude, antigravity] { try FileManager.default.removeItem(at: target) } _ = try SkillOperations.installResolvedReport(scope: .user, environment: environment) #expect(try Data(contentsOf: fixture.store(.user).resolvedURL) == bytes) #expect(try fixture.body(shared).contains("A")) #expect(try fixture.body(claude).contains("A")) + #expect(try fixture.body(antigravity).contains("A")) _ = try SkillOperations.remove( skillNames: ["demo"], scope: .user, agents: [.codex], environment: environment) #expect(FileManager.default.fileExists(atPath: shared.path)) - #expect(try fixture.store(.user).loadResolved().skills["demo"]?.installs.count == 4) + #expect(try fixture.store(.user).loadResolved().skills["demo"]?.installs.count == 5) _ = try SkillOperations.remove( skillNames: ["demo"], scope: .user, agents: [.claudeCode], environment: environment) #expect(!FileManager.default.fileExists(atPath: claude.path)) #expect(FileManager.default.fileExists(atPath: shared.path)) _ = try SkillOperations.remove(skillNames: ["demo"], scope: .user, environment: environment) #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) diff --git a/Tests/AgentsSkillsTests/SkillLifecycleTests.swift b/Tests/AgentsSkillsTests/SkillLifecycleTests.swift index be8445f..997b23d 100644 --- a/Tests/AgentsSkillsTests/SkillLifecycleTests.swift +++ b/Tests/AgentsSkillsTests/SkillLifecycleTests.swift @@ -1,5 +1,9 @@ import AgentsCore +import AgentsInstructions +import AgentsManifest +import AgentsUpdates import Foundation +import StateTestSupport import Testing @testable import AgentsSkills @@ -147,15 +151,40 @@ struct SkillLifecycleTests { } @Test(arguments: [InstallMode.link, .copy]) - func rejectsNonGitPinnedSources(_ mode: InstallMode) throws { + func nonGitSourcesFreezeResourcesAndRejectGitRequirements(_ mode: InstallMode) throws { let fixture = try SkillFixture() - try fixture.skill("demo", body: "live") - #expect(throws: (any Error).self) { try fixture.add(mode: mode) } + try fixture.skill("demo", body: "Local snapshot") + let script = fixture.repo.appendingPathComponent("skills/demo/run.sh") + try Data("#!/bin/sh\nexit 0\n".utf8).write(to: script) + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: script.path) + #expect(throws: (any Error).self) { + try SkillOperations.add( + AddOptions( + source: fixture.repo.path, agents: [.codex], mode: mode, + sourceRequirement: .branch("master"), environment: fixture.environment)) + } #expect(!FileManager.default.fileExists(atPath: fixture.store().resolvedURL.path)) + _ = try fixture.add(mode: mode) + let store = fixture.store() + let ledger = try store.loadLedger() + #expect(ledger.resources.values.contains { $0.kind == .embedded }) + let bytes = try Data(contentsOf: store.resolvedURL) + try FileManager.default.removeItem(at: fixture.repo) + try FileManager.default.removeItem(at: fixture.target("demo")) + try FileManager.default.removeItem(at: store.cacheDirectory) + _ = try SkillOperations.installResolvedReport(environment: fixture.environment) + #expect(try fixture.body(fixture.target("demo")).contains("Local snapshot")) + let flags = try FileHash.executableFlags(fixture.target("demo")) + #expect(flags["run.sh"] == true) + #expect(try Data(contentsOf: store.resolvedURL) == bytes) } - @Test(arguments: ["agents.json", "agents.resolved"], ["add", "update", "install", "remove"]) - func corruptStateStopsEveryMutation(_ filename: String, _ operation: String) throws { + @Test( + arguments: [StateStore.declarationFileName, StateStore.resolvedFileName], + ["add", "update", "install", "remove"]) + func corruptStateStopsDeclarationEditsAndInvalidLedgerStopsRestore( + _ filename: String, _ operation: String + ) throws { let fixture = try SkillFixture() try fixture.skill("demo", body: "A") try fixture.commit() @@ -163,6 +192,11 @@ struct SkillLifecycleTests { let corrupt = fixture.store().directory.appendingPathComponent(filename) try Data("{broken".utf8).write(to: corrupt) let before = try fixture.stateAndTargetBytes() + if filename == StateStore.declarationFileName && operation == "install" { + _ = try SkillOperations.installResolvedReport(environment: fixture.environment) + #expect(try fixture.stateAndTargetBytes() == before) + return + } #expect(throws: (any Error).self) { switch operation { case "add": _ = try fixture.add() @@ -194,24 +228,28 @@ struct SkillLifecycleTests { @Test func skillMutationsPreserveInstructionAndWatchDeclarations() throws { let fixture = try SkillFixture() try fixture.skill("demo", body: "A") + let instructions = fixture.repo.appendingPathComponent("instructions") + try FileManager.default.createDirectory(at: instructions, withIntermediateDirectories: true) + try Data("---\ndescription: Rules\n---\n# Rules\nFrozen rules\n".utf8).write( + to: instructions.appendingPathComponent("rules.md")) try fixture.commit() _ = try fixture.add() + _ = try InstructionOperations.add( + InstructionAddOptions( + source: "fixture", names: ["rules"], agents: [.codex], environment: fixture.environment)) var declaration = try fixture.store().loadDeclaration() - declaration.instructions = InstructionsDeclaration( - sections: ["fixture:rules"], - chatgpt: ["prompt": PromptDeclaration(sections: ["fixture:rules"])]) + try declaration.updateInstructions { + $0?.chatgpt = ["prompt": PromptDeclaration(sections: ["fixture:rules"])] + } declaration.watch = ["fixture"] - var lock = try fixture.store().loadResolved() - let skill = try #require(lock.skills["demo"]) - lock.instructions = LockedInstructions(sections: [ - LockedSection( - name: "rules", source: skill.source, revision: skill.revision, - path: "instructions/rules.md", hash: skill.hash!) - ]) - try fixture.store().save(declaration: declaration, resolved: lock) + try fixture.store().save(declaration: declaration, ledger: fixture.store().loadLedger()) + _ = try UpdateOperations.withPreparedUpdate(environment: fixture.environment) { try $0.apply() } + let lock = try fixture.store().loadResolved() + let ledger = try fixture.store().loadLedger() + #expect(ledger.version == 2) try SkillOperations.remove(skillNames: ["demo"], environment: fixture.environment) #expect(try fixture.store().loadResolved().instructions == lock.instructions) - #expect(try fixture.store().loadDeclaration().instructions == declaration.instructions) + #expect(try fixture.store().loadDeclaration().instructions == (try declaration.instructions)) #expect(try fixture.store().loadDeclaration().watch == ["fixture"]) } diff --git a/Tests/AgentsSkillsTests/SourceAliasTests.swift b/Tests/AgentsSkillsTests/SourceAliasTests.swift index ff9fdd4..6627139 100644 --- a/Tests/AgentsSkillsTests/SourceAliasTests.swift +++ b/Tests/AgentsSkillsTests/SourceAliasTests.swift @@ -1,10 +1,46 @@ import AgentsCore +import AgentsManifest import AgentsSkills +import AgentsUpdates import Foundation import Testing @Suite("Source aliases on add") struct SkillSourceAliasTests { + @Test(arguments: [false, true]) + func addSelectsTheRequestedRootOfASharedRepository(located: Bool) throws { + let fixture = try SkillFixture() + try fixture.skill("first", body: "First root") + let second = fixture.repo.appendingPathComponent("second/skills/second") + try FileManager.default.createDirectory(at: second, withIntermediateDirectories: true) + try "---\nname: second\ndescription: Test skill\n---\n\nSecond root\n".write( + to: second.appendingPathComponent("SKILL.md"), atomically: true, encoding: .utf8) + try fixture.commit() + try fixture.store().save( + declaration: Declaration(sources: [ + "a": SourceDeclaration(kind: .local, location: fixture.repo.path, path: "."), + "b": SourceDeclaration(kind: .local, location: fixture.repo.path, path: "second"), + ]), ledger: ResolvedLedger()) + let sources = try fixture.store().loadDeclaration().sources + _ = try SkillOperations.add( + AddOptions( + source: "a", agents: [.codex], skillNames: ["first"], + environment: fixture.environment)) + let first = try fixture.body(fixture.target("first")) + let result = try SkillOperations.add( + AddOptions( + source: located ? fixture.repo.path + "@path:second" : "b", + agents: [.codex], skillNames: ["second"], environment: fixture.environment)) + #expect(result.installed.map(\.skill) == ["second"]) + let declaration = try fixture.store().loadDeclaration() + #expect(declaration.sources == sources) + let skills = try declaration.skills + #expect(skills?["a"]?.select == .names(["first"])) + #expect(skills?["b"]?.select == .names(["second"])) + #expect(try fixture.body(fixture.target("first")) == first) + #expect(try fixture.body(fixture.target("second")).contains("Second root")) + } + @Test func sourcesSharingALastComponentReceiveDistinctAliases() throws { let fixture = try SkillFixture() try fixture.skill("demo", body: "A") @@ -22,6 +58,6 @@ struct SkillSourceAliasTests { let declaration = try fixture.store().loadDeclaration() #expect(declaration.sources["source"]?.location == fixture.repo.path) #expect(declaration.sources["mirror-source"]?.location == mirror.path) - #expect(declaration.skills?["mirror-source"]?.select == .names(["other"])) + #expect((try declaration.skills)?["mirror-source"]?.select == .names(["other"])) } } diff --git a/Tests/AgentsSkillsTests/SourceShorthandTests.swift b/Tests/AgentsSkillsTests/SourceShorthandTests.swift index b99b1b4..12f403d 100644 --- a/Tests/AgentsSkillsTests/SourceShorthandTests.swift +++ b/Tests/AgentsSkillsTests/SourceShorthandTests.swift @@ -1,6 +1,9 @@ import AgentsCore +import AgentsManifest import AgentsSkills +import AgentsUpdates import Foundation +import StateTestSupport import Testing @Suite("Typed source shorthand") @@ -19,9 +22,12 @@ struct SourceShorthandTests { #expect( declaration.sources == [ "source": SourceDeclaration( - kind: .local, location: fixture.repo.path, requirement: .branch("master")) + kind: .local, location: fixture.repo.path, requirement: .branch("master"), + environment: SourceEnvironment( + projectDirectory: fixture.environment.projectDirectory, + homeDirectory: fixture.environment.homeDirectory)) ]) - #expect(declaration.skills?["source"]?.select == .names(["demo"])) + #expect((try declaration.skills)?["source"]?.select == .names(["demo"])) } @Test func sourceListingFiltersToTheSelectedSkill() throws { @@ -58,7 +64,7 @@ struct SourceShorthandTests { let fixture = try SkillFixture() try fixture.skill("demo", body: "A") try fixture.commit() - try fixture.store().save(declaration: Declaration(), resolved: ResolvedState()) + try fixture.store().save(declaration: Declaration(), ledger: ResolvedLedger()) let watch = SkillOperations.watchOperations() #expect(throws: CoreError.self) { try watch.add(fixture.repo.path + "@skill:demo", environment: fixture.environment) diff --git a/Tests/AgentsSkillsTests/TransactionDoctorTests.swift b/Tests/AgentsSkillsTests/TransactionDoctorTests.swift new file mode 100644 index 0000000..d59d64f --- /dev/null +++ b/Tests/AgentsSkillsTests/TransactionDoctorTests.swift @@ -0,0 +1,104 @@ +import AgentsInstructions +import AgentsManifest +import AgentsSkills +import AgentsUpdates +import Foundation +import StateTestSupport +import Testing + +@testable import AgentsCore + +@Suite("Transaction conflict diagnostics") +struct TransactionDoctorTests { + @Test func bothDoctorsReportOwnerActionAndPreservedLocationsWithoutReplay() throws { + let fixture = try SkillFixture() + let store = fixture.store() + try store.save(declaration: Declaration(), ledger: ResolvedLedger()) + let target = fixture.environment.projectDirectory.appendingPathComponent("AGENTS.md") + try Data("original".utf8).write(to: target) + let saved = fixture.root.appendingPathComponent("saved-original") + #expect(throws: CoreError.invalidState("interrupt after removing preimage")) { + try store.withLock { + let transaction = FileTransaction(store: store) { point in + if point == TransactionCheckpoint.progress(0, .applied).name { + let journal = try StateStore.decode( + Data(contentsOf: store.directory.appendingPathComponent("transaction.json")), + as: TransactionJournal.self) + let backup = target.deletingLastPathComponent().appendingPathComponent( + journal.containerName(0) + ).appendingPathComponent(TransactionSlot.exchanged.name(0)) + try FileManager.default.moveItem(at: backup, to: saved) + throw CoreError.invalidState("interrupt after removing preimage") + } + } + try transaction.replace(target, with: .data(Data("published".utf8))) + try transaction.commit() + } + } + let before = try FileSnapshot.read(at: fixture.root) + let skills = try SkillOperations.doctor(environment: fixture.environment) + #expect(skills.checks.map(\.id) == ["unresolved-transaction"]) + let instructions = try InstructionOperations.doctor(environment: fixture.environment) + #expect(instructions.diagnostics.map(\.kind) == [.unresolvedTransaction]) + for message in skills.checks.map(\.message) + instructions.diagnostics.map(\.message) { + #expect(message.contains("owner action is required")) + #expect(message.contains("expected slots: " + TransactionSlot.exchanged.name(0))) + #expect(message.contains("instructions-project/AGENTS.md")) + #expect(message.contains(".agents-")) + } + #expect(try FileSnapshot.read(at: fixture.root) == before) + } + + @Test func equalBytesInAnotherTargetDescendantInvalidatePreparation() throws { + let fixture = try SkillFixture() + try fixture.skill("demo", body: "original") + try fixture.commit() + _ = try fixture.add(mode: .copy) + let target = fixture.target("demo").appendingPathComponent("SKILL.md") + let state = try FileSnapshot.read(at: fixture.store().resolvedURL) + var replacement: FileSnapshot? + #expect { + try SkillOperations.updateInstalled( + environment: fixture.environment, apply: true, + beforeApply: { _ in + let bytes = try Data(contentsOf: target) + try bytes.write(to: target, options: .atomic) + replacement = try FileSnapshot.read(at: target) + }) + } throws: { error in + guard case CoreError.invalidState(let reason) = error else { return false } + return reason.contains("target changed during preparation") + } + #expect(replacement != nil) + #expect(try FileSnapshot.read(at: target) == replacement) + #expect(try FileSnapshot.read(at: fixture.store().resolvedURL) == state) + } + + @Test func instructionCallbackCannotReplacePreparedInodeWithEqualBytes() throws { + let fixture = try SkillFixture() + let root = fixture.environment.projectDirectory + let own = root.appendingPathComponent(".agent/instructions") + try FileManager.default.createDirectory(at: own, withIntermediateDirectories: true) + try Data("---\ndescription: Rules\n---\n\n# Rules\n\nOriginal\n".utf8) + .write(to: own.appendingPathComponent("rules.md")) + _ = try InstructionOperations.add( + InstructionAddOptions( + source: ".", names: ["rules"], agents: [.codex], + environment: fixture.environment)) + let target = root.appendingPathComponent("AGENTS.md") + let state = try FileSnapshot.read(at: fixture.store().resolvedURL) + var external: FileSnapshot? + #expect { + try InstructionOperations.updateInstalled(environment: fixture.environment, apply: true) { + _ in + try Data(contentsOf: target).write(to: target, options: .atomic) + external = try FileSnapshot.read(at: target) + } + } throws: { error in + guard case CoreError.invalidState(let reason) = error else { return false } + return reason.contains("path changed during preparation") + } + #expect(try FileSnapshot.read(at: target) == external) + #expect(try FileSnapshot.read(at: fixture.store().resolvedURL) == state) + } +} diff --git a/Tests/AgentsSkillsTests/UnmanagedTargetTests.swift b/Tests/AgentsSkillsTests/UnmanagedTargetTests.swift index 14233b3..359d5e0 100644 --- a/Tests/AgentsSkillsTests/UnmanagedTargetTests.swift +++ b/Tests/AgentsSkillsTests/UnmanagedTargetTests.swift @@ -1,3 +1,4 @@ +import AgentsUpdates import Foundation import Testing diff --git a/Tests/AgentsSkillsTests/UpdateReportingTests.swift b/Tests/AgentsSkillsTests/UpdateReportingTests.swift index b7e5bf0..6f2b8ba 100644 --- a/Tests/AgentsSkillsTests/UpdateReportingTests.swift +++ b/Tests/AgentsSkillsTests/UpdateReportingTests.swift @@ -1,4 +1,7 @@ +import AgentsManifest +import AgentsUpdates import Foundation +import StateTestSupport import Testing @testable import AgentsCore @@ -91,60 +94,6 @@ struct UpdateReportingTests { #expect(try !flag(file)) } - @Test(arguments: ["prepared", "cached", "staged"]) - func rejectsModeDisagreementBeforePublication(_ kind: String) throws { - let fixture = try SkillFixture() - try fixture.skill("demo", body: "same") - try fixture.commit() - _ = try fixture.add(mode: .copy) - let store = fixture.store() - let before = try fixture.stateAndTargetBytes() - try store.withLock { - let resolutions = try SourceResolutionSession(store: store) - let plan = try SkillOperations.prepareUpdate( - store: store, declaration: store.readDeclaration(), previous: store.readResolved(), - resolutions: resolutions) - if kind == "prepared" { - let lifecycle = try SkillLifecycle(store: store, provider: WellKnownProvider()) - let source = try lifecycle.discover( - store.readDeclaration().sources["fixture"]!, live: false, fullDepth: true) - let prepared = try lifecycle.prepare( - source.skills[0], in: source, - declaration: SkillDeclaration(select: .all, mode: .copy), defaultAgents: [.codex]) - try FileManager.default.setAttributes( - [.posixPermissions: 0o755], - ofItemAtPath: prepared.directory.appendingPathComponent("SKILL.md").path) - #expect(throws: CoreError.self) { try lifecycle.validate(prepared, name: "demo") } - } else if kind == "cached" { - let record = try #require(plan.next.skills["demo"]) - let path = SourceCache(store: store).materializedURL( - sourceID: record.source, revision: record.revision! - ) - .appendingPathComponent("skills/demo/SKILL.md") - try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: path.path) - #expect(throws: CoreError.self) { try plan.retain() } - } else { - let retained = try plan.retain() - let transaction = FileTransaction(store: store) { step in - if step == "stage.0.ready" { - let parent = fixture.target("demo").deletingLastPathComponent() - let staged = try #require( - FileManager.default.contentsOfDirectory( - at: parent, - includingPropertiesForKeys: nil - ).first { $0.lastPathComponent.hasSuffix(".new") }) - try FileManager.default.setAttributes( - [.posixPermissions: 0o755], - ofItemAtPath: staged.appendingPathComponent("SKILL.md").path) - } - } - try plan.stage(retained: retained, transaction: transaction) - #expect(throws: CoreError.self) { try transaction.commit() } - } - } - #expect(try fixture.stateAndTargetBytes() == before) - } - @Test(arguments: [[AgentID.codex, .claudeCode], [.codex, .cursor]]) func liveMembershipAndLostLockPreserveOwnership(_ agents: [AgentID]) throws { let fixture = try SkillFixture() @@ -154,7 +103,7 @@ struct UpdateReportingTests { declaration: Declaration( sources: ["fixture": SourceDeclaration(kind: .local, location: fixture.repo.path)], skills: ["fixture": SkillDeclaration(select: .all, agents: agents, mode: .edit)]), - resolved: ResolvedState()) + ledger: ResolvedLedger()) let initial = try #require( SkillOperations.updateInstalled(environment: fixture.environment).first) #expect(initial.membership.count == agents.count) @@ -188,8 +137,8 @@ struct UpdateReportingTests { SkillOperations.updateInstalled(environment: fixture.environment).first) #expect(repair.membership.allSatisfy { $0.before == $0.after } && !repair.changes.isEmpty) var declaration = try store.loadDeclaration() - declaration.skills = nil - try store.save(declaration: declaration, resolved: store.loadResolved()) + try declaration.setSkills(nil) + try store.save(declaration: declaration, ledger: store.loadLedger()) let removed = try #require( SkillOperations.updateInstalled(environment: fixture.environment).first) #expect(removed.changed && removed.changes.isEmpty && removed.newVersion == nil) @@ -208,16 +157,16 @@ struct UpdateReportingTests { _ = try fixture.add(mode: .edit) let store = fixture.store() var declaration = try store.loadDeclaration() - declaration.skills?["fixture"]?.agents = [.codex, .cursor, .claudeCode] - try store.save(declaration: declaration, resolved: store.loadResolved()) + try declaration.updateSkills { $0?["fixture"]?.agents = [.codex, .cursor, .claudeCode] } + try store.save(declaration: declaration, ledger: store.loadLedger()) let added = try #require( SkillOperations.updateInstalled(environment: fixture.environment).first) #expect(added.membership.first { $0.agent == .codex }?.before == .installed(mode: .edit)) #expect(added.membership.first { $0.agent == .cursor }?.before == .absent) _ = try SkillOperations.updateInstalled(environment: fixture.environment, apply: true) - declaration.skills?["fixture"]?.agents = [.codex, .cursor] - declaration.skills?["fixture"]?.mode = .copy - try store.save(declaration: declaration, resolved: store.loadResolved()) + try declaration.updateSkills { $0?["fixture"]?.agents = [.codex, .cursor] } + try declaration.updateSkills { $0?["fixture"]?.mode = .copy } + try store.save(declaration: declaration, ledger: store.loadLedger()) let changed = try #require( SkillOperations.updateInstalled(environment: fixture.environment).first) #expect(changed.membership.first { $0.agent == .claudeCode }?.after == .absent) @@ -227,6 +176,14 @@ struct UpdateReportingTests { }) #expect(Set(changed.changes.map(\.path)).count == changed.changes.count) _ = try SkillOperations.updateInstalled(environment: fixture.environment, apply: true) + let partial = try #require( + UpdateOperations.preview( + UpdateRequest(operation: .remove, kinds: [.skills], names: ["demo"], agents: [.codex]), + environment: fixture.environment + ).skills.first) + #expect(partial.changes.isEmpty) + #expect(partial.membership.first { $0.agent == .cursor }?.after == .installed(mode: .copy)) + #expect(try fixture.body(fixture.target("demo")).contains("live")) } @Test func lossOfRecordAndSelectionDoesNotInventRemoval() throws { @@ -234,7 +191,7 @@ struct UpdateReportingTests { try fixture.skill("demo", body: "live") _ = try fixture.add(mode: .edit) let store = fixture.store() - try store.save(declaration: Declaration(), resolved: ResolvedState()) + try store.save(declaration: Declaration(), ledger: ResolvedLedger()) try FileManager.default.removeItem(at: store.resolvedURL) #expect(try SkillOperations.updateInstalled(environment: fixture.environment).isEmpty) _ = try SkillOperations.updateInstalled(environment: fixture.environment, apply: true) diff --git a/Tests/AgentsSkillsTests/WatchSubscriptionTests.swift b/Tests/AgentsSkillsTests/WatchSubscriptionTests.swift index de156ee..1e95788 100644 --- a/Tests/AgentsSkillsTests/WatchSubscriptionTests.swift +++ b/Tests/AgentsSkillsTests/WatchSubscriptionTests.swift @@ -1,6 +1,10 @@ import AgentsCore +import AgentsInstructions +import AgentsManifest import AgentsSkills +import AgentsUpdates import Foundation +import StateTestSupport import Testing @Suite("Watch subscriptions") @@ -13,11 +17,13 @@ struct WatchSubscriptionTests { try writeInstruction("removed", body: "old", fixture: fixture) try fixture.commit() let initial = try fixture.head() - try fixture.store().save(declaration: Declaration(), resolved: ResolvedState()) + try fixture.store().save(declaration: Declaration(), ledger: ResolvedLedger()) let watch = SkillOperations.watchOperations() - #expect( - try watch.add(fixture.repo.path, alias: "upstream", environment: fixture.environment) - == .revision(initial)) + let id = try SourceDeclaration(kind: .local, location: fixture.repo.path).identity( + environment: fixture.environment) + let added = try watch.add( + fixture.repo.path, alias: "upstream", environment: fixture.environment) + #expect(added.alias == "upstream" && added.sourceID == id && added.seen == .revision(initial)) #expect(try fixture.store().loadDeclaration().skills == nil) #expect(try fixture.store().loadResolved().skills.isEmpty) #expect(!FileManager.default.fileExists(atPath: fixture.target("changed").path)) @@ -57,7 +63,10 @@ struct WatchSubscriptionTests { #expect(try stateBytes(fixture) == bytes) #expect(try fixture.head() == current) - try watch.seen("upstream", environment: fixture.environment) + let acknowledged = try watch.seen("upstream", environment: fixture.environment) + #expect( + acknowledged.alias == "upstream" && acknowledged.sourceID == id + && acknowledged.seen == .revision(current)) #expect(try watch.status(environment: fixture.environment).first?.changes.isEmpty == true) try fixture.skill("later", body: "later") try fixture.commit() @@ -85,10 +94,12 @@ struct WatchSubscriptionTests { let store = fixture.store(scope) let lock = try Data(contentsOf: store.resolvedURL) let installed = try fixture.body(fixture.target("demo", scope: scope)) - try watch.add("fixture", scope: scope, environment: fixture.environment) - try watch.remove(fixture.repo.path, scope: scope, environment: fixture.environment) + let added = try watch.add("fixture", scope: scope, environment: fixture.environment) + let removed = try watch.remove( + fixture.repo.path, scope: scope, environment: fixture.environment) + #expect(removed.alias == "fixture" && removed.sourceID == added.sourceID && removed.seen == nil) #expect(try store.loadWatch().sources.isEmpty) - #expect(try store.loadDeclaration().watch == []) + #expect(try store.loadDeclaration().watch == nil) #expect(try store.loadDeclaration().skills?["fixture"] != nil) #expect(try Data(contentsOf: store.resolvedURL) == lock) #expect(try fixture.body(fixture.target("demo", scope: scope)) == installed) @@ -105,11 +116,12 @@ struct WatchSubscriptionTests { "source": SourceDeclaration( kind: .local, location: fixture.repo.path, requirement: .exact("1.0.0")) - ]), resolved: ResolvedState()) + ]), ledger: ResolvedLedger()) try fixture.skill("demo", body: "head") try fixture.commit() let watch = SkillOperations.watchOperations() - #expect(try watch.add("source", environment: fixture.environment) == .revision(fixture.head())) + #expect( + try watch.add("source", environment: fixture.environment).seen == .revision(fixture.head())) try fixture.skill("demo", body: "uncommitted") #expect(try watch.status(environment: fixture.environment).first?.changes.isEmpty == true) try git(fixture, ["checkout", "-b", "next-default"]) @@ -320,7 +332,7 @@ struct WatchSubscriptionTests { { _ = try SkillOperations.remove(skillNames: ["demo"], environment: fixture.environment) }, { try fixture.store().save( - declaration: Declaration(), resolved: ResolvedState(), watch: WatchState()) + declaration: Declaration(), ledger: ResolvedLedger(), watch: WatchState()) }, ] for mutate in mutations { @@ -337,24 +349,23 @@ struct WatchSubscriptionTests { try watch.add(fixture.repo.path, environment: fixture.environment) } #expect(!FileManager.default.fileExists(atPath: fixture.store().declarationURL.path)) + let instructions = fixture.repo.appendingPathComponent("instructions") + try FileManager.default.createDirectory(at: instructions, withIntermediateDirectories: true) + try Data("---\ndescription: Canonical rules\n---\n# Rules\nCanonical\n".utf8).write( + to: instructions.appendingPathComponent("canonical.md")) try fixture.commit() - let declaration = Declaration( - sources: ["rules": SourceDeclaration(kind: .local, location: fixture.repo.path)], - instructions: InstructionsDeclaration(sections: ["rules:canonical"])) - let lock = ResolvedState( - sources: ["local:" + fixture.repo.path: LockedSource(kind: .local)], - instructions: LockedInstructions(sections: [ - LockedSection( - name: "canonical", source: "local:" + fixture.repo.path, - revision: try fixture.head(), path: "instructions/canonical.md", - hash: "sha256:" + String(repeating: "a", count: 64)) - ])) - try fixture.store().save(declaration: declaration, resolved: lock) + _ = try InstructionOperations.add( + InstructionAddOptions( + source: fixture.repo.path, alias: "rules", names: ["canonical"], agents: [.codex], + environment: fixture.environment)) + let declaration = try fixture.store().loadDeclaration() + #expect( + try fixture.store().loadLedger().components.values.contains { $0.kind == "instructions" }) let lockBytes = try Data(contentsOf: fixture.store().resolvedURL) try watch.add("rules", environment: fixture.environment) try watch.seen("rules", environment: fixture.environment) try watch.remove("rules", environment: fixture.environment) - #expect(try fixture.store().loadDeclaration().instructions == declaration.instructions) + #expect(try fixture.store().loadDeclaration().instructions == (try declaration.instructions)) #expect(try Data(contentsOf: fixture.store().resolvedURL) == lockBytes) } } diff --git a/Tests/AgentsSkillsTests/WellKnownArtifactTests.swift b/Tests/AgentsSkillsTests/WellKnownArtifactTests.swift index b51a80d..5dd801f 100644 --- a/Tests/AgentsSkillsTests/WellKnownArtifactTests.swift +++ b/Tests/AgentsSkillsTests/WellKnownArtifactTests.swift @@ -131,26 +131,20 @@ extension WellKnownSourceTests { } @Test func fetchesDigestVerifiedZipArchives() throws { - let archiveRoot = try temporaryDirectory() - defer { removeTemporaryDirectory(archiveRoot) } - try """ - --- - name: zip-skill - description: Zip skill. - --- - # Zip - """.write(to: archiveRoot.appendingPathComponent("SKILL.md"), atomically: true, encoding: .utf8) - try FileManager.default.createDirectory( - at: archiveRoot.appendingPathComponent("references"), withIntermediateDirectories: true) - try "Zip Reference".write( - to: archiveRoot.appendingPathComponent("references/README.md"), atomically: true, - encoding: .utf8) - let outputRoot = try temporaryDirectory() - defer { removeTemporaryDirectory(outputRoot) } - let archive = outputRoot.appendingPathComponent("skill.zip") - try ProcessRunner.run( - "/usr/bin/env", arguments: ["zip", "-qr", archive.path, "."], workingDirectory: archiveRoot) - let archiveData = try Data(contentsOf: archive) + let skill = Data( + """ + --- + name: zip-skill + description: Zip skill. + --- + # Zip + """.utf8) + let reference = Data("Zip Reference".utf8) + let archiveData = zipArchive(entries: [ + ("SKILL.md", skill, 0o100644), + ("references/", Data(), 0o040755), + ("references/README.md", reference, 0o100644), + ]) let digest = "sha256:" + FileHash.sha256Hex(data: archiveData) let responses: [String: Data] = [ @@ -180,8 +174,8 @@ extension WellKnownSourceTests { let skills = try provider.fetchAllSkills(from: "https://example.com") #expect(skills.count == 1) - #expect(skills[0].files["SKILL.md"] != nil) - #expect(skills[0].files["references/README.md"] == Data("Zip Reference".utf8)) + #expect(skills[0].files["SKILL.md"] == skill) + #expect(skills[0].files["references/README.md"] == reference) } @Test func rejectsSymlinkEntriesInWellKnownArchives() throws { diff --git a/Tests/AgentsUpdatesTests/AgentClientInspectionTests.swift b/Tests/AgentsUpdatesTests/AgentClientInspectionTests.swift new file mode 100644 index 0000000..700d500 --- /dev/null +++ b/Tests/AgentsUpdatesTests/AgentClientInspectionTests.swift @@ -0,0 +1,243 @@ +import AgentsCore +import AgentsUpdates +import CPlatform +import Foundation +import Testing + +struct AgentClientInspectionTests { + private func fixture() throws -> URL { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + return root + } + + @Test func missingClientsKeepRegistryRecordsAndStaticEvidence() throws { + let root = try fixture() + defer { try? FileManager.default.removeItem(at: root) } + let environment = RuntimeEnvironment( + projectDirectory: root.appendingPathComponent("project"), + homeDirectory: root.appendingPathComponent("absent-home"), environment: [:]) + let before = try FileManager.default.contentsOfDirectory(atPath: root.path) + let report = try AgentClientOperations.inspect(environment: environment) + #expect(report.clients.map(\.agent) == AgentID.allCases) + #expect(report.startedAt <= report.finishedAt) + #expect(!report.pathCoverage.pathWasSupplied) + #expect( + report.clients.flatMap(\.commands).allSatisfy { + $0.status == .unavailable && $0.version.rawVersion == nil + && $0.version.unknownReason == .unavailable + }) + #expect(report.clients.flatMap(\.configurationLocations).allSatisfy { $0.status == .notFound }) + let claude = try #require(report.clients.first { $0.agent == .claudeCode }) + #expect( + claude.schemaEvidence.contains { + $0.kind == .mcpServer && $0.scope == "local" && $0.revision == "installed:2.1.309" + }) + #expect(claude.commands.allSatisfy { $0.version.rawVersion == nil }) + #expect(claude.schemaEvidence.contains { $0.kind == .skills && $0.status == .unverified }) + let codex = try #require(report.clients.first { $0.agent == .codex }) + #expect( + codex.configurationLocations.contains { + $0.identity == "codex.mcp.user" + && $0.location?.path + == environment.homeDirectory.appendingPathComponent(".codex/config.toml").path + }) + #expect( + codex.schemaEvidence.contains { + $0.kind == .command && $0.status == .unsupportedUnderEvidence + }) + let cursor = try #require(report.clients.first { $0.agent == .cursor }) + #expect( + cursor.schemaEvidence.contains { + $0.surface.identifier == "cursorCloud" && $0.kind == .mcpServer && $0.status == .unverified + }) + #expect( + cursor.schemaEvidence.contains { + $0.surface.identifier == "cursorEditor" && $0.kind == .command && $0.scope == "user" + && $0.placement == .standalone && $0.status == .unverified + }) + #expect( + cursor.schemaEvidence.contains { + $0.surface.identifier == "cursorEditor" && $0.kind == .command && $0.scope == "user" + && $0.placement == .pluginMember && $0.status == .recorded + }) + let antigravity = try #require(report.clients.first { $0.agent == .antigravity }) + for kind in [DeclaredComponentKind.instructions, .skills, .hook, .mcpServer] { + #expect( + Set( + antigravity.schemaEvidence.filter { + $0.kind == kind && $0.status == .recorded + }.map(\.scope)) == ["project", "user"]) + } + #expect( + antigravity.schemaEvidence.contains { + $0.kind == .subagent && $0.status == .unsupportedUnderEvidence + }) + #expect( + antigravity.configurationLocations.contains { + $0.identity == "antigravity.hooks.user" + && $0.location?.path + == environment.homeDirectory.appendingPathComponent(".gemini/config/hooks.json").path + }) + #expect(try FileManager.default.contentsOfDirectory(atPath: root.path) == before) + } + + @Test func pathOrderSymlinksAndCursorRolesNeverExecuteClients() throws { + let root = try fixture() + defer { try? FileManager.default.removeItem(at: root) } + let first = root.appendingPathComponent("first") + let second = root.appendingPathComponent("second") + for directory in [first, second] { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + } + let sentinel = root.appendingPathComponent("executed") + let executable = second.appendingPathComponent("codex") + try Data("#!/bin/sh\ntouch '\(sentinel.path)'\n".utf8).write(to: executable) + try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: executable.path) + try FileManager.default.createSymbolicLink( + at: first.appendingPathComponent("codex"), withDestinationURL: executable) + try Data("not executable".utf8).write(to: first.appendingPathComponent("cursor")) + let bundle = root.appendingPathComponent("Cursor.app") + let launcher = bundle.appendingPathComponent("Contents/Resources/app/bin/cursor") + try FileManager.default.createDirectory( + at: launcher.deletingLastPathComponent(), withIntermediateDirectories: true) + try FileManager.default.copyItem(at: executable, to: launcher) + try FileManager.default.createSymbolicLink( + at: second.appendingPathComponent("cursor"), withDestinationURL: launcher) + try PropertyListSerialization.data( + fromPropertyList: [ + "CFBundleIdentifier": "com.todesktop.230313mzl4w4u92", + "CFBundleShortVersionString": "3.27-test", "CFBundleVersion": "42", + ], format: .xml, options: 0 + ).write(to: bundle.appendingPathComponent("Contents/Info.plist")) + try FileManager.default.createDirectory( + at: first.appendingPathComponent("cursor-agent"), withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink( + atPath: first.appendingPathComponent("gemini").path, + withDestinationPath: root.appendingPathComponent("missing").path) + let environment = RuntimeEnvironment( + projectDirectory: root, homeDirectory: root, + environment: ["PATH": ":relative:\(first.path):\(second.path)"]) + let bytes = try Data(contentsOf: executable) + let report = try AgentClientOperations.inspect(environment: environment) + #expect(report.pathCoverage.excludedEntries == ["", "relative"]) + #expect(report.pathCoverage.absoluteDirectories.map(\.path) == [first.path, second.path]) + let codex = try #require(report.clients.first { $0.agent == .codex }?.commands.first) + #expect(codex.location == first.appendingPathComponent("codex")) + #expect(codex.resolvedLocation == executable) + #expect(codex.version.unknownReason == .unrecognizedLayout) + let cursor = try #require(report.clients.first { $0.agent == .cursor }) + #expect( + cursor.commands.first { $0.role == .editorLauncher }?.location + == second.appendingPathComponent("cursor")) + #expect(cursor.commands.first { $0.role == .editorLauncher }?.version.rawVersion == "3.27-test") + #expect(cursor.commands.first { $0.role == .editorLauncher }?.version.build == "42") + #expect(cursor.commands.first { $0.name == "cursor-agent" }?.status == .notFound) + #expect(cursor.commands.first { $0.name == "cursor-agent" }?.version.rawVersion == nil) + #expect(!FileManager.default.fileExists(atPath: sentinel.path)) + #expect(try Data(contentsOf: executable) == bytes) + } + + @Test func pathSearchPermissionsAndExistingConfigurationRemainLocalObservations() throws { + let root = try fixture() + defer { try? FileManager.default.removeItem(at: root) } + let denied = root.appendingPathComponent("denied") + let bin = root.appendingPathComponent("bin") + let state = root.appendingPathComponent(".agents/transaction.json") + let configuration = root.appendingPathComponent(".codex/config.toml") + for directory in [ + denied, bin, state.deletingLastPathComponent(), configuration.deletingLastPathComponent(), + ] { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + } + let canary = Data("not configuration; never parse or recover".utf8) + try canary.write(to: state) + try canary.write(to: configuration) + let executable = bin.appendingPathComponent("codex") + try Data("never execute".utf8).write(to: executable) + try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: executable.path) + try FileManager.default.setAttributes([.posixPermissions: 0], ofItemAtPath: denied.path) + defer { + try? FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: denied.path) + } + let environment = RuntimeEnvironment( + projectDirectory: root, homeDirectory: root, + environment: ["PATH": "\(denied.path):\(bin.path)"]) + let report = try AgentClientOperations.inspect(environment: environment) + let command = try #require(report.clients.first { $0.agent == .codex }?.commands.first) + #expect(command.location == executable) + #expect( + command.lookupIssues.contains { $0.path.hasPrefix(denied.path) && $0.status == .inaccessible } + == (access(denied.path, X_OK) != 0) + ) + #expect( + report.clients.first { $0.agent == .codex }?.configurationLocations.contains { + $0.identity == "codex.mcp.user" && $0.status == .present + } == true) + #expect(try Data(contentsOf: state) == canary) + #expect(try Data(contentsOf: configuration) == canary) + #expect( + try FileManager.default.contentsOfDirectory(atPath: state.deletingLastPathComponent().path) + == ["transaction.json"]) + } + + @Test func ownerLocationsPreserveOverridesAlternativesAndSemanticRecords() throws { + let root = try fixture() + defer { try? FileManager.default.removeItem(at: root) } + var environment = RuntimeEnvironment( + projectDirectory: root.appendingPathComponent("project"), + homeDirectory: root.appendingPathComponent("home"), + environment: [ + "CODEX_HOME": root.appendingPathComponent("codex-override").path, + "CLAUDE_CONFIG_DIR": root.appendingPathComponent("claude-override").path, + "GEMINI_CLI_HOME": root.appendingPathComponent("gemini-native").path, + "OPENCODE_CONFIG_DIR": root.appendingPathComponent("opencode-native").path, + "XDG_CONFIG_HOME": root.appendingPathComponent("xdg").path, + ]) + let report = try AgentClientOperations.inspect(environment: environment) + let claude = try #require(report.clients.first { $0.agent == .claudeCode }) + let regions = claude.configurationLocations.filter { $0.identity.hasPrefix("claude.mcp.") } + #expect(regions.count == 2) + #expect(Set(regions.compactMap(\.location)).count == 1) + #expect(Set(regions.map(\.scope)) == ["local", "user"]) + let opencode = try #require(report.clients.first { $0.agent == .opencode }) + #expect( + opencode.configurationLocations.contains { + $0.location?.path == root.appendingPathComponent("opencode-native/opencode.jsonc").path + }) + #expect( + opencode.configurationLocations.contains { + $0.location?.path == root.appendingPathComponent("xdg/opencode/skills").path + }) + let codex = try #require(report.clients.first { $0.agent == .codex }) + #expect( + codex.configurationLocations.contains { + $0.identity == "codex.mcp.user" + && $0.location?.path == root.appendingPathComponent("codex-override/config.toml").path + }) + #expect( + codex.configurationLocations.contains { + $0.purpose == .instructions + && $0.location?.path == root.appendingPathComponent("codex-override/AGENTS.md").path + }) + let project = try AgentClientOperations.inspect(scope: .project, environment: environment) + #expect( + project.clients.first { $0.agent == .claudeCode }?.configurationLocations.contains { + $0.identity == "instructions.CLAUDE.local.md" + } == true) + environment.environment["CODEX_HOME"] = "relative" + let invalid = try AgentClientOperations.inspect(environment: environment) + #expect( + invalid.clients.first { $0.agent == .codex }?.configurationLocations.contains { + $0.identity == "codex.mcp.user" && $0.status == .invalid && $0.location == nil + && $0.diagnostic?.contains("CODEX_HOME") == true + } == true) + #expect(invalid.clients.first { $0.agent == .claudeCode }?.schemaEvidence.isEmpty == false) + #expect( + report.clients.first { $0.agent == .cursor }?.configurationLocations.contains { + $0.identity == "claudeAgent.user" + && $0.location?.path == root.appendingPathComponent("claude-override/agents").path + } == true) + #expect(try FileManager.default.contentsOfDirectory(atPath: root.path).isEmpty) + } +} diff --git a/Tests/AgentsUpdatesTests/AntigravityAdapterTests.swift b/Tests/AgentsUpdatesTests/AntigravityAdapterTests.swift new file mode 100644 index 0000000..d3065a7 --- /dev/null +++ b/Tests/AgentsUpdatesTests/AntigravityAdapterTests.swift @@ -0,0 +1,178 @@ +import AgentsCore +import AgentsSkills +import AgentsUpdates +import Foundation +import Testing + +struct AntigravityAdapterTests { + @Test(arguments: [InstallScope.project, .user]) + func namedHooksAndMCPMergeReplayAndRemove(_ scope: InstallScope) throws { + let f = try UpdateFixture(scope: scope) + let root = + scope == .project + ? f.root.appendingPathComponent(".agents") + : f.environment.homeDirectory.appendingPathComponent(".gemini/config") + let hooks = root.appendingPathComponent("hooks.json") + let mcp = root.appendingPathComponent("mcp_config.json") + let handwrittenHook = #""" + "local-hook": {"SessionStart":[{"command":"never-run-local"}]} + """# + let handwrittenServer = #""" + "local-server": {"command":"never-run-local"} + """# + let originalHooks = "{\n \(handwrittenHook)\n}\n" + let originalMCP = + "{\n \"settings\": {\"keep\": true}, \"mcpServers\": {\n \(handwrittenServer)\n }\n}\n" + try f.write(originalHooks, to: hooks) + try f.write(originalMCP, to: mcp) + let events = [ + "SessionStart", "PreToolUse", "PostToolUse", "PreInvocation", "PostInvocation", "Stop", + ] + let handlers: [ComponentDeclaration] = events.map { event in + .hook( + name: "managed-" + event, event: .native(event), + run: .init(executable: "never-run", arguments: ["two words", "it's literal"]), + matcher: event.hasSuffix("ToolUse") ? "run_command|view_file" : nil, + timeoutSeconds: 8, agents: [.antigravity], condition: .init(scopes: [scope]), + native: ["antigravity": ["enabled": .boolean(false)]]) + } + let components = + handlers + [ + .mcpServer( + name: "managed-http", + transport: .streamableHTTP( + url: "https://fixture.invalid/mcp", headers: ["X-Profile": .literal("compact")]), + agents: [.antigravity]), + .mcpServer( + name: "managed-stdio", + transport: .stdio( + .init( + executable: "never-run", arguments: ["--test"], + environment: ["MODE": .literal("fixture")])), + agents: [.antigravity]), + ] + let excluded = ComponentDeclaration.hook( + name: "other-scope", event: .native("Stop"), run: .init(executable: "never-run"), + agents: [.antigravity], condition: .init(scopes: [scope == .project ? .user : .project])) + try f.store.save(declaration: .init(components: components + [excluded]), ledger: .init()) + let preview = try f.preview() + #expect(preview.components.count == components.count) + #expect(try f.bytes(hooks) == Data(originalHooks.utf8)) + #expect(try f.bytes(mcp) == Data(originalMCP.utf8)) + try UpdateOperations.withPreparedUpdate(scope: scope, environment: f.environment) { + _ = try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + let installedHooks = try f.bytes(hooks) + let installedMCP = try f.bytes(mcp) + #expect(String(decoding: installedHooks, as: UTF8.self).contains(handwrittenHook)) + #expect(String(decoding: installedMCP, as: UTF8.self).contains(handwrittenServer)) + let hookDocument = try json(installedHooks) + #expect(hookDocument["other-scope"] == nil) + for event in events { + let definition = try #require(hookDocument["managed-" + event] as? [String: Any]) + #expect(definition["enabled"] as? Bool == false) + let outer = try #require((definition[event] as? [[String: Any]])?.first) + let handler: [String: Any] + if event.hasSuffix("ToolUse") { + #expect(outer["matcher"] as? String == "run_command|view_file") + handler = try #require((outer["hooks"] as? [[String: Any]])?.first) + } else { + handler = outer + } + #expect(handler["type"] as? String == "command") + #expect(handler["timeout"] as? Int == 8) + #expect(handler["command"] as? String == #"'never-run' 'two words' 'it'\''s literal'"#) + } + let servers = try #require(try json(installedMCP)["mcpServers"] as? [String: [String: Any]]) + #expect(servers["managed-http"]?["serverUrl"] as? String == "https://fixture.invalid/mcp") + #expect(servers["managed-http"]?["headers"] as? [String: String] == ["X-Profile": "compact"]) + #expect(servers["managed-stdio"]?["args"] as? [String] == ["--test"]) + #expect(servers["managed-stdio"]?["env"] as? [String: String] == ["MODE": "fixture"]) + + let installed = try UpdateOperations.inspect(scope: scope, environment: f.environment) + #expect(installed.deployments.count == components.count) + #expect(installed.deployments.allSatisfy { $0.status == .current }) + let locked = try f.bytes(f.store.resolvedURL) + try f.write(originalHooks, to: hooks) + try f.write(originalMCP, to: mcp) + _ = try UpdateOperations.restore(scope: scope, environment: f.environment) + #expect(try f.bytes(hooks) == installedHooks) + #expect(try f.bytes(mcp) == installedMCP) + #expect(try f.bytes(f.store.resolvedURL) == locked) + _ = try UpdateOperations.withPreparedUpdate( + .init(operation: .remove, selections: installed.components.map(\.selection)), + scope: scope, environment: f.environment + ) { try $0.apply() } + let remainingHooks = try f.bytes(hooks) + let remainingMCP = try f.bytes(mcp) + #expect(try Set(json(remainingHooks).keys) == ["local-hook"]) + #expect(String(decoding: remainingHooks, as: UTF8.self).contains(handwrittenHook)) + #expect( + try (json(remainingMCP)["mcpServers"] as? [String: Any])?.keys.sorted() == ["local-server"]) + #expect(String(decoding: remainingMCP, as: UTF8.self).contains(handwrittenServer)) + #expect(try (json(remainingMCP)["settings"] as? [String: Bool])?["keep"] == true) + } + + @Test func workspaceSkillRetainsSharedPhysicalInstallationUntilLastRecipient() throws { + let f = try UpdateFixture() + let sibling = f.root.appendingPathComponent(".agents/skills/handwritten/SKILL.md") + try f.write("---\nname: handwritten\ndescription: Fixture.\n---\nHandwritten.\n", to: sibling) + let handwritten = try f.bytes(sibling) + let agents: [AgentID] = [.antigravity, .codex] + _ = try SkillOperations.add( + .init(source: f.repo.path, agents: agents, environment: f.environment)) + let target = f.root.appendingPathComponent(".agents/skills/demo/SKILL.md") + #expect(FileManager.default.fileExists(atPath: target.path)) + _ = try SkillOperations.remove( + skillNames: ["demo"], agents: [.antigravity], environment: f.environment) + #expect(try f.store.loadResolved().skills["demo"]?.installs.keys.sorted() == ["codex"]) + #expect(FileManager.default.fileExists(atPath: target.path)) + _ = try SkillOperations.remove( + skillNames: ["demo"], agents: [.codex], environment: f.environment) + #expect(!FileManager.default.fileExists(atPath: target.path)) + #expect(try f.bytes(sibling) == handwritten) + } + + @Test func unsupportedTranslationsAndNamedOwnerCollisionsReportBeforePublication() throws { + let f = try UpdateFixture() + let file = f.root.appendingPathComponent(".agents/hooks.json") + let handwritten = #"{"check":{"Stop":[{"command":"never-run-local"}]}}"# + try f.write(handwritten, to: file) + func hook( + _ event: HookEventDeclaration, executable: String = "never-run", matcher: String? = nil + ) + -> ComponentDeclaration + { + .hook( + name: "check", event: event, run: .init(executable: executable), matcher: matcher, + agents: [.antigravity]) + } + func rejection(_ components: [ComponentDeclaration], contains text: String) throws { + try f.store.save(declaration: .init(components: components), ledger: .init()) + do { + _ = try f.preview() + Issue.record("Expected planning to reject \(text)") + } catch { + #expect(String(describing: error).localizedCaseInsensitiveContains(text)) + } + #expect(try f.bytes(file) == Data(handwritten.utf8)) + } + try rejection([hook(.native("Stop"), matcher: "*")], contains: "ignores matchers") + try rejection([hook(.sessionEnd)], contains: "explicit native event") + try rejection([hook(.native("SessionEnd"))], contains: "absent from") + try rejection( + [ + .mcpServer( + name: "legacy", transport: .sse(url: "https://fixture.invalid/sse"), + agents: [.antigravity]) + ], contains: "requires Streamable HTTP") + try rejection( + [hook(.native("Stop")), hook(.native("Stop"), executable: "different")], + contains: "conflict") + try rejection([hook(.native("Stop"))], contains: "ownership does not match") + } + + private func json(_ data: Data) throws -> [String: Any] { + try #require(try JSONSerialization.jsonObject(with: data) as? [String: Any]) + } +} diff --git a/Tests/AgentsUpdatesTests/AntigravityInstructionTests.swift b/Tests/AgentsUpdatesTests/AntigravityInstructionTests.swift new file mode 100644 index 0000000..284a1e4 --- /dev/null +++ b/Tests/AgentsUpdatesTests/AntigravityInstructionTests.swift @@ -0,0 +1,380 @@ +import AgentsCore +import AgentsInstructions +import AgentsManifest +import AgentsUpdates +import Foundation +import Testing + +struct AntigravityInstructionTests { + private let ruleDirectory = ".gemini/config/rules" + private let memexPath = ".agent/instructions/general/managed.md" + + @Test func installsOnlySelectedGlobalRulesAndRestoresLockedReferenceBytes() throws { + let f = try UpdateFixture(scope: .user) + try f.write( + """ + --- + description: A separate rule. + --- + + # Modular + + @[Shared](../includes/shared.md) + """, to: f.repo.appendingPathComponent("instructions/modular.md")) + let includes = f.repo.appendingPathComponent("includes") + try f.write( + "---\ndescription: Included frontmatter.\n---\nLocked @[body](body.txt).", + to: includes.appendingPathComponent("shared.md")) + let body = includes.appendingPathComponent("body.txt") + try f.write("nested content. Notify @reviewer and open @guide.md or `@./code.md`", to: body) + try f.commit() + try f.write( + """ + version: 1 + sources: + fixture: {path: \(f.repo.path.debugDescription)} + components: + - kind: instructions + agents: [codex, gemini-cli, antigravity] + sections: + - {source: fixture, name: rules, condition: {agents: [codex, gemini-cli]}} + - {source: fixture, name: modular, condition: {agents: [antigravity]}} + """, to: f.store.declarationURL) + let rules = f.environment.homeDirectory.appendingPathComponent(ruleDirectory) + let personal = rules.appendingPathComponent("handwritten.md") + try f.write("Handwritten rule", to: personal) + let preview = try f.preview() + let rule = try #require(preview.instructions.targets.first { $0.afterAgents == [.antigravity] }) + #expect(rule.url.deletingLastPathComponent().path == rules.path) + #expect(preview.instructions.advisories.contains { $0.contains("20,000-token") }) + #expect(preview.instructions.conflicts.isEmpty) + #expect(!FileManager.default.fileExists(atPath: rule.url.path)) + let output = try #require(rule.after) + let text = String(decoding: output, as: UTF8.self) + #expect(text.hasPrefix("---\ntrigger: always_on\n")) + #expect(text.contains("Locked nested content.")) + #expect(text.contains("Notify @reviewer and open @guide.md or `@./code.md`")) + #expect(!text.contains("Included frontmatter")) + #expect(!text.contains("# Rules")) + try apply(f, preview: preview) + let legacy = try f.bytes(f.instruction(.geminiCLI)) + #expect(String(decoding: legacy, as: UTF8.self).contains("# Rules")) + #expect(!String(decoding: legacy, as: UTF8.self).contains("# Modular")) + #expect(try f.bytes(personal) == Data("Handwritten rule".utf8)) + #expect(!(try f.preview()).hasChanges) + let lock = try f.store.loadLedger() + let deployment = try #require(lock.deployments.first { $0.recipients == [.antigravity] }) + let owner = try #require(deployment.owners.first.flatMap { lock.components[$0] }) + #expect(deployment.owners.count == 1) + #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 }) + + try f.write("new upstream bytes", to: body) + try f.commit() + try FileManager.default.removeItem(at: rule.url) + #expect(try doctor(f).diagnostics.contains { $0.kind == .missingTarget && $0.path == rule.url }) + let restored = try InstructionOperations.installResolvedReport( + scope: .user, environment: f.environment) + #expect(restored.targets.contains { $0.target == rule.target && $0.changed }) + #expect(try f.bytes(rule.url) == output) + #expect(try f.bytes(f.instruction(.geminiCLI)) == legacy) + let inspection = try UpdateOperations.inspect(scope: .user, environment: f.environment) + #expect( + inspection.deployments.contains { $0.location.path == rule.url.path && $0.status == .current } + ) + let mapping = InstructionOperations.export(projectRoots: [], environment: f.environment) + #expect( + mapping[0].targets.first { $0.target == rule.target }?.sections.map(\.name) == ["modular"]) + try (output + Data("Changed contents.\n".utf8)).write(to: rule.url) + #expect(try doctor(f).diagnostics.contains { $0.kind == .drift && $0.path == rule.url }) + } + + @Test func exactByteLimitIncludesDescriptionAndMultibyteExpansion() throws { + let f = try UpdateFixture(scope: .user) + let file = f.repo.appendingPathComponent("instructions/rules.md") + let include = f.repo.appendingPathComponent("instructions/content.txt") + try f.write("---\ndescription: Boundary.\n---\n\n# Limit\n\n@[size](content.txt)\n", to: file) + try f.write("x", to: include) + try f.commit() + try declare(f, name: "rules") + let sample = try #require(f.preview().instructions.targets.first?.after) + let budget = 24_000 - sample.count + 1 + let body = String(repeating: "界", count: budget / 3) + String(repeating: "x", count: budget % 3) + try f.write(body, to: include) + try f.commit() + let exact = try f.preview() + #expect(exact.instructions.targets.first?.after?.count == 24_000) + let before = try f.bytes(f.store.resolvedURL) + try f.write(body + "x", to: include) + try f.commit() + do { + _ = try f.preview() + Issue.record("accepted 24,001 bytes") + } catch { + #expect(String(describing: error).contains("agents-rules-")) + #expect(String(describing: error).contains("24001 UTF-8 bytes")) + #expect(String(describing: error).contains("limit 24000 bytes")) + } + #expect(try f.bytes(f.store.resolvedURL) == before) + } + + @Test func adoptsExactMemexBytesAndRejectsStalePreview() throws { + let f = try UpdateFixture(scope: .user) + let legacy = try seedMemex(f) + let before = try f.bytes(legacy) + let initial = try f.preview() + #expect(initial.instructions.conflicts.isEmpty) + #expect( + initial.instructions.targets.contains { + $0.url == legacy && $0.before == before && $0.after == nil + }) + let rule = try #require(initial.instructions.targets.first { $0.afterAgents == [.antigravity] }) + // Replacement with the same bytes changes the file generation. + try before.write(to: legacy, options: .atomic) + #expect(throws: UpdateApplyError.self) { try apply(f, preview: initial) } + #expect(try f.bytes(legacy) == before) + #expect(!FileManager.default.fileExists(atPath: rule.url.path)) + + try apply(f, preview: f.preview()) + #expect(!FileManager.default.fileExists(atPath: legacy.path)) + #expect(try f.bytes(rule.url) == rule.after) + #expect(!(try f.preview()).hasChanges) + let removed = try InstructionOperations.remove( + names: ["general/managed"], scope: .user, environment: f.environment) + let removal = try #require(removed.targets.first { $0.target == rule.target }) + #expect(removal.beforeAgents == [.antigravity] && removal.afterAgents.isEmpty) + #expect(removal.after == nil && removal.changed && !removal.foreign && removal.drift == .clean) + #expect(!FileManager.default.fileExists(atPath: rule.url.path)) + } + + @Test func interruptedMemexMigrationRollsBackBothFilesAndLock() throws { + let f = try UpdateFixture(scope: .user) + let legacy = try seedMemex(f) + let preview = try f.preview() + let rule = try #require(preview.instructions.targets.first { $0.afterAgents == [.antigravity] }) + let legacyBytes = try f.bytes(legacy) + let lock = try f.bytes(f.store.resolvedURL) + var interrupted = false + let result = UpdateOperations.perform( + scope: .user, environment: f.environment, + checkpoint: { step in + if step.contains(".applied"), FileManager.default.fileExists(atPath: rule.url.path), + !FileManager.default.fileExists(atPath: legacy.path) + { + interrupted = true + throw CoreError.invalidState("fixture interrupted after moving the Memex rule") + } + }, { try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) }) + #expect(interrupted) + #expect(result.disposition == .rolledBack) + #expect(!result.recovery.pending) + #expect(try f.bytes(legacy) == legacyBytes) + #expect(try f.bytes(f.store.resolvedURL) == lock) + #expect(!FileManager.default.fileExists(atPath: rule.url.path)) + } + + @Test func refusesMemexMismatchAndDestinationCollisionEvenWithReplace() throws { + let f = try UpdateFixture(scope: .user) + let legacy = try seedMemex(f) + let altered = try f.bytes(legacy) + Data("Personal edits\n".utf8) + try altered.write(to: legacy) + let preview = try f.preview() + let rule = try #require(preview.instructions.targets.first { $0.afterAgents == [.antigravity] }) + #expect(preview.instructions.conflicts.contains { $0.contains(legacy.lastPathComponent) }) + #expect(throws: UpdateApplyError.self) { try apply(f, preview: preview) } + #expect(try f.bytes(legacy) == altered) + #expect(!FileManager.default.fileExists(atPath: rule.url.path)) + + try FileManager.default.removeItem(at: legacy) + try f.write("Handwritten collision", to: rule.url) + let replace = UpdateRequest(kinds: [.instructions], replace: true) + let collision = try UpdateOperations.preview(replace, scope: .user, environment: f.environment) + #expect(collision.instructions.targets.first?.foreign == true) + #expect(collision.instructions.conflicts.contains { $0.contains(rule.url.lastPathComponent) }) + #expect(throws: UpdateApplyError.self) { try apply(f, request: replace, preview: collision) } + #expect(try f.bytes(rule.url) == Data("Handwritten collision".utf8)) + } + + @Test func refusesUnresolvedReferencesAndSymlinkedRulesDirectory() throws { + let f = try UpdateFixture(scope: .user) + let input = f.repo.appendingPathComponent("instructions/rules.md") + try declare(f, name: "rules") + for test in ["@[missing](absent.md)", "@[escape](../../outside.md)", "@[incomplete]("] { + try f.write("---\ndescription: Rules.\n---\n# Rule\n\n" + test, to: input) + try f.commit() + #expect(throws: (any Error).self) { try f.preview() } + } + try f.write("---\ndescription: Rules.\n---\n# Rule\n", to: input) + try f.commit() + let outside = f.root.appendingPathComponent("outside-rules") + let rules = f.environment.homeDirectory.appendingPathComponent(ruleDirectory) + for directory in [outside, rules.deletingLastPathComponent()] { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + } + try FileManager.default.createSymbolicLink(at: rules, withDestinationURL: outside) + #expect(throws: (any Error).self) { try f.preview() } + #expect(try FileManager.default.contentsOfDirectory(atPath: outside.path).isEmpty) + } + + @Test func projectRulesRequireOptInAndUseNativeGlobs() throws { + let f = try UpdateFixture() + let source = f.repo.appendingPathComponent("instructions/rules.md") + try f.write( + """ + --- + description: Scoped rules. + paths: ["Sources/**/*.swift", "Tests/*.swift"] + --- + # Rule + + Project rules. + """, to: source) + try f.commit() + try declare(f, name: "rules", agents: nil) + #expect( + try f.preview().instructions.targets.allSatisfy { !$0.afterAgents.contains(.antigravity) }) + + try declare(f, name: "rules") + let native = f.root.appendingPathComponent(".agents/rules") + let handwritten = native.appendingPathComponent("handwritten.md") + try f.write("# Handwritten rule\n", to: handwritten) + let preview = try f.preview() + let rule = try #require(preview.instructions.targets.first { $0.afterAgents == [.antigravity] }) + let installed = rule.url + #expect(installed.deletingLastPathComponent().path == native.resolvingSymlinksInPath().path) + #expect(!FileManager.default.fileExists(atPath: installed.path)) + try UpdateOperations.withPreparedUpdate(environment: f.environment) { + _ = try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + let expected = try f.bytes(installed) + let text = String(decoding: expected, as: UTF8.self) + #expect(text.contains(#"globs: "Sources/**/*.swift, Tests/*.swift""#)) + #expect(text.contains("trigger: glob")) + #expect( + !FileManager.default.fileExists(atPath: f.root.appendingPathComponent("AGENTS.md").path)) + try FileManager.default.removeItem(at: installed) + _ = try UpdateOperations.restore(environment: f.environment) + #expect(try f.bytes(installed) == expected) + _ = try InstructionOperations.remove( + names: ["rules"], agents: [.antigravity], environment: f.environment) + #expect(!FileManager.default.fileExists(atPath: installed.path)) + #expect(try f.bytes(handwritten) == Data("# Handwritten rule\n".utf8)) + } + + @Test func addPreservesSiblingRecipientsAndSeparatesSameNamedSections() throws { + let f = try UpdateFixture(scope: .user) + try declare(f, name: "rules", agents: [.codex, .geminiCLI]) + _ = try f.apply() + let before = try f.bytes(f.instruction(.codex)) + let second = try UpdateFixture() + let firstAdd = try InstructionOperations.add( + InstructionAddOptions( + source: f.repo.path, names: ["rules"], agents: [.antigravity, .codex], + scope: .user, environment: f.environment)) + let firstRule = try #require( + firstAdd.result?.targets.first { $0.afterAgents == [.antigravity] }) + #expect(try doctor(f).diagnostics.allSatisfy { $0.kind != .invalidTarget }) + let secondAdd = try InstructionOperations.add( + InstructionAddOptions( + source: second.repo.path, alias: "second", names: ["rules"], + agents: [.antigravity], scope: .user, environment: f.environment)) + let secondRules = try #require( + secondAdd.result?.targets.filter { $0.afterAgents == [.antigravity] }) + #expect(secondRules.count == 2) + #expect(Set(secondRules.map(\.target)).count == 2) + #expect(secondRules.contains { $0.target == firstRule.target && !$0.changed }) + #expect(try f.bytes(f.instruction(.codex)) == before) + #expect(try f.bytes(f.instruction(.geminiCLI)) == before) + } + + @Test func addingExplicitAliasPreservesBothDiscoveryRootsAndLegacyTarget() throws { + let f = try UpdateFixture(scope: .user) + for root in ["first", "second"] { + try f.write( + "---\ndescription: Review.\n---\n# Review\n\n\(root) instructions.\n", + to: f.repo.appendingPathComponent(root + "/instructions/review.md")) + } + try f.commit() + let a = SourceDeclaration(kind: .local, location: f.repo.path, path: "first") + let b = SourceDeclaration(kind: .local, location: f.repo.path, path: "second") + let sameRoot = SourceDeclaration(kind: .local, location: f.repo.path, path: "./first") + #expect(throws: CoreError.self) { + try Declaration(sources: ["a": a, "duplicate": sameRoot]).validate(environment: f.environment) + } + try f.store.save( + declaration: Declaration( + sources: ["a": a, "b": b], + instructions: .init(agents: [.codex], sections: ["a:review"])), + ledger: ResolvedLedger()) + _ = try f.apply() + let codex = try f.bytes(f.instruction(.codex)) + for source in ["b", f.repo.path + "@path:second"] { + let addition = try InstructionOperations.add( + .init( + source: source, names: ["review"], agents: [.antigravity], + scope: .user, environment: f.environment)) + let rule = try #require(addition.result?.targets.first { $0.afterAgents == [.antigravity] }) + #expect( + String(decoding: try #require(rule.after), as: UTF8.self).contains("second instructions.")) + #expect(try f.bytes(f.instruction(.codex)) == codex) + let declaration = try f.store.loadDeclaration() + #expect( + declaration.sources["a"]?.path == "first" && declaration.sources["b"]?.path == "second") + let references = declaration.components.flatMap { component -> [String] in + guard case .instructions(let instructions) = component else { return [] } + return instructions.sectionReferences.map(\.reference) + } + #expect(references == ["a:review", "b:review"]) + } + } + + private func declare( + _ f: UpdateFixture, name: String, agents: [AgentID]? = [.antigravity], subpath: String? = nil + ) throws { + try f.store.save( + declaration: Declaration( + sources: ["fixture": SourceDeclaration(kind: .local, location: f.repo.path, path: subpath)], + instructions: InstructionsDeclaration(agents: agents, sections: ["fixture:" + name])), + ledger: ResolvedLedger()) + } + + private func seedMemex(_ f: UpdateFixture) throws -> URL { + try f.write( + "---\ndescription: Managed.\n---\n\n# Managed\n\nPinned contents.\n", + to: f.repo.appendingPathComponent(memexPath)) + try f.commit() + let revision = try f.git(["rev-parse", "HEAD"]) + let legacy = f.environment.homeDirectory.appendingPathComponent( + ruleDirectory + "/memex-managed.md") + try f.write( + """ + --- + trigger: always_on + description: "Managed." + --- + + + + # Managed + + Pinned contents. + + """, to: legacy) + try declare(f, name: "general/managed", subpath: ".agent") + return legacy + } + + private func doctor(_ f: UpdateFixture) throws -> InstructionDoctorReport { + try InstructionOperations.doctor(scope: .user, environment: f.environment) + } + + private func apply( + _ f: UpdateFixture, request: UpdateRequest = UpdateRequest(), preview: CombinedUpdateReport + ) throws { + _ = try UpdateOperations.withPreparedUpdate(request, scope: .user, environment: f.environment) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + } +} diff --git a/Tests/AgentsUpdatesTests/AuthorLockedPackageTests.swift b/Tests/AgentsUpdatesTests/AuthorLockedPackageTests.swift new file mode 100644 index 0000000..f38da27 --- /dev/null +++ b/Tests/AgentsUpdatesTests/AuthorLockedPackageTests.swift @@ -0,0 +1,153 @@ +import AgentsCore +import AgentsUpdates +import Foundation +import Testing + +@Suite("Author locked dependencies") +struct AuthorLockedPackageTests { + @Test func packsMixedEmbeddedAndGitResourcesWithTheCatalogUnavailable() throws { + let fixture = try UpdateFixture() + let vendorProject = fixture.root.appendingPathComponent("vendor") + var vendorEnvironment = fixture.environment + vendorEnvironment.projectDirectory = vendorProject + let catalog = fixture.root.appendingPathComponent("catalog") + try FileManager.default.createDirectory(at: catalog, withIntermediateDirectories: false) + let origin = try MarketplaceOrigin(kind: .directory, location: catalog.path) + for package in [ + BundlePackage(name: "leaf", version: "1.0.0"), + try BundlePackage( + name: "starter", version: "1.0.0", + dependencies: [.init(package: "leaf", requirement: .exact("1.0.0"))]), + ] { + let project = vendorProject.appendingPathComponent(package.name) + try FileManager.default.createDirectory(at: vendorProject, withIntermediateDirectories: true) + vendorEnvironment.projectDirectory = project + try AuthorPackageOperations.scaffold(package, at: project, environment: vendorEnvironment) + let artifact = try AuthorPackageOperations.preview(environment: vendorEnvironment) + try AuthorPackageOperations.publish(artifact, to: catalog, environment: vendorEnvironment) + } + try fixture.install(agents: [.codex]) + let root = try MarketplaceRoot( + name: "vendor", catalog: origin, package: "starter", requirement: .exact("1.0.0"), + selections: [ + .init( + package: "starter", member: .init(kind: .skills, name: "getting-started"), + targets: [.codex]) + ]) + let resolution = try MarketplaceOperations.previewResolution( + .install(root), environment: fixture.environment) + _ = try MarketplaceOperations.withPreparedResolution(resolution) { try $0.apply() } + let ledger = try fixture.store.loadLedger() + #expect(ledger.resources.values.contains { $0.kind == .git }) + #expect(ledger.resources.values.contains { $0.kind == .embedded }) + let spec = AuthorPackageSpecification( + package: .init(name: "mixed", version: "2.0.0"), + lockedMembers: [ + .init(kind: .skills, name: "getting-started"), .init(kind: .instructions, name: "rules"), + ]) + try FileManager.default.removeItem(at: catalog) + let before = try FileHash.folderHash(fixture.root) + let artifact = try AuthorPackageOperations.preview(spec, environment: fixture.environment) + #expect(try FileHash.folderHash(fixture.root) == before) + #expect(Set(artifact.inspection.components.map(\.name)) == ["getting-started", "rules"]) + let skill = try #require(artifact.inspection.components.first { $0.kind == .skills }) + #expect(Set(skill.sources.compactMap(\.packageName)) == ["starter", "leaf"]) + #expect(!String(decoding: artifact.archive, as: UTF8.self).contains(fixture.root.path)) + let consumer = try UpdateFixture() + let assignment = BundleImportSelection(componentID: skill.id, targets: [.codex]) + let preview = try BundleOperations.previewImport( + artifact.inspection, selections: [assignment], scope: .project, + environment: consumer.environment) + _ = try BundleOperations.withPreparedImport(preview) { try $0.apply() } + let installed = try UpdateOperations.inspect(environment: consumer.environment) + #expect(installed.components.map(\.name) == ["getting-started"]) + + let policy = fixture.root.appendingPathComponent("org.yaml") + var denied = fixture.environment + denied.userOrganizationPolicy = .init(.local(policy)) + try fixture.write("enforcement: block\ndependencies: {deny: ['_local/leaf']}", to: policy) + do { + _ = try AuthorPackageOperations.preview(spec, environment: denied) + Issue.record("Transitive package was not denied.") + } catch let error as OrganizationPolicyFailure { + #expect( + error.report.findings.contains { $0.rule == "package-deny" && $0.identity == "_local/leaf" } + ) + } + let output = fixture.root.appendingPathComponent("denied.bundle") + #expect(throws: OrganizationPolicyFailure.self) { + try AuthorPackageOperations.write(artifact, to: output, environment: denied) + } + #expect(!FileManager.default.fileExists(atPath: output.path)) + } + + @Test func missingOrTamperedLockAndLiveDependenciesCannotBePacked() throws { + let fixture = try UpdateFixture() + let spec = AuthorPackageSpecification( + package: .init(name: "offline", version: "1.0.0"), + lockedMembers: [.init(kind: .skills, name: "demo")]) + #expect(throws: CoreError.self) { + try AuthorPackageOperations.preview(spec, environment: fixture.environment) + } + try fixture.install(mode: .edit, agents: [.codex]) + #expect(throws: CoreError.self) { + try AuthorPackageOperations.preview(spec, environment: fixture.environment) + } + + let embedded = try UpdateFixture() + let publisher = try AuthorPackageOperations.preview( + .init(package: .init(name: "fixture", version: "1.0.0"), skills: ["source/skills/demo"]), + environment: embedded.environment) + let consumer = try UpdateFixture() + let selection = try #require(publisher.inspection.components.first) + let preview = try BundleOperations.previewImport( + publisher.inspection, selections: [.init(componentID: selection.id, targets: [.codex])], + scope: .project, environment: consumer.environment) + _ = try BundleOperations.withPreparedImport(preview) { try $0.apply() } + let ledger = try consumer.store.loadLedger() + let id = try #require(ledger.contentObjects.keys.sorted().first) + let before = try consumer.bytes(consumer.store.resolvedURL) + var document = try #require(JSONSerialization.jsonObject(with: before) as? [String: Any]) + var objects = try #require(document["contentObjects"] as? [String: String]) + objects[id] = Data("tampered dependency".utf8).base64EncodedString() + document["contentObjects"] = objects + try JSONSerialization.data( + withJSONObject: document, options: [.sortedKeys, .withoutEscapingSlashes] + ) + .write(to: consumer.store.resolvedURL) + let tampered = try consumer.bytes(consumer.store.resolvedURL) + #expect(throws: (any Error).self) { + try AuthorPackageOperations.preview(spec, environment: consumer.environment) + } + #expect(try consumer.bytes(consumer.store.resolvedURL) == tampered) + } + + @Test func sameLengthChangesToACachedGitFileRejectTheCapturedBytes() throws { + let fixture = try UpdateFixture() + try fixture.install(agents: [.codex]) + let spec = AuthorPackageSpecification( + package: .init(name: "offline-git", version: "1.0.0"), + lockedMembers: [.init(kind: .instructions, name: "rules")]) + _ = try AuthorPackageOperations.preview(spec, environment: fixture.environment) + let ledger = try fixture.store.loadLedger() + let resource = try #require( + ledger.resources.values.first { + $0.kind == .git && $0.path == "instructions/rules.md" + }) + let source = try #require(ledger.sources[resource.source]) + let identity = try ledger.sourceIdentity( + resource.source, roots: fixture.store.ledgerRoots(recordedIn: ledger)) + let cached = SourceCache(store: fixture.store) + .materializedURL(sourceID: identity, revision: source.revision) + .appendingPathComponent(resource.path) + let original = try fixture.bytes(cached) + var tampered = original + tampered[tampered.startIndex] ^= 1 + try FileManager.default.setAttributes([.posixPermissions: 0o644], ofItemAtPath: cached.path) + try tampered.write(to: cached) + #expect(throws: CoreError.self) { + try AuthorPackageOperations.preview(spec, environment: fixture.environment) + } + #expect(try fixture.bytes(cached) == tampered) + } +} diff --git a/Tests/AgentsUpdatesTests/AuthorPackageTests.swift b/Tests/AgentsUpdatesTests/AuthorPackageTests.swift new file mode 100644 index 0000000..f820409 --- /dev/null +++ b/Tests/AgentsUpdatesTests/AuthorPackageTests.swift @@ -0,0 +1,403 @@ +import AgentsCore +import AgentsUpdates +import Foundation +import Testing + +@Suite("Author project packaging") +struct AuthorPackageTests { + private let package = BundlePackage( + name: "workbench", version: "1.0.0", description: "Author fixture description", + author: "Fixture Author") + + @Test func freshScaffoldPacksExplicitSourceWithoutInstallationAndRelocates() throws { + let fixture = try UpdateFixture() + let project = fixture.root.appendingPathComponent("author-one") + let environment = authorEnvironment(fixture, project: project) + let scaffold = try AuthorPackageOperations.scaffold( + package, at: project, environment: environment) + #expect(scaffold.skills == ["skills/getting-started"]) + #expect( + try AuthorPackageOperations.scaffold(package, at: project, environment: environment) + == scaffold) + let original = try AuthorPackageOperations.preview(environment: environment) + #expect(original.inspection.components.map(\.name) == ["getting-started"]) + let skill = project.appendingPathComponent(scaffold.skills[0]) + try fixture.write("Do not include\n", to: project.appendingPathComponent(".env")) + try fixture.write("Draft\n", to: project.appendingPathComponent(".agent/instructions/draft.md")) + try fixture.write( + "An invisible\u{200B} character\n", to: skill.appendingPathComponent("notes.txt")) + let script = skill.appendingPathComponent("scripts/run") + try fixture.write("#!/bin/sh\nexit 99\n", to: script) + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: script.path) + try FileManager.default.createSymbolicLink( + atPath: skill.appendingPathComponent("notes-link").path, withDestinationPath: "notes.txt") + try FileManager.default.createDirectory( + at: skill.appendingPathComponent("empty"), withIntermediateDirectories: false) + try fixture.write( + "Reference bytes\n", to: project.appendingPathComponent(".agent/instructions/attachment.txt")) + try fixture.write( + "---\ndescription: Fixture rules\n---\n# Rules\n\n[Attachment](attachment.txt)\n", + to: project.appendingPathComponent(".agent/instructions/rules.md")) + try fixture.write( + """ + version: 1 + components: + - kind: mcpServer + name: docs + transport: + kind: stdio + executable: never-launch-this-program + arguments: [serve, --token, fixture-literal, --mode=single] + environment: + REGION: {env: REGION} + TOKEN: {secret: docs-token} + """, + to: project.appendingPathComponent(".agent/agents.yaml")) + let specification = AuthorPackageSpecification( + package: package, instructions: ["rules"], skills: scaffold.skills, mcpServers: ["docs"]) + try JSONEncoder().encode(specification).write( + to: project.appendingPathComponent(AuthorPackageOperations.specificationFilename)) + let before = try FileHash.folderHash(fixture.root) + let captured = try AuthorPackageOperations.preview(environment: environment) + #expect(try FileHash.folderHash(fixture.root) == before) + #expect(captured.digest != original.digest) + #expect(captured.inspection.components.map(\.name) == ["rules", "getting-started", "docs"]) + #expect( + captured.includedPaths.contains { $0.entry.path == "payload/instructions/attachment.txt" }) + #expect( + captured.includedPaths.contains { + $0.entry.path == "payload/skill/scripts/run" && $0.entry.executable + }) + #expect( + captured.includedPaths.contains { + $0.entry.path == "payload/skill/empty" && $0.entry.kind == .directory + }) + #expect(captured.includedPaths.contains { $0.entry.link == "notes.txt" }) + #expect( + !captured.includedPaths.contains { + $0.entry.path.contains("draft.md") || $0.entry.path.contains(".env") + }) + #expect( + captured.contentFindings.contains { + $0.reason == .zeroWidthCharacter && $0.location.path.hasSuffix("notes.txt") + }) + #expect(captured.warnings.count == 1 && captured.warnings[0].count == 2) + let wire = String(decoding: captured.archive, as: UTF8.self) + #expect( + wire.contains("docs-token") && wire.contains("REGION") && wire.contains("--mode=single")) + #expect(!wire.contains("fixture-literal") && !wire.contains(project.path)) + #expect( + !FileManager.default.fileExists( + atPath: project.appendingPathComponent(".agent/agents.resolved").path)) + let relocated = fixture.root.appendingPathComponent("author-two") + try FileManager.default.moveItem(at: project, to: relocated) + let restored = try AuthorPackageOperations.rebuild( + expectedDigest: captured.digest, environment: authorEnvironment(fixture, project: relocated)) + #expect(restored.archive == captured.archive) + } + + @Test func capturedAndExplicitlyReadArchivesPublishIdenticalBytesAfterDrift() throws { + let fixture = try UpdateFixture() + let project = fixture.root.appendingPathComponent("author") + let environment = authorEnvironment(fixture, project: project) + try AuthorPackageOperations.scaffold(package, at: project, environment: environment) + let capture = try AuthorPackageOperations.preview(environment: environment) + let file = fixture.root.appendingPathComponent("reviewed.bundle") + try AuthorPackageOperations.write(capture, to: file, environment: environment) + try AuthorPackageOperations.write(capture, to: file, environment: environment) + #expect(try fixture.bytes(file) == capture.archive) + let explicit = try AuthorPackageOperations.readArchive( + at: file, expectedDigest: capture.digest, environment: environment) + try fixture.write("not an archive", to: file) + #expect(throws: CoreError.self) { + try AuthorPackageOperations.write(capture, to: file, environment: environment) + } + #expect(try fixture.bytes(file) == Data("not an archive".utf8)) + let changed = project.appendingPathComponent("skills/getting-started/added.txt") + try fixture.write("not reviewed", to: changed) + #expect(throws: CoreError.self) { + try AuthorPackageOperations.rebuild(expectedDigest: capture.digest, environment: environment) + } + let rebuilt = try AuthorPackageOperations.preview(environment: environment) + #expect(rebuilt.digest != capture.digest) + let catalog = fixture.root.appendingPathComponent("catalog") + try FileManager.default.createDirectory(at: catalog, withIntermediateDirectories: false) + let release = try AuthorPackageOperations.publish( + explicit, to: catalog, environment: environment) + #expect(release.archiveDigest == capture.digest) + #expect(release.summary == package.description) + #expect( + try AuthorPackageOperations.publish(capture, to: catalog, environment: environment) == release + ) + #expect(throws: MarketplaceError.self) { + try AuthorPackageOperations.publish(rebuilt, to: catalog, environment: environment) + } + let verified = try MarketplaceOperations.acquire(release, environment: environment) + #expect(verified.archive == capture.archive) + #expect(try verified.inspectBundle().components.map(\.name) == ["getting-started"]) + } + + @Test func credentialNamesAndEscapingReferencesFailWithoutChangingProject() throws { + let fixture = try UpdateFixture() + let project = fixture.root.appendingPathComponent("author") + let environment = authorEnvironment(fixture, project: project) + let scaffold = try AuthorPackageOperations.scaffold( + package, at: project, environment: environment) + let skill = project.appendingPathComponent(scaffold.skills[0]) + for name in [".env.template", "identity.PEM", "id_ed25519"] { + let file = skill.appendingPathComponent(name) + try fixture.write("fixture only", to: file) + let before = try FileHash.folderHash(project) + do { + _ = try AuthorPackageOperations.preview(environment: environment) + Issue.record("Expected credential filename refusal") + } catch let error as CoreError { + #expect( + error.description.contains("credential file refused") && error.description.contains(name)) + } + #expect(try FileHash.folderHash(project) == before) + try FileManager.default.removeItem(at: file) + } + let link = skill.appendingPathComponent("outside") + try FileManager.default.createSymbolicLink( + atPath: link.path, withDestinationPath: "../../../source") + #expect(throws: CoreError.self) { + try AuthorPackageOperations.preview(environment: environment) + } + try FileManager.default.removeItem(at: link) + try fixture.write( + "---\ndescription: Fixture rules\n---\n# Rules\n\n[Escapes](../../.env)\n", + to: project.appendingPathComponent(".agent/instructions/rules.md")) + #expect(throws: CoreError.self) { + try AuthorPackageOperations.preview( + .init(package: package, instructions: ["rules"]), environment: environment) + } + } + + @Test func changedOrganizationPolicyBlocksEveryOutputBeforeStaging() throws { + let fixture = try UpdateFixture() + let policy = fixture.root.appendingPathComponent("org.yaml") + var environment = fixture.environment + environment.userOrganizationPolicy = .init(.local(policy)) + try fixture.write("enforcement: warn\ndependencies: {deny: ['_local/workbench']}", to: policy) + let project = fixture.root.appendingPathComponent("author") + try AuthorPackageOperations.scaffold(package, at: project, environment: environment) + environment.projectDirectory = project + let capture = try AuthorPackageOperations.preview(environment: environment) + #expect(capture.policyFindings.contains { $0.rule == "package-deny" && $0.outcome == .warn }) + let native = try NativePluginOperations.preview(capture, for: .codex, environment: environment) + let catalog = fixture.root.appendingPathComponent("catalog") + try FileManager.default.createDirectory(at: catalog, withIntermediateDirectories: false) + try fixture.write("enforcement: block\ndependencies: {deny: ['_local/workbench']}", to: policy) + let before = try FileHash.folderHash(fixture.root) + #expect(throws: OrganizationPolicyFailure.self) { + try AuthorPackageOperations.preview(environment: environment) + } + #expect(throws: OrganizationPolicyFailure.self) { + try AuthorPackageOperations.scaffold( + package, at: fixture.root.appendingPathComponent("denied"), environment: environment) + } + #expect(throws: OrganizationPolicyFailure.self) { + try AuthorPackageOperations.write( + capture, to: fixture.root.appendingPathComponent("denied.bundle"), environment: environment) + } + #expect(throws: OrganizationPolicyFailure.self) { + try AuthorPackageOperations.publish(capture, to: catalog, environment: environment) + } + #expect(throws: OrganizationPolicyFailure.self) { + try MarketplaceOperations.publishBundle( + capture.archive, to: catalog, environment: environment) + } + #expect(throws: OrganizationPolicyFailure.self) { + try NativePluginOperations.write( + native, to: fixture.root.appendingPathComponent("denied-plugin"), environment: environment) + } + #expect(try FileHash.folderHash(fixture.root) == before) + } + + @Test func sourcePolicyAlsoAppliesToAnAlreadyCapturedArtifact() throws { + let fixture = try UpdateFixture() + let project = fixture.root.appendingPathComponent("author") + let environment = authorEnvironment(fixture, project: project) + try AuthorPackageOperations.scaffold(package, at: project, environment: environment) + let capture = try AuthorPackageOperations.preview(environment: environment) + try fixture.write( + "version: 1\ndeny: [local]\n", + to: SourcePolicyOperations.policyURL(scope: .project, environment: environment)) + let destination = fixture.root.appendingPathComponent("denied.bundle") + #expect(throws: SourcePolicyFailure.self) { + try AuthorPackageOperations.preview(environment: environment) + } + #expect(throws: SourcePolicyFailure.self) { + try AuthorPackageOperations.write(capture, to: destination, environment: environment) + } + #expect(!FileManager.default.fileExists(atPath: destination.path)) + } + + @Test(arguments: [InstallScope.user, .project]) + func bothDirectoryPublishersReadTheCurrentDestinationPolicy(_ authority: InstallScope) throws { + let fixture = try UpdateFixture() + let project = fixture.root.appendingPathComponent("author") + let environment = authorEnvironment(fixture, project: project) + try AuthorPackageOperations.scaffold(package, at: project, environment: environment) + let artifact = try AuthorPackageOperations.preview(environment: environment) + let catalog = fixture.root.appendingPathComponent("catalog") + try FileManager.default.createDirectory(at: catalog, withIntermediateDirectories: false) + let origin = try #require(SourceOrigin.local(at: catalog).identity) + let policy = SourcePolicyOperations.policyURL(scope: authority, environment: environment) + try fixture.write("version: 1\ndeny: [{local: '\(origin)'}]\n", to: policy) + func refusesCatalog(_ publish: () throws -> MarketplaceRelease) throws { + do { + _ = try publish() + Issue.record("A revoked catalog received a release") + } catch let error as SourcePolicyFailure { + #expect(error.violations.map(\.origin) == [.local(at: catalog)]) + #expect(error.violations.map(\.scope.rawValue) == [authority.rawValue]) + } + #expect(try FileManager.default.contentsOfDirectory(atPath: catalog.path).isEmpty) + } + try refusesCatalog { + try MarketplaceOperations.publishBundle( + artifact.archive, to: catalog, environment: environment) + } + try refusesCatalog { + try AuthorPackageOperations.publish(artifact, to: catalog, environment: environment) + } + try refusesCatalog { + try MarketplaceOperations.publish(artifact.archive, to: catalog, environment: environment) { + _ in + try MarketplaceCoordinate(package: package.name, version: package.version) + } + } + if authority == .project { + let userRelease = try MarketplaceOperations.publishBundle( + artifact.archive, to: catalog, scope: .user, environment: environment) + #expect(userRelease.archiveDigest == artifact.digest) + } + } + + @Test(arguments: [true, false]) + func literalMCPBindingRequiresSymbolicReplacementInBothExportPaths(_ stdio: Bool) throws { + let fixture = try UpdateFixture() + let name = "literal-fixture" + let value = "synthetic-private-value" + let transport = + stdio + ? "kind: stdio, executable: never-launch, environment: {FIXTURE_VALUE: '\(value)'}" + : "kind: streamableHTTP, url: 'https://fixture.invalid/mcp', headers: {Authorization: '\(value)'}" + try fixture.write( + """ + version: 1 + components: + - kind: mcpServer + name: \(name) + agents: [codex] + transport: {\(transport)} + """, to: fixture.store.declarationURL) + func refusesLiteral(_ share: () throws -> Void) throws { + do { + try share() + Issue.record("An unattested literal was accepted") + } catch let error as CoreError { + #expect(error.description.contains("environment or secret reference")) + #expect(error.description.contains(stdio ? "FIXTURE_VALUE" : "Authorization")) + #expect(!error.description.contains(value)) + } + } + try refusesLiteral { + _ = try AuthorPackageOperations.preview( + .init(package: package, mcpServers: [name]), environment: fixture.environment) + } + _ = try fixture.apply() + let scope = try UpdateOperations.inspect(environment: fixture.environment) + let previous = try fixture.snapshot() + try refusesLiteral { + _ = try BundleOperations.export( + package, selections: scope.components.map(\.selection), scope: .project, + environment: fixture.environment) + } + try refusesLiteral { + _ = try AuthorPackageOperations.preview( + .init(package: package, lockedMembers: [.init(kind: .mcpServer, name: name)]), + environment: fixture.environment) + } + #expect(try fixture.snapshot() == previous) + } + + @Test(arguments: [false, true]) + func codexBearerVariableSurvivesPackageInstallation(authored: Bool) throws { + let publisher = try UpdateFixture() + try publisher.write( + """ + version: 1 + components: + - kind: mcpServer + name: team-service + agents: [codex] + transport: {kind: streamableHTTP, url: 'https://fixture.invalid/mcp'} + native: {codex: {bearer_token_env_var: TEAM_SERVICE_TOKEN}} + """, to: publisher.store.declarationURL) + var environment = publisher.environment + environment.environment["TEAM_SERVICE_TOKEN"] = "synthetic-value-never-exported" + let archive: Data + if authored { + archive = try AuthorPackageOperations.preview( + .init(package: package, mcpServers: ["team-service"]), environment: environment + ).archive + } else { + _ = try publisher.apply() + let scope = try UpdateOperations.inspect(environment: environment) + archive = try BundleOperations.export( + package, selections: scope.components.map(\.selection), scope: .project, + environment: environment) + } + #expect(!String(decoding: archive, as: UTF8.self).contains("synthetic-value-never-exported")) + let bundle = try BundleOperations.inspect(archive) + let server = try #require(bundle.components.first) + let recipient = try UpdateFixture() + let preview = try BundleOperations.previewImport( + bundle, selections: [.init(componentID: server.id, targets: [.codex])], scope: .project, + environment: recipient.environment) + _ = try BundleOperations.withPreparedImport(preview) { try $0.apply() } + let config = try String( + contentsOf: recipient.environment.projectDirectory.appendingPathComponent( + ".codex/config.toml"), + encoding: .utf8) + #expect(config.contains("bearer_token_env_var") && config.contains("TEAM_SERVICE_TOKEN")) + } + + @Test func outputRaceIsNoReplace() async throws { + let fixture = try UpdateFixture() + let environment = fixture.environment + let author = fixture.root.appendingPathComponent("author") + try AuthorPackageOperations.scaffold(package, at: author, environment: environment) + let authored = authorEnvironment(fixture, project: author) + let first = try AuthorPackageOperations.preview(environment: authored) + try fixture.write( + "Second generation\n", to: author.appendingPathComponent("skills/getting-started/new.txt")) + let second = try AuthorPackageOperations.preview(environment: authored) + let destination = fixture.root.appendingPathComponent("raced.bundle") + let winners = await withTaskGroup(of: Bool.self) { group in + for candidate in [first, second] { + group.addTask { + do { + try AuthorPackageOperations.write(candidate, to: destination, environment: authored) + return true + } catch { return false } + } + } + return await group.reduce(0) { $0 + ($1 ? 1 : 0) } + } + #expect(winners == 1) + #expect([first.archive, second.archive].contains(try fixture.bytes(destination))) + #expect( + try FileManager.default.contentsOfDirectory(atPath: fixture.root.path).allSatisfy { + !$0.hasPrefix(".stage-") + }) + } + + private func authorEnvironment(_ fixture: UpdateFixture, project: URL) -> RuntimeEnvironment { + RuntimeEnvironment( + projectDirectory: project, homeDirectory: fixture.environment.homeDirectory, environment: [:]) + } +} diff --git a/Tests/AgentsUpdatesTests/CombinedUpdateTests.swift b/Tests/AgentsUpdatesTests/CombinedUpdateTests.swift index c55bffc..7201a75 100644 --- a/Tests/AgentsUpdatesTests/CombinedUpdateTests.swift +++ b/Tests/AgentsUpdatesTests/CombinedUpdateTests.swift @@ -1,9 +1,11 @@ -import AgentsCore import AgentsInstructions +import AgentsManifest import AgentsSkills import Foundation +import StateTestSupport import Testing +@testable import AgentsCore @testable import AgentsUpdates @Suite("Combined updates") @@ -13,9 +15,9 @@ struct CombinedUpdateTests { try fixture.install(mode: .edit, agents: [.codex]) try fixture.advance() var declaration = try fixture.store.loadDeclaration() - declaration.skills?["fixture"]?.mode = .copy + try declaration.updateSkills { $0?["fixture"]?.mode = .copy } declaration.sources["fixture"]?.requirement = .branch("main") - try fixture.store.save(declaration: declaration, resolved: fixture.store.loadResolved()) + try fixture.store.save(declaration: declaration, ledger: fixture.store.loadLedger()) let before = try fixture.snapshot() let preview = try fixture.preview() let skill = try #require(preview.skills.first) @@ -54,12 +56,17 @@ struct CombinedUpdateTests { try fixture.install(agents: [.codex]) try fixture.write("Hand written.\n", to: fixture.instruction(.geminiCLI)) var declaration = try fixture.store.loadDeclaration() - declaration.instructions?.agents = [.codex, .geminiCLI] - try fixture.store.save(declaration: declaration, resolved: fixture.store.loadResolved()) + try declaration.updateInstructions { $0?.agents = [.codex, .geminiCLI] } + try fixture.store.save(declaration: declaration, ledger: fixture.store.loadLedger()) let preview = try fixture.preview() #expect(preview.instructions.targets.contains { $0.target == "GEMINI.md" && $0.foreign }) let before = try fixture.snapshot() - #expect(throws: InstructionError.unownedTargets(["GEMINI.md"])) { try fixture.apply() } + #expect { try fixture.apply() } throws: { error in + guard let failure = error as? UpdateApplyError, case .unchanged = failure.disposition, + let underlying = failure.underlyingError as? InstructionError + else { return false } + return underlying == .unownedTargets(["GEMINI.md"]) + } #expect(try fixture.snapshot() == before) #expect(try fixture.bytes(fixture.instruction(.geminiCLI)) == Data("Hand written.\n".utf8)) } @@ -69,12 +76,12 @@ struct CombinedUpdateTests { let fixture = try UpdateFixture() try fixture.install(mode: .edit, agents: [.codex]) var declaration = try fixture.store.loadDeclaration() - declaration.skills?["fixture"]?.mode = .copy + try declaration.updateSkills { $0?["fixture"]?.mode = .copy } declaration.sources["fixture"]?.requirement = .branch("main") - try fixture.store.save(declaration: declaration, resolved: fixture.store.loadResolved()) + try fixture.store.save(declaration: declaration, ledger: fixture.store.loadLedger()) let before = try fixture.snapshot() var called = false - #expect(throws: CoreError.invalidState("edit installs must be local, unpinned live links")) { + #expect(throws: CoreError.self) { try InstructionOperations.updateInstalled( environment: fixture.environment, apply: apply, beforeApply: { _ in called = true }) } @@ -91,12 +98,12 @@ struct CombinedUpdateTests { try fixture.commit() try fixture.install(mode: .edit, agents: [.codex]) var declaration = try fixture.store.loadDeclaration() - declaration.skills?["fixture"]?.mode = .copy + try declaration.updateSkills { $0?["fixture"]?.mode = .copy } declaration.sources["fixture"]?.requirement = .branch("main") - try fixture.store.save(declaration: declaration, resolved: fixture.store.loadResolved()) + try fixture.store.save(declaration: declaration, ledger: fixture.store.loadLedger()) let before = try fixture.snapshot() var called = false - #expect(throws: CoreError.invalidState("edit installs must be local, unpinned live links")) { + #expect(throws: CoreError.self) { try SkillOperations.updateInstalled( environment: fixture.environment, skillNames: ["demo"], apply: apply, beforeApply: { _ in called = true }) @@ -160,10 +167,12 @@ struct CombinedUpdateTests { } var declaration = try fixture.store.loadDeclaration() declaration.sources["live"] = SourceDeclaration(kind: .local, location: live.path) - declaration.skills?["live"] = SkillDeclaration(select: .all, agents: [.codex], mode: .edit) + try declaration.updateSkills { + $0?["live"] = SkillDeclaration(select: .all, agents: [.codex], mode: .edit) + } declaration.sources["rules"] = SourceDeclaration(kind: .local, location: rules.repo.path) - declaration.instructions?.sections = ["rules:rules"] - declaration.instructions?.chatgpt?["weekly"]?.sections = ["rules:rules"] + try declaration.updateInstructions { $0?.sections = ["rules:rules"] } + try declaration.updateInstructions { $0?.chatgpt?["weekly"]?.sections = ["rules:rules"] } declaration.sources["watched"] = SourceDeclaration( kind: .wellKnown, location: "https://example.test") declaration.watch = ["watched"] @@ -172,7 +181,7 @@ struct CombinedUpdateTests { seen: .artifacts(["observed": "sha256:" + String(repeating: "b", count: 64)])) ]) try fixture.store.save( - declaration: declaration, resolved: fixture.store.loadResolved(), watch: watch) + declaration: declaration, ledger: fixture.store.loadLedger(), watch: watch) try fixture.advance() let before = try fixture.snapshot() #expect(throws: UpdateApplyError.self) { @@ -180,8 +189,10 @@ struct CombinedUpdateTests { environment: fixture.environment, checkpoint: { step in // Pruning is queued after both kinds and the merged state; rollback restores it too. - if step == "journal.committed.renamed" { return } - if step.hasPrefix("replace."), !step.hasSuffix(".renamed"), + if step == TransactionCheckpoint.persisted(.committed, .terminal, .renamed).name { + return + } + if step.hasPrefix("entry."), step.hasSuffix(".applied"), !FileManager.default.fileExists(atPath: unused.path) { throw CoreError.invalidState("pruning interrupted") @@ -216,7 +227,21 @@ struct CombinedUpdateTests { guard step == "plan.skills" else { return } attempts += 1 if attempts == 1 { - try fixture.declare() + let store = fixture.store + let source = fixture.repo.path + let finished = DispatchSemaphore(value: 0) + Thread.detachNewThread { + defer { finished.signal() } + do { + try store.save( + declaration: Declaration( + sources: ["fixture": SourceDeclaration(kind: .local, location: source)], + skills: ["fixture": SkillDeclaration(select: .all, agents: [.codex], mode: .copy)] + ), + ledger: ResolvedLedger()) + } catch { Issue.record(error) } + } + try #require(finished.wait(timeout: .now() + 10) == .success) if throwFirst { throw CoreError.invalidState("discarded read") } } }) @@ -232,9 +257,9 @@ struct CombinedUpdateTests { try fixture.declare() var declaration = try fixture.store.loadDeclaration() declaration.sources["rules"] = SourceDeclaration(kind: .local, location: other.repo.path) - declaration.instructions?.sections = ["rules:rules"] - declaration.instructions?.chatgpt?["weekly"]?.sections = ["rules:rules"] - try fixture.store.save(declaration: declaration, resolved: ResolvedState()) + try declaration.updateInstructions { $0?.sections = ["rules:rules"] } + try declaration.updateInstructions { $0?.chatgpt?["weekly"]?.sections = ["rules:rules"] } + try fixture.store.save(declaration: declaration, ledger: ResolvedLedger()) _ = try fixture.apply() try fixture.advance() try other.advance() @@ -257,7 +282,7 @@ struct CombinedUpdateTests { sources: ["fixture": SourceDeclaration(kind: .local, location: fixture.repo.path)], skills: ["fixture": SkillDeclaration(select: .all, agents: [.codex], mode: .copy)], instructions: InstructionsDeclaration(agents: [.claudeCode], sections: ["fixture:rules"])), - resolved: ResolvedState()) + ledger: ResolvedLedger()) var called = false #expect(throws: CoreError.self) { try UpdateOperations.withPreparedUpdate(scope: .user, environment: environment) { _ in @@ -335,7 +360,7 @@ struct CombinedUpdateTests { try UpdateOperations.withPreparedUpdate( environment: fixture.environment, checkpoint: { step in - if step == "stage.0.ready" { + if step == TransactionCheckpoint.stage(0, .constructed).name { let file = cache.appendingPathComponent("skills/demo/run.sh") if dimension == "bytes" { try fixture.write("corrupt", to: file) @@ -363,7 +388,7 @@ struct CombinedUpdateTests { var journals = 0 let receipt = try UpdateOperations.withPreparedUpdate( scope: scope, environment: fixture.environment, - checkpoint: { if $0 == "journal.preparing" { journals += 1 } }, + checkpoint: { if $0 == TransactionCheckpoint.phase(.preparing).name { journals += 1 } }, { update in #expect(update.report == preview) #expect(try fixture.snapshot() == before) @@ -415,8 +440,8 @@ struct CombinedUpdateTests { if kind == "skills" { try fixture.write("invalid", to: fixture.repo.appendingPathComponent("skills/demo/SKILL.md")) var declaration = try fixture.store.loadDeclaration() - declaration.skills?["fixture"]?.select = .names(["demo"]) - try fixture.store.save(declaration: declaration, resolved: fixture.store.loadResolved()) + try declaration.updateSkills { $0?["fixture"]?.select = .names(["demo"]) } + try fixture.store.save(declaration: declaration, ledger: fixture.store.loadLedger()) try fixture.commit() } else if kind == "instructions" { try fixture.write("invalid", to: fixture.repo.appendingPathComponent("instructions/rules.md")) @@ -488,7 +513,12 @@ struct CombinedUpdateTests { try FileManager.default.createSymbolicLink( at: fixture.target(), withDestinationURL: fixture.repo.appendingPathComponent("skills/demo")) - case "declaration": try fixture.write("{}\n", to: fixture.store.declarationURL) + case "declaration": + // A comment changes no declared intent but still invalidates the preparation. + let declaration = try fixture.bytes(fixture.store.declarationURL) + try fixture.write( + String(decoding: declaration, as: UTF8.self) + "// Edited.\n", + to: fixture.store.declarationURL) case "resolved": try fixture.write("{}\n", to: fixture.store.resolvedURL) default: try fixture.write("{}\n", to: fixture.store.watchURL) } @@ -538,12 +568,14 @@ struct CombinedUpdateTests { #expect(!FileManager.default.fileExists(atPath: fixture.store.resolvedURL.path)) try fixture.declare() var declaration = try fixture.store.loadDeclaration() - declaration.skills = nil - try fixture.store.save(declaration: declaration, resolved: ResolvedState()) + try declaration.setSkills(nil) + try fixture.store.save(declaration: declaration, ledger: ResolvedLedger()) #expect(try fixture.apply().report.skills.isEmpty) - declaration.instructions = nil - declaration.skills = ["fixture": SkillDeclaration(select: .all, agents: [.codex], mode: .copy)] - try fixture.store.save(declaration: declaration, resolved: fixture.store.loadResolved()) + try declaration.setInstructions(nil) + try declaration.setSkills([ + "fixture": SkillDeclaration(select: .all, agents: [.codex], mode: .copy) + ]) + try fixture.store.save(declaration: declaration, ledger: fixture.store.loadLedger()) _ = try fixture.apply() #expect(try fixture.store.loadResolved().instructions == LockedInstructions()) #expect(try !fixture.preview().hasChanges) @@ -553,9 +585,9 @@ struct CombinedUpdateTests { let fixture = try UpdateFixture() try fixture.install() var declaration = try fixture.store.loadDeclaration() - declaration.skills = nil - declaration.instructions?.sections = [] - try fixture.store.save(declaration: declaration, resolved: fixture.store.loadResolved()) + try declaration.setSkills(nil) + try declaration.updateInstructions { $0?.sections = [] } + try fixture.store.save(declaration: declaration, ledger: fixture.store.loadLedger()) _ = try fixture.apply() try fixture.git(["commit", "--allow-empty", "-m", "repin"]) let prompt = try fixture.preview() @@ -567,11 +599,13 @@ struct CombinedUpdateTests { to: fixture.repo.appendingPathComponent("instructions/second.md") ) try fixture.commit() - declaration.instructions?.chatgpt?["weekly"]?.sections = ["fixture:rules", "fixture:second"] - try fixture.store.save(declaration: declaration, resolved: fixture.store.loadResolved()) + try declaration.updateInstructions { + $0?.chatgpt?["weekly"]?.sections = ["fixture:rules", "fixture:second"] + } + try fixture.store.save(declaration: declaration, ledger: fixture.store.loadLedger()) _ = try fixture.apply() - declaration.instructions?.chatgpt?["weekly"]?.sections.reverse() - try fixture.store.save(declaration: declaration, resolved: fixture.store.loadResolved()) + try declaration.updateInstructions { $0?.chatgpt?["weekly"]?.sections.reverse() } + try fixture.store.save(declaration: declaration, ledger: fixture.store.loadLedger()) #expect(try fixture.preview().hasChanges) _ = try fixture.apply() #expect(try !fixture.preview().hasChanges) diff --git a/Tests/AgentsUpdatesTests/ComponentInventoryTests.swift b/Tests/AgentsUpdatesTests/ComponentInventoryTests.swift new file mode 100644 index 0000000..cd3fed0 --- /dev/null +++ b/Tests/AgentsUpdatesTests/ComponentInventoryTests.swift @@ -0,0 +1,270 @@ +import AgentsCore +import Foundation +import Testing + +@testable import AgentsUpdates + +@Suite("Distributable locked inventory") +struct ComponentInventoryTests { + private let date = Date(timeIntervalSince1970: 1_704_067_200) + private let commit = String(repeating: "a", count: 40) + private let archive = "sha256:" + String(repeating: "b", count: 64) + private let tree = "sha256:" + String(repeating: "c", count: 64) + private let file = "sha256:" + String(repeating: "d", count: 64) + private let catalogCommit = String(repeating: "e", count: 40) + private let localPath = FileManager.default.temporaryDirectory.appendingPathComponent( + "private-worktree" + ).path + + @Test func spdxPackagesAndRelationships() throws { + let data = try fixture().inventory(format: .spdx, createdAt: date) + let document = try object(data) + let creation = try #require(document["creationInfo"] as? [String: Any]) + #expect(document["spdxVersion"] as? String == "SPDX-2.3") + #expect(document["dataLicense"] as? String == "CC0-1.0") + #expect(document["SPDXID"] as? String == "SPDXRef-DOCUMENT") + #expect(creation["created"] as? String == "2024-01-01T00:00:00Z") + #expect(creation["creators"] as? [String] == ["Tool: agents"]) + let namespace = try #require(document["documentNamespace"] as? String) + #expect(URL(string: namespace)?.scheme == "https") + #expect(URL(string: namespace)?.fragment == nil) + + let packages = try #require(document["packages"] as? [[String: Any]]) + let ids = packages.compactMap { $0["SPDXID"] as? String } + #expect(packages.count == 7) + #expect(Set(ids).count == packages.count) + #expect( + ids.allSatisfy { + $0.range(of: #"^SPDXRef-[a-zA-Z0-9.-]+$"#, options: .regularExpression) != nil + }) + for package in packages { + #expect(package["filesAnalyzed"] as? Bool == false) + #expect(package["licenseDeclared"] as? String == "NOASSERTION") + #expect(package["licenseConcluded"] as? String == "NOASSERTION") + #expect(package["downloadLocation"] as? String == "NOASSERTION") + #expect(package["copyrightText"] as? String == "NOASSERTION") + } + + let git = try named("github.com/team/tools", in: packages) + #expect(git["versionInfo"] as? String == "2.3.4") + #expect((git["sourceInfo"] as? String)?.contains("agents:revision " + commit) == true) + let refs = try #require(git["externalRefs"] as? [[String: String]]) + #expect( + refs == [ + [ + "referenceCategory": "PACKAGE-MANAGER", "referenceType": "purl", + "referenceLocator": "pkg:github/team/tools@\(commit)#packages/review%20kit", + ] + ]) + + let release = try named("team-kit", in: packages) + #expect(release["versionInfo"] as? String == "1.2.3") + #expect( + (release["sourceInfo"] as? String)?.contains("agents:catalog-commit " + catalogCommit) == true + ) + #expect( + release["checksums"] as? [[String: String]] == [ + [ + "algorithm": "SHA256", "checksumValue": String(archive.dropFirst(7)), + ] + ]) + let child = try named("review", in: packages) + let evidence = try #require(child["sourceInfo"] as? String) + #expect(evidence.contains("agents:resource-tree-sha256 " + tree + " skills/review")) + #expect(evidence.contains("agents:resource-file-sha256 " + file + " notes.md")) + + let relationships = try #require(document["relationships"] as? [[String: String]]) + let known = Set(ids + ["SPDXRef-DOCUMENT"]) + for relationship in relationships { + #expect(known.contains(relationship["spdxElementId"] ?? "")) + #expect(known.contains(relationship["relatedSpdxElement"] ?? "")) + } + try requireRelationship("DESCRIBES", from: document, to: release, in: relationships) + try requireRelationship("CONTAINS", from: git, to: child, in: relationships) + try requireRelationship("CONTAINS", from: release, to: child, in: relationships) + let contained = try named("github.com/team/tools#extras", in: packages) + try requireRelationship("CONTAINS", from: git, to: contained, in: relationships) + } + + @Test func cycloneDXPackagesAndRelationships() throws { + let data = try fixture().inventory(format: .cycloneDX, createdAt: date) + let document = try object(data) + #expect(document["bomFormat"] as? String == "CycloneDX") + #expect(document["specVersion"] as? String == "1.6") + #expect(document["version"] as? Int == 1) + #expect((document["metadata"] as? [String: String])?["timestamp"] == "2024-01-01T00:00:00Z") + + let roots = try #require(document["components"] as? [[String: Any]]) + let all = roots + roots.flatMap { $0["components"] as? [[String: Any]] ?? [] } + #expect(Set(all.compactMap { $0["bom-ref"] as? String }).count == 7) + let git = try named("github.com/team/tools", in: roots) + #expect(git["purl"] as? String == "pkg:github/team/tools@\(commit)#packages/review%20kit") + #expect(git["version"] as? String == "2.3.4") + #expect(property("agents:revision", in: git) == commit) + let children = try #require(git["components"] as? [[String: Any]]) + let child = try named("review", in: children) + #expect(child["type"] as? String == "data") + #expect(property("agents:resource-tree-sha256", in: child) == tree + " skills/review") + #expect(property("agents:resource-file-sha256", in: child) == file + " notes.md") + #expect(child["hashes"] == nil) + + let release = try named("team-kit", in: roots) + #expect(release["version"] as? String == "1.2.3") + #expect( + release["purl"] as? String + == "pkg:github/team/catalog@\(catalogCommit)#inventory/releases/team-kit/1.2.3") + #expect( + release["hashes"] as? [[String: String]] == [ + [ + "alg": "SHA-256", "content": String(archive.dropFirst(7)), + ] + ]) + #expect(property("agents:archive-digest", in: release) == archive) + #expect(property("agents:contains", in: release) == (child["bom-ref"] as? String)) + let contained = try named("github.com/team/tools#extras", in: roots) + #expect(contained["purl"] as? String == "pkg:github/team/tools@\(commit)#extras") + #expect(property("agents:contains", in: git) == (contained["bom-ref"] as? String)) + } + + @Test(arguments: [InventoryFormat.cycloneDX, .spdx]) + func fixedTimestampIsReproducibleAndOmitsPrivateFields(_ format: InventoryFormat) throws { + let data = try fixture().inventory(format: format, createdAt: date) + #expect(data == (try fixture().inventory(format: format, createdAt: date))) + #expect( + data != (try fixture().inventory(format: format, createdAt: date.addingTimeInterval(1)))) + let encoded = String(decoding: data, as: UTF8.self) + for privateValue in [ + localPath, "catalog-private-user", "private-index-token", "private-config-value", + ] { + #expect(!encoded.contains(privateValue)) + } + let legacy = try fixture().cycloneDXInventory() + #expect(legacy == (try fixture().inventory(format: .cycloneDX))) + #expect(try object(legacy)["metadata"] == nil) + } + + @Test func repositoryURLsUseEstablishedTypesAndUnambiguousRoots() throws { + let sources = [ + gitSource("bitbucket.org/Workspace/TeamKit", roots: ["one", "two"]), + gitSource("gitlab.com/Group/subgroup/TeamKit", roots: ["plugin"]), + gitSource("git.example.test/Team/kit", roots: ["."]), + gitSource("git.example.test:8443/Team/kit", roots: ["profile:default"]), + ] + let document = try object(inspection(sources: sources).cycloneDXInventory()) + let components = try #require(document["components"] as? [[String: Any]]) + let urls = components.compactMap { $0["purl"] as? String } + #expect( + urls == [ + "pkg:bitbucket/workspace/teamkit@" + commit, + "pkg:git/gitlab.com/Group/subgroup/TeamKit@\(commit)#plugin", + "pkg:git/git.example.test/Team/kit@\(commit)", + "pkg:git/git.example.test:8443/Team/kit@\(commit)#profile:default", + ]) + } + + private func fixture() throws -> ScopeInspection { + let git = gitSource("github.com/team/tools", roots: ["packages/review kit"]) + let local = SourceInspection( + record: "local", identity: "local:" + localPath, kind: .local, revision: "live", + version: nil, container: nil, namespace: nil, location: URL(fileURLWithPath: localPath), + uses: []) + let index = SourceInspection( + record: "index", identity: "https://index.example.test/skills?token=private-index-token", + kind: .wellKnown, revision: tree, version: nil, container: nil, namespace: nil, + location: nil, uses: []) + let childRecord = "sha256:" + String(repeating: "f", count: 64) + let child = ComponentInspection( + record: childRecord, sourceRecord: git.record, declaringSourceRecord: local.record, + selection: .init(identity: localPath + "/review", occurrence: nil, generation: "locked"), + kind: .skills, name: "review", source: git.identity, declaringSource: local.identity, + root: "packages/review kit", group: nil, revision: commit, version: "2.3.4", mcpRegistry: nil, + configuration: .object(["token": .string("private-config-value")]), + conditions: [], recipients: [.codex], copyRecipients: [], chatGPT: false, + resources: ["tree", "file"], + occurrences: []) + let treeResource = resource( + "tree", path: "skills/review", hash: tree, kind: "directory", source: git) + let fileResource = resource("file", path: "notes.md", hash: file, kind: "file", source: git) + let release = try pin( + "team-kit", child: childRecord, + origin: MarketplaceOrigin( + kind: .git, location: "ssh://catalog-private-user@github.com/team/catalog.git", + subpath: "inventory"), + commit: catalogCommit) + let localRelease = try pin( + "local-kit", child: childRecord, + origin: MarketplaceOrigin(kind: .directory, location: localPath), + commit: nil) + let contained = SourceInspection( + record: "contained", identity: git.identity + ":contained:6:extras", kind: .local, + revision: commit, version: nil, container: git.identity, namespace: ":contained:6:extras", + location: nil, uses: []) + return inspection( + sources: [git, local, index, contained], components: [child], + resources: [treeResource, fileResource], releases: [release, localRelease]) + } + + private func gitSource(_ identity: String, roots: [String]) -> SourceInspection { + .init( + record: identity, identity: identity, kind: .git, revision: commit, version: "2.3.4", + container: nil, namespace: nil, location: nil, + uses: roots.map { .init(root: $0, requirement: nil) }) + } + + private func resource( + _ id: String, path: String, hash: String, kind: String, source: SourceInspection + ) -> ResourceInspection { + .init( + sourceRecord: source.record, identity: id, source: source.identity, path: path, hash: hash, + kind: "git", location: URL(fileURLWithPath: localPath + "/" + path), + entries: [.init(path: ".", kind: kind, executable: false, link: nil, byteCount: nil)], + support: []) + } + + private func pin( + _ name: String, child: String, origin: MarketplaceOrigin, commit: String? + ) throws -> MarketplacePin { + let coordinate = try MarketplaceCoordinate(package: name, version: "1.2.3") + return MarketplacePin( + dependency: try MarketplaceDependency(name: name, catalog: origin, coordinate: coordinate), + archiveDigest: archive, catalogCommit: commit, sourceAliases: [name], + componentRecords: [child], contributionDigest: tree) + } + + private func inspection( + sources: [SourceInspection], components: [ComponentInspection] = [], + resources: [ResourceInspection] = [], releases: [MarketplacePin] = [] + ) -> ScopeInspection { + .init( + additionDestination: nil, scope: .project, document: nil, declaration: nil, + generation: "locked", sources: sources, components: components, groups: [], + marketplacePackages: releases, marketplaceGraph: nil, marketplaceIssue: nil, + pendingMarketplaceDeployment: nil, + resources: resources, deployments: [], + watch: nil, recovery: .init(pending: false, requiresOwner: false, diagnostic: nil), + readLocations: [URL(fileURLWithPath: localPath)]) + } + + private func object(_ data: Data) throws -> [String: Any] { + try #require(try JSONSerialization.jsonObject(with: data) as? [String: Any]) + } + + private func named(_ name: String, in objects: [[String: Any]]) throws -> [String: Any] { + try #require(objects.first { $0["name"] as? String == name }) + } + + private func property(_ name: String, in component: [String: Any]) -> String? { + (component["properties"] as? [[String: String]])?.first { $0["name"] == name }?["value"] + } + + private func requireRelationship( + _ kind: String, from: [String: Any], to: [String: Any], in relationships: [[String: String]] + ) throws { + let source = try #require(from["SPDXID"] as? String) + let target = try #require(to["SPDXID"] as? String) + #expect( + relationships.contains([ + "spdxElementId": source, "relationshipType": kind, "relatedSpdxElement": target, + ])) + } +} diff --git a/Tests/AgentsUpdatesTests/ConsumerLifecycleRegressionTests.swift b/Tests/AgentsUpdatesTests/ConsumerLifecycleRegressionTests.swift new file mode 100644 index 0000000..73a3d24 --- /dev/null +++ b/Tests/AgentsUpdatesTests/ConsumerLifecycleRegressionTests.swift @@ -0,0 +1,595 @@ +import AgentsCore +import AgentsInstructions +import AgentsManifest +import AgentsSkills +import AgentsUpdates +import Foundation +import Testing + +#if canImport(Darwin) + import Darwin +#else + import Glibc +#endif + +struct ConsumerLifecycleRegressionTests { + @Test(arguments: ["valid", "missing", "escape"]) + func frozenRestoreValidatesReceivingCheckoutLinks(mode: String) throws { + let f = try UpdateFixture() + let guide = f.root.appendingPathComponent("guide.md") + try f.write("Guide", to: guide) + try f.write( + "---\ndescription: Rules.\n---\n# Rules\n\n[Guide](guide.md)\n", + to: f.repo.appendingPathComponent("instructions/rules.md")) + try f.commit() + try f.install(agents: [.codex]) + let locked = try f.bytes(f.instruction()) + try f.write( + "mutable author must not be read", to: f.repo.appendingPathComponent("instructions/rules.md")) + try f.write(String(decoding: locked, as: UTF8.self) + "\nEdited\n", to: f.instruction()) + let outside = FileManager.default.temporaryDirectory.appendingPathComponent( + "restore-link-" + UUID().uuidString) + defer { try? FileManager.default.removeItem(at: outside) } + if mode != "valid" { try FileManager.default.removeItem(at: guide) } + if mode == "escape" { + try f.write("Outside", to: outside) + try FileManager.default.createSymbolicLink(at: guide, withDestinationURL: outside) + } + let before = try f.snapshot() + var delivered = false + do { + _ = try UpdateOperations.withPreparedUpdate( + UpdateRequest(operation: .restore), environment: f.environment + ) { + delivered = true + return try $0.apply() + } + #expect(mode == "valid") + #expect(try f.bytes(f.instruction()) == locked) + } catch { + if mode == "valid" { throw error } + #expect(!delivered) + #expect(try f.snapshot() == before) + } + } + + @Test func restoreRechecksLinkDestinationBeforePublication() throws { + let f = try UpdateFixture() + let guide = f.root.appendingPathComponent("guide.md") + try f.write("Guide", to: guide) + try f.write( + "---\ndescription: Rules.\n---\n# Rules\n\n[Guide](guide.md)\n", + to: f.repo.appendingPathComponent("instructions/rules.md")) + try f.commit() + try f.install(agents: [.codex]) + try f.write( + String(decoding: f.bytes(f.instruction()), as: UTF8.self) + "\nEdited\n", to: f.instruction()) + let before = try f.snapshot() + #expect(throws: (any Error).self) { + try UpdateOperations.withPreparedUpdate( + UpdateRequest(operation: .restore), environment: f.environment + ) { + try FileManager.default.removeItem(at: guide) + return try $0.apply() + } + } + #expect(try f.snapshot() == before) + } + + @Test func ordinaryPartialRemovalKeepsSharedInstructionTargetAndSurvivingPins() throws { + let f = try UpdateFixture() + try f.write( + "---\ndescription: Other.\n---\n# Other\n\nFrozen survivor\n", + to: f.repo.appendingPathComponent("instructions/other.md")) + try f.commit() + try f.declare(agents: [.codex]) + var declaration = try f.store.loadDeclaration() + try declaration.updateInstructions { $0?.sections.append("fixture:other") } + try f.store.save(declaration: declaration, ledger: ResolvedLedger()) + _ = try f.apply() + let previous = try f.store.readLedger() + let skillBytes = try f.bytes(f.target().appendingPathComponent("SKILL.md")) + try f.advance() + try f.write( + "---\ndescription: Other.\n---\n# Other\n\nMutable producer changed\n", + to: f.repo.appendingPathComponent("instructions/other.md")) + try f.commit() + let before = try f.snapshot() + let preview = try UpdateOperations.preview( + .init(operation: .remove, kinds: [.instructions], names: ["rules"]), + environment: f.environment) + let target = try #require(preview.instructions.targets.first { $0.url == f.instruction() }) + let after = try #require(target.after) + #expect(String(decoding: after, as: UTF8.self).contains("Frozen survivor")) + #expect(!String(decoding: after, as: UTF8.self).contains("# Rules")) + #expect(target.afterAgents == [.codex]) + #expect(try f.snapshot() == before) + _ = try InstructionOperations.remove(names: ["rules"], environment: f.environment) + #expect(try f.bytes(f.instruction()) == after) + #expect(try f.bytes(f.target().appendingPathComponent("SKILL.md")) == skillBytes) + let next = try f.store.readLedger() + for (id, component) in previous.components + where component.kind == "skills" || component.name == "other" { + #expect(next.components[id] == component) + #expect(next.sources[component.source] == previous.sources[component.source]) + } + let deployment = try #require( + next.deployments.first { + $0.route == "agents/instructions@1" && $0.target.path == "AGENTS.md" + }) + #expect(deployment.expectedHash == "sha256:" + FileHash.sha256Hex(data: after)) + #expect( + try UpdateOperations.inspect(environment: f.environment).deployments.filter { + $0.location == f.instruction() + }.allSatisfy { $0.status == .current }) + } + + @Test func handwrittenSharedInstructionPartialRemovalRefusesBeforeCallback() throws { + let f = try UpdateFixture() + try f.write( + "---\ndescription: Other.\n---\n# Other\n", + to: f.repo.appendingPathComponent("instructions/other.md")) + try f.commit() + try f.declare(agents: [.codex]) + var declaration = try f.store.loadDeclaration() + try declaration.updateInstructions { $0?.sections.append("fixture:other") } + try f.store.save(declaration: declaration, ledger: ResolvedLedger()) + _ = try f.apply() + try f.write("Handwritten shared destination", to: f.instruction()) + let before = try f.snapshot() + let preview = try UpdateOperations.preview( + .init(operation: .remove, kinds: [.instructions], names: ["rules"]), + environment: f.environment) + let target = try #require(preview.instructions.targets.first { $0.url == f.instruction() }) + #expect(target.foreign) + #expect(target.after != nil) + var callbacks = 0 + #expect(throws: InstructionError.self) { + try InstructionOperations.remove(names: ["rules"], environment: f.environment) { _ in + callbacks += 1 + } + } + #expect(callbacks == 0) + #expect(try f.snapshot() == before) + } + + @Test func explicitRemovalRetargetsSurvivorsAndKeepsSkillPin() throws { + let f = try UpdateFixture() + try f.write( + "---\ndescription: Other.\n---\n# Other\n", + to: f.repo.appendingPathComponent("instructions/other.md")) + try f.commit() + try f.declare(agents: [.codex]) + var declaration = try f.store.loadDeclaration() + try declaration.updateInstructions { $0?.sections.append("fixture:other") } + try f.store.save(declaration: declaration, ledger: ResolvedLedger()) + _ = try f.apply() + let previous = try f.store.readLedger() + let skill = try f.bytes(f.target().appendingPathComponent("SKILL.md")) + try f.advance() + _ = try InstructionOperations.remove( + names: ["other"], agents: [.geminiCLI], environment: f.environment) + #expect(!FileManager.default.fileExists(atPath: f.instruction().path)) + #expect( + String(decoding: try f.bytes(f.instruction(.geminiCLI)), as: UTF8.self).contains("# Rules")) + #expect(try f.bytes(f.target().appendingPathComponent("SKILL.md")) == skill) + let next = try f.store.readLedger() + for (id, component) in previous.components where component.kind == "skills" { + #expect(next.components[id] == component) + } + } + + @Test func survivorRetargetDoesNotAuthorizeChangedOwnContent() throws { + let f = try UpdateFixture() + let own = f.root.appendingPathComponent(".agent/instructions/guide.md") + try f.write("---\ndescription: Own.\n---\n# Own\n\nLocked\n", to: own) + try f.declare(agents: [.codex]) + var declaration = try f.store.loadDeclaration() + try declaration.updateInstructions { $0?.sections = ["guide", "fixture:rules"] } + try f.store.save(declaration: declaration, ledger: ResolvedLedger()) + _ = try f.apply() + try f.write("---\ndescription: Own.\n---\n# Own\n\nChanged\n", to: own) + let before = try f.snapshot() + var delivered = false + #expect(throws: (any Error).self) { + try InstructionOperations.remove( + names: ["rules"], agents: [.geminiCLI], environment: f.environment + ) { _ in delivered = true } + } + #expect(!delivered) + #expect(try f.snapshot() == before) + } + + @Test func instructionMutationRefusesUnappliedSkillRecipientChange() throws { + let f = try UpdateFixture() + try f.install(agents: [.codex]) + var declaration = try f.store.loadDeclaration() + declaration.components = declaration.components.map { + guard case .skills(let source, var selection) = $0 else { return $0 } + selection.agents = [.cursor] + return .skills(source: source, selection) + } + try f.store.save(declaration: declaration, ledger: f.store.readLedger()) + let before = try f.snapshot() + var delivered = false + #expect(throws: (any Error).self) { + try InstructionOperations.add( + InstructionAddOptions( + source: f.repo.path, alias: "fixture", names: ["rules"], environment: f.environment) + ) { _ in delivered = true } + } + #expect(!delivered) + #expect(try f.snapshot() == before) + } + + @Test func retainedEditedOutputReportsNoManagedRecipients() throws { + let f = try UpdateFixture() + try f.install(agents: [.codex]) + try f.write("edited generated output", to: f.instruction()) + let report = try InstructionOperations.remove(names: ["rules"], environment: f.environment) + let target = try #require(report.targets.first { $0.url == f.instruction() }) + #expect(target.before == target.after) + #expect(target.afterAgents.isEmpty) + #expect(try f.bytes(f.instruction()) == Data("edited generated output".utf8)) + } + + @Test func foreignTakeoverRefusesBeforeCallbackButPreviewRemainsAvailable() throws { + let f = try UpdateFixture() + try f.declare(agents: [.codex]) + try f.write("handwritten", to: f.instruction()) + let before = try f.snapshot() + #expect(try f.preview().instructions.targets.contains { $0.foreign }) + var delivered = false + #expect(throws: (any Error).self) { + try UpdateOperations.withPreparedUpdate(environment: f.environment) { + delivered = true + return try $0.apply() + } + } + #expect(!delivered) + #expect(try f.snapshot() == before) + } + + @Test func installedSkillsAndUnchangedUpdateKeepRecordedNamedTarget() throws { + let f = try UpdateFixture() + try f.declare(agents: [.codex, .claudeCode]) + var declaration = try f.store.loadDeclaration() + declaration.components.append( + .command( + name: "review", description: "Review", prompt: .literal("Review exact sources."), + agents: [.claudeCode])) + try f.store.save(declaration: declaration, ledger: ResolvedLedger()) + _ = try f.apply() + + let ledger = try f.store.loadLedger() + let command = try #require(ledger.deployments.first { $0.route.hasSuffix("-components@1") }) + let commandURL = try command.target.resolve(roots: f.store.ledgerRoots(recordedIn: ledger)) + let commandBytes = try f.bytes(commandURL) + let managed = try SkillOperations.listManaged(environment: f.environment) + #expect(managed.map(\.name) == ["demo", "demo"]) + #expect(Set(managed.map(\.agent)) == [.codex, .claudeCode]) + #expect(managed.allSatisfy { $0.status == .installed }) + + let request = UpdateRequest(kinds: [.skills]) + let before = try f.snapshot() + let preview = try UpdateOperations.preview(request, environment: f.environment) + #expect(!preview.hasChanges) + #expect(preview.readLocations.contains { $0.path == commandURL.path }) + let skills = try SkillOperations.updateInstalled(environment: f.environment) + #expect(skills.map(\.skill) == preview.skills.map(\.skill)) + _ = try UpdateOperations.withPreparedUpdate(request, environment: f.environment) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + #expect(try f.snapshot() == before) + #expect(try f.bytes(commandURL) == commandBytes) + } + + @Test func missingLiveSkillReconciliationReplaysOnlyPreviousNativeResources() throws { + let f = try UpdateFixture() + try f.declare(mode: .edit, agents: [.codex]) + var declaration = try f.store.loadDeclaration() + declaration.components.append( + .command( + name: "review", description: "Review", prompt: .literal("Frozen review"), + agents: [.claudeCode])) + try f.store.save(declaration: declaration, ledger: ResolvedLedger()) + _ = try f.apply() + let ledger = try f.store.readLedger() + let command = try #require(ledger.deployments.first { $0.route.hasSuffix("-components@1") }) + let commandURL = try command.target.resolve(roots: f.store.ledgerRoots) + let commandBytes = try f.bytes(commandURL) + try FileManager.default.removeItem(at: f.repo.appendingPathComponent("skills/demo")) + let before = try f.snapshot() + #expect(throws: (any Error).self) { try UpdateOperations.restore(environment: f.environment) } + #expect(try f.snapshot() == before) + _ = try SkillOperations.updateInstalled(environment: f.environment, apply: true) + #expect(try f.store.loadResolved().skills.isEmpty) + #expect(try f.bytes(commandURL) == commandBytes) + } + + @Test func namedSkillActionsDoNotReadUnselectedFIFO() throws { + let f = try UpdateFixture() + try f.write( + "---\nname: broken\ndescription: Broken.\n---\nBroken\n", + to: f.repo.appendingPathComponent("skills/broken/SKILL.md")) + try f.commit() + try f.declare(agents: [.codex]) + _ = try f.apply() + let broken = f.target().deletingLastPathComponent().appendingPathComponent("broken") + let fifo = broken.appendingPathComponent("fifo") + #expect(mkfifo(fifo.path, 0o600) == 0) + let brokenBytes = try f.bytes(broken.appendingPathComponent("SKILL.md")) + try f.advance() + let updated = try SkillOperations.updateInstalled( + environment: f.environment, skillNames: ["demo"], apply: true) + #expect(updated.map(\.skill) == ["demo"]) + _ = try SkillOperations.remove(skillNames: ["demo"], environment: f.environment) + #expect(try f.bytes(broken.appendingPathComponent("SKILL.md")) == brokenBytes) + var info = stat() + #expect(lstat(fifo.path, &info) == 0) + #expect(info.st_mode & mode_t(S_IFMT) == mode_t(S_IFIFO)) + let before = try f.snapshot() + #expect(throws: (any Error).self) { + try SkillOperations.updateInstalled( + environment: f.environment, skillNames: ["broken"], apply: true) + } + #expect(try f.snapshot() == before) + } +} + +extension ConsumerLifecycleRegressionTests { + private func finiteRules(_ f: UpdateFixture) -> Declaration { + Declaration( + sources: ["fixture": SourceDeclaration(kind: .local, location: f.repo.path)], + components: [ + .instructions(InstructionsDeclaration(agents: [.codex], sections: ["fixture:extra"])) + ]) + } + + private func writeFiniteRules(_ f: UpdateFixture) throws { + try f.write( + "---\ndescription: Extra.\n---\n# Extra\n\nSelected addition\n", + to: f.repo.appendingPathComponent("instructions/extra.md")) + try f.commit() + } + + @Test func finiteAdditionPreservesPinsAndSharedInstructionSurvivors() throws { + let f = try UpdateFixture() + try f.install(agents: [.codex]) + let previous = try f.store.loadLedger() + let original = try f.store.loadDeclaration() + try f.advance() + try writeFiniteRules(f) + let before = try FileHash.folderHash(f.root) + let scope = try UpdateOperations.inspect(environment: f.environment) + let discovery = try #require(try UpdateOperations.captureAddition(finiteRules(f), in: scope)) + #expect(try FileHash.folderHash(f.root) == before) + var request = discovery.updateRequest() + request.replace = true + request.changingAccess = true + let preview = try UpdateOperations.preview(request, environment: f.environment) + let target = try #require(preview.instructions.targets.first { $0.url == f.instruction() }) + let bytes = try #require(target.after) + #expect(String(decoding: bytes, as: UTF8.self).contains("Selected addition")) + #expect(String(decoding: bytes, as: UTF8.self).contains("old")) + #expect(!String(decoding: bytes, as: UTF8.self).contains("\nnew\n")) + _ = try UpdateOperations.withPreparedUpdate(request, environment: f.environment) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + #expect(try f.bytes(f.instruction()) == bytes) + let next = try f.store.loadLedger() + for (id, component) in previous.components { + #expect(next.components[id] == component) + #expect(next.sources[component.source] == previous.sources[component.source]) + } + let declaration = try f.store.loadDeclaration() + #expect(Array(declaration.components.prefix(original.components.count)) == original.components) + #expect(declaration.sources["fixture"] == original.sources["fixture"]) + } + + @Test func capturedAdditionRejectsForeignDestinationAndMutatedRequest() throws { + let f = try UpdateFixture() + let other = try UpdateFixture() + try writeFiniteRules(f) + for fixture in [f, other] { + try fixture.store.save(declaration: Declaration(agents: [.codex]), ledger: ResolvedLedger()) + } + #expect(try f.bytes(f.store.declarationURL) == other.bytes(other.store.declarationURL)) + var environment = f.environment + environment.environment["INSPECTION_SECRET"] = "CAPTURED_ENVIRONMENT_CANARY" + let inspection = try UpdateOperations.inspect(environment: environment) + #expect(!String(reflecting: inspection).contains("CAPTURED_ENVIRONMENT_CANARY")) + let discovery = try #require( + try UpdateOperations.captureAddition(finiteRules(f), in: inspection)) + #expect(!String(reflecting: discovery).contains("CAPTURED_ENVIRONMENT_CANARY")) + let otherBefore = try FileHash.folderHash(other.root) + var called = false + #expect(throws: (any Error).self) { + try UpdateOperations.withPreparedUpdate( + discovery.updateRequest(), environment: other.environment + ) { + _ in called = true + } + } + #expect(!called) + #expect(try FileHash.folderHash(other.root) == otherBefore) + var modified = discovery.updateRequest() + modified.operation = .update + #expect(throws: (any Error).self) { + try UpdateOperations.preview(modified, environment: f.environment) + } + _ = try UpdateOperations.withPreparedUpdate( + discovery.updateRequest(), environment: f.environment + ) { + try $0.apply() + } + #expect(try f.store.loadDeclaration().sources["fixture"] != nil) + } + + @Test(arguments: ["declaration", "ledger", "source"]) + func capturedAdditionRejectsChangedEvidence(_ changed: String) throws { + let f = try UpdateFixture() + try f.install(agents: [.codex]) + try writeFiniteRules(f) + let discovery = try #require( + try UpdateOperations.captureAddition( + finiteRules(f), in: UpdateOperations.inspect(environment: f.environment))) + if changed == "declaration" { + try f.write( + String(decoding: f.bytes(f.store.declarationURL), as: UTF8.self) + "\n# changed\n", + to: f.store.declarationURL) + } else if changed == "ledger" { + try f.write( + String(decoding: f.bytes(f.store.resolvedURL), as: UTF8.self) + "\n", + to: f.store.resolvedURL) + } else { + try f.write( + "---\ndescription: Extra.\n---\n# Extra\n\nChanged selected source\n", + to: f.repo.appendingPathComponent("instructions/extra.md")) + try f.commit() + } + var called = false + #expect(throws: (any Error).self) { + try UpdateOperations.withPreparedUpdate(discovery.updateRequest(), environment: f.environment) + { + _ in called = true + } + } + #expect(!called) + } + + @Test func emptyAdditionDoesNotInitializeAndPendingAuthoredGraphIsProtected() throws { + let f = try UpdateFixture() + let scope = try UpdateOperations.inspect(environment: f.environment) + let before = try FileHash.folderHash(f.root) + #expect( + try UpdateOperations.captureAddition( + Declaration(sources: ["unused": .init(kind: .local, location: "/absent")]), in: scope) + == nil) + #expect(try FileHash.folderHash(f.root) == before) + try f.declare(agents: [.codex]) + try writeFiniteRules(f) + #expect(throws: (any Error).self) { + try UpdateOperations.captureAddition( + finiteRules(f), in: UpdateOperations.inspect(environment: f.environment)) + } + } +} + +extension ConsumerLifecycleRegressionTests { + @Test(arguments: [false, true]) + func finiteAdditionProtectsConditionalProducerUsesAndConflictingPins(_ sharedSource: Bool) throws + { + let f = try UpdateFixture() + let producerFixture = try sharedSource ? f : UpdateFixture() + try producerFixture.write( + """ + version: 1 + groups: + tools: + components: [{kind: mcpServer, name: protected-tool, transport: {kind: stdio, executable: never-run}, agents: [claude-code]}] + exports: [tools] + """, to: producerFixture.repo.appendingPathComponent(".agent/agents.yaml")) + try producerFixture.commit() + try f.declare(agents: [.codex]) + var original = try f.store.loadDeclaration() + let alias = sharedSource ? "fixture" : "producer" + if !sharedSource { + original.sources[alias] = .init(kind: .local, location: producerFixture.repo.path) + } + original.uses = [.init(name: "tools", source: alias, condition: .init(scopes: [.project]))] + try f.store.save(declaration: original, ledger: ResolvedLedger()) + _ = try f.apply() + let previous = try UpdateOperations.inspect(environment: f.environment) + let producer = try #require(previous.components.first { $0.name == "protected-tool" }) + #expect(producer.occurrences.allSatisfy { !$0.consumerEditable }) + try writeFiniteRules(f) + let scope = try UpdateOperations.inspect(environment: f.environment) + var conflicting = finiteRules(f) + conflicting.sources["fixture"]?.location = f.root.path + #expect(throws: (any Error).self) { + try UpdateOperations.captureAddition(conflicting, in: scope) + } + if sharedSource { + let before = try f.snapshot() + #expect(throws: (any Error).self) { + try UpdateOperations.captureAddition(finiteRules(f), in: scope) + } + #expect(try f.snapshot() == before) + return + } + let discovery = try #require(try UpdateOperations.captureAddition(finiteRules(f), in: scope)) + let preview = try UpdateOperations.preview( + discovery.updateRequest(), environment: f.environment) + _ = try UpdateOperations.withPreparedUpdate( + discovery.updateRequest(), environment: f.environment + ) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + let next = try UpdateOperations.inspect(environment: f.environment) + let retained = try #require(next.components.first { $0.name == "protected-tool" }) + #expect(retained.revision == producer.revision) + #expect(retained.configuration == producer.configuration) + #expect(retained.conditions == producer.conditions) + #expect(retained.occurrences.allSatisfy { !$0.consumerEditable }) + #expect(try f.store.loadDeclaration().uses == original.uses) + #expect(throws: (any Error).self) { + try UpdateOperations.preview( + .init(operation: .remove, selections: [retained.selection]), + environment: f.environment) + } + } + +} + +extension ConsumerLifecycleRegressionTests { + @Test func finiteAdditionRefusesNewForeignTargetBeforeCallback() throws { + let f = try UpdateFixture() + try writeFiniteRules(f) + let discovery = try #require( + try UpdateOperations.captureAddition( + finiteRules(f), in: UpdateOperations.inspect(environment: f.environment))) + _ = try UpdateOperations.preview(discovery.updateRequest(), environment: f.environment) + try f.write("Handwritten after preview\n", to: f.instruction()) + var called = false + #expect(throws: (any Error).self) { + try UpdateOperations.withPreparedUpdate(discovery.updateRequest(), environment: f.environment) + { + _ in called = true + } + } + #expect(!called) + #expect(try f.bytes(f.instruction()) == Data("Handwritten after preview\n".utf8)) + #expect(!FileManager.default.fileExists(atPath: f.store.declarationURL.path)) + #expect(!FileManager.default.fileExists(atPath: f.store.resolvedURL.path)) + } +} + +extension ConsumerLifecycleRegressionTests { + @Test func finiteNamedCommandAdmitsItsNewClosedRoute() throws { + let f = try UpdateFixture() + let scope = try UpdateOperations.inspect(environment: f.environment) + let discovery = try #require( + try UpdateOperations.captureAddition( + Declaration(components: [ + .command( + name: "review", description: "Review sources", + prompt: .literal("Review exact sources."), agents: [.claudeCode]) + ]), in: scope)) + let before = try FileHash.folderHash(f.root) + let preview = try UpdateOperations.preview( + discovery.updateRequest(), environment: f.environment) + #expect(try FileHash.folderHash(f.root) == before) + _ = try UpdateOperations.withPreparedUpdate( + discovery.updateRequest(), environment: f.environment + ) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + let installed = try UpdateOperations.inspect(environment: f.environment) + let deployment = try #require(installed.deployments.first) + #expect(deployment.status == .current) + #expect( + try String(contentsOf: deployment.location, encoding: .utf8).contains("Review exact sources.") + ) + } +} diff --git a/Tests/AgentsUpdatesTests/ConsumerSourceRegressionTests.swift b/Tests/AgentsUpdatesTests/ConsumerSourceRegressionTests.swift new file mode 100644 index 0000000..eefd02e --- /dev/null +++ b/Tests/AgentsUpdatesTests/ConsumerSourceRegressionTests.swift @@ -0,0 +1,140 @@ +import AgentsCore +import AgentsInstructions +import AgentsManifest +import AgentsSkills +import AgentsUpdates +import Foundation +import StateTestSupport +import Testing + +@Suite("Consumer local source provenance", .serialized) +struct ConsumerSourceRegressionTests { + private func declare(_ fixture: UpdateFixture, mode: InstallMode = .copy, source: URL? = nil) + throws + { + try fixture.store.save( + declaration: Declaration( + sources: ["local": .init(kind: .local, location: (source ?? fixture.repo).path)], + skills: ["local": .init(select: .all, agents: [.codex], mode: mode)]), + ledger: fixture.store.loadLedger()) + } + + @Test(arguments: [InstallMode.copy, .link]) + func retainedGitSelectionRefusesWorkingTreeDowngrade(_ mode: InstallMode) throws { + let fixture = try UpdateFixture() + try declare(fixture, mode: mode) + _ = try fixture.apply() + let committed = try fixture.bytes(fixture.target().appendingPathComponent("SKILL.md")) + let revision = try fixture.git(["rev-parse", "HEAD"]) + try fixture.writeSource("uncommitted working tree") + _ = try SkillOperations.updateInstalled(environment: fixture.environment, apply: true) + #expect(try fixture.bytes(fixture.target().appendingPathComponent("SKILL.md")) == committed) + #expect(try fixture.store.loadResolved().skills["demo"]?.revision == revision) + try FileManager.default.removeItem(at: fixture.repo.appendingPathComponent(".git")) + let before = try fixture.snapshot() + do { + _ = try SkillOperations.updateInstalled(environment: fixture.environment, apply: true) + Issue.record("a recorded Git selection became a working-tree snapshot") + } catch { + let diagnostic = String(describing: error) + #expect(diagnostic.contains("Git could not ")) + #expect(diagnostic.contains(fixture.repo.path)) + #expect(diagnostic.contains("fatal:")) + #expect(diagnostic.contains(fixture.store.declarationURL.path)) + } + #expect(try fixture.snapshot() == before) + } + + @Test func genuineDirectoryTracksItsWorkingContent() throws { + let fixture = try UpdateFixture() + try FileManager.default.removeItem(at: fixture.repo.appendingPathComponent(".git")) + try declare(fixture) + _ = try fixture.apply() + try fixture.writeSource("new directory bytes") + _ = try SkillOperations.updateInstalled(environment: fixture.environment, apply: true) + #expect( + String( + decoding: try fixture.bytes(fixture.target().appendingPathComponent("SKILL.md")), + as: UTF8.self + ).contains("new directory bytes")) + #expect(try fixture.store.loadResolved().skills["demo"]?.revision == nil) + } + + @Test func explicitEditRemainsLiveAfterGitMetadataDisappears() throws { + let fixture = try UpdateFixture() + try declare(fixture) + _ = try fixture.apply() + try FileManager.default.removeItem(at: fixture.repo.appendingPathComponent(".git")) + try fixture.writeSource("live edit bytes") + try declare(fixture, mode: .edit) + _ = try SkillOperations.updateInstalled(environment: fixture.environment, apply: true) + #expect( + fixture.target().resolvingSymlinksInPath().path + == fixture.repo.appendingPathComponent("skills/demo").resolvingSymlinksInPath().path) + #expect( + String( + decoding: try fixture.bytes(fixture.target().appendingPathComponent("SKILL.md")), + as: UTF8.self + ).contains("live edit bytes")) + try fixture.writeSource("later live bytes") + #expect( + String( + decoding: try fixture.bytes(fixture.target().appendingPathComponent("SKILL.md")), + as: UTF8.self + ).contains("later live bytes")) + } + + @Test func aliasRebindingUsesActualRecordedSourceIdentity() throws { + let fixture = try UpdateFixture() + try declare(fixture) + _ = try fixture.apply() + let directory = fixture.root.appendingPathComponent("directory") + try fixture.write( + "---\nname: demo\ndescription: Directory\n---\nRebound content\n", + to: directory.appendingPathComponent("skills/demo/SKILL.md")) + try declare(fixture, source: directory) + _ = try SkillOperations.updateInstalled(environment: fixture.environment, apply: true) + #expect( + String( + decoding: try fixture.bytes(fixture.target().appendingPathComponent("SKILL.md")), + as: UTF8.self + ).contains("Rebound content")) + #expect(try fixture.store.loadResolved().skills["demo"]?.source == "local:" + directory.path) + } +} + +@Suite("Consumer native instruction projection", .serialized) +struct ConsumerProjectionRegressionTests { + @Test(arguments: [InstallScope.project, .user]) + func nativeCommandDoesNotBecomeInstructionTarget(_ scope: InstallScope) throws { + let fixture = try UpdateFixture(scope: scope) + try fixture.write( + """ + version: 1 + sources: {rules: {path: "\(fixture.repo.path)"}} + components: + - {kind: command, name: review, description: Review, prompt: Review sources., agents: [claude-code]} + - {kind: instructions, agents: [codex, claude-code], sections: [{name: rules, source: rules}]} + """, to: fixture.store.declarationURL) + if scope == .project { + try fixture.write( + "# Existing Claude instructions\n", to: fixture.root.appendingPathComponent("CLAUDE.md")) + } + _ = try fixture.apply() + let ledger = try fixture.store.loadLedger() + #expect(ledger.deployments.contains { $0.route == "agents/claude-components@1" }) + if scope == .project { + #expect(ledger.deployments.contains { $0.route == "agents/claude-import@1" }) + } + let healthy = try InstructionOperations.doctor(scope: scope, environment: fixture.environment) + #expect(!healthy.diagnostics.contains { $0.kind == .invalidTarget }) + let file = fixture.instruction() + let original = try fixture.bytes(file) + try (original + Data("\nEdited target\n".utf8)).write(to: file) + let drift = try InstructionOperations.doctor(scope: scope, environment: fixture.environment) + #expect(drift.diagnostics.contains { $0.kind == .drift && $0.path == file }) + try FileManager.default.removeItem(at: file) + let missing = try InstructionOperations.doctor(scope: scope, environment: fixture.environment) + #expect(missing.diagnostics.contains { $0.kind == .missingTarget && $0.path == file }) + } +} diff --git a/Tests/AgentsUpdatesTests/ContentAuditTests.swift b/Tests/AgentsUpdatesTests/ContentAuditTests.swift new file mode 100644 index 0000000..74696c0 --- /dev/null +++ b/Tests/AgentsUpdatesTests/ContentAuditTests.swift @@ -0,0 +1,442 @@ +import AgentsCore +import AgentsUpdates +import Foundation +import StateTestSupport +import Testing + +struct ContentAuditTests { + @Test func discoversSixAgentProfilesWithoutALock() throws { + let fixture = try Fixture() + let marker = "\u{202e}" + let prompts = [ + "src/AGENTS.override.md": "Codex" + marker, + ".codex/agents/reviewer.toml": "developer_instructions = 'Codex\(marker)'", + ".claude/rules/nested/review.md": "Claude" + marker, + ".claude/skills/fixture/SKILL.md": "Skill" + marker, + ".cursor/rules/nested/review.mdc": "Cursor" + marker, + ".gemini/commands/nested/review.toml": "prompt = 'Gemini\(marker)'", + ".opencode/commands/review.md": "OpenCode" + marker, + ".agents/rules/nested/review.md": "Antigravity" + marker, + ".agents/skills/common/SKILL.md": "Shared skill" + marker, + ".agent/instructions/review.md": "Project authoring" + marker, + ] + for (path, text) in prompts { try fixture.write(path, text) } + + try fixture.write(".agents/skills/common/examples/reference.md", marker) + try fixture.write(".codex/auth.json", #"{"prompt":"\u202e"}"#) + try fixture.write(".claude/history/AGENTS.md", marker) + try fixture.write(".cursor/rules/credentials.local.mdc", marker) + try fixture.write("other-checkout/.git", "gitdir: unrelated") + try fixture.write("other-checkout/AGENTS.md", marker) + try fixture.write(".claude/hooks/run.sh", marker) + try fixture.write(".claude/hooks/package.json", #"{"type":"module"}"#) + try fixture.write( + ".codex/hooks.json", + #"{"hooks":{"Stop":[{"hooks":[{"type":"command","command":"\u202e"}]}]}}"#) + try fixture.write( + ".agents/hooks.json", #"{"hooks":{"PreToolUse":{"Bash":[{"command":"\u202e"}]}}}"#) + + let audit = ContentAuditOperations.scan(environment: fixture.environment) + #expect(Set(audit.findings.map(\.location.path)) == Set(prompts.keys)) + #expect(audit.findings.allSatisfy { $0.ownership == .untracked && $0.severity == .critical }) + #expect(audit.ciExitCode == 1) + #expect(audit.targets.first { $0.path == ".claude/hooks/package.json" }?.status == .skipped) + #expect(audit.targets.first { $0.path == ".codex/hooks.json" }?.status == .skipped) + #expect(!audit.readLocations.contains { $0.path.contains("other-checkout") }) + #expect(!audit.readLocations.contains(fixture.url(".codex/auth.json"))) + #expect(!FileManager.default.fileExists(atPath: fixture.url(".agent/.agents.lock").path)) + #expect(!FileManager.default.fileExists(atPath: fixture.url(".agent/agents.resolved").path)) + + let onlyCursor = ContentAuditOperations.scan( + agents: [.cursor], environment: fixture.environment) + #expect(onlyCursor.findings.contains { $0.location.path.hasPrefix(".cursor/rules/") }) + #expect(!onlyCursor.findings.contains { $0.location.path.hasPrefix(".claude/") }) + } + + @Test func scansOnlyIndexedNativeFieldsAndReportsSourceCoordinates() throws { + let fixture = try Fixture() + let claude = ".claude/settings.json" + try fixture.write( + claude, + #""" + { + "name": "\u202E", + "hooks": { + "Stop/~end": [ + {"hooks":[{"type":"command","command":"\u202E","prompt":"\u202E"}]}, + {"hooks":[{"type":"prompt","prompt":"A\n🧭\uDB40\uDD00"}]} + ] + } + } + """#) + let cursor = ".cursor/hooks.json" + try fixture.write( + cursor, + #"{"version":1,"hooks":{"stop":[{"command":"\u202E"},{"type":"prompt","prompt":"\u200B"}]}}"#) + let gemini = ".gemini/commands/tasks/review.toml" + try fixture.write( + gemini, + #""" + description = "\u202E" + prompt = """ + Read 🧭\u202E + """ + """#) + let opencode = "opencode.jsonc" + try fixture.write( + opencode, + #""" + // Sidebar setting + {"commands":{"a/b":{"template":"Read\u202E","model":"\u202E"}}, + "agents":{"sample":{"system":"Inspect\u200B","description":"\u202E"}}, + "mcp":{"ignored":{"command":["\u202E"]}},} + """#) + + let audit = ContentAuditOperations.scan(environment: fixture.environment) + #expect(audit.findings.count == 5) + let claudeFinding = try #require(audit.findings.first { $0.location.path == claude }) + #expect(claudeFinding.codePoint == 0xe0100) + #expect(claudeFinding.location.field == "/hooks/Stop~1~0end/1/hooks/0/prompt") + #expect(claudeFinding.location.line == 6) + #expect(claudeFinding.location.promptLine == 2) + #expect(claudeFinding.location.promptColumn == 3) + let raw = try String(contentsOf: fixture.url(claude), encoding: .utf8) + let lines = raw.split(separator: "\n") + try #require(lines.count > 5) + let claudeLine = lines[5] + let escape = try #require(claudeLine.range(of: #"\uDB40"#)) + #expect(claudeFinding.location.column == claudeLine[.. URL { environment.projectDirectory.appendingPathComponent(path) } + + @discardableResult + func write(_ path: String, _ text: String) throws -> URL { + let file = url(path) + try writeAbsolute(file, text) + return file + } + + func writeAbsolute(_ file: URL, _ text: String) throws { + try FileManager.default.createDirectory( + at: file.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data(text.utf8).write(to: file) + } + } +} diff --git a/Tests/AgentsUpdatesTests/DeclarationYAMLUpdateTests.swift b/Tests/AgentsUpdatesTests/DeclarationYAMLUpdateTests.swift new file mode 100644 index 0000000..b502388 --- /dev/null +++ b/Tests/AgentsUpdatesTests/DeclarationYAMLUpdateTests.swift @@ -0,0 +1,171 @@ +import AgentsCore +import AgentsManifest +import AgentsUpdates +import Foundation +import StateTestSupport +import Testing + +struct DeclarationYAMLUpdateTests { + @Test(arguments: [InstallScope.project, .user]) + func createsFirstDeclarationWithExactBytes(_ scope: InstallScope) throws { + let fixture = try UpdateFixture(scope: scope) + let yaml = """ + \u{FEFF}# Déclaration + version: 1 # keep spacing + defaultAgents: [codex] + components: + - kind: mcpServer + name: documentation + transport: {kind: stdio, executable: fixture-command} + """ + let bytes = Data(yaml.replacingOccurrences(of: "\n", with: "\r\n").utf8) + let request = UpdateRequest(declarationYAML: bytes, expectedDeclarationDigest: "absent") + let report = try UpdateOperations.preview( + request, scope: scope, environment: fixture.environment) + #expect(report.hasChanges) + #expect(report.components.map(\.name) == ["documentation"]) + #expect(try fixture.store.loadManifest() == nil) + #expect(!FileManager.default.fileExists(atPath: fixture.store.resolvedURL.path)) + + let applied = try UpdateOperations.withPreparedUpdate( + request, scope: scope, environment: fixture.environment + ) { + try $0.apply(ifUnchangedFrom: report.displayedFingerprint) + } + #expect(applied.report.hasChanges) + #expect(try fixture.bytes(fixture.store.declarationURL) == bytes) + #expect(FileManager.default.fileExists(atPath: fixture.store.resolvedURL.path)) + let inspection = try UpdateOperations.inspect(scope: scope, environment: fixture.environment) + #expect(inspection.deployments.contains { $0.status == .current }) + } + + @Test func commentOnlyEditReportsChangesAndConfirmsExactBytes() throws { + let fixture = try UpdateFixture() + let url = fixture.store.declarationURL + try fixture.store.save(declaration: Declaration(), ledger: ResolvedLedger()) + try fixture.write("version: 1\n# Before\n", to: url) + let baseline = try #require(try fixture.store.loadManifest()) + let previousLock = try fixture.bytes(fixture.store.resolvedURL) + let bytes = Data("version: 1\n# After\n".utf8) + let request = UpdateRequest(declarationYAML: bytes, expectedDeclarationDigest: baseline.digest) + let report = try UpdateOperations.preview(request, environment: fixture.environment) + #expect(report.hasChanges) + #expect(report.components.isEmpty) + #expect(report.skills.isEmpty) + #expect(!report.instructions.hasChanges) + #expect(try fixture.bytes(url) == Data(baseline.bytes)) + + let alternate = UpdateRequest( + declarationYAML: Data("version: 1\n# Another draft\n".utf8), + expectedDeclarationDigest: baseline.digest) + let alternateReport = try UpdateOperations.preview(alternate, environment: fixture.environment) + #expect(alternateReport.displayedFingerprint != report.displayedFingerprint) + #expect(throws: UpdateApplyError.self) { + try UpdateOperations.withPreparedUpdate(request, environment: fixture.environment) { + try $0.apply(ifUnchangedFrom: alternateReport.displayedFingerprint) + } + } + #expect(try fixture.bytes(url) == Data(baseline.bytes)) + + _ = try UpdateOperations.withPreparedUpdate(request, environment: fixture.environment) { + try $0.apply(ifUnchangedFrom: report.displayedFingerprint) + } + #expect(try fixture.bytes(url) == bytes) + #expect(try fixture.bytes(fixture.store.resolvedURL) == previousLock) + let updated = try #require(try fixture.store.loadManifest()) + #expect(updated.declaration == baseline.declaration) + let unchanged = UpdateRequest(declarationYAML: bytes, expectedDeclarationDigest: updated.digest) + let unchangedReport = try UpdateOperations.preview(unchanged, environment: fixture.environment) + #expect(!unchangedReport.hasChanges) + } + + @Test func invalidYAMLIsRejectedBeforePublication() throws { + let fixture = try UpdateFixture() + let url = fixture.store.declarationURL + try fixture.write("version: 1\n", to: url) + let baseline = try #require(try fixture.store.loadManifest()) + for bytes in [ + Data("version: [\n".utf8), + Data("version: 1\nwatch: [missing-source]\n".utf8), + Data([0xFF]), + Data(repeating: 0x20, count: ManifestLimits.Input.bytes + 1), + ] { + let request = UpdateRequest( + declarationYAML: bytes, expectedDeclarationDigest: baseline.digest) + #expect(throws: ManifestFailure.self) { + try UpdateOperations.preview(request, environment: fixture.environment) + } + #expect(throws: ManifestFailure.self) { + try UpdateOperations.withPreparedUpdate(request, environment: fixture.environment) { + try $0.apply() + } + } + } + #expect(try fixture.bytes(url) == Data(baseline.bytes)) + #expect(!FileManager.default.fileExists(atPath: fixture.store.resolvedURL.path)) + } + + @Test func staleDigestRejectsCommentChangeAfterPreview() throws { + let fixture = try UpdateFixture() + let url = fixture.store.declarationURL + try fixture.write("version: 1\n# Before\n", to: url) + let baseline = try #require(try fixture.store.loadManifest()) + let request = UpdateRequest( + declarationYAML: Data("version: 1\n# Draft\n".utf8), + expectedDeclarationDigest: baseline.digest) + let report = try UpdateOperations.preview(request, environment: fixture.environment) + let external = "version: 1\n# External edit\n" + try fixture.write(external, to: url) + #expect(throws: CoreError.self) { + try UpdateOperations.withPreparedUpdate(request, environment: fixture.environment) { + try $0.apply(ifUnchangedFrom: report.displayedFingerprint) + } + } + #expect(try fixture.bytes(url) == Data(external.utf8)) + #expect(!FileManager.default.fileExists(atPath: fixture.store.resolvedURL.path)) + } + + @Test func absentDigestDoesNotReplaceMissingDeclarationInEstablishedScope() throws { + let fixture = try UpdateFixture() + try fixture.store.save(declaration: Declaration(), ledger: ResolvedLedger()) + let previousLock = try fixture.bytes(fixture.store.resolvedURL) + try FileManager.default.removeItem(at: fixture.store.declarationURL) + let request = UpdateRequest( + declarationYAML: Data("version: 1\n".utf8), expectedDeclarationDigest: "absent") + let error = CoreError.missingDeclaration(fixture.store.declarationURL.path) + #expect(throws: error) { + try UpdateOperations.preview(request, environment: fixture.environment) + } + #expect(throws: error) { + try UpdateOperations.withPreparedUpdate(request, environment: fixture.environment) { + try $0.apply() + } + } + #expect(!FileManager.default.fileExists(atPath: fixture.store.declarationURL.path)) + #expect(try fixture.bytes(fixture.store.resolvedURL) == previousLock) + } + + @Test func editedSourcesMustPassSourcePolicy() throws { + let fixture = try UpdateFixture() + let policy = SourcePolicyOperations.policyURL(scope: .project, environment: fixture.environment) + try fixture.write("version: 1\ndeny: [local]\n", to: policy) + let bytes = Data( + """ + version: 1 + sources: {fixture: {path: ./source}} + components: + - {kind: skills, source: fixture, select: [demo], agents: [codex], mode: edit} + """.utf8) + let request = UpdateRequest(declarationYAML: bytes, expectedDeclarationDigest: "absent") + #expect(throws: SourcePolicyFailure.self) { + try UpdateOperations.preview(request, environment: fixture.environment) + } + #expect(throws: SourcePolicyFailure.self) { + try UpdateOperations.withPreparedUpdate(request, environment: fixture.environment) { + try $0.apply() + } + } + #expect(try fixture.store.loadManifest() == nil) + #expect(!FileManager.default.fileExists(atPath: fixture.target().path)) + } +} diff --git a/Tests/AgentsUpdatesTests/ExistingGlobalConfigurationTests.swift b/Tests/AgentsUpdatesTests/ExistingGlobalConfigurationTests.swift new file mode 100644 index 0000000..7cf2b8d --- /dev/null +++ b/Tests/AgentsUpdatesTests/ExistingGlobalConfigurationTests.swift @@ -0,0 +1,688 @@ +import AgentsInstructions +import AgentsManifest +import AgentsSkills +import AgentsUpdates +import Foundation +import StateTestSupport +import Testing + +@testable import AgentsCore + +@Suite("Use Existing Configuration") +struct ExistingGlobalConfigurationTests { + @Test func recognitionAndCancellationNeedNoWrites() throws { + let f = try UpdateFixture(scope: .user) + let empty = try FileHash.folderHash(f.environment.homeDirectory) + #expect(try !ExistingGlobalConfiguration.isAvailable(environment: f.environment)) + #expect(try FileHash.folderHash(f.environment.homeDirectory) == empty) + let json = try #require(f.store.configurationJSONURL) + try f.write("{}", to: json) + #expect(try !ExistingGlobalConfiguration.isAvailable(environment: f.environment)) + try ResolvedLedgerCodec.encode(ResolvedLedger(), limits: .standard).write( + to: f.store.resolvedURL) + #expect(try !ExistingGlobalConfiguration.isAvailable(environment: f.environment)) + try StateStore.encodeState(ResolvedState()).write(to: f.store.resolvedURL) + let before = try FileHash.folderHash(f.environment.homeDirectory) + #expect(try ExistingGlobalConfiguration.isAvailable(environment: f.environment)) + let cancelled = try ExistingGlobalConfiguration.preview(environment: f.environment) + #expect(cancelled.skillCount == 0) + #expect(cancelled.declarationURL == f.store.declarationURL) + #expect(try FileHash.folderHash(f.environment.homeDirectory) == before) + #expect(!FileManager.default.fileExists(atPath: cancelled.originalLedgerURL.path)) + #expect( + !FileManager.default.fileExists( + atPath: f.store.directory.appendingPathComponent(".agents.lock").path)) + } + + @Test func importsIndependentPinsAndInspectsActualNativeInstalls() throws { + let input = try ExistingProfile() + let f = input.fixture + let before = try f.snapshot() + let preview = try ExistingGlobalConfiguration.preview(environment: f.environment) + #expect(preview.sourceCount == 2) + #expect(preview.skillCount == 2) + #expect(preview.installationCount == 2) + #expect(preview.instructionCount == 2) + #expect(preview.originalLedgerURL.lastPathComponent == "agents.resolved.original") + #expect(try f.snapshot() == before) + try ExistingGlobalConfiguration.apply(preview) + #expect(try f.bytes(input.json) == input.declarationBytes) + #expect(try f.bytes(preview.originalLedgerURL) == input.lockBytes) + #expect(try f.bytes(f.store.watchURL) == input.watchBytes) + #expect(try !ExistingGlobalConfiguration.isAvailable(environment: f.environment)) + let declaration = try f.store.loadDeclaration() + #expect(declaration.agents == [.codex, .claudeCode]) + #expect(try declaration.skills?["fixture"]?.select == .all) + #expect(try declaration.skills?["fixture"]?.exclude == ["excluded"]) + let override = try #require(try declaration.skills?["fixture"]?.overrides?["demo"]) + #expect(override.mode == .link) + #expect(override.agents == [.codex, .geminiCLI, .claudeCode]) + #expect(try declaration.instructions?.sections == ["fixture:rules"]) + #expect(try declaration.instructions?.chatgpt?["weekly"]?.append == "custom.md") + #expect(try declaration.skills?["live"]?.select == .names(["edit-demo", "uninstalled"])) + #expect(declaration.watch == ["fixture"]) + #expect(try f.store.loadResolved().normalized == input.expected.normalized) + let snapshot = try UpdateOperations.inspect(scope: .user, environment: f.environment) + #expect(snapshot.readLocations.contains(input.json)) + #expect( + snapshot.components.first { $0.kind == .skills && $0.name == "demo" }?.version == "1.2.0") + #expect(snapshot.components.first { $0.kind == .instructions }?.version == "1.3.0") + let skills = snapshot.deployments.filter { $0.format == "agents/skill@1" } + #expect(skills.filter { $0.status == .current }.count == 3) + #expect(skills.filter { $0.status == .missing }.count == 1) + #expect(snapshot.deployments.first { $0.format == "agents/instructions@1" }?.status == .drifted) + #expect( + snapshot.deployments.first { $0.format == "agents/claude-import@1" }?.status == .current) + #expect(try f.bytes(f.instruction()) == Data("Edited outside agents.\n".utf8)) + let statePaths = [f.store.declarationURL.path, f.store.resolvedURL.path] + #expect( + try f.snapshot().filter { !statePaths.contains($0.key) } + == before.filter { !statePaths.contains($0.key) }) + } + + @Test(arguments: [true, false]) + func importedArtifactUsesItsRetainedLocation(_ includeRemote: Bool) throws { + let f = try UpdateFixture(scope: .user) + let cache = SourceCache(store: f.store) + let pin = try f.git(["rev-parse", "HEAD"]) + let remote = "example.invalid/remote" + let gitTree = cache.materializedURL(sourceID: remote, revision: pin) + let remoteSkill = gitTree.appendingPathComponent("skills/demo") + let content = try f.bytes(f.repo.appendingPathComponent("skills/demo/SKILL.md")) + try f.write( + String(decoding: content, as: UTF8.self), to: remoteSkill.appendingPathComponent("SKILL.md")) + let artifactBytes = Data( + "---\nname: index-demo\ndescription: Index fixture\n---\n\nBody\n".utf8) + let index = "https://index.example.invalid" + let artifact = LockedArtifact( + type: .skillMD, url: index + "/demo/SKILL.md", + digest: "sha256:" + FileHash.sha256Hex(data: artifactBytes)) + let artifactTree = try cache.artifactContentURL(digest: artifact.digest) + try f.write( + String(decoding: artifactBytes, as: UTF8.self), + to: artifactTree.appendingPathComponent("SKILL.md")) + try FileManager.default.createDirectory( + at: f.target().deletingLastPathComponent(), withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink( + at: f.target(), withDestinationURL: remoteSkill.resolvingSymlinksInPath()) + let artifactInstall = f.target().deletingLastPathComponent().appendingPathComponent( + "index-demo") + try FileManager.default.createSymbolicLink( + at: artifactInstall, withDestinationURL: artifactTree) + let artifactLink = try PathIdentity(artifactInstall) + var lock = ResolvedState( + sources: [ + remote: .init(kind: .git, url: "https://" + remote), + index: .init(kind: .wellKnown), + ], + skills: [ + "demo": .init( + source: remote, revision: pin, path: "skills/demo", + hash: try "sha256:" + FileHash.folderHash(remoteSkill), installs: ["codex": .link]), + "index-demo": .init( + source: index, artifact: artifact, + hash: try "sha256:" + FileHash.folderHash(artifactTree), installs: ["codex": .link]), + ]) + if !includeRemote { + try FileManager.default.removeItem(at: f.target()) + try FileManager.default.removeItem(at: gitTree) + lock.sources.removeValue(forKey: remote) + lock.skills.removeValue(forKey: "demo") + } + let remoteSource = includeRemote ? "\"remote\":{\"git\":\"https://\(remote)\"}," : "" + let remoteSelection = includeRemote ? "\"remote\":{\"select\":[\"demo\"]}," : "" + let json = try #require(f.store.configurationJSONURL) + try f.write( + """ + {"agents":["codex"],"sources":{\(remoteSource)"index":{"well-known":"\(index)"}}, + "skills":{\(remoteSelection)"index":{"select":["index-demo"],"mode":"link"}}} + """, to: json) + try StateStore.encodeState(lock).write(to: f.store.resolvedURL) + let cacheHash = try FileHash.folderHash(f.store.cacheDirectory) + let preview = try ExistingGlobalConfiguration.preview(environment: f.environment) + #expect(preview.installationCount == lock.skills.count) + try ExistingGlobalConfiguration.apply(preview) + #expect(try f.store.loadResolved().normalized == lock.normalized) + #expect(try FileHash.folderHash(f.store.cacheDirectory) == cacheHash) + let inventory = try UpdateOperations.inspect(scope: .user, environment: f.environment) + #expect( + inventory.deployments.map(\.status) == Array(repeating: .current, count: lock.skills.count)) + #expect( + inventory.resources.first { $0.kind == "artifact" }?.location?.path == artifactTree.path) + let restore = UpdateRequest(operation: .restore, kinds: [.skills]) + let report = try UpdateOperations.preview(restore, scope: .user, environment: f.environment) + try #require(!report.hasChanges) + _ = try SkillOperations.installResolvedReport(scope: .user, environment: f.environment) + try artifactLink.validate() + #expect(try FileHash.folderHash(f.store.cacheDirectory) == cacheHash) + + if !includeRemote { + let declaration = try f.store.loadDeclaration() + _ = try UpdateOperations.withPreparedUpdate( + UpdateRequest(operation: .declaration(declaration)), scope: .user, + environment: f.environment + ) { try $0.apply() } + try artifactLink.validate() + let reapplied = try UpdateOperations.inspect(scope: .user, environment: f.environment) + #expect(reapplied.resources.first?.location?.path == artifactTree.path) + + try FileManager.default.removeItem(at: artifactTree) + _ = try SkillOperations.installResolvedReport(scope: .user, environment: f.environment) + try artifactLink.validate() + #expect(try f.bytes(artifactTree.appendingPathComponent("SKILL.md")) == artifactBytes) + let restored = try UpdateOperations.inspect(scope: .user, environment: f.environment) + #expect(restored.resources.first?.location?.path == artifactTree.path) + #expect(restored.deployments.map(\.status) == [.current]) + + var invalid = try f.store.loadLedger() + let id = try #require(invalid.resources.first { $0.value.kind == .artifact }?.key) + invalid.resources[id]?.location = .init(kind: .registered, root: "state", path: "cache/other") + #expect(throws: CoreError.self) { + _ = try ResolvedLedgerCodec.encode(invalid, limits: .standard) + } + } + } + + @Test func importsAndInspectsLargeLiveEditSourceWithoutReplacingTheLink() throws { + let f = try UpdateFixture(scope: .user) + let directory = f.repo.appendingPathComponent("skills/demo").resolvingSymlinksInPath() + let blob = directory.appendingPathComponent("references/blob") + try f.write("", to: blob) + let length = UInt64(max(180 * 1024 * 1024, LedgerLimits.standard.resourceBytes)) + 1 + do { + let handle = try FileHandle(forWritingTo: blob) + defer { try? handle.close() } + try handle.truncate(atOffset: length) + } + try FileManager.default.createDirectory( + at: f.target().deletingLastPathComponent(), withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink(at: f.target(), withDestinationURL: directory) + let targetIdentity = try PathIdentity(f.target()) + let sourceIdentity = "local:" + f.repo.path + let json = try #require(f.store.configurationJSONURL) + try f.write( + """ + {"sources":{"fixture":{"local":"\(f.repo.path)"}}, + "skills":{"fixture":{"select":["demo"],"agents":["codex"],"mode":"edit"}}} + """, to: json) + let saved = ResolvedState( + sources: [sourceIdentity: .init(kind: .local)], + skills: [ + "demo": .init(source: sourceIdentity, path: "skills/demo", installs: ["codex": .edit]) + ]) + let lockBytes = try StateStore.encodeState(saved) + try lockBytes.write(to: f.store.resolvedURL) + + let preview = try ExistingGlobalConfiguration.preview(environment: f.environment) + #expect(preview.skillCount == 1) + #expect(preview.installationCount == 1) + try ExistingGlobalConfiguration.apply(preview) + try targetIdentity.validate() + #expect(try f.bytes(preview.originalLedgerURL) == lockBytes) + #expect(try f.store.loadResolved() == saved) + + let snapshot = try UpdateOperations.inspect(scope: .user, environment: f.environment) + #expect(snapshot.components.map(\.name) == ["demo"]) + #expect(snapshot.deployments.map(\.status) == [.current]) + let resource = try #require(snapshot.resources.first) + #expect(resource.kind == "liveEdit") + #expect(resource.location?.resolvingSymlinksInPath().path == directory.path) + #expect(resource.entries.isEmpty) + #expect(snapshot.readLocations.contains { $0.resolvingSymlinksInPath().path == directory.path }) + let attributes = try FileManager.default.attributesOfItem(atPath: blob.path) + #expect((attributes[.size] as? NSNumber)?.uint64Value == length) + } + + @Test(arguments: ["declaration", "native", "cache", "edit-source", "edit-link", "backup", "yaml"]) + func confirmationRejectsStaleEvidence(_ changed: String) throws { + let input = try ExistingProfile() + let f = input.fixture + let preview = try ExistingGlobalConfiguration.preview(environment: f.environment) + switch changed { + case "declaration": try f.write("{}\n", to: input.json) + case "native": try f.write("New native bytes\n", to: f.instruction()) + case "cache": + try f.write( + "Pinned resource changed\n", to: input.pinnedSkill.appendingPathComponent("run.sh")) + case "edit-source": + try f.write( + "New reference data\n", to: f.root.appendingPathComponent("live/edit-demo/references.txt")) + case "edit-link": + let link = f.target().deletingLastPathComponent().appendingPathComponent("edit-demo") + try FileManager.default.removeItem(at: link) + try FileManager.default.createSymbolicLink(at: link, withDestinationURL: f.repo) + case "backup": try f.write("Retained lock copy\n", to: preview.originalLedgerURL) + default: try f.write("version: 1\n", to: f.store.declarationURL) + } + let before = try FileHash.folderHash(f.environment.homeDirectory) + #expect(throws: ExistingGlobalConfigurationError.self) { + try ExistingGlobalConfiguration.apply(preview) + } + let after = try FileManager.default.contentsOfDirectory(atPath: f.store.directory.path) + #expect(!after.contains("transaction.json")) + #expect(try f.bytes(f.store.resolvedURL) == input.lockBytes) + #expect(try FileHash.folderHash(f.environment.homeDirectory) == before) + if changed == "backup" { + #expect(try f.bytes(preview.originalLedgerURL) == Data("Retained lock copy\n".utf8)) + } + } + + @Test func aChangedSkillIsAnExplicitConflict() throws { + let input = try ExistingProfile() + let f = input.fixture + let changed = f.target(.claudeCode) + try f.write("Unrelated directory\n", to: changed.appendingPathComponent("SKILL.md")) + #expect(try ExistingGlobalConfiguration.isAvailable(environment: f.environment)) + do { + _ = try ExistingGlobalConfiguration.preview(environment: f.environment) + Issue.record("Imported a skill path with unrelated contents") + } catch let error as ExistingGlobalConfigurationError { + #expect(error.localizedDescription.contains(changed.path)) + #expect(error.localizedDescription.contains("move the changed entry aside")) + } + #expect(try f.bytes(f.store.resolvedURL) == input.lockBytes) + } + + @Test func pendingOperationTakesPriorityOverRecognitionAndPreview() throws { + let f = try UpdateFixture(scope: .user) + try f.write("{}", to: f.store.directory.appendingPathComponent("transaction.json")) + for operation in [ + { _ = try ExistingGlobalConfiguration.isAvailable(environment: f.environment) }, + { _ = try ExistingGlobalConfiguration.preview(environment: f.environment) }, + ] { + do { + try operation() + Issue.record("Inspected a scope with a pending operation") + } catch let error as ExistingGlobalConfigurationError { + guard case .recovery = error else { + Issue.record(error) + continue + } + #expect(error.localizedDescription.contains("Finish it in the tool that started it")) + } + } + #expect( + try f.bytes(f.store.directory.appendingPathComponent("transaction.json")) == Data("{}".utf8)) + } + + @Test(arguments: [false, true]) + func retargetedInstallationRootInvalidatesConfirmation(_ duringPublication: Bool) throws { + let input = try ExistingProfile() + let f = input.fixture + let parent = f.target().deletingLastPathComponent() + let inspected = f.store.directory.appendingPathComponent("inspected-skills") + let other = f.store.directory.appendingPathComponent("other-skills") + try FileManager.default.moveItem(at: parent, to: inspected) + try FileManager.default.createDirectory(at: other, withIntermediateDirectories: false) + try FileManager.default.createSymbolicLink(at: parent, withDestinationURL: inspected) + let preview = try ExistingGlobalConfiguration.preview(environment: f.environment) + let nativeBefore = try FileHash.folderHash(inspected) + func redirect() throws { + try FileManager.default.removeItem(at: parent) + try FileManager.default.createSymbolicLink(at: parent, withDestinationURL: other) + } + if !duringPublication { try redirect() } + + #expect(throws: ExistingGlobalConfigurationError.self) { + try ExistingGlobalConfiguration.apply(preview) { checkpoint in + if duringPublication, checkpoint == TransactionCheckpoint.progress(2, .applied).name { + try redirect() + } + } + } + #expect(try FileHash.folderHash(inspected) == nativeBefore) + #expect(try FileManager.default.contentsOfDirectory(atPath: other.path).isEmpty) + try expectUnapplied(preview, ledger: input.lockBytes, fixture: f) + } + + @Test func staleConfirmationLeavesPendingNativeRecoveryForItsOwner() throws { + let input = try ExistingProfile() + let f = input.fixture + let preview = try ExistingGlobalConfiguration.preview(environment: f.environment) + try ExistingGlobalConfiguration.apply(preview) + let native = f.target().deletingLastPathComponent().appendingPathComponent("target/SKILL.md") + try f.write("installed content\n", to: native) + try f.write("partly published content\n", to: f.root.appendingPathComponent("new/SKILL.md")) + let child = try launch( + f, command: "inspection-transaction", + argument: TransactionCheckpoint.progress(0, .applied).name) + defer { terminate(child) } + try waitFor("ready", fixture: f, child: child) + terminate(child) + + let journal = f.store.directory.appendingPathComponent("transaction.json") + let pending = try f.bytes(journal) + #expect(try f.bytes(native) == Data("partly published content\n".utf8)) + do { + try ExistingGlobalConfiguration.apply(preview) + Issue.record("Confirmed configuration during native recovery") + } catch let error as ExistingGlobalConfigurationError { + guard case .recovery = error else { + Issue.record(error) + return + } + } + #expect(try f.bytes(journal) == pending) + #expect(try f.bytes(native) == Data("partly published content\n".utf8)) + #expect(throws: CoreError.transactionRecovered(f.store.directory.path)) { + try f.store.withLock {} + } + #expect(try f.bytes(native) == Data("installed content\n".utf8)) + } + + @Test(arguments: [ + TransactionCheckpoint.preconditions.name, TransactionCheckpoint.progress(2, .applied).name, + ]) + func lostOfflinePinAbortsConfirmation(_ point: String) throws { + let input = try ExistingProfile() + let f = input.fixture + let preview = try ExistingGlobalConfiguration.preview(environment: f.environment) + let displaced = f.root.appendingPathComponent("displaced-source") + #expect(throws: ExistingGlobalConfigurationError.self) { + try ExistingGlobalConfiguration.apply(preview) { checkpoint in + if checkpoint == point { try FileManager.default.moveItem(at: f.repo, to: displaced) } + } + } + #expect(FileManager.default.fileExists(atPath: displaced.path)) + try expectUnapplied(preview, ledger: input.lockBytes, fixture: f) + } + + @Test(arguments: ["\"team\"", "null"]) + func rejectsUnsupportedSkillSelectionPath(_ path: String) throws { + let f = try UpdateFixture(scope: .user) + let json = try #require(f.store.configurationJSONURL) + try f.write( + """ + {"sources":{"team":{"git":"example.invalid/team","path":"skills"}}, + "skills":{"team":{"select":"all","path":\(path)}}} + """, to: json) + try StateStore.encodeState(ResolvedState()).write(to: f.store.resolvedURL) + do { + _ = try ExistingGlobalConfiguration.preview(environment: f.environment) + Issue.record("Accepted an unsupported skill selection path") + } catch let error as ExistingGlobalConfigurationError { + #expect(error.localizedDescription.contains("skills.team.path is unsupported")) + #expect(error.localizedDescription.contains("sources.team.path")) + } + } + + @Test func preservesSourceDiscoveryPathAndSelection() throws { + let f = try UpdateFixture(scope: .user) + let json = try #require(f.store.configurationJSONURL) + try f.write( + """ + {"sources":{"team":{"git":"example.invalid/team","path":"skills/team"}}, + "skills":{"team":{"select":"all","exclude":["retired"],"overrides":{"current":{"mode":"copy"}}}}} + """, to: json) + try StateStore.encodeState(ResolvedState()).write(to: f.store.resolvedURL) + try ExistingGlobalConfiguration.apply( + ExistingGlobalConfiguration.preview(environment: f.environment)) + + let declaration = try f.store.loadDeclaration() + #expect(declaration.sources["team"]?.path == "skills/team") + let selection = try #require(try declaration.skills?["team"]) + #expect(selection.select == .all) + #expect(selection.path == nil) + #expect(selection.exclude == ["retired"]) + #expect(selection.overrides?["current"]?.mode == .copy) + } + + @Test func rejectsAliasesForOneNormalizedSourceWithDistinctRoots() throws { + let f = try UpdateFixture(scope: .user) + let json = try #require(f.store.configurationJSONURL) + try f.write( + """ + {"sources":{"team":{"git":"https://example.invalid/shared.git","path":"team"}, + "tools":{"git":"https://example.invalid/shared","path":"tools"}}} + """, to: json) + try StateStore.encodeState(ResolvedState()).write(to: f.store.resolvedURL) + do { + _ = try ExistingGlobalConfiguration.preview(environment: f.environment) + Issue.record("Accepted two aliases for one saved source identity") + } catch let error as ExistingGlobalConfigurationError { + #expect(error.localizedDescription.contains("'team' and 'tools'")) + #expect(error.localizedDescription.contains("Use one alias per source")) + } + } + + @Test func reopensAnEditLinkThroughItsAuthoredSourceAlias() throws { + let f = try UpdateFixture(scope: .user) + let alias = try importEditAlias(f) + let installed = try PathIdentity(f.target()) + let alternate = f.repo.appendingPathComponent("skills/alternate") + try FileManager.default.copyItem( + at: f.repo.appendingPathComponent("skills/demo"), to: alternate) + try FileManager.default.removeItem(at: alias) + try FileManager.default.createSymbolicLink(atPath: alias.path, withDestinationPath: "alternate") + + let inventory = try UpdateOperations.inspect(scope: .user, environment: f.environment) + #expect(inventory.deployments.map(\.status) == [.current]) + #expect(inventory.resources.first?.location?.path == alias.path) + _ = try SkillOperations.installResolvedReport(scope: .user, environment: f.environment) + try installed.validate() + #expect( + try FileManager.default.destinationOfSymbolicLink(atPath: f.target().path) == alias.path) + } + + @Test(arguments: [false, true]) + func declinesAnEditAliasRetargetedOutsideItsSource(_ afterPreparation: Bool) throws { + let f = try UpdateFixture(scope: .user) + let alias = try importEditAlias(f) + let installed = try PathIdentity(f.target()) + let ledger = try f.bytes(f.store.resolvedURL) + let outside = f.root.appendingPathComponent("outside") + try FileManager.default.copyItem(at: f.repo.appendingPathComponent("skills/demo"), to: outside) + func retarget() throws { + try FileManager.default.removeItem(at: alias) + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: outside) + } + if !afterPreparation { try retarget() } + do { + if afterPreparation { + _ = try UpdateOperations.withPreparedUpdate( + UpdateRequest(operation: .restore, kinds: [.skills]), scope: .user, + environment: f.environment + ) { prepared in + try retarget() + return try prepared.apply() + } + } else { + _ = try SkillOperations.installResolvedReport(scope: .user, environment: f.environment) + } + Issue.record("Restored an edit source outside its recorded source directory") + } catch { + let cause = (error as? UpdateApplyError)?.underlyingError ?? error + guard case CoreError.unsafePath(let message) = cause else { + Issue.record(error) + return + } + #expect(message.contains("outside its recorded source directory")) + #expect(message.contains("Point the source alias inside")) + } + + let inventory = try UpdateOperations.inspect(scope: .user, environment: f.environment) + let deployment = try #require(inventory.deployments.first) + #expect(deployment.status == .drifted) + #expect(deployment.diagnostic?.contains("Point the source alias inside") == true) + #expect(inventory.resources.first?.location?.path == alias.path) + #expect(try f.bytes(f.store.resolvedURL) == ledger) + try installed.validate() + #expect( + try FileManager.default.destinationOfSymbolicLink(atPath: f.target().path) == alias.path) + #expect(try FileManager.default.destinationOfSymbolicLink(atPath: alias.path) == outside.path) + } + + private func importEditAlias(_ f: UpdateFixture) throws -> URL { + let alias = f.repo.appendingPathComponent("skills/current") + try FileManager.default.createSymbolicLink(atPath: alias.path, withDestinationPath: "demo") + let target = f.target() + try FileManager.default.createDirectory( + at: target.deletingLastPathComponent(), withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink(at: target, withDestinationURL: alias) + let json = try #require(f.store.configurationJSONURL) + try f.write( + """ + {"sources":{"fixture":{"local":"\(f.repo.path)"}}, + "skills":{"fixture":{"select":["demo"],"agents":["codex"],"mode":"edit"}}} + """, to: json) + let identity = "local:" + f.repo.path + let saved = ResolvedState( + sources: [identity: .init(kind: .local)], + skills: ["demo": .init(source: identity, path: "skills/current", installs: ["codex": .edit])]) + try StateStore.encodeState(saved).write(to: f.store.resolvedURL) + try ExistingGlobalConfiguration.apply( + ExistingGlobalConfiguration.preview(environment: f.environment)) + return alias + } + + @Test(arguments: [ + TransactionCheckpoint.progress(1, .applied).name, TransactionCheckpoint.phase(.committed).name, + ]) + func recoveryAfterKilledWriterKeepsOneGeneration(_ point: String) throws { + let input = try ExistingProfile() + let f = input.fixture + let preview = try ExistingGlobalConfiguration.preview(environment: f.environment) + let child = try launch(f, command: "existing-configuration", argument: point) + defer { terminate(child) } + try waitFor("ready", fixture: f, child: child) + terminate(child) + let pending = try UpdateOperations.inspect(scope: .user, environment: f.environment) + #expect(pending.recovery.pending) + #expect(pending.readLocations.contains(input.json)) + #expect(throws: ExistingGlobalConfigurationError.self) { + try ExistingGlobalConfiguration.preview(environment: f.environment) + } + #expect(throws: CoreError.transactionRecovered(f.store.directory.path)) { + try f.store.withLock {} + } + if point == TransactionCheckpoint.phase(.committed).name { + #expect(try f.store.loadResolved().normalized == input.expected.normalized) + #expect(try f.bytes(preview.originalLedgerURL) == input.lockBytes) + } else { + #expect(try f.bytes(f.store.resolvedURL) == input.lockBytes) + #expect(try ExistingGlobalConfiguration.isAvailable(environment: f.environment)) + #expect(!FileManager.default.fileExists(atPath: preview.originalLedgerURL.path)) + try ExistingGlobalConfiguration.apply( + ExistingGlobalConfiguration.preview(environment: f.environment)) + } + #expect(try f.bytes(input.json) == input.declarationBytes) + #expect(try f.bytes(f.store.watchURL) == input.watchBytes) + } + + private func expectUnapplied( + _ preview: ExistingGlobalConfigurationPreview, ledger: Data, fixture: UpdateFixture + ) throws { + #expect(try fixture.bytes(preview.ledgerURL) == ledger) + #expect(!FileManager.default.fileExists(atPath: preview.declarationURL.path)) + #expect(!FileManager.default.fileExists(atPath: preview.originalLedgerURL.path)) + #expect(try ExistingGlobalConfiguration.isAvailable(environment: fixture.environment)) + } +} + +private struct ExistingProfile { + let fixture: UpdateFixture + let json: URL + let declarationBytes: Data + let lockBytes: Data + let watchBytes: Data + let expected: ResolvedState + let pinnedSkill: URL + + init() throws { + let f = try UpdateFixture(scope: .user) + fixture = f + json = try #require(f.store.configurationJSONURL) + let cache = SourceCache(store: f.store) + let identity = "local:" + f.repo.path + let skillRevision = try f.git(["rev-parse", "HEAD"]) + let materialized = cache.materializedURL(sourceID: identity, revision: skillRevision) + pinnedSkill = materialized.appendingPathComponent("skills/demo") + try FileManager.default.createDirectory( + at: pinnedSkill.deletingLastPathComponent(), withIntermediateDirectories: true) + try FileManager.default.copyItem( + at: f.repo.appendingPathComponent("skills/demo"), to: pinnedSkill) + try FileManager.default.setAttributes( + [.posixPermissions: 0o755], ofItemAtPath: pinnedSkill.appendingPathComponent("run.sh").path) + try FileManager.default.createDirectory( + at: f.target().deletingLastPathComponent(), withIntermediateDirectories: true) + let relative = PathSafety.relativePath(pinnedSkill.path, to: f.store.directory.path) + try FileManager.default.createSymbolicLink( + atPath: f.target().path, withDestinationPath: "../" + relative) + + try f.advance() + let instructionRevision = try f.git(["rev-parse", "HEAD"]) + let instructionBytes = try f.bytes(f.repo.appendingPathComponent("instructions/rules.md")) + try f.writeSource("later HEAD and dirty working tree") + try f.commit() + try f.writeSource("dirty") + let section = LockedSection( + name: "rules", source: identity, revision: instructionRevision, version: "1.3.0", + path: "instructions/rules.md", hash: Instructions.hash(instructionBytes)) + let rendered = try Instructions.render([ + Instructions.validateSource(instructionBytes, id: "rules") + ]) + try f.write("Edited outside agents.\n", to: f.instruction()) + let forwarding = ClaudeForwarding.renderBlock(for: .root) + try f.write("Custom prose\n\n" + forwarding, to: f.instruction(.claudeCode)) + + let live = f.root.appendingPathComponent("live") + let edit = live.appendingPathComponent("edit-demo") + try f.write( + "---\nname: edit-demo\ndescription: Live fixture\n---\n\nNew live content\n", + to: edit.appendingPathComponent("SKILL.md")) + try FileManager.default.createSymbolicLink( + at: f.target().deletingLastPathComponent().appendingPathComponent("edit-demo"), + withDestinationURL: edit.resolvingSymlinksInPath()) + let editIdentity = "local:" + live.path + let unused = "example.invalid/unused" + var lock = ResolvedState( + sources: [ + identity: .init(kind: .local, requirement: .branch("main")), + editIdentity: .init(kind: .local), + unused: .init(kind: .git, url: "https://" + unused), + ], + skills: [ + "demo": .init( + source: identity, revision: skillRevision, version: "1.2.0", path: "skills/demo", + hash: try "sha256:" + FileHash.folderHash(pinnedSkill), + installs: ["codex": .link, "gemini-cli": .link, "claude-code": .link]), + "edit-demo": .init(source: editIdentity, path: "edit-demo", installs: ["codex": .edit]), + ], + instructions: .init( + sections: [section], chatgpt: ["weekly": .init(sections: [section], append: "custom.md")], + targets: [ + InstructionLocations.key(for: f.instruction(), store: f.store): .init( + agents: [.codex], headingOffset: 0, blockHash: Instructions.hash(Data(rendered.utf8)), + created: true), + InstructionLocations.key(for: f.instruction(.claudeCode), store: f.store): .init( + agents: [.claudeCode], import: "AGENTS.md", + blockHash: Instructions.hash(Data(forwarding.utf8)), created: false), + ])) + lockBytes = try StateStore.encodeState(lock) + try lockBytes.write(to: f.store.resolvedURL) + lock.sources.removeValue(forKey: unused) + expected = lock + watchBytes = Data("{ \"version\": 1, \"sources\": {} }\n".utf8) + try watchBytes.write(to: f.store.watchURL) + declarationBytes = Data( + """ + { + "agents": ["codex","claude-code"], + "sources": { + "fixture": {"local": "\(f.repo.path)", "branch": "main"}, + "live": {"local": "\(live.path)"} + }, + "skills": { + "fixture": {"select":"all","exclude":["excluded"],"mode":"copy", + "overrides":{"demo":{"agents":["codex","gemini-cli","claude-code"],"mode":"link"}}}, + "live": {"select":["edit-demo","uninstalled"],"agents":["codex"],"mode":"edit"} + }, + "instructions": {"agents":["codex"],"sections":["fixture:rules"], + "chatgpt":{"weekly":{"sections":["fixture:rules"],"append":"custom.md"}}}, + "watch": ["fixture"] + } + + """.utf8) + try declarationBytes.write(to: json) + } +} diff --git a/Tests/AgentsUpdatesTests/FiniteSkillInstallationTests.swift b/Tests/AgentsUpdatesTests/FiniteSkillInstallationTests.swift new file mode 100644 index 0000000..9abd66c --- /dev/null +++ b/Tests/AgentsUpdatesTests/FiniteSkillInstallationTests.swift @@ -0,0 +1,93 @@ +import AgentsCore +import AgentsManifest +import AgentsSkills +import AgentsUpdates +import Foundation +import Testing + +struct FiniteSkillInstallationTests { + @Test func registeredLoaderAliasExposesLogicalAndPhysicalReadLocations() throws { + let f = try UpdateFixture() + let physical = f.root.appendingPathComponent("physical-claude") + try FileManager.default.createDirectory(at: physical, withIntermediateDirectories: false) + try FileManager.default.createSymbolicLink( + at: f.root.appendingPathComponent(".claude"), withDestinationURL: physical) + _ = try SkillOperations.add( + AddOptions( + source: f.repo.path, agents: [.claudeCode], mode: .copy, + all: true, environment: f.environment)) + let expected = Set([ + f.target(.claudeCode).path, physical.appendingPathComponent("skills/demo").path, + ]) + #expect(Set(try f.preview().readLocations.map(\.path)).isSuperset(of: expected)) + #expect( + Set(try UpdateOperations.inspect(environment: f.environment).readLocations.map(\.path)) + .isSuperset(of: expected)) + } + + @Test func liveMetadataUsesDeclaredNameWhileInstallationUsesCanonicalName() throws { + let f = try UpdateFixture(scope: .user) + let file = f.repo.appendingPathComponent("skills/demo/SKILL.md") + try f.write("---\nname: Demo Skill\ndescription: fixture\n---\nLive body\n", to: file) + try f.commit() + _ = try SkillOperations.add( + AddOptions( + source: f.repo.path, agents: [.claudeCode], scope: .user, + mode: .edit, all: true, environment: f.environment)) + let current = try UpdateOperations.inspect(scope: .user, environment: f.environment) + #expect(current.deployments.first?.location.lastPathComponent == "demo-skill") + #expect(current.deployments.first?.status == .current) + try f.write("---\nname: Other Skill\ndescription: fixture\n---\nLive body\n", to: file) + let changed = try UpdateOperations.inspect(scope: .user, environment: f.environment) + #expect(changed.deployments.first?.status == .drifted) + } + + @Test(arguments: [InstallMode.link, .copy, .edit]) + func userClaudeSkillUsesLegacyIntentionAcrossPublicLifecycle(_ mode: InstallMode) throws { + let f = try UpdateFixture(scope: .user) + _ = try SkillOperations.add( + AddOptions( + source: f.repo.path, alias: "fixture", agents: [.claudeCode], scope: .user, + mode: mode, all: true, environment: f.environment)) + let target = f.target(.claudeCode) + #expect(FileManager.default.fileExists(atPath: target.appendingPathComponent("SKILL.md").path)) + if mode != .copy { + #expect((try? FileManager.default.destinationOfSymbolicLink(atPath: target.path)) != nil) + } + let before = try FileHash.folderHash(f.root) + let preview = try f.preview() + #expect(try FileHash.folderHash(f.root) == before) + #expect(try SkillOperations.listManaged(scope: .user, environment: f.environment).count == 1) + #expect(try SkillOperations.listInstalled(scope: .user, environment: f.environment).count == 1) + #expect(try SkillOperations.doctor(scope: .user, environment: f.environment).checks.isEmpty) + _ = try UpdateOperations.withPreparedUpdate(scope: .user, environment: f.environment) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + try f.advance() + _ = try SkillOperations.updateInstalled(scope: .user, environment: f.environment, apply: true) + #expect( + try String(contentsOf: target.appendingPathComponent("SKILL.md"), encoding: .utf8).contains( + "new")) + try FileManager.default.removeItem(at: target) + _ = try SkillOperations.installResolvedReport(scope: .user, environment: f.environment) + #expect( + try UpdateOperations.inspect(scope: .user, environment: f.environment).deployments.allSatisfy + { $0.status == .current }) + if mode == .edit { + let alternate = f.root.appendingPathComponent("equal-live-source") + try FileManager.default.copyItem( + at: f.repo.appendingPathComponent("skills/demo"), to: alternate) + try FileManager.default.removeItem(at: target) + try FileManager.default.createSymbolicLink(at: target, withDestinationURL: alternate) + let drift = try UpdateOperations.inspect(scope: .user, environment: f.environment) + #expect(drift.deployments.first?.status == .drifted) + _ = try SkillOperations.installResolvedReport(scope: .user, environment: f.environment) + #expect( + try UpdateOperations.inspect(scope: .user, environment: f.environment).deployments.first? + .status == .current) + } + _ = try SkillOperations.remove(skillNames: ["demo"], scope: .user, environment: f.environment) + #expect(!FileManager.default.fileExists(atPath: target.path)) + #expect(try SkillOperations.listManaged(scope: .user, environment: f.environment).isEmpty) + } +} diff --git a/Tests/AgentsUpdatesTests/FirstUserDeclarationTests.swift b/Tests/AgentsUpdatesTests/FirstUserDeclarationTests.swift new file mode 100644 index 0000000..b0a842c --- /dev/null +++ b/Tests/AgentsUpdatesTests/FirstUserDeclarationTests.swift @@ -0,0 +1,114 @@ +import AgentsCore +import AgentsManifest +import Foundation +import Testing + +@testable import AgentsUpdates + +struct FirstUserDeclarationTests { + @Test func firstUserMCPDeclarationCanConfirmPurePreview() throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent( + "first-user-declaration-" + UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + let environment = RuntimeEnvironment( + projectDirectory: root, homeDirectory: root, environment: [:]) + let store = StateStore(scope: .user, environment: environment) + try FileManager.default.createDirectory(at: store.directory, withIntermediateDirectories: true) + try Data("version: 1\ndefaultAgents: [codex]\n".utf8).write(to: store.declarationURL) + var declaration = try store.loadDeclaration() + declaration.components.append( + .mcpServer( + name: "documentation", transport: .stdio(.init(executable: "fixture-command")))) + let request = UpdateRequest(operation: .declaration(declaration)) + let before = try FileHash.folderHash(root) + let preview = try UpdateOperations.preview(request, scope: .user, environment: environment) + #expect(try FileHash.folderHash(root) == before) + let selectedText = try #require(preview.components.first?.symbolicAfter) + let selectedFields = try #require( + JSONSerialization.jsonObject(with: Data(selectedText.utf8)) as? [String: Any]) + #expect(selectedFields["command"] as? String == "fixture-command") + #expect(selectedFields["kind"] == nil && selectedFields["object"] == nil) + #expect( + try UpdateOperations.preview(request, scope: .user, environment: environment) + .displayedFingerprint == preview.displayedFingerprint) + _ = try UpdateOperations.withPreparedUpdate(request, scope: .user, environment: environment) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + let current = try UpdateOperations.inspect(scope: .user, environment: environment) + #expect(current.components.count == 1) + #expect(current.components.first?.name == "documentation") + #expect(current.deployments.allSatisfy { $0.status == .current }) + let config = root.appendingPathComponent(".codex/config.toml") + #expect(try String(contentsOf: config, encoding: .utf8).contains("fixture-command")) + } + @Test func readablePreviewContainsOnlySelectedSymbolicConfiguration() throws { + let f = try UpdateFixture() + let sibling = "UNMANAGED-SIBLING-MUST-STAY-PRIVATE" + let config = f.root.appendingPathComponent(".mcp.json") + try f.write( + "{\"mcpServers\":{\"unmanaged\":{\"command\":\"" + sibling + "\"}}}", to: config) + try f.store.save( + declaration: Declaration(components: [ + .mcpServer( + name: "selected", transport: .stdio(.init(executable: "fixture-command")), + agents: [.claudeCode]) + ]), ledger: ResolvedLedger()) + let before = try FileHash.folderHash(f.root) + let preview = try f.preview() + #expect(try FileHash.folderHash(f.root) == before) + #expect(preview.components.first?.symbolicBefore == nil) + let after = try #require(preview.components.first?.symbolicAfter) + #expect(after.contains("fixture-command")) + #expect(!after.contains(sibling) && !after.contains("unmanaged")) + #expect(!String(decoding: try JSONEncoder().encode(preview), as: UTF8.self).contains(sibling)) + _ = try UpdateOperations.withPreparedUpdate(environment: f.environment) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + #expect(try String(contentsOf: config, encoding: .utf8).contains(sibling)) + } + + @Test func readableProjectionPreservesNumericLexemesAndSymbolicReferences() throws { + let payload = LedgerValue(object: [ + "limit": .init("1e200", kind: .decimal), + "environment": .init("FIXTURE_INPUT", kind: .environment), + "credential": .init("fixture-token", kind: .secret), + "text": .init("quoted \"field\"\nnext line"), + ]) + let rendered = try UpdateOperations.symbolicConfigurationText(payload) + #expect(rendered.contains("1e200")) + let fields = try #require( + JSONSerialization.jsonObject(with: Data(rendered.utf8)) as? [String: Any]) + #expect((fields["environment"] as? [String: String])?["environment"] == "FIXTURE_INPUT") + #expect((fields["credential"] as? [String: String])?["secret"] == "fixture-token") + #expect(fields["text"] as? String == "quoted \"field\"\nnext line") + } + + @Test func nativeAccessChangeInvalidatesDisplayedConfirmation() throws { + let f = try UpdateFixture(scope: .user) + try f.store.save( + declaration: Declaration(components: [ + .mcpServer( + name: "documentation", transport: .stdio(.init(executable: "fixture-command")), + agents: [.codex]) + ]), ledger: ResolvedLedger()) + _ = try f.apply() + let before = try f.preview() + let config = f.environment.homeDirectory.appendingPathComponent(".codex/config.toml") + let parent = config.deletingLastPathComponent() + let mode = try #require( + try FileManager.default.attributesOfItem(atPath: parent.path)[.posixPermissions] as? NSNumber) + try FileManager.default.setAttributes( + [.posixPermissions: mode.intValue == 0o700 ? 0o755 : 0o700], ofItemAtPath: parent.path) + let after = try f.preview() + #expect(before.displayedFingerprint != after.displayedFingerprint) + let bytes = try Data(contentsOf: config) + #expect(throws: (any Error).self) { + try UpdateOperations.withPreparedUpdate(scope: .user, environment: f.environment) { + try $0.apply(ifUnchangedFrom: before.displayedFingerprint) + } + } + #expect(try Data(contentsOf: config) == bytes) + } + +} diff --git a/Tests/AgentsUpdatesTests/GitAcquisitionTests.swift b/Tests/AgentsUpdatesTests/GitAcquisitionTests.swift new file mode 100644 index 0000000..e693d63 --- /dev/null +++ b/Tests/AgentsUpdatesTests/GitAcquisitionTests.swift @@ -0,0 +1,556 @@ +import AgentsUpdates +import Foundation +import StateTestSupport +import Testing + +@testable import AgentsCore + +// Each case launches multiple Git children. Serializing this suite leaves queue capacity +// for the asynchronous registry fixture's readiness deadline. +@Suite(.serialized, .enabled(if: GitHTTPSFixture.toolsAvailable)) +struct GitAcquisitionTests { + @Test func productionUpdateReusesExactObjectsAndRetainsOfflineLinks() throws { + let fixture = try GitHTTPSFixture() + defer { fixture.remove() } + let first = try fixture.environment("first") + let second = try fixture.environment("second") + let naked = try fixture.environment("naked") + let cache = AcquisitionCache(environment: first) + let url = fixture.url("package") + let source = SourceDeclaration(kind: .git, location: url, requirement: .branch("main")) + let acquisition = try #require(GitAcquisition(source, environment: first)) + + try GitAcquisition.$fixtureCertificateAuthority.withValue(fixture.certificate) { + let original = try fixture.release("version-one") + try install(source, in: first) + let originalBytes = try Data(contentsOf: fixture.skill(first)) + #expect(String(decoding: originalBytes, as: UTF8.self).contains("version-one")) + #expect(try acquisition.observedRevision("refs/heads/main") == original) + let firstInventory = try cache.inspect() + #expect(firstInventory.entries.contains { $0.store == .git && $0.object == original }) + #expect(firstInventory.entries.contains { $0.store == .deployed }) + #expect( + try cache.verifiedDeployedBytes(sha256: FileHash.sha256Hex(data: originalBytes)) + == originalBytes) + let target = fixture.skill(first).deletingLastPathComponent() + _ = try FileManager.default.destinationOfSymbolicLink(atPath: target.path) + let destination = try #require(PathSafety.realPath(target.path)) + let state = StateStore(scope: .project, environment: first).cacheDirectory + let statePath = try #require(PathSafety.realPath(state.path)) + #expect(destination.hasPrefix(statePath + "/")) + #expect(!destination.hasPrefix(cache.root.resolvingSymlinksInPath().path + "/")) + + try fixture.copyLock(from: first, to: second) + let requestsBefore = try fixture.requests() + let policy = SourcePolicyOperations.policyURL(scope: .project, environment: second) + try Data("version: 1\ndeny: [{git: '\(url)'}]\n".utf8).write(to: policy) + #expect(throws: SourcePolicyFailure.self) { + try UpdateOperations.restore(environment: second, offline: true) + } + #expect(try fixture.requests() == requestsBefore) + try FileManager.default.removeItem(at: policy) + _ = try UpdateOperations.restore(environment: second, offline: true) + #expect(try fixture.requests() == requestsBefore) + #expect(try Data(contentsOf: fixture.skill(second)) == originalBytes) + + let advanced = try fixture.release("version-two") + try UpdateOperations.withPreparedUpdate(.init(operation: .update), environment: first) { + _ = try $0.apply() + } + #expect(try acquisition.observedRevision("refs/heads/main") == advanced) + _ = try UpdateOperations.restore(environment: second, offline: true) + #expect(try acquisition.observedRevision("refs/heads/main") == advanced) + #expect(try Data(contentsOf: fixture.skill(second)) == originalBytes) + let firstBytes = try Data(contentsOf: fixture.skill(first)) + #expect(String(decoding: firstBytes, as: UTF8.self).contains("version-two")) + + try fixture.copyLock(from: first, to: naked) + #expect(try cache.apply(cache.preview(.clean)).isComplete) + fixture.stop() + #expect(try Data(contentsOf: fixture.skill(first)) == firstBytes) + #expect(try Data(contentsOf: fixture.skill(second)) == originalBytes) + try FileManager.default.removeItem(at: target) + _ = try UpdateOperations.restore(environment: first, offline: true) + #expect(try Data(contentsOf: fixture.skill(first)) == firstBytes) + #expect(throws: (any Error).self) { + try UpdateOperations.preview(.init(operation: .update), environment: first) + } + do { + _ = try UpdateOperations.restore(environment: naked, offline: true) + Issue.record("A naked lock unexpectedly restored with no state or acquisition") + } catch { + #expect(String(describing: error).contains("cached Git commit \(advanced)")) + } + } + #expect(try fixture.requests().allSatisfy { !$0.contains("credential=1") }) + } + + @Test func preparedUpdateRetainsItsPackAcrossConcurrentCleanAndProducerLoss() throws { + let fixture = try GitHTTPSFixture() + defer { fixture.remove() } + let environment = try fixture.environment("prepared") + let cache = AcquisitionCache(environment: environment) + let source = SourceDeclaration( + kind: .git, location: fixture.url("package"), requirement: .branch("main")) + _ = try fixture.release("prepared") + try GitAcquisition.$fixtureCertificateAuthority.withValue(fixture.certificate) { + try UpdateOperations.withPreparedUpdate( + request(source), environment: environment + ) { prepared in + let preview = try cache.preview(.clean) + #expect(preview.candidates.contains { $0.store == .git && !$0.isGitObservation }) + #expect(try cache.apply(preview).isComplete) + fixture.stop() + _ = try prepared.apply() + } + } + #expect(try Data(contentsOf: fixture.skill(environment)).count > 0) + #expect(try cache.apply(cache.preview(.clean)).isComplete) + #expect(try Data(contentsOf: fixture.skill(environment)).count > 0) + } + + @Test func privateAndRefusedInstallsNeverPublishDeployedBytes() throws { + let fixture = try GitHTTPSFixture() + defer { fixture.remove() } + let environment = try fixture.environment("public-contested") + let cache = AcquisitionCache(environment: environment) + let privateRevision = try fixture.release("private-and-public") + try fixture.git([ + "clone", "--bare", "--no-local", fixture.repository.path, + fixture.root.appendingPathComponent("private.git").path, + ]) + let privateConfig = fixture.root.appendingPathComponent("private.gitconfig") + try fixture.git([ + "config", "--file", privateConfig.path, "http.sslCAInfo", fixture.certificate.path, + ]) + try fixture.git([ + "config", "--file", privateConfig.path, "credential.helper", + "!f() { printf 'username=fixture\\npassword=fixture\\n'; }; f", + ]) + let anonymousConfig = fixture.root.appendingPathComponent("anonymous.gitconfig") + try fixture.git([ + "config", "--file", anonymousConfig.path, "http.sslCAInfo", fixture.certificate.path, + ]) + for (project, config, result) in [ + ("private-first", privateConfig, "applied"), ("private-second", anonymousConfig, "refused"), + ] { + let arguments = + [project, fixture.url("private"), result] + + (result == "refused" ? [privateRevision] : []) + let child = try fixture.child(arguments, configuration: config) + defer { try? ProcessWait.terminate(child) } + try ProcessWait.exit(child, root: fixture.root, timeout: 20) + #expect(child.terminationStatus == 0) + } + #expect(try cache.inspect().entries.isEmpty) + #expect(try Data(contentsOf: fixture.skill(fixture.environment("private-first"))).count > 0) + #expect( + !FileManager.default.fileExists( + atPath: try fixture.skill(fixture.environment("private-second")).path)) + + let source = SourceDeclaration( + kind: .git, location: fixture.url("package"), requirement: .branch("main")) + try FileManager.default.createDirectory( + at: fixture.skill(environment).deletingLastPathComponent(), withIntermediateDirectories: true) + try Data("unmanaged skill".utf8).write(to: fixture.skill(environment)) + GitAcquisition.$fixtureCertificateAuthority.withValue(fixture.certificate) { + #expect(throws: (any Error).self) { try install(source, in: environment) } + } + #expect(try cache.inspect().entries.allSatisfy { $0.store != .deployed }) + #expect(try Data(contentsOf: fixture.skill(environment)) == Data("unmanaged skill".utf8)) + } + + @Test func anonymousGitDoesNotFollowRedirects() throws { + let fixture = try GitHTTPSFixture() + defer { fixture.remove() } + _ = try fixture.release("redirect target") + let environment = try fixture.environment("redirect") + let source = SourceDeclaration(kind: .git, location: fixture.url("redirect")) + let acquisition = try #require(GitAcquisition(source, environment: environment)) + GitAcquisition.$fixtureCertificateAuthority.withValue(fixture.certificate) { + #expect(throws: GitError.self) { try acquisition.discover() } + } + let requests = try fixture.requests() + #expect(requests.count == 1) + #expect(requests.first?.contains("/redirect.git/") == true) + #expect(requests.first?.contains("credential=0") == true) + #expect(try AcquisitionCache(environment: environment).inspect().entries.isEmpty) + } + + @Test func localLiveProducerRemainsAuthoritativeWhenMissing() throws { + let fixture = try GitHTTPSFixture() + defer { fixture.remove() } + let environment = try fixture.environment("live") + let producer = fixture.root.appendingPathComponent("local") + let skill = producer.appendingPathComponent("skills/fixture/SKILL.md") + try FileManager.default.createDirectory( + at: skill.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data("---\nname: fixture\ndescription: Live fixture\n---\n# Fixture\n".utf8).write( + to: skill) + let intent = Declaration( + agents: [.codex], sources: ["fixture": .init(kind: .local, location: producer.path)], + skills: ["fixture": .init(select: .names(["fixture"]), mode: .edit)]) + try UpdateOperations.withPreparedUpdate( + .init(operation: .declaration(intent)), environment: environment + ) { _ = try $0.apply() } + let cache = AcquisitionCache(environment: environment) + #expect(try cache.apply(cache.preview(.clean)).isComplete) + #expect(try Data(contentsOf: fixture.skill(environment)) == Data(contentsOf: skill)) + try FileManager.default.removeItem(at: producer) + do { + _ = try UpdateOperations.restore(environment: environment, offline: true) + Issue.record("A live install restored without its producer") + } catch { + #expect(String(describing: error).contains("live edit skill source")) + } + } + + @Test func transportIdentityPreservesCasePortsAndCredentialEligibility() throws { + let fixture = try GitHTTPSFixture() + defer { fixture.remove() } + let environment = try fixture.environment("keys") + let values = [ + "https://example.invalid/repo.git", "https://example.invalid/Repo.git", + "https://example.invalid:443/repo.git", "https://example.invalid/repo", + ] + let keys = try values.map { + let acquisition = try #require( + GitAcquisition( + .init(kind: .git, location: $0), environment: environment)) + return acquisition.key(String(repeating: "a", count: 40)) + } + #expect(Set(keys).count == values.count) + for url in [ + "http://example.invalid/repo", "git@example.invalid:repo", "https://a:b@example.invalid/repo", + ] { + #expect(GitAcquisition(.init(kind: .git, location: url), environment: environment) == nil) + } + var credentialed = environment + credentialed.credentialedGitHosts = ["EXAMPLE.invalid"] + #expect( + GitAcquisition(.init(kind: .git, location: values[0]), environment: credentialed) == nil) + } + + @Test func managedCredentialReachesOnlyItsExactGitRepository() throws { + let fixture = try GitHTTPSFixture() + defer { fixture.remove() } + var environment = try fixture.environment("managed") + try FileManager.default.createDirectory( + at: environment.homeDirectory, withIntermediateDirectories: false) + let url = fixture.url("org/private") + let source = SourceDeclaration(kind: .git, location: url, requirement: .branch("main")) + let authority = try SourceAuthority(URLComponents(string: url)!) + let binding = try SourceCredentialBinding( + route: .direct, authority: authority, path: "/org/private.git", gitUsername: "fixture" + ) { "fixture-managed-secret" } + environment.sourceAccess = .init(providers: [authority: .github], credentials: [binding]) + let first = try fixture.release("managed-first") + let privateURL = fixture.root.appendingPathComponent("org/private.git") + try FileManager.default.createDirectory( + at: privateURL.deletingLastPathComponent(), withIntermediateDirectories: false) + try fixture.git(["clone", "--bare", fixture.repository.path, privateURL.path]) + + try GitAcquisition.$fixtureCertificateAuthority.withValue(fixture.certificate) { + let store = StateStore(scope: .project, environment: environment) + let cache = SourceCache(store: store) + #expect(GitAcquisition(source, environment: environment) == nil) + #expect(try cache.inspectRevision(source).revision == first) + #expect(try cache.resolve(source).revision == first) + let second = try fixture.release("managed-second") + try fixture.git(["-C", fixture.repository.path, "push", privateURL.path, "main"]) + #expect(try cache.resolve(source).revision == second) + try install(source, in: environment) + + var proxied = environment + proxied.sourceAccess = .init( + egress: .proxyOnly, + mirrors: [ + try SourceArchiveMirror( + source: authority, base: URL(string: "https://archive-fixture.invalid/base")!, + flavor: .github) + ]) + let directRequests = try fixture.requests() + #expect(throws: SourceAccessError.routeChanged) { + _ = try UpdateOperations.restore(environment: proxied, offline: true) + } + let zip = fixture.root.appendingPathComponent("managed.zip") + try fixture.git([ + "-C", fixture.repository.path, "archive", "--format=zip", "--prefix=fixture/", + "--output", zip.path, "HEAD", + ]) + let archive = try Data(contentsOf: zip) + try PackageSourceHTTP.$fixture.withValue( + { request, _ in + #expect( + request.url?.absoluteString + == "https://archive-fixture.invalid/base/org/private/archive/refs/heads/main.zip") + return .init(status: 200, body: archive) + }, + operation: { + try UpdateOperations.withPreparedUpdate(.init(operation: .update), environment: proxied) { + _ = try $0.apply() + } + }) + #expect(try store.loadLedger().sources.values.contains { $0.archive != nil }) + #expect(try fixture.requests() == directRequests) + + #expect(try cache.resolve(source).revision == second) + let mirror = try cache.mirrorURL(sourceID: source.identity(environment: environment)) + let rewritten = fixture.url("redirect") + try fixture.git(["-C", mirror.path, "config", "url.\(rewritten).insteadOf", url]) + let before = try fixture.requests() + #expect(throws: SourceAccessError.routeChanged) { _ = try cache.resolve(source) } + #expect(try fixture.requests() == before) + } + let requests = try fixture.requests() + #expect(requests.contains { $0.contains("credential=1") }) + #expect(requests.allSatisfy { $0.contains("/org/private.git/") }) + } + + private func request(_ source: SourceDeclaration) -> UpdateRequest { + UpdateRequest( + operation: .declaration( + Declaration( + agents: [.codex], sources: ["fixture": source], + skills: ["fixture": .init(select: .names(["fixture"]), mode: .link)]))) + } + + private func install(_ source: SourceDeclaration, in environment: RuntimeEnvironment) throws { + try UpdateOperations.withPreparedUpdate(request(source), environment: environment) { + _ = try $0.apply() + } + } +} + +private final class GitHTTPSFixture { + static var toolsAvailable: Bool { + ["/usr/bin/python3", "/usr/bin/openssl", "/usr/bin/git"].allSatisfy { + FileManager.default.isExecutableFile(atPath: $0) + } + } + + let root: URL + let repository: URL + let certificate: URL + private let process = Process() + private var base = "" + + init() throws { + root = FileManager.default.temporaryDirectory.appendingPathComponent( + "agents-git-https-" + UUID().uuidString) + repository = root.appendingPathComponent("package.git") + certificate = root.appendingPathComponent("certificate.pem") + do { + try setUp() + } catch { + remove() + throw error + } + } + + private func setUp() throws { + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: false) + let key = root.appendingPathComponent("key.pem") + let config = root.appendingPathComponent("openssl.cnf") + try Data( + """ + [req] + distinguished_name = dn + x509_extensions = extension + prompt = no + [dn] + CN = 127.0.0.1 + [extension] + basicConstraints = critical,CA:TRUE + subjectAltName = IP:127.0.0.1 + """.utf8 + ).write(to: config) + try run( + "/usr/bin/openssl", + [ + "req", "-new", "-x509", "-newkey", "rsa:2048", "-nodes", "-days", "2", + "-config", config.path, "-keyout", key.path, "-out", certificate.path, + ]) + try git(["init", "--initial-branch=main", repository.path]) + try git(["-C", repository.path, "config", "user.name", "Acquisition Fixture"]) + try git(["-C", repository.path, "config", "user.email", "fixture@example.invalid"]) + try git(["-C", repository.path, "config", "http.getanyfile", "false"]) + try FileManager.default.createDirectory( + at: repository.appendingPathComponent("skills/fixture"), withIntermediateDirectories: true) + let script = root.appendingPathComponent("server.py") + try Data(Self.server.utf8).write(to: script) + process.executableURL = URL(fileURLWithPath: "/usr/bin/python3") + process.arguments = [script.path, root.path, certificate.path, key.path] + process.environment = ["PATH": "/usr/bin:/bin", "HOME": root.path] + process.standardInput = FileHandle.nullDevice + process.standardOutput = FileHandle.nullDevice + try process.run() + let ready = root.appendingPathComponent("port") + try ProcessWait.marker(ready, child: process, root: root, timeout: 10) + base = "https://127.0.0.1:" + (try String(contentsOf: ready, encoding: .utf8)) + } + + func release(_ contents: String) throws -> String { + let directory = repository.appendingPathComponent("skills/fixture") + try Data( + """ + --- + name: fixture + description: Acquisition cache fixture + --- + # Fixture + \(contents) + """.utf8 + ).write(to: directory.appendingPathComponent("SKILL.md")) + try Data([0x01, 0x04, 0x07]).write(to: directory.appendingPathComponent("asset.bin")) + try git(["-C", repository.path, "add", "."]) + try git(["-C", repository.path, "commit", "-m", contents]) + return try ProcessRunner.run( + "/usr/bin/git", arguments: ["-C", repository.path, "rev-parse", "HEAD"] + ).stdout.trimmingCharacters(in: .newlines) + } + + func git(_ arguments: [String]) throws { + try run("/usr/bin/git", ["-c", "gc.auto=0", "-c", "maintenance.auto=false"] + arguments) + } + + private func run(_ path: String, _ arguments: [String]) throws { + if path == "/usr/bin/openssl" { + let child = Process() + child.executableURL = URL(fileURLWithPath: path) + child.arguments = arguments + child.standardError = FileHandle.nullDevice + child.environment = ["PATH": "/usr/bin:/bin", "HOME": root.path] + try child.run() + defer { try? ProcessWait.terminate(child) } + try ProcessWait.exit(child, root: root, timeout: 10) + try #require(child.terminationStatus == 0) + } else { + try ProcessRunner.run(path, arguments: arguments) + } + } + + func url(_ name: String) -> String { base + "/" + name + ".git" } + + func environment(_ project: String) throws -> RuntimeEnvironment { + let path = root.appendingPathComponent(project) + try FileManager.default.createDirectory(at: path, withIntermediateDirectories: true) + return RuntimeEnvironment( + projectDirectory: path, homeDirectory: root.appendingPathComponent("home"), environment: [:], + acquisitionCacheRoot: root.appendingPathComponent("shared/cache")) + } + + func copyLock(from: RuntimeEnvironment, to: RuntimeEnvironment) throws { + let original = StateStore(scope: .project, environment: from) + let target = StateStore(scope: .project, environment: to) + try FileManager.default.createDirectory(at: target.directory, withIntermediateDirectories: true) + try FileManager.default.copyItem(at: original.declarationURL, to: target.declarationURL) + try FileManager.default.copyItem(at: original.resolvedURL, to: target.resolvedURL) + } + + func skill(_ environment: RuntimeEnvironment) -> URL { + environment.projectDirectory.appendingPathComponent(".agents/skills/fixture/SKILL.md") + } + + func requests() throws -> [String] { + try String(contentsOf: root.appendingPathComponent("requests"), encoding: .utf8) + .split(separator: "\n").map(String.init) + } + + func child(_ arguments: [String], configuration: URL) throws -> Process { + var directory = Bundle(for: GitFixtureBundle.self).bundleURL + while !FileManager.default.isExecutableFile( + atPath: directory.appendingPathComponent("StateTestProcess").path), directory.path != "/" + { + directory.deleteLastPathComponent() + } + let child = Process() + child.executableURL = directory.appendingPathComponent("StateTestProcess") + child.arguments = [root.path, "acquisition-private-install"] + arguments + child.environment = [ + "PATH": "/usr/bin:/bin", "HOME": root.appendingPathComponent("home").path, + "GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": configuration.path, + ] + try child.run() + return child + } + + func stop() { + if process.isRunning { try? ProcessWait.terminate(process) } + } + + func remove() { + stop() + try? FileManager.default.removeItem(at: root) + } + + private static let server = #""" + import base64, http.server, os, pathlib, ssl, subprocess, sys, urllib.parse + + root, cert, key = sys.argv[1:] + backend = pathlib.Path(subprocess.check_output( + ["/usr/bin/git", "--exec-path"], text=True).strip()) / "git-http-backend" + + class Handler(http.server.BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def do_GET(self): + self.serve_git() + + def do_POST(self): + self.serve_git() + + def serve_git(self): + parsed = urllib.parse.urlsplit(self.path) + headers = self.headers + supplied = bool(headers.get("Authorization") or headers.get("Cookie") + or headers.get("X-Fixture-Secret")) + with open(os.path.join(root, "requests"), "a") as log: + log.write(f"{self.command} {parsed.path} credential={int(supplied)}\n") + if parsed.path.startswith(("/private.git/", "/org/private.git/")): + token = b"fixture:fixture" if parsed.path.startswith("/private.git/") else b"fixture:fixture-managed-secret" + expected = "Basic " + base64.b64encode(token).decode() + if headers.get("Authorization") != expected: + self.send_response(401) + self.send_header("WWW-Authenticate", 'Basic realm="Fixture"') + self.end_headers() + return + if parsed.path.startswith("/redirect.git/"): + self.send_response(302) + self.send_header("Location", self.path.replace("/redirect.git/", "/package.git/")) + self.end_headers() + return + length = int(headers.get("Content-Length", "0")) + env = {"PATH": "/usr/bin:/bin", "HOME": root, "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": "/dev/null", "GIT_PROJECT_ROOT": root, + "GIT_HTTP_EXPORT_ALL": "1", "REQUEST_METHOD": self.command, + "PATH_INFO": urllib.parse.unquote(parsed.path), "QUERY_STRING": parsed.query, + "CONTENT_TYPE": headers.get("Content-Type", ""), "CONTENT_LENGTH": str(length), + "HTTP_GIT_PROTOCOL": headers.get("Git-Protocol", "")} + result = subprocess.run([backend], input=self.rfile.read(length), + env=env, capture_output=True) + meta, _, body = result.stdout.partition(b"\r\n\r\n") + response = [field.split(b": ", 1) for field in meta.split(b"\r\n") if b": " in field] + status = next((int(value.split()[0]) for name, value in response + if name.lower() == b"status"), 200) + self.send_response(status) + for name, value in response: + if name.lower() != b"status": + self.send_header(name.decode(), value.decode()) + self.end_headers() + self.wfile.write(body) + + server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) + context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + context.load_cert_chain(cert, key) + server.socket = context.wrap_socket(server.socket, server_side=True) + port = pathlib.Path(root, "port") + temporary = port.with_suffix(".tmp") + temporary.write_text(str(server.server_port)) + temporary.replace(port) + server.serve_forever() + """# +} + +private final class GitFixtureBundle: NSObject {} diff --git a/Tests/AgentsUpdatesTests/HostedMarketplaceTLSTests.swift b/Tests/AgentsUpdatesTests/HostedMarketplaceTLSTests.swift new file mode 100644 index 0000000..64ec3ab --- /dev/null +++ b/Tests/AgentsUpdatesTests/HostedMarketplaceTLSTests.swift @@ -0,0 +1,126 @@ +#if os(macOS) + import AgentsCore + import Foundation + import Darwin + import Testing + + @testable import AgentsUpdates + + @Suite("Hosted marketplace loopback TLS") + struct HostedMarketplaceTLSTests { + @Test(.enabled(if: ProcessInfo.processInfo.environment["AGENTS_TEST_HOSTED_TLS"] == "1")) + func verifiesTLSAndControlsRedirectsAndResponseSize() throws { + let fixture = try UpdateFixture() + let root = fixture.root + let ca = root.appendingPathComponent("certificate.pem") + let caKey = root.appendingPathComponent("authority.key") + _ = try ProcessRunner.run( + "/usr/bin/openssl", + arguments: [ + "req", "-x509", "-newkey", "rsa:2048", "-days", "1", "-nodes", + "-subj", "/CN=Hosted Marketplace Loopback CA", "-keyout", caKey.path, + "-out", ca.path, + ]) + let request = root.appendingPathComponent("server.csr") + let key = root.appendingPathComponent("fixture.key") + _ = try ProcessRunner.run( + "/usr/bin/openssl", + arguments: [ + "req", "-new", "-newkey", "rsa:2048", "-nodes", "-subj", "/CN=127.0.0.1", + "-keyout", key.path, "-out", request.path, + ]) + let extensions = root.appendingPathComponent("tls.conf") + try fixture.write( + """ + basicConstraints = critical,CA:FALSE + subjectAltName = IP:127.0.0.1 + extendedKeyUsage = serverAuth + keyUsage = critical,digitalSignature,keyEncipherment + """, to: extensions) + let leaf = root.appendingPathComponent("server.pem") + _ = try ProcessRunner.run( + "/usr/bin/openssl", + arguments: [ + "x509", "-req", "-in", request.path, "-CA", ca.path, "-CAkey", caKey.path, + "-CAcreateserial", "-days", "1", "-extfile", extensions.path, "-out", leaf.path, + ]) + let der = root.appendingPathComponent("certificate.der") + _ = try ProcessRunner.run( + "/usr/bin/openssl", + arguments: ["x509", "-in", ca.path, "-outform", "der", "-out", der.path]) + let anchor = try Data(contentsOf: der) + + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/env") + process.arguments = ["python3", "-c", Self.server, root.path] + process.standardOutput = FileHandle.nullDevice + process.standardError = FileHandle.nullDevice + let exited = DispatchSemaphore(value: 0) + process.terminationHandler = { _ in exited.signal() } + try process.run() + defer { + if process.isRunning { process.terminate() } + if exited.wait(timeout: .now() + .seconds(3)) == .timedOut { + if process.isRunning { _ = kill(process.processIdentifier, SIGKILL) } + #expect(exited.wait(timeout: .now() + .seconds(3)) == .success) + } + } + let portFile = root.appendingPathComponent("port") + let clock = ContinuousClock() + let deadline = clock.now + .seconds(3) + var port: Int? + while process.isRunning && clock.now < deadline { + if let value = try? String(contentsOf: portFile, encoding: .utf8), let number = Int(value) { + port = number + break + } + Thread.sleep(forTimeInterval: 0.01) + } + let authority = try "https://127.0.0.1:\(#require(port))" + let redirect = try URLRequest(url: #require(URL(string: authority + "/redirect"))) + #expect(throws: HostedMarketplaceError.requestFailed) { + try HostedMarketplaceHTTP.fetch(redirect, maximumBytes: 32) + } + let hop = try HostedMarketplaceHTTP.fetch( + redirect, maximumBytes: 32, localTrustAnchor: anchor) + #expect(hop.status == 307) + #expect(hop.location == "/data") + let hit = root.appendingPathComponent("data-hit") + #expect(!FileManager.default.fileExists(atPath: hit.path)) + var data = try URLRequest(url: #require(URL(string: authority + "/data"))) + data.setValue("Bearer synthetic-loopback", forHTTPHeaderField: "Authorization") + #expect(throws: HostedMarketplaceError.responseTooLarge) { + try HostedMarketplaceHTTP.fetch(data, maximumBytes: 4, localTrustAnchor: anchor) + } + let received = try HostedMarketplaceHTTP.fetch( + data, maximumBytes: 32, localTrustAnchor: anchor) + #expect(String(decoding: received.bytes, as: UTF8.self) == "Bearer synthetic-loopback") + } + + private static let server = """ + import http.server, pathlib, ssl, sys + root = pathlib.Path(sys.argv[1]) + class Handler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + if self.path == "/redirect": + self.send_response(307) + self.send_header("Location", "/data") + self.send_header("Set-Cookie", "fixture=redirect; Secure; Path=/") + self.end_headers() + return + (root / "data-hit").touch() + body = self.headers.get("Authorization", "").encode() + if self.headers.get("Cookie"): + body = b"unexpected-cookie" + self.send_response(200) + self.end_headers() + self.wfile.write(body) + server = http.server.HTTPServer(("127.0.0.1", 0), Handler) + context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + context.load_cert_chain(root / "server.pem", root / "fixture.key") + server.socket = context.wrap_socket(server.socket, server_side=True) + (root / "port").write_text(str(server.server_port)) + server.serve_forever() + """ + } +#endif diff --git a/Tests/AgentsUpdatesTests/HostedMarketplaceTests.swift b/Tests/AgentsUpdatesTests/HostedMarketplaceTests.swift new file mode 100644 index 0000000..c21fe09 --- /dev/null +++ b/Tests/AgentsUpdatesTests/HostedMarketplaceTests.swift @@ -0,0 +1,679 @@ +import AgentsCore +import AgentsManifest +import Foundation +import Synchronization +import Testing + +@testable import AgentsUpdates + +#if canImport(FoundationNetworking) + import FoundationNetworking +#endif + +@Suite("Hosted HTTPS marketplace") +struct HostedMarketplaceTests { + private static let token = "synthetic-team-token" + + @Test func canonicalIdentityAndIndexAdmission() throws { + let origin = try MarketplaceOrigin( + kind: .hosted, location: "HTTPS://TEAM.invalid:443/a/index.json") + #expect(origin.location == "https://team.invalid/a/index.json") + #expect(origin == (try MarketplaceOrigin(hostedIndex: #require(origin.hostedIndex)))) + for bad in [ + "http://team.invalid/a/index.json", "https://user@team.invalid/a/index.json", + "https://team.invalid/a/index.json#x", "https://team.invalid/a/index.json?token=value", + "https://team.invalid/a/%2e/index.json", "https://team.invalid/a/../index.json", + "https://team.invalid/a/%2Findex.json", "https://team.invalid/a//index.json", + ] { + #expect(throws: MarketplaceError.self) { try MarketplaceOrigin(kind: .hosted, location: bad) } + } + + let package = try GraphCatalog() + let bytes = try package.archive("demo", "1.0.0") + let fixture = try HostedFixture(archive: bytes) + let market = HostedResponses(fixture.responses) + let consumer = try UpdateFixture() + let catalog = try MarketplaceOperations.verifyCatalog( + fixture.registration, environment: consumer.environment, hostedAccess: market.access()) + #expect(catalog.search("HanDbook").map(\.coordinate.package) == ["demo"]) + #expect(catalog.indexDigest == ReleaseMetadata.digest(fixture.index)) + #expect(!FileManager.default.fileExists(atPath: consumer.store.directory.path)) + + let valid = try HostedMarketplaceIndex.read(fixture.index, maximumReleases: 2) + let entry = try #require(valid.releases.first) + #expect(throws: MarketplaceError.self) { + try HostedMarketplaceIndex.read(fixture.index, maximumReleases: 0) + } + #expect(throws: MarketplaceError.self) { + try HostedMarketplaceIndex.read( + ResolvedLedgerCodec.bytes( + HostedMarketplaceIndex(formatVersion: 1, releases: [entry, entry])), + maximumReleases: 2) + } + for path in [ + "/outside.bundle", "../outside.bundle", "a/../outside.bundle", "a%2fb", "a//b", + "https://outside.invalid/bundle", "a?token=value", "a#fragment", + ] { + let bad = HostedMarketplaceIndex.Entry( + coordinate: entry.coordinate, archiveDigest: entry.archiveDigest, + archiveByteCount: entry.archiveByteCount, summary: nil, archivePath: path) + #expect(throws: MarketplaceError.self) { + try HostedMarketplaceIndex.read( + ResolvedLedgerCodec.bytes(HostedMarketplaceIndex(formatVersion: 1, releases: [bad])), + maximumReleases: 2) + } + } + + market.set(fixture.archiveURL, status: 200, bytes: bytes + Data([0])) + #expect(throws: HostedMarketplaceError.responseTooLarge) { + try MarketplaceOperations.verifyCatalog( + fixture.registration, environment: consumer.environment, hostedAccess: market.access()) + } + var changed = bytes + changed[changed.startIndex] ^= 1 + market.set(fixture.archiveURL, status: 200, bytes: changed) + #expect(throws: MarketplaceError.integrityMismatch("demo@1.0.0")) { + try MarketplaceOperations.verifyCatalog( + fixture.registration, environment: consumer.environment, hostedAccess: market.access()) + } + } + + @Test func userRegistrationAndPerHopCredentialIsolation() throws { + let package = try GraphCatalog() + let fixture = try HostedFixture(archive: package.archive("demo", "1.0.0")) + let market = HostedResponses(fixture.responses) + let consumer = try UpdateFixture() + let index = fixture.registration.origin.location + let alias = fixture.registration.name + let environment = consumer.environment + let mirror = try #require(URL(string: "https://cdn.invalid")) + let cdn = mirror.absoluteString + "/snapshots/demo.bundle" + let returned = "https://team.invalid/team/return.bundle" + market.set(fixture.archiveURL, status: 302, location: cdn) + market.set(cdn, status: 307, location: returned) + market.set(returned, status: 200, bytes: fixture.archive) + market.requireToken(at: index) + let access = market.access(downloadOrigins: [try .http(mirror.absoluteString)]) { url in + url.absoluteString == index ? Self.token : nil + } + + try MarketplaceDirectory.register( + fixture.registration, scope: .project, environment: environment) + #expect(throws: HostedMarketplaceError.credentialRequired) { + try MarketplaceOperations.browse( + fixture.registration, environment: environment, hostedAccess: access) + } + #expect(market.takeRequests() == [.init(url: index, authorization: nil)]) + + try MarketplaceDirectory.register(fixture.registration, scope: .user, environment: environment) + let selected = try MarketplaceOperations.browse( + fixture.registration, environment: environment, hostedAccess: access + ).select(package: "demo") + let verified = try MarketplaceOperations.acquire( + selected, environment: environment, hostedAccess: access) + #expect( + verified.hostedEvidence?.archiveRequests.map(\.absoluteString) == [ + fixture.archiveURL, cdn, returned, + ]) + #expect( + market.takeRequests() == [ + .init(url: index, authorization: "Bearer " + Self.token), + .init(url: fixture.archiveURL, authorization: "Bearer " + Self.token), + .init(url: cdn, authorization: nil), .init(url: returned, authorization: nil), + ]) + + let userPolicy = SourcePolicyOperations.policyURL(scope: .user, environment: environment) + try consumer.write("version: 1\ndeny: [{http: 'https://cdn.invalid'}]\n", to: userPolicy) + #expect(throws: SourcePolicyFailure.self) { + try MarketplaceOperations.acquire(selected, environment: environment, hostedAccess: access) + } + #expect(market.takeRequests().map(\.url) == [fixture.archiveURL]) + try FileManager.default.removeItem(at: userPolicy) + let org = consumer.root.appendingPathComponent("org.yaml") + try consumer.write("enforcement: block\nsources: {deny: ['https://cdn.invalid']}\n", to: org) + var governed = environment + governed.userOrganizationPolicy = .init(.local(org)) + #expect(throws: OrganizationPolicyFailure.self) { + try MarketplaceOperations.acquire(selected, environment: governed, hostedAccess: access) + } + #expect(market.takeRequests().map(\.url) == [fixture.archiveURL]) + + market.set(index, status: 302, location: cdn) + #expect(throws: MarketplaceError.self) { + try MarketplaceOperations.browse( + fixture.registration, environment: environment, hostedAccess: access) + } + #expect(market.takeRequests().map(\.url) == [index]) + market.set(index, status: 200, bytes: fixture.index) + + #expect(throws: HostedMarketplaceError.redirectDenied) { + try MarketplaceOperations.acquire( + selected, environment: environment, hostedAccess: market.access()) + } + #expect(market.takeRequests().map(\.url) == [fixture.archiveURL]) + + market.set(fixture.archiveURL, status: 302, location: "/team-sibling/demo.bundle") + #expect(throws: MarketplaceError.self) { + try MarketplaceOperations.acquire(selected, environment: environment, hostedAccess: access) + } + #expect(market.takeRequests().map(\.url) == [fixture.archiveURL]) + + let wrong = try MarketplaceRegistration( + name: alias, + origin: MarketplaceOrigin(kind: .hosted, location: "https://team.invalid/other/index.json")) + try MarketplaceDirectory.unregister(alias, scope: .user, environment: environment) + try MarketplaceDirectory.register(wrong, scope: .user, environment: environment) + let shouldNotTransfer = market.access { _ in Self.token } + #expect(throws: HostedMarketplaceError.credentialRequired) { + try MarketplaceOperations.browse( + fixture.registration, environment: environment, hostedAccess: shouldNotTransfer) + } + #expect(market.takeRequests() == [.init(url: index, authorization: nil)]) + + try MarketplaceDirectory.register( + MarketplaceRegistration(name: "original", origin: fixture.registration.origin), + scope: .user, environment: environment) + for invalid in ["", "\r\nX-Test: injected", "two words", "\u{1F512}"] { + #expect(throws: HostedMarketplaceError.invalidCredential) { + try MarketplaceOperations.browse( + fixture.registration, environment: environment, + hostedAccess: market.access { _ in invalid }) + } + } + #expect(market.takeRequests().isEmpty) + } + + @Test func privateHostedLockWritesReviewedBytesAndDeploysInAnotherProjectOffline() throws { + let producer = try GraphCatalog() + let remote = try HostedFixture(archive: producer.archive("starter", "1.0.0")) + let market = HostedResponses(remote.responses) + let consumer = try UpdateFixture() + let env = consumer.environment + let index = remote.registration.origin.location + market.requireToken(at: index) + try MarketplaceDirectory.register(remote.registration, scope: .user, environment: env) + let access = market.access { url in url.absoluteString == index ? Self.token : nil } + let root = try MarketplaceRoot( + name: "starter", catalog: remote.registration.origin, package: "starter", + requirement: .exact("1.0.0"), + selections: [ + MarketplaceMemberSelection( + package: "starter", member: .init(kind: .skills, name: "demo"), targets: [.codex]) + ]) + func preview() throws -> MarketplaceLockPreview { + try MarketplaceOperations.previewLockOnly( + .install(root), environment: env, hostedAccess: access) + } + let revoked = try preview() + let policy = SourcePolicyOperations.policyURL(scope: .project, environment: env) + try consumer.write("version: 1\ndeny: [{http: 'https://team.invalid'}]\n", to: policy) + #expect(throws: CoreError.self) { try MarketplaceOperations.writeLockOnly(revoked) } + #expect(!FileManager.default.fileExists(atPath: consumer.store.resolvedURL.path)) + try FileManager.default.removeItem(at: policy) + let checked = try preview() + #expect(!market.takeRequests().isEmpty) + market.set(index, status: 503) + market.set(remote.archiveURL, status: 503) + _ = try MarketplaceOperations.writeLockOnly(checked) + #expect(!FileManager.default.fileExists(atPath: consumer.target().path)) + #expect(market.takeRequests().isEmpty) + let cold = try UpdateFixture() + for name in ["agents.yaml", "agents.resolved"] { + let text = try String( + contentsOf: consumer.store.directory.appendingPathComponent(name), encoding: .utf8) + #expect(!text.contains(Self.token)) + try cold.write(text, to: cold.store.directory.appendingPathComponent(name)) + } + let deployment = try MarketplaceOperations.previewFrozenDeployment( + environment: cold.environment) + _ = try MarketplaceOperations.deployFrozen(deployment) + #expect( + try cold.bytes(cold.target().appendingPathComponent("SKILL.md")) + == producer.author.bytes(producer.author.target().appendingPathComponent("SKILL.md"))) + #expect( + try UpdateOperations.inspect(environment: cold.environment).pendingMarketplaceDeployment + == nil) + #expect(market.takeRequests().isEmpty) + } + + @Test func deniedHostedStagingLeavesTheOutputDirectoryEmpty() throws { + let producer = try GraphCatalog() + let bundle = try producer.archive("starter", "1.0.0") + let consumer = try UpdateFixture() + let env = consumer.environment + let directory = consumer.root.appendingPathComponent("stage", isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false) + let policy = consumer.root.appendingPathComponent("organization.yaml") + var denied = env + denied.userOrganizationPolicy = .init(.local(policy)) + try consumer.write("enforcement: block\ndependencies: {deny: ['_local/starter']}\n", to: policy) + #expect(throws: OrganizationPolicyFailure.self) { + try MarketplaceOperations.exportHostedBundle(bundle, to: directory, environment: denied) + } + #expect(try FileManager.default.contentsOfDirectory(atPath: directory.path).isEmpty) + } + + @Test func recapturePreservesNamedHostedReleaseAndChecksItsDownloadRoute() throws { + let producer = try GraphCatalog() + let remote = try HostedFixture(archive: producer.archive("starter", "1.0.0")) + let market = HostedResponses(remote.responses) + let author = try UpdateFixture() + let environment = author.environment + let index = remote.registration.origin.location + let cdn = "https://cdn.invalid" + let download = cdn + "/snapshots/starter.bundle" + market.set(remote.archiveURL, status: 302, location: download) + market.set(download, status: 200, bytes: remote.archive) + market.requireToken(at: index) + try MarketplaceDirectory.register(remote.registration, scope: .user, environment: environment) + let access = market.access(downloadOrigins: [try .http(cdn)]) { + $0.absoluteString == index ? Self.token : nil + } + let root = try MarketplaceRoot( + name: "starter", catalog: remote.registration.origin, package: "starter", + requirement: .exact("1.0.0"), + selections: [ + .init(package: "starter", member: .init(kind: .skills, name: "demo"), targets: [.codex]) + ]) + let reviewed = try MarketplaceOperations.previewResolution( + .install(root), environment: environment, hostedAccess: access) + _ = try MarketplaceOperations.withPreparedResolution(reviewed) { try $0.apply() } + #expect(market.takeRequests().map(\.url).contains(download)) + + let package = BundlePackage(name: "derivative", version: "2.0.0") + let spec = AuthorPackageSpecification( + package: package, lockedMembers: [.init(kind: .skills, name: "demo")]) + let authorCapture = try AuthorPackageOperations.preview(spec, environment: environment) + let installed = try UpdateOperations.inspect(environment: environment) + let selection = try #require(installed.components.first?.selection) + let bytes = try BundleOperations.export( + package, selections: [selection], scope: .project, environment: environment) + let installedExport = try BundleOperations.inspect(bytes) + for capture in [authorCapture.inspection, installedExport] { + let member = try #require(capture.components.first) + let named = try #require(member.sources.first { $0.packageName == "starter" }) + #expect(named.identity == index) + #expect(named.root == "team/index.json") + #expect(named.origin == (try .http("https://team.invalid"))) + #expect(named.version == "1.0.0") + #expect(named.revision == BundleArchive.digest(remote.archive)) + #expect( + member.sources.contains { + $0.origin == (try? .http(cdn)) && $0.root == "snapshots/starter.bundle" + }) + #expect( + !String(decoding: try ResolvedLedgerCodec.bytes(member.sources), as: UTF8.self) + .contains(Self.token)) + } + + let catalog = author.root.appendingPathComponent("derivatives") + try FileManager.default.createDirectory(at: catalog, withIntermediateDirectories: false) + let sourcePolicy = SourcePolicyOperations.policyURL(scope: .project, environment: environment) + try author.write("version: 1\ndeny: [{http: '\(cdn)'}]\n", to: sourcePolicy) + #expect(throws: SourcePolicyFailure.self) { + try AuthorPackageOperations.publish(authorCapture, to: catalog, environment: environment) + } + #expect(throws: SourcePolicyFailure.self) { + try MarketplaceOperations.publishBundle(bytes, to: catalog, environment: environment) + } + #expect(try FileManager.default.contentsOfDirectory(atPath: catalog.path).isEmpty) + try FileManager.default.removeItem(at: sourcePolicy) + + let policyURL = author.root.appendingPathComponent("org.yaml") + var restricted = environment + restricted.projectOrganizationPolicy = .init(.local(policyURL)) + try author.write("enforcement: block\nsources: {deny: ['\(download)']}\n", to: policyURL) + #expect(throws: OrganizationPolicyFailure.self) { + try AuthorPackageOperations.preview(spec, environment: restricted) + } + #expect(throws: OrganizationPolicyFailure.self) { + try BundleOperations.export( + package, selections: [selection], scope: .project, environment: restricted) + } + #expect(market.takeRequests().isEmpty) + } + + @Test func capturesGraphAndRestoresInAnIndependentProject() throws { + let package = try GraphCatalog() + let child = try HostedFixture( + path: "/child", archive: package.archive("leaf", "1.0.0")) + let edge = try MarketplacePackageRequirement( + package: "leaf", requirement: .exact("1.0.0"), catalog: child.registration.origin) + let parent = try HostedFixture(archive: package.archive("root", "1.0.0", dependencies: [edge])) + let market = HostedResponses(parent.responses.merging(child.responses) { _, next in next }) + let access = market.access { _ in Self.token } + let consumer = try UpdateFixture() + let root = try MarketplaceRoot( + name: "path", catalog: parent.registration.origin, package: "root", + requirement: .upToNextMajor(from: "1.0.0"), + selections: [ + MarketplaceMemberSelection( + package: "leaf", catalog: child.registration.origin, + member: .init(kind: .skills, name: "demo"), targets: [.codex]) + ]) + try MarketplaceDirectory.register( + child.registration, scope: .project, environment: consumer.environment) + #expect(throws: HostedMarketplaceError.registrationRequired) { + try MarketplaceOperations.resolve( + .install(root), environment: consumer.environment, hostedAccess: access) + } + #expect( + market.takeRequests().map(\.url) == [parent.registration.origin.location, parent.archiveURL]) + try MarketplaceDirectory.register( + child.registration, scope: .user, environment: consumer.environment) + + func preview() throws -> MarketplaceResolutionPreview { + try MarketplaceOperations.previewResolution( + .install(root), environment: consumer.environment, hostedAccess: access) + } + + let revoked = try preview() + let policyURL = SourcePolicyOperations.policyURL( + scope: .project, environment: consumer.environment) + try consumer.write("version: 1\ndeny: [{http: 'https://team.invalid'}]\n", to: policyURL) + #expect(throws: CoreError.self) { + try MarketplaceOperations.withPreparedResolution(revoked) { try $0.apply() } + } + #expect(!FileManager.default.fileExists(atPath: consumer.target().path)) + #expect(!FileManager.default.fileExists(atPath: consumer.store.resolvedURL.path)) + try FileManager.default.removeItem(at: policyURL) + + let untrusted = try preview() + try MarketplaceDirectory.unregister( + child.registration.name, scope: .user, environment: consumer.environment) + #expect(throws: HostedMarketplaceError.registrationRequired) { + try MarketplaceOperations.withPreparedResolution(untrusted) { try $0.apply() } + } + #expect(!FileManager.default.fileExists(atPath: consumer.store.resolvedURL.path)) + try MarketplaceDirectory.register( + child.registration, scope: .user, environment: consumer.environment) + + let stale = try preview() + try consumer.write("version: 1\n", to: consumer.store.declarationURL) + #expect(throws: CoreError.self) { + try MarketplaceOperations.withPreparedResolution(stale) { try $0.apply() } + } + #expect(!FileManager.default.fileExists(atPath: consumer.store.resolvedURL.path)) + + let replaced = try preview() + let sameManifest = try consumer.bytes(consumer.store.declarationURL) + try sameManifest.write(to: consumer.store.declarationURL, options: .atomic) + #expect(throws: CoreError.self) { + try MarketplaceOperations.withPreparedResolution(replaced) { try $0.apply() } + } + #expect(!FileManager.default.fileExists(atPath: consumer.store.resolvedURL.path)) + + let reviewed = try preview() + _ = market.takeRequests() + market.set(child.archiveURL, status: 404) + _ = try MarketplaceOperations.withPreparedResolution(reviewed) { try $0.apply() } + #expect(market.takeRequests().isEmpty) + let ledger = try consumer.store.loadLedger() + let graph = try #require(ledger.marketplaceGraph) + #expect( + Set(graph.nodes.compactMap(\.id.catalog.hostedIndex)) == [ + try #require(child.registration.origin.hostedIndex), + try #require(parent.registration.origin.hostedIndex), + ]) + for release in graph.nodes { + let archive = release.coordinate.package == "root" ? parent.archive : child.archive + #expect(ledger.contentObjects[release.archiveDigest] == archive) + #expect(release.hostedEvidence?.archiveByteCount == archive.count) + } + var corrupt = ledger.contentObjects + let leaf = try #require(graph.nodes.first { $0.id.package == "leaf" }) + corrupt[leaf.archiveDigest] = Data(repeating: 0, count: child.archive.count) + #expect(throws: (any Error).self) { + try MarketplaceGraphChange.validateHosted( + graph, objects: corrupt, policy: SourcePolicySnapshot(store: consumer.store).effective, + organizationPolicy: OrganizationPolicySnapshot(store: consumer.store)) + } + let lock = try consumer.bytes(consumer.store.resolvedURL) + #expect(!String(decoding: lock, as: UTF8.self).contains(Self.token)) + + let cold = try UpdateFixture() + for name in ["agents.yaml", "agents.resolved"] { + try cold.write( + String(contentsOf: consumer.store.directory.appendingPathComponent(name), encoding: .utf8), + to: cold.store.directory.appendingPathComponent(name)) + } + var corruptLock = ledger + corruptLock.contentObjects = corrupt + try ResolvedLedgerCodec.bytes(corruptLock).write(to: cold.store.resolvedURL, options: .atomic) + #expect(throws: CoreError.self) { + try UpdateOperations.restore(environment: cold.environment) + } + #expect(!FileManager.default.fileExists(atPath: cold.target().path)) + try lock.write(to: cold.store.resolvedURL, options: .atomic) + _ = try UpdateOperations.restore(environment: cold.environment) + #expect(try cold.bytes(cold.store.resolvedURL) == lock) + #expect( + try cold.bytes(cold.target().appendingPathComponent("SKILL.md")) + == consumer.bytes(consumer.target().appendingPathComponent("SKILL.md"))) + #expect(market.takeRequests().isEmpty) + + let other = try MarketplaceRegistration( + name: parent.registration.name, + origin: MarketplaceOrigin(kind: .hosted, location: "https://team.invalid/other/index.json")) + try MarketplaceDirectory.register(other, scope: .user, environment: consumer.environment) + let rebound = try MarketplaceRoot( + name: root.name, catalog: other.origin, package: root.package, requirement: root.requirement) + #expect(throws: MarketplaceError.originConflict(root.name)) { + try MarketplaceOperations.resolve( + .install(rebound), environment: consumer.environment, hostedAccess: access) + } + #expect(market.takeRequests().isEmpty) + + let latest = try HostedFixture(archive: package.archive("root", "1.1.0", dependencies: [edge])) + let updatedIndex = try HostedMarketplaceIndex( + formatVersion: 1, + releases: [ + #require(HostedMarketplaceIndex.read(parent.index, maximumReleases: 2).releases.first), + #require(HostedMarketplaceIndex.read(latest.index, maximumReleases: 2).releases.first), + ]) + market.set( + parent.registration.origin.location, status: 200, + bytes: try ResolvedLedgerCodec.bytes(updatedIndex)) + market.set(latest.archiveURL, status: 200, bytes: latest.archive) + let available = try MarketplaceOperations.resolve( + .reconcile, environment: consumer.environment, hostedAccess: access) + let rootVersions = try #require( + available.nodes.first { $0.versions.node.package == "root" }?.versions) + #expect(rootVersions.eligible.version == "1.0.0") + #expect(rootVersions.latest?.version == "1.1.0") + let upgrade = try MarketplaceOperations.previewResolution( + .upgrade("path"), environment: consumer.environment, hostedAccess: access) + #expect( + upgrade.report.marketplaceGraphChange?.after?.nodes.contains { + $0.coordinate.version == "1.1.0" + } == true) + let changedIndex = HostedMarketplaceIndex( + formatVersion: 1, + releases: updatedIndex.releases.map { entry in + guard entry.coordinate.version == "1.0.0" else { return entry } + return .init( + coordinate: entry.coordinate, + archiveDigest: latest.archive == parent.archive + ? "" : ReleaseMetadata.digest(latest.archive), + archiveByteCount: entry.archiveByteCount, summary: entry.summary, + archivePath: entry.archivePath) + }) + market.set( + parent.registration.origin.location, status: 200, + bytes: try ResolvedLedgerCodec.bytes(changedIndex)) + #expect(throws: MarketplaceError.integrityMismatch("root@1.0.0")) { + try MarketplaceOperations.resolve( + .upgrade("path"), environment: consumer.environment, hostedAccess: access) + } + #expect(try consumer.bytes(consumer.store.resolvedURL) == lock) + } + + @Test func exportSerializesPublicationAndRetainsTheVisibleIndexOnInterruption() async throws { + let author = try GraphCatalog() + let first = try author.archive("kit", "1.0.0") + let second = try author.archive("kit", "1.1.0") + let third = try author.archive("tool", "1.0.0") + let stage = author.catalog + let mirror = author.author.root.appendingPathComponent("mirror", isDirectory: true) + try FileManager.default.createDirectory(at: mirror, withIntermediateDirectories: false) + let index = try MarketplaceOperations.exportHostedBundle(first, to: stage) + let initial = try Data(contentsOf: index) + struct Interrupted: Error {} + #expect(throws: Interrupted.self) { + try MarketplaceOperations.exportHostedBundle(second, to: stage, summary: nil) { + throw Interrupted() + } + } + #expect(try Data(contentsOf: index) == initial) + #expect( + try Data(contentsOf: stage.appendingPathComponent("releases/kit/1.1.0/package.bundle")) + == second) + async let addSecond = MarketplaceOperations.exportHostedBundle(second, to: stage) + async let addThird = MarketplaceOperations.exportHostedBundle(third, to: stage) + let published = try await [addSecond, addThird] + #expect(published == [index, index]) + let final = try Data(contentsOf: index) + _ = try MarketplaceOperations.exportHostedBundle(third, to: mirror) + _ = try MarketplaceOperations.exportHostedBundle(first, to: mirror) + let mirrored = try MarketplaceOperations.exportHostedBundle(second, to: mirror) + #expect(try Data(contentsOf: mirrored) == final) + _ = try MarketplaceOperations.exportHostedBundle(first, to: stage, summary: "ignored on replay") + #expect(try Data(contentsOf: index) == final) + let conflict = try author.archive( + "kit", "1.0.0", dependencies: [.init(package: "tool", requirement: .exact("1.0.0"))]) + #expect(throws: MarketplaceError.publicationConflict("kit@1.0.0")) { + try MarketplaceOperations.exportHostedBundle(conflict, to: stage) + } + #expect(try Data(contentsOf: index) == final) + let contest = author.author.root.appendingPathComponent("contest", isDirectory: true) + try FileManager.default.createDirectory(at: contest, withIntermediateDirectories: false) + @Sendable func publish(_ bytes: Data) -> Result { + Result { try MarketplaceOperations.exportHostedBundle(bytes, to: contest) } + } + async let candidateOne = publish(first) + async let candidateTwo = publish(conflict) + let contestResults = await [candidateOne, candidateTwo] + #expect(contestResults.filter { (try? $0.get()) != nil }.count == 1) + let rejected = contestResults.compactMap { result -> MarketplaceError? in + guard case .failure(let error) = result else { return nil } + return error as? MarketplaceError + } + #expect(rejected == [.publicationConflict("kit@1.0.0")], "\(contestResults)") + + let relocated = author.author.root.appendingPathComponent("relocated", isDirectory: true) + try FileManager.default.createDirectory(at: relocated, withIntermediateDirectories: false) + let manualArchive = relocated.appendingPathComponent("first.bundle") + try first.write(to: manualArchive) + try FileManager.default.setAttributes( + [.posixPermissions: 0o600, .modificationDate: Date(timeIntervalSince1970: 123)], + ofItemAtPath: manualArchive.path) + let entry = try #require( + HostedMarketplaceIndex.read(initial, maximumReleases: 1).releases.first) + let alternate = HostedMarketplaceIndex.Entry( + coordinate: entry.coordinate, archiveDigest: entry.archiveDigest, + archiveByteCount: entry.archiveByteCount, summary: entry.summary, archivePath: "first.bundle") + let relocatedIndex = relocated.appendingPathComponent(MarketplaceOperations.hostedIndexFilename) + try ResolvedLedgerCodec.bytes( + HostedMarketplaceIndex(formatVersion: 1, releases: [alternate]) + ).write(to: relocatedIndex) + _ = try MarketplaceOperations.exportHostedBundle(third, to: relocated) + let mixed = try HostedMarketplaceIndex.read( + Data(contentsOf: relocatedIndex), maximumReleases: 2) + #expect( + mixed.releases.map(\.archivePath) == [ + "first.bundle", "releases/tool/1.0.0/package.bundle", + ]) + #expect(try Data(contentsOf: manualArchive) == first) + + try Data([0]).write(to: stage.appendingPathComponent("releases/kit/1.0.0/package.bundle")) + #expect(throws: MarketplaceError.integrityMismatch("kit@1.0.0")) { + try MarketplaceOperations.exportHostedBundle(third, to: stage) + } + #expect(try Data(contentsOf: index) == final) + } +} + +private struct HostedFixture { + let registration: MarketplaceRegistration + let archive: Data + let index: Data + let archiveURL: String + + init(path: String = "/team", archive: Data) throws { + let package = try BundleOperations.inspect(archive).package + registration = try MarketplaceRegistration( + name: String(path.dropFirst()), + origin: MarketplaceOrigin( + kind: .hosted, location: "https://team.invalid" + path + "/index.json")) + let coordinate = try MarketplaceCoordinate(package: package.name, version: package.version) + let filename = coordinate.releasePath + "/package.bundle" + self.archive = archive + archiveURL = "https://team.invalid" + path + "/" + filename + let entry = HostedMarketplaceIndex.Entry( + coordinate: coordinate, archiveDigest: ReleaseMetadata.digest(archive), + archiveByteCount: archive.count, summary: "Team handbook", archivePath: filename) + index = try ResolvedLedgerCodec.bytes( + HostedMarketplaceIndex(formatVersion: 1, releases: [entry])) + } + + var responses: [String: HostedMarketplaceHTTP.Response] { + [ + registration.origin.location: .init(status: 200, location: nil, bytes: index), + archiveURL: .init(status: 200, location: nil, bytes: archive), + ] + } +} + +private final class HostedResponses: Sendable { + struct Request: Equatable { + let url: String + let authorization: String? + } + + struct State { + var responses: [String: HostedMarketplaceHTTP.Response] + var requests: [Request] = [] + var privateURLs: Set = [] + } + + private let state: Mutex + + init(_ responses: [String: HostedMarketplaceHTTP.Response]) { + state = Mutex(State(responses: responses)) + } + + func set(_ url: String, status: Int, location: String? = nil, bytes: Data = Data()) { + state.withLock { $0.responses[url] = .init(status: status, location: location, bytes: bytes) } + } + + func requireToken(at url: String) { + state.withLock { _ = $0.privateURLs.insert(url) } + } + + func takeRequests() -> [Request] { + state.withLock { + let captured = $0.requests + $0.requests.removeAll() + return captured + } + } + + func access( + downloadOrigins: Set = [], + credentialProvider: HostedMarketplaceAccess.CredentialProvider? = nil + ) -> HostedMarketplaceAccess { + HostedMarketplaceAccess( + downloadOrigins: downloadOrigins, credentialProvider: credentialProvider + ) { request, _ in + self.state.withLock { state in + let url = request.url!.absoluteString + let authorization = request.value(forHTTPHeaderField: "Authorization") + state.requests.append(Request(url: url, authorization: authorization)) + if state.privateURLs.contains(url), authorization != "Bearer synthetic-team-token" { + return .init(status: 401, location: nil, bytes: Data()) + } + return state.responses[url] ?? .init(status: 404, location: nil, bytes: Data()) + } + } + } +} diff --git a/Tests/AgentsUpdatesTests/ImplicitReadFootprintTests.swift b/Tests/AgentsUpdatesTests/ImplicitReadFootprintTests.swift new file mode 100644 index 0000000..e522df3 --- /dev/null +++ b/Tests/AgentsUpdatesTests/ImplicitReadFootprintTests.swift @@ -0,0 +1,159 @@ +import AgentsCore +import AgentsManifest +import Foundation +import Testing + +@testable import AgentsUpdates + +struct ImplicitReadFootprintTests { + @Test(arguments: [InstallScope.project, .user]) + func implicitResourcesKeepInputsAndTargetsWithoutWatchingOwnedMirrors(_ scope: InstallScope) + throws + { + let f = try UpdateFixture(scope: scope) + let root = scope == .user ? f.store.directory : f.root + let tool = root.appendingPathComponent("bin/tool") + let body = root.appendingPathComponent("prompts/body.md") + try f.write("#!/bin/sh\nexit 0\n", to: tool) + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: tool.path) + try f.write("Prompt body", to: body) + let declaration = Declaration( + agents: [.claudeCode], + components: [ + .mcpServer(name: "tool", transport: .stdio(.init(executable: "./bin/tool"))), + .command(name: "body", description: "Body", prompt: .file(.init(path: "prompts/body.md"))), + ]) + let request = UpdateRequest(operation: .declaration(declaration)) + let report = try UpdateOperations.preview(request, scope: scope, environment: f.environment) + let discovery = try UpdateOperations.discover( + declaration, scope: scope, environment: f.environment) + _ = try UpdateOperations.withPreparedUpdate(request, scope: scope, environment: f.environment) { + try $0.apply(ifUnchangedFrom: report.displayedFingerprint) + } + let inspection = try UpdateOperations.inspect(scope: scope, environment: f.environment) + for locations in [report.readLocations, discovery.readLocations, inspection.readLocations] { + let paths = Set(locations.map(\.path)) + #expect(!paths.contains(root.path)) + #expect( + paths.isSuperset(of: [ + tool.path, body.path, f.store.declarationURL.path, + f.store.resolvedURL.path, f.store.watchURL.path, + ])) + let mirror = f.store.directory.appendingPathComponent("cache/mirrors/owned.git/FETCH_HEAD") + #expect( + !locations.contains { mirror.path.hasPrefix($0.path + "/") || mirror.path == $0.path }) + } + let selected = try #require(inspection.components.first { $0.kind == .mcpServer }) + let connection = try MCPConnectionOperations.snapshot( + selection: selected.selection, scope: scope, environment: f.environment) + #expect(connection.readDependencies.map { $0.url.path }.contains(tool.path)) + if scope == .user { + #expect(!connection.readDependencies.map { $0.url.path }.contains(root.path)) + } + #expect( + Set(inspection.readLocations.map(\.path)).isSuperset( + of: + inspection.deployments.map { $0.location.path })) + } + + @Test func absentDeclarationsAndGroupResourcesRemainInputs() throws { + let f = try UpdateFixture() + let absent = f.root.appendingPathComponent("absent-source") + let declaration = Declaration( + sources: ["unused": .init(kind: .local, location: absent.path, path: "nested")], + groups: [ + .init( + name: "unused", + components: [ + .command(name: "future", description: "Future", prompt: .file(.init(path: "future.md"))) + ]) + ]) + let paths = try UpdateOperations.readLocations( + declarations: [declaration], ledgers: [], store: f.store) + #expect( + Set(paths.map(\.path)).isSuperset(of: [ + absent.path, f.root.appendingPathComponent("future.md").path, + ])) + } + + @Test func emptyOwnSkillAndPluginSelectionsKeepDiscoveryRoots() throws { + let f = try UpdateFixture(scope: .user) + let plugin = f.store.directory.appendingPathComponent("plugins/empty") + try f.write( + "{\"name\":\"empty\",\"version\":\"1.0.0\"}", + to: plugin.appendingPathComponent(".claude-plugin/plugin.json")) + let declaration = Declaration( + agents: [.claudeCode], + components: [ + .plugin(name: "empty", path: "plugins/empty", source: ".", agents: []) + ]) + let report = try UpdateOperations.preview( + .init(operation: .declaration(declaration)), scope: .user, environment: f.environment) + #expect(report.readLocations.map(\.path).contains(plugin.path)) + #expect(!report.readLocations.map(\.path).contains(f.store.directory.path)) + let ownSkills = Declaration(components: [.skills(source: ".", .init(select: .all))]) + let ownReport = try UpdateOperations.preview( + .init(operation: .declaration(ownSkills)), scope: .user, environment: f.environment) + #expect(ownReport.readLocations.map(\.path).contains(f.store.directory.path)) + } + + @Test func explicitRootsRetainWholeTreeSemanticsAndLiveIsNotEnoughToSuppressThem() throws { + let f = try UpdateFixture() + let sameRoot = Declaration(sources: [ + "own": .init(kind: .local, location: f.root.path, path: "skills") + ]) + var ledger = ResolvedLedger() + ledger.sources["implicit"] = .init( + kind: .local, location: .init(kind: .absolute, path: f.root.path), revision: "live") + let elsewhere = f.root.appendingPathComponent("elsewhere") + ledger.sources["explicit"] = .init( + kind: .local, location: .init(kind: .absolute, path: elsewhere.path), revision: "live") + ledger.sources["pinned"] = .init( + kind: .local, location: .init(kind: .absolute, path: f.root.path), + revision: String(repeating: "a", count: 40)) + let paths = try UpdateOperations.readLocations( + declarations: [sameRoot], ledgers: [ledger], store: f.store) + #expect(Set(paths.map(\.path)).isSuperset(of: [f.root.path, elsewhere.path])) + ledger.sources = ["implicit": ledger.sources["implicit"]!] + ledger.sourceUses = [.init(source: "implicit", root: "skills")] + let retained = try UpdateOperations.readLocations( + declarations: [], ledgers: [ledger], store: f.store) + #expect(retained.map(\.path).contains(f.root.path)) + } + + @Test func supportingFilesAndLinkReplacementRemainInputs() throws { + let f = try UpdateFixture(scope: .user) + let root = f.store.directory + let selected = root.appendingPathComponent("bin/tool") + let support = root.appendingPathComponent("shared/actual") + try f.write("#!/bin/sh\n", to: support) + try FileManager.default.createDirectory( + at: selected.deletingLastPathComponent(), withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink( + atPath: selected.path, withDestinationPath: "../shared/actual") + let declaration = Declaration( + agents: [], + components: [ + .mcpServer(name: "supported", transport: .stdio(.init(executable: "bin/tool"))) + ]) + let request = UpdateRequest(operation: .declaration(declaration)) + let first = try UpdateOperations.preview(request, scope: .user, environment: f.environment) + let paths = first.readLocations + #expect(Set(paths.map(\.path)).isSuperset(of: [selected.path, support.path])) + #expect(!paths.map(\.path).contains(root.path)) + #expect(!paths.map(\.path).contains(root.appendingPathComponent("shared").path)) + try f.write("#!/bin/sh\n# changed support\n", to: support) + let changed = try UpdateOperations.preview(request, scope: .user, environment: f.environment) + #expect(changed.displayedFingerprint != first.displayedFingerprint) + let replacement = root.appendingPathComponent("shared/replacement") + try f.write("#!/bin/sh\n", to: replacement) + try FileManager.default.removeItem(at: selected) + try FileManager.default.createSymbolicLink( + atPath: selected.path, withDestinationPath: "../shared/replacement") + let replaced = try UpdateOperations.preview(request, scope: .user, environment: f.environment) + #expect(replaced.readLocations.map(\.path).contains(selected.path)) + #expect(replaced.readLocations.map(\.path).contains(replacement.path)) + #expect(!replaced.readLocations.map(\.path).contains(support.path)) + #expect(replaced.displayedFingerprint != changed.displayedFingerprint) + } +} diff --git a/Tests/AgentsUpdatesTests/ImportNativeExecutableLifecycleTests.swift b/Tests/AgentsUpdatesTests/ImportNativeExecutableLifecycleTests.swift new file mode 100644 index 0000000..90a4e03 --- /dev/null +++ b/Tests/AgentsUpdatesTests/ImportNativeExecutableLifecycleTests.swift @@ -0,0 +1,116 @@ +import AgentsCore +import AgentsUpdates +import Components +import Foundation +import Testing + +struct ImportNativeExecutableLifecycleTests { + @Test(arguments: [false, true], [(false, false), (false, true), (true, false), (true, true)]) + func nativeContainerExecutableUsesItsDeclaredInputRoot( + _ linked: Bool, _ configuration: (Bool, Bool) + ) throws { + let (rootBasename, gemini) = configuration + let f = try UpdateFixture() + let input = f.root.appendingPathComponent("producer") + let executable = rootBasename ? "server" : "bin/server" + let document = gemini ? "gemini-extension.json" : ".claude-plugin/plugin.json" + let prefix = gemini ? "${extensionPath}/" : "${CLAUDE_PLUGIN_ROOT}/" + let cwd = gemini ? ",\"cwd\":\"./cwd\"" : "" + try f.write( + "{\"name\":\"producer\",\"version\":\"1.2.3\",\"mcpServers\":{\"review\":{\"command\":\"" + + prefix + executable + "\"" + cwd + "}}}", + to: input.appendingPathComponent("bundle/" + document)) + if gemini { + try f.write( + "Working directory support", to: input.appendingPathComponent("bundle/cwd/config.txt")) + } + let program = linked ? "shared/server" : executable + try f.write("Frozen executable bytes\n", to: input.appendingPathComponent("bundle/" + program)) + try FileManager.default.setAttributes( + [.posixPermissions: 0o755], + ofItemAtPath: input.appendingPathComponent("bundle/" + program).path) + if linked { + try FileManager.default.createDirectory( + at: input.appendingPathComponent("bundle/bin"), withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink( + atPath: input.appendingPathComponent("bundle/" + executable).path, + withDestinationPath: rootBasename ? "shared/server" : "../shared/server") + } + let report = try SourceImportOperations.inspect( + format: gemini ? "geminiExtensionV1" : "claudePluginV1", root: input, + document: "bundle/" + document) + #expect(report.diagnostics.isEmpty) + #expect(report.sources.first?.declaration?.location == "bundle") + #expect( + report.resources.contains { $0.path == executable && $0.sourceAlias == "native-input" }) + guard case .mcpServer(_, .stdio(let run), _, _, _, _) = report.components.first?.declaration + else { + Issue.record("Expected native MCP executable") + return + } + #expect(run.executable == (rootBasename ? "./server" : "bin/server")) + #expect(run.executableSource == "native-input") + let request = try report.updateRequest(in: UpdateOperations.inspect(environment: f.environment)) + let preview = try UpdateOperations.preview(request, environment: f.environment) + _ = try UpdateOperations.withPreparedUpdate(request, environment: f.environment) { + #expect($0.report.displayedFingerprint == preview.displayedFingerprint) + return try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + func verify() throws { + let installed = try UpdateOperations.inspect(environment: f.environment) + #expect(installed.deployments.allSatisfy { $0.status == .current }) + let component = try #require(installed.components.first { $0.kind == .mcpServer }) + let ledger = try f.store.readLedger() + let record = try #require(ledger.components.values.first { $0.kind == "mcpServer" }) + try LedgerReplay.withLockedResources( + ledger, store: f.store, roots: f.store.ledgerRoots, limits: .standard + ) { _, resources, _ in + let programID = try #require(record.resources.first) + let program = try #require(resources[programID]) + #expect(try String(contentsOf: program, encoding: .utf8) == "Frozen executable bytes\n") + let mode = + try FileManager.default.attributesOfItem(atPath: program.resolvingSymlinksInPath().path)[ + .posixPermissions] as? NSNumber + #expect((mode?.intValue ?? 0) & 0o777 == 0o755) + if linked { + #expect( + try FileManager.default.destinationOfSymbolicLink(atPath: program.path) + == (rootBasename ? "shared/server" : "../shared/server")) + } + if gemini { + #expect(record.resources.count == 2) + let directory = try #require(resources[record.resources[1]]) + #expect( + try String(contentsOf: directory.appendingPathComponent("config.txt"), encoding: .utf8) + == "Working directory support") + } + } + let snapshot = try MCPConnectionOperations.snapshot( + selection: component.selection, scope: .project, environment: f.environment) + let description = MCPConnectionOperations.describe(snapshot) + #expect(description.executableIsCaptured) + #expect(description.executable == executable) + #expect(description.workingDirectoryIsCaptured == gemini) + if gemini { #expect(description.workingDirectory == "cwd") } + } + try verify() + let installed = try UpdateOperations.inspect(environment: f.environment) + try FileManager.default.removeItem(at: input) + for target in Set(installed.deployments.map(\.location)) { + try FileManager.default.removeItem(at: target) + } + try FileManager.default.removeItem(at: f.store.cacheDirectory) + _ = try UpdateOperations.restore(environment: f.environment) + try verify() + } + @Test func sourceQualifiedAmbientCommandCannotProduceSnapshot() throws { + let f = try UpdateFixture() + #expect(throws: MCPConnectionPreparationError.self) { + try MCPConnectionOperations.snapshot( + selectionID: "qualified", + transport: .stdio(.init(executable: "tool", executableSource: "producer")), + workingDirectory: .live(f.root)) + } + } + +} diff --git a/Tests/AgentsUpdatesTests/ImportNativeLifecycleTests.swift b/Tests/AgentsUpdatesTests/ImportNativeLifecycleTests.swift new file mode 100644 index 0000000..4a927e0 --- /dev/null +++ b/Tests/AgentsUpdatesTests/ImportNativeLifecycleTests.swift @@ -0,0 +1,125 @@ +import AgentsCore +import AgentsUpdates +import Foundation +import Testing + +struct ImportNativeLifecycleTests { + @Test(arguments: [AgentID.claudeCode, .cursor, .geminiCLI], [false, true]) + func standaloneNativeSkillRetainsContainerSupportThroughColdRestore( + _ agent: AgentID, _ atInputRoot: Bool + ) throws { + let f = try UpdateFixture() + let input = f.root.appendingPathComponent("producer") + let prefix = atInputRoot ? "" : "bundle/" + let container = atInputRoot ? input : input.appendingPathComponent("bundle") + let format: String + let suffix: String + switch agent { + case .claudeCode: + format = "claudePluginV1" + suffix = ".claude-plugin/plugin.json" + case .cursor: + format = "cursorPluginV1" + suffix = ".cursor-plugin/plugin.json" + default: + format = "geminiExtensionV1" + suffix = "gemini-extension.json" + } + try f.write( + #"{"name":"producer","version":"1.2.3"}"#, to: container.appendingPathComponent(suffix)) + let body = "---\nname: helper\ndescription: Helper\n---\nFrozen helper\n" + try f.write(body, to: container.appendingPathComponent("skills/helper/SKILL.md")) + try f.write("Frozen support\n", to: container.appendingPathComponent("shared/tool.txt")) + try FileManager.default.setAttributes( + [.posixPermissions: 0o755], + ofItemAtPath: container.appendingPathComponent("shared/tool.txt").path) + try FileManager.default.createSymbolicLink( + atPath: container.appendingPathComponent("skills/helper/reference.txt").path, + withDestinationPath: "../../shared/tool.txt") + try f.write( + "---\nname: helper\ndescription: Hidden\n---\nHidden support skill\n", + to: container.appendingPathComponent("shared/extras/SKILL.md")) + try FileManager.default.createSymbolicLink( + atPath: container.appendingPathComponent("skills/helper/data").path, + withDestinationPath: "../../shared/extras") + try f.write( + "---\nname: helper\ndescription: Sibling\n---\nUnselected sibling\n", + to: container.appendingPathComponent("other/SKILL.md")) + try f.write( + "---\nname: second\ndescription: Second\n---\nSelected second\n", + to: container.appendingPathComponent("skills/second/SKILL.md")) + let report = try SourceImportOperations.inspect( + format: format, root: input, document: prefix + suffix) + #expect(report.diagnostics.isEmpty) + #expect(report.components.count == 2) + #expect(report.sources.count == 1) + let skillSource = try #require(report.sources.first { $0.alias == "native-input" }) + #expect(skillSource.declaration?.location == (atInputRoot ? "." : "bundle")) + #expect(skillSource.declaration?.path == nil) + let helper = try #require( + report.components.first { + if case .skills(_, let selection) = $0.declaration { + return selection.path == "skills/helper" + } + return false + }) + guard case .skills(let alias, let selection) = helper.declaration else { + Issue.record("Expected selected native skill") + return + } + #expect(alias == "native-input" && selection.path == "skills/helper") + let scope = try UpdateOperations.inspect(environment: f.environment) + let originalRequest = try report.updateRequest(in: scope) + try f.write("Refreshed support\n", to: container.appendingPathComponent("shared/tool.txt")) + #expect(throws: (any Error).self) { + try UpdateOperations.withPreparedUpdate(originalRequest, environment: f.environment) { _ in + Issue.record("Changed linked support must reject the original request") + } + } + let refreshed = try SourceImportOperations.inspect( + format: format, root: input, document: prefix + suffix) + let request = try refreshed.updateRequest(in: scope) + let preview = try UpdateOperations.preview(request, environment: f.environment) + _ = try UpdateOperations.withPreparedUpdate(request, environment: f.environment) { + #expect($0.report.displayedFingerprint == preview.displayedFingerprint) + return try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + let installed = try UpdateOperations.inspect(environment: f.environment) + #expect(Set(installed.components.compactMap(\.name)) == ["helper", "second"]) + #expect(installed.deployments.allSatisfy { $0.status == .current }) + let tree = try #require( + installed.deployments.first { $0.location.lastPathComponent == "helper" }?.location) + func verify() throws { + #expect( + try String(contentsOf: tree.appendingPathComponent("SKILL.md"), encoding: .utf8) == body) + #expect( + try String(contentsOf: tree.appendingPathComponent("reference.txt"), encoding: .utf8) + == "Refreshed support\n") + #expect( + try FileManager.default.destinationOfSymbolicLink( + atPath: tree.appendingPathComponent("reference.txt").path) == "../../shared/tool.txt") + let support = tree.appendingPathComponent("reference.txt").resolvingSymlinksInPath() + let mode = + try FileManager.default.attributesOfItem(atPath: support.path)[.posixPermissions] + as? NSNumber + #expect((mode?.intValue ?? 0) & 0o777 == 0o755) + #expect( + try FileManager.default.destinationOfSymbolicLink( + atPath: tree.appendingPathComponent("data").path) == "../../shared/extras") + #expect( + try String(contentsOf: tree.appendingPathComponent("data/SKILL.md"), encoding: .utf8) + .contains("Hidden support skill")) + } + try verify() + try FileManager.default.removeItem(at: input) + for target in Set(installed.deployments.map(\.location)) { + try FileManager.default.removeItem(at: target) + } + try FileManager.default.removeItem(at: f.store.cacheDirectory) + _ = try UpdateOperations.restore(environment: f.environment) + try verify() + let restored = try UpdateOperations.inspect(environment: f.environment) + #expect(Set(restored.components.compactMap(\.name)) == ["helper", "second"]) + #expect(restored.deployments.allSatisfy { $0.status == .current }) + } +} diff --git a/Tests/AgentsUpdatesTests/InitializationIntegrationTests.swift b/Tests/AgentsUpdatesTests/InitializationIntegrationTests.swift new file mode 100644 index 0000000..9d521f8 --- /dev/null +++ b/Tests/AgentsUpdatesTests/InitializationIntegrationTests.swift @@ -0,0 +1,158 @@ +import AgentsInstructions +import AgentsSkills +import Foundation +import Testing + +@testable import AgentsCore +@testable import AgentsUpdates + +@Suite struct InitializationIntegrationTests { + @Test func descriptionsArePureAndCreationUsesExactTemplates() throws { + let f = try UpdateFixture() + let before = try FileSnapshot.read(at: f.root) + let instruction = try UpdateOperations.describeInstructionsInitialization( + named: "own", environment: f.environment) + let skill = try UpdateOperations.describeSkillInitialization( + named: "My Skill", directory: f.root, environment: f.environment) + #expect(try FileSnapshot.read(at: f.root) == before) + #expect(instruction.file == f.root.appendingPathComponent(".agent/instructions/own.md")) + #expect(skill.file == f.root.appendingPathComponent("my-skill/SKILL.md")) + for description in [instruction, skill] { + let completion = UpdateOperations.initialize(description) + #expect(completion.disposition == .committed && !completion.recovery.pending) + _ = try completion.result.get() + #expect(try String(contentsOf: description.file, encoding: .utf8) == description.template) + let duplicate = UpdateOperations.initialize(description) + #expect(duplicate.disposition == .unchanged && !duplicate.recovery.pending) + #expect(throws: (any Error).self) { try duplicate.result.get() } + } + } + + @Test func absentStandaloneDirectoryUsesItsExistingParent() throws { + let f = try UpdateFixture() + let directory = f.root.appendingPathComponent("My Selected Skill") + let description = try UpdateOperations.describeSkillInitialization( + directory: directory, environment: f.environment) + #expect(description.existingRoot.path == f.root.path) + #expect(description.file == directory.appendingPathComponent("SKILL.md")) + #expect(!FileManager.default.fileExists(atPath: directory.path)) + #expect(try UpdateOperations.initialize(description).result.get().path == directory.path) + } + + @Test func namedSkillUnderAbsentSelectedDirectoryCapturesBothLevels() throws { + let f = try UpdateFixture() + let directory = f.root.appendingPathComponent("Chosen Directory") + let before = try FileSnapshot.read(at: f.root) + let description = try UpdateOperations.describeSkillInitialization( + named: "My Skill", directory: directory, environment: f.environment) + #expect(description.existingRoot.path == f.root.path) + #expect(description.file == directory.appendingPathComponent("my-skill/SKILL.md")) + #expect(try FileSnapshot.read(at: f.root) == before) + let completion = UpdateOperations.initialize(description) + let result = try completion.result.get() + #expect(result.path == directory.appendingPathComponent("my-skill").path) + #expect(completion.disposition == .committed && !completion.recovery.pending) + #expect(try String(contentsOf: description.file, encoding: .utf8) == description.template) + } + + @Test(arguments: [false, true]) + func missingOrReplacedObservedProjectIsNeverRecreated(_ replace: Bool) throws { + let f = try UpdateFixture() + let selected = f.root.appendingPathComponent("selected") + let moved = f.root.appendingPathComponent("moved") + try FileManager.default.createDirectory(at: selected, withIntermediateDirectories: false) + var environment = f.environment + environment.projectDirectory = selected + let description = try UpdateOperations.describeInstructionsInitialization( + named: "own", environment: environment) + let skill = try UpdateOperations.describeProjectSkillInitialization( + named: "new", environment: environment) + try FileManager.default.moveItem(at: selected, to: moved) + if replace { + try FileManager.default.createDirectory(at: selected, withIntermediateDirectories: false) + } + let completion = UpdateOperations.initialize(description) + #expect(completion.disposition == .unchanged) + let skillCompletion = UpdateOperations.initialize(skill) + #expect(skillCompletion.disposition == .unchanged) + #expect(throws: (any Error).self) { try skillCompletion.result.get() } + if !replace { + #expect(throws: (any Error).self) { + try UpdateOperations.describeProjectSkillInitialization(environment: environment) + } + } + #expect(throws: (any Error).self) { try completion.result.get() } + #expect(FileManager.default.fileExists(atPath: selected.path) == replace) + #expect(!FileManager.default.fileExists(atPath: selected.appendingPathComponent(".agent").path)) + #expect(!FileManager.default.fileExists(atPath: moved.appendingPathComponent(".agent").path)) + } + + @Test(arguments: [false, true]) + func actualPublicationAndFailedRecoveryKeepDistinctOuterOutcomes(_ committed: Bool) throws { + let f = try UpdateFixture() + let description = try UpdateOperations.describeInstructionsInitialization( + named: "own", environment: f.environment) + let parent = description.file.deletingLastPathComponent() + let displaced = f.root.appendingPathComponent("displaced-instructions") + let stop = + committed + ? TransactionCheckpoint.phase(.committed).name + : TransactionCheckpoint.progress(0, .applied).name + let completion = UpdateOperations.initialize(description) { point in + if point == stop { + try FileManager.default.moveItem(at: parent, to: displaced) + throw CoreError.invalidState("fixture publication interruption") + } + } + #expect(completion.disposition == (committed ? .committed : .recoveryRequired)) + #expect(completion.recovery.pending) + #expect(throws: (any Error).self) { try completion.result.get() } + #expect( + try String(contentsOf: displaced.appendingPathComponent("own.md"), encoding: .utf8) + == description.template) + let blocked = UpdateOperations.initialize(description) + #expect(blocked.disposition == .unchanged && blocked.recovery.pending) + #expect(!blocked.recoveredBeforePreparation) + #expect(throws: (any Error).self) { try blocked.result.get() } + try FileManager.default.moveItem(at: displaced, to: parent) + let recovered = UpdateOperations.initialize(description) + #expect(recovered.disposition == .unchanged && recovered.recoveredBeforePreparation) + #expect(!recovered.recovery.pending) + #expect(FileManager.default.fileExists(atPath: description.file.path) == committed) + } + + @Test func rollbackTerminalSurvivesMovedScopeAndPendingDisposal() throws { + let f = try UpdateFixture() + let description = try UpdateOperations.describeInstructionsInitialization( + named: "own", environment: f.environment) + let moved = f.root.deletingLastPathComponent().appendingPathComponent( + f.root.lastPathComponent + "-moved") + let completion = UpdateOperations.initialize(description) { point in + if point == TransactionCheckpoint.publication(0, .created).name { + throw CoreError.invalidState("fixture rollback") + } + if point == "recovery." + TransactionCheckpoint.phase(.rolledBack).name { + try FileManager.default.moveItem(at: f.root, to: moved) + throw CoreError.invalidState("fixture cleanup unavailable") + } + } + #expect(completion.disposition == .rolledBack && completion.recovery.pending) + #expect(!FileManager.default.fileExists(atPath: description.file.path)) + try FileManager.default.moveItem(at: moved, to: f.root) + let recovered = UpdateOperations.initialize(description) + #expect(recovered.recoveredBeforePreparation && !recovered.recovery.pending) + } + + @Test func stagingFailureIsUnchangedWithoutACommittedFile() throws { + let f = try UpdateFixture() + let description = try UpdateOperations.describeSkillInitialization( + named: "new", directory: f.root, environment: f.environment) + let completion = UpdateOperations.initialize(description) { point in + if point == TransactionCheckpoint.stage(0, .constructed).name { + throw CoreError.invalidState("fixture staging failure") + } + } + #expect(completion.disposition == .unchanged && !completion.recovery.pending) + #expect(!FileManager.default.fileExists(atPath: description.file.path)) + } +} diff --git a/Tests/AgentsUpdatesTests/InstructionBuildTests.swift b/Tests/AgentsUpdatesTests/InstructionBuildTests.swift new file mode 100644 index 0000000..42a27e1 --- /dev/null +++ b/Tests/AgentsUpdatesTests/InstructionBuildTests.swift @@ -0,0 +1,534 @@ +import AgentsCore +import AgentsInstructions +import AgentsUpdates +import Foundation +import Testing + +struct InstructionBuildTests { + @Test func outputPreviewSkipsUnrelatedNativePluginMembers() throws { + let fixture = try UpdateFixture() + try fixture.write( + #"{"name":"review"}"#, + to: fixture.root.appendingPathComponent("plugin/.claude-plugin/plugin.json")) + try fixture.write( + "# Invalid sample\n", to: fixture.root.appendingPathComponent("plugin/skills/broken/SKILL.md") + ) + try fixture.write( + """ + version: 1 + sources: {fixture: {path: ./source}} + components: + - {kind: plugin, name: review, path: plugin, source: ".", mode: components} + - kind: instructions + sections: [{name: rules, source: fixture, recipients: [codex, chatgpt-app]}] + """, to: fixture.store.declarationURL) + let before = try fixture.snapshot() + let outputs = try InstructionOperations.previewOutputs(environment: fixture.environment) + .instructions.outputs + #expect(Set(outputs.map(\.recipient)) == [.local(.codex), .chatGPTApp]) + let copy = try #require(outputs.first { $0.recipient == .chatGPTApp }) + #expect(copy.content == Data("# Rules\n\nold\n".utf8)) + #expect { + try InstructionOperations.previewCompilation(environment: fixture.environment) + } throws: { error in + String(describing: error).contains("native plugin invalidInput") + } + #expect(try fixture.snapshot() == before) + } + + @Test func namedSkillsValidateOnlyTheirOwnRetainedRevision() throws { + let fixture = try UpdateFixture() + let a = fixture.repo.appendingPathComponent("skills/a/SKILL.md") + let b = fixture.repo.appendingPathComponent("skills/b/SKILL.md") + let oldA = "---\nname: a\ndescription: A\n---\nOld A\n" + let newB = "---\nname: b\ndescription: B\n---\nNew B\n" + try fixture.write(oldA, to: a) + try fixture.write("# Malformed old B\n", to: b) + try fixture.commit() + let old = try fixture.git(["rev-parse", "HEAD"]) + func declaration(_ names: [String]) -> Declaration { + Declaration( + sources: ["fixture": .init(kind: .local, location: fixture.repo.path)], + skills: ["fixture": .init(select: .names(names), agents: [.codex], mode: .copy)]) + } + func apply(_ names: [String]) throws { + let request = UpdateRequest(operation: .declaration(declaration(names))) + _ = try UpdateOperations.withPreparedUpdate(request, environment: fixture.environment) { + try $0.apply() + } + } + try apply(["a"]) + try fixture.write("# Malformed new A\n", to: a) + try fixture.write(newB, to: b) + try fixture.commit() + let latest = try fixture.git(["rev-parse", "HEAD"]) + try apply(["a", "b"]) + let skills = try fixture.store.loadResolved().skills + #expect(skills["a"]?.revision == old) + #expect(skills["b"]?.revision == latest) + let targets = fixture.target().deletingLastPathComponent() + #expect(try fixture.bytes(targets.appendingPathComponent("a/SKILL.md")) == Data(oldA.utf8)) + #expect(try fixture.bytes(targets.appendingPathComponent("b/SKILL.md")) == Data(newB.utf8)) + let before = try fixture.snapshot() + _ = try InstructionOperations.previewCompilation(environment: fixture.environment) + #expect(try fixture.snapshot() == before) + } + + @Test func compilationWithNamedSkillsIgnoresUnselectedMalformedSamples() throws { + let fixture = try UpdateFixture(scope: .user) + let sample = "scripts/skill-format-check/tests/missing-fields/SKILL.md" + try fixture.write("# Invalid sample\n", to: fixture.repo.appendingPathComponent(sample)) + try fixture.commit() + let yaml = """ + version: 1 + sources: {fixture: {path: ./source}} + components: + - kind: skills + source: fixture + path: skills + select: [demo] + agents: [codex] + - kind: instructions + sections: [{name: rules, source: fixture, recipients: [codex, chatgpt-app]}] + """ + try fixture.write(yaml, to: fixture.store.declarationURL) + let installed = try fixture.apply().report.instructions.outputs + try fixture.write( + yaml.replacingOccurrences(of: " path: skills\n", with: ""), + to: fixture.store.declarationURL) + let before = try fixture.snapshot() + + let compile = try InstructionOperations.previewCompilation( + scope: .user, environment: fixture.environment) + #expect(compile.report.instructions.outputs == installed) + #expect(compile.report.skills.isEmpty) + #expect(try fixture.snapshot() == before) + + try fixture.write( + yaml.replacingOccurrences(of: " path: skills\n", with: "") + .replacingOccurrences(of: "select: [demo]", with: "select: [missing-fields]"), + to: fixture.store.declarationURL) + let malformedSelection = try fixture.snapshot() + let outputs = try InstructionOperations.previewOutputs( + scope: .user, environment: fixture.environment) + #expect(outputs.instructions.outputs == installed) + #expect(outputs.skills.isEmpty && outputs.components.isEmpty) + #expect(try fixture.snapshot() == malformedSelection) + #expect { + try InstructionOperations.previewCompilation(scope: .user, environment: fixture.environment) + } throws: { error in + String(describing: error).contains(sample) + } + #expect(try fixture.snapshot() == malformedSelection) + } + + @Test(arguments: ["missing-fields", "broken-by-name", "all"]) + func selectedMalformedSkillsReportTheirSourceRelativePaths(_ selection: String) throws { + let fixture = try UpdateFixture() + let leaf = selection == "broken-by-name" ? "different-directory" : "missing-fields" + let sample = "scripts/skill-format-check/tests/\(leaf)/SKILL.md" + try fixture.write( + selection == "broken-by-name" ? "---\nname: broken-by-name\n---\n# Invalid\n" : "# Invalid\n", + to: fixture.repo.appendingPathComponent(sample)) + try fixture.commit() + try fixture.write( + """ + version: 1 + sources: {fixture: {path: ./source}} + components: + - kind: skills + source: fixture + select: \(selection == "all" ? "all" : "[\(selection)]") + agents: [codex] + """, to: fixture.store.declarationURL) + let before = try fixture.snapshot() + #expect { + try fixture.preview() + } throws: { error in + String(describing: error).contains(sample) + && String(describing: error).contains("requires name and description") + } + #expect(try fixture.snapshot() == before) + } + + @Test func previewsAndAppliesTheSameCandidateBytes() throws { + let fixture = try UpdateFixture() + let shared = fixture.instruction() + let forwarding = fixture.root.appendingPathComponent("CLAUDE.md") + let original = "Custom Claude content.\n" + try fixture.write(original, to: forwarding) + try fixture.write( + "---\ndescription: Own section\n---\n# Own section\n\nProject content.\n", + to: fixture.root.appendingPathComponent(".agent/instructions/rules.md")) + let yaml = """ + version: 1 + defaultAgents: [codex, claude-code] + sources: + team/rules: {path: ./source} + components: + - {kind: skills, source: team/rules, select: [demo], agents: [codex], mode: copy} + - kind: instructions + sections: + - {name: rules, source: team/rules, recipients: [chatgpt-app, gemini-app]} + - {name: rules, recipients: [codex, claude-code, chatgpt-app]} + - {name: rules, source: team/rules, recipients: [gemini-app], condition: {scopes: [user]}} + chatgpt: + weekly: + sections: [{name: rules, source: team/rules}] + """ + let request = UpdateRequest( + declarationYAML: Data(yaml.utf8), expectedDeclarationDigest: "absent") + let preview = try UpdateOperations.preview(request, environment: fixture.environment) + let outputs = preview.instructions.outputs + #expect(outputs.count == 5) + #expect(Set(outputs.map(\.id)).count == 5) + let chatGPT = try #require(outputs.first { $0.recipient == .chatGPTApp }) + let gemini = try #require(outputs.first { $0.recipient == .geminiApp }) + #expect(chatGPT.fileURL == nil && gemini.fileURL == nil) + #expect( + String(decoding: chatGPT.content, as: UTF8.self) + == "# Rules\n\nold\n\n# Own section\n\nProject content.\n") + #expect(String(decoding: gemini.content, as: UTF8.self) == "# Rules\n\nold\n") + let local = outputs.filter { $0.fileURL?.path == shared.path } + #expect(Set(local.map(\.recipient)) == [.local(.codex), .local(.claudeCode)]) + #expect(Set(local.map(\.content)).count == 1) + #expect(local.allSatisfy { !String(decoding: $0.content, as: UTF8.self).contains("old") }) + let claude = try #require(outputs.first { $0.fileURL?.path == forwarding.path }) + #expect(String(decoding: claude.content, as: UTF8.self).hasSuffix(original)) + #expect(String(decoding: claude.content, as: UTF8.self).contains("@AGENTS.md")) + #expect(!FileManager.default.fileExists(atPath: shared.path)) + #expect(!FileManager.default.fileExists(atPath: fixture.store.declarationURL.path)) + #expect(!FileManager.default.fileExists(atPath: fixture.store.resolvedURL.path)) + #expect(try fixture.bytes(forwarding) == Data(original.utf8)) + + let applied = try UpdateOperations.withPreparedUpdate(request, environment: fixture.environment) + { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + #expect(applied.report.instructions.outputs == outputs) + for output in outputs { + if let file = output.fileURL { #expect(try fixture.bytes(file) == output.content) } + } + let unchanged = try fixture.preview().instructions + #expect(!unchanged.hasChanges) + #expect(unchanged.outputs == outputs) + let prompt = try InstructionOperations.renderChatGPT( + prompt: "weekly", environment: fixture.environment) + #expect(prompt == gemini.content) + + func inspectedUnits() throws -> [ComponentInspection] { + try UpdateOperations.inspect(environment: fixture.environment).components.filter { + $0.kind == .instructions + } + } + let units = try inspectedUnits() + #expect(units.count == 4) + let mixed = try #require(units.first { !$0.recipients.isEmpty }) + #expect(mixed.copyRecipients == [.chatGPTApp]) + let copyOnly = try #require(units.first { $0.copyRecipients.count == 2 }) + #expect(copyOnly.recipients.isEmpty && copyOnly.copyRecipients == [.chatGPTApp, .geminiApp]) + #expect( + units.filter { $0.chatGPT || $0.conditions.contains { $0.scopes == [.user] } } + .allSatisfy { $0.copyRecipients.isEmpty }) + + try FileManager.default.removeItem(at: fixture.target()) + let partial = UpdateRequest(kinds: [.skills]) + let repaired = try UpdateOperations.withPreparedUpdate( + partial, environment: fixture.environment + ) { + try $0.apply() + } + #expect(repaired.report.instructions.outputs.isEmpty) + #expect(FileManager.default.fileExists(atPath: fixture.target().path)) + #expect(try inspectedUnits().map(\.copyRecipients) == units.map(\.copyRecipients)) + } + + @Test func addingLocalsPreservesExplicitRecipientsAndDistinctOccurrences() throws { + let fixture = try UpdateFixture(scope: .user) + try fixture.write( + "---\ndescription: Other.\n---\n# Other rules\n\nOther source content.\n", + to: fixture.repo.appendingPathComponent("other/instructions/rules.md")) + try fixture.commit() + try fixture.write( + """ + version: 1 + defaultAgents: [codex] + sources: + team/rules: {path: ./source} + team/other: {path: ./source, subpath: other} + components: + - kind: instructions + sections: + - {name: rules, source: team/rules, recipients: [gemini-cli, gemini-app], condition: {scopes: [project]}} + - {name: rules, source: team/rules, recipients: [codex, chatgpt-app], condition: {scopes: [user]}} + - {name: rules, source: team/other, recipients: [gemini-app]} + """, to: fixture.store.declarationURL) + let baseline = try fixture.apply().report.instructions.outputs + let original = try fixture.store.loadDeclaration() + let snapshot = try fixture.snapshot() + #expect(throws: CoreError.self) { + try InstructionOperations.add( + .init( + source: fixture.repo.path, alias: "team/other", scope: .user, + environment: fixture.environment)) + } + + func add(_ agents: [AgentID]? = nil) throws -> InstructionUpdateReport { + let result = try InstructionOperations.add( + .init( + source: fixture.repo.path, names: ["rules"], agents: agents, scope: .user, + environment: fixture.environment)) + return try #require(result.result) + } + #expect(try !add().hasChanges) + #expect(try fixture.snapshot() == snapshot) + + let added = try add([.geminiCLI, .codex]) + let before = try #require(try original.instructions) + let after = try #require(try fixture.store.loadDeclaration().instructions) + #expect(after.sectionReferences.map(\.reference) == before.sectionReferences.map(\.reference)) + #expect(after.sectionReferences[0] == before.sectionReferences[0]) + #expect(after.sectionReferences[2] == before.sectionReferences[2]) + #expect(after.sectionReferences[1].condition == before.sectionReferences[1].condition) + #expect( + after.sectionReferences[1].recipients == [.local(.codex), .chatGPTApp, .local(.geminiCLI)]) + #expect(added.outputs.filter { $0.recipient != .local(.geminiCLI) } == baseline) + let gemini = try #require(added.outputs.first { $0.recipient == .local(.geminiCLI) }) + #expect(try fixture.bytes(fixture.instruction(.geminiCLI)) == gemini.content) + + let updated = try fixture.snapshot() + #expect(try !add([.geminiCLI, .codex]).hasChanges) + #expect(try fixture.snapshot() == updated) + } + + @Test func copyOnlyBuildUsesItsScopeAndReplaysWithoutDeployments() throws { + let fixture = try UpdateFixture(scope: .user) + try fixture.write( + "---\ndescription: Project section\n---\n# Project section\n", + to: fixture.root.appendingPathComponent(".agent/instructions/separate.md")) + let project = StateStore(scope: .project, environment: fixture.environment) + try fixture.write( + """ + version: 1 + components: + - kind: instructions + sections: [{name: separate, recipients: [chatgpt-app]}] + """, to: project.declarationURL) + let user = """ + version: 1 + defaultAgents: [codex, claude-code] + sources: + team/rules: {path: ./source} + components: + - kind: instructions + sections: + - {name: rules, source: team/rules, recipients: [chatgpt-app]} + """ + try fixture.write(user, to: fixture.store.declarationURL) + let preview = try fixture.preview().instructions + let output = try #require(preview.outputs.first) + #expect(preview.outputs.count == 1) + #expect(preview.hasChanges && preview.targets.isEmpty) + #expect(output.recipient == .chatGPTApp && output.fileURL == nil) + #expect(String(decoding: output.content, as: UTF8.self) == "# Rules\n\nold\n") + + let lock = fixture.store.resolvedURL + #expect(!FileManager.default.fileExists(atPath: lock.path)) + #expect(try fixture.apply().report.instructions.outputs == preview.outputs) + #expect(try fixture.store.loadResolved().instructions.targets.isEmpty) + let before = try fixture.bytes(lock) + try fixture.advance() + let restored = try InstructionOperations.installResolvedReport( + scope: .user, environment: fixture.environment) + #expect(restored.outputs == preview.outputs) + #expect(restored.targets.isEmpty && !restored.hasChanges) + #expect(try fixture.bytes(lock) == before) + #expect(!FileManager.default.fileExists(atPath: fixture.instruction().path)) + } + + @Test func addingLocalsKeepsPlatformSpecificRoutesDisjoint() throws { + let fixture = try UpdateFixture(scope: .user) + #if os(macOS) + let current = DeclarationPlatform.macOS + let other = DeclarationPlatform.linux + #else + let current = DeclarationPlatform.linux + let other = DeclarationPlatform.macOS + #endif + try fixture.write( + """ + version: 1 + sources: {fixture: {path: ./source}} + components: + - kind: instructions + sections: + - {name: rules, source: fixture, recipients: [codex, chatgpt-app]} + - {name: rules, source: fixture, recipients: [gemini-cli], condition: {platforms: [\(other.rawValue)]}} + """, to: fixture.store.declarationURL) + _ = try fixture.apply() + let original = try #require(try fixture.store.loadDeclaration().instructions) + let options = InstructionAddOptions( + source: "fixture", agents: [.geminiCLI], scope: .user, environment: fixture.environment) + let added = try InstructionOperations.add(options) + #expect(added.result?.outputs.contains { $0.recipient == .local(.geminiCLI) } == true) + let selections = try fixture.store.loadDeclaration().components.compactMap { + component -> InstructionsDeclaration? in + if case .instructions(let selection) = component { return selection } + return nil + } + #expect(selections.first == original) + let fallback = try #require(selections.last?.sectionReferences.last) + #expect(fallback.condition == DeclarationCondition(scopes: [.user], platforms: [current])) + #expect(try InstructionOperations.add(options).result?.hasChanges == false) + } + + @Test func addingLocalsUsesOnlyEffectiveRecipientsOfActiveNestedGroups() throws { + let fixture = try UpdateFixture(scope: .user) + try fixture.write( + "---\ndescription: Extra rules\n---\n# Extra rules\n", + to: fixture.repo.appendingPathComponent("instructions/extra.md")) + try fixture.commit() + try fixture.write( + """ + version: 1 + defaultAgents: [codex] + sources: {team/rules: {path: ./source}} + groups: + leaf: + components: + - kind: instructions + sections: [{name: rules, source: team/rules, recipients: [codex, gemini-cli, chatgpt-app]}] + nested: + uses: [{group: leaf, condition: {agents: [codex]}}] + inactive: + components: + - kind: instructions + sections: [{name: rules, source: team/rules, recipients: [gemini-cli]}] + unused: + components: + - kind: instructions + sections: [{name: rules, source: team/rules, recipients: [gemini-cli]}] + unrelated: + components: + - kind: instructions + sections: [{name: extra, source: team/rules, recipients: [opencode]}] + uses: [{group: nested}, {group: inactive, condition: {scopes: [project]}}, {group: unrelated}] + """, to: fixture.store.declarationURL) + let outputs = try fixture.apply().report.instructions.outputs + let copy = try #require(outputs.first { $0.recipient == .chatGPTApp }) + let codex = try fixture.bytes(fixture.instruction()) + let original = try fixture.store.loadDeclaration() + let unrelated = fixture.instruction(.opencode) + try FileManager.default.removeItem(at: unrelated) + let before = try fixture.snapshot() + + func add(_ agents: [AgentID]) throws -> InstructionUpdateReport { + let outcome = try InstructionOperations.add( + .init( + source: "team/rules", names: ["rules"], agents: agents, scope: .user, + environment: fixture.environment)) + return try #require(outcome.result) + } + #expect(try !add([.codex]).hasChanges) + #expect(try fixture.snapshot() == before) + + let added = try add([.codex, .geminiCLI]) + let declaration = try fixture.store.loadDeclaration() + #expect(declaration.groups == original.groups && declaration.uses == original.uses) + let instructions = try #require(try declaration.instructions) + #expect(instructions.agents == [.geminiCLI]) + #expect(instructions.sectionReferences.map(\.reference) == ["team/rules:rules"]) + #expect(added.outputs.first { $0.recipient == .chatGPTApp } == copy) + #expect(try fixture.bytes(fixture.instruction(.geminiCLI)) == codex) + #expect(try fixture.bytes(fixture.instruction()) == codex) + #expect(!FileManager.default.fileExists(atPath: unrelated.path)) + let updated = try fixture.snapshot() + #expect(try !add([.codex, .geminiCLI]).hasChanges) + #expect(try fixture.snapshot() == updated) + } + + @Test func olderReportsDecodeWithoutBuildOutputs() throws { + let json = """ + {"sections":[],"targets":[],"changedPrompts":[],"lockMissing":false,"hasChanges":false} + """ + let decoded = try JSONDecoder().decode(InstructionUpdateReport.self, from: Data(json.utf8)) + #expect(decoded.outputs.isEmpty) + } + + @Test func addingLocalCanReuseTheGroupsExactSharedTarget() throws { + let fixture = try UpdateFixture() + try fixture.write( + """ + version: 1 + sources: {fixture: {path: ./source}} + groups: + shared: + components: + - kind: instructions + sections: [{name: rules, source: fixture, recipients: [codex, chatgpt-app]}] + uses: [{group: shared}] + """, to: fixture.store.declarationURL) + let file = fixture.instruction() + let declaration = try fixture.bytes(fixture.store.declarationURL) + #expect(!FileManager.default.fileExists(atPath: fixture.store.resolvedURL.path)) + #expect(!FileManager.default.fileExists(atPath: file.path)) + let codex = InstructionAddOptions( + source: "fixture", names: ["rules"], agents: [.codex], environment: fixture.environment) + let initial = try #require(try InstructionOperations.add(codex).result) + #expect(initial.hasChanges) + #expect(FileManager.default.fileExists(atPath: fixture.store.resolvedURL.path)) + #expect(initial.targets.map(\.afterAgents) == [[.codex]]) + #expect(Set(initial.outputs.map(\.recipient)) == [.local(.codex), .chatGPTApp]) + #expect(try fixture.bytes(fixture.store.declarationURL) == declaration) + let before = try fixture.bytes(file) + #expect(initial.outputs.first { $0.recipient == .local(.codex) }?.content == before) + let applied = try fixture.snapshot() + #expect(try InstructionOperations.add(codex).result?.hasChanges == false) + #expect(try fixture.snapshot() == applied) + + let options = InstructionAddOptions( + source: "fixture", agents: [.codex, .claudeCode], environment: fixture.environment) + let added = try InstructionOperations.add(options) + #expect(added.result?.targets.first { $0.url == file }?.afterAgents == [.claudeCode, .codex]) + #expect(try fixture.bytes(file) == before) + let mapping = InstructionOperations.export( + projectRoots: [fixture.root], environment: fixture.environment) + #expect( + mapping.first { $0.scope == .project }?.targets.first?.sections.map(\.name) == ["rules"]) + #expect(try InstructionOperations.add(options).result?.hasChanges == false) + } + + @Test func readdingAnExportedGroupsSourceLeavesBothDeclarationsIntact() throws { + let fixture = try UpdateFixture(scope: .user) + let producer = try UpdateFixture() + let producerManifest = producer.repo.appendingPathComponent(".agent/agents.yaml") + try producer.write( + """ + version: 1 + sources: {payload: {path: "\(fixture.repo.path)"}} + exports: [rules] + groups: + rules: + components: + - kind: instructions + sections: [{name: rules, source: payload, recipients: [codex, chatgpt-app]}] + """, to: producerManifest) + try producer.commit() + try fixture.write( + """ + version: 1 + sources: {producer: {path: "\(producer.repo.path)"}} + uses: [{group: rules, source: producer}] + """, to: fixture.store.declarationURL) + _ = try fixture.apply() + let before = try fixture.snapshot() + let upstream = try producer.bytes(producerManifest) + let result = try InstructionOperations.add( + .init( + source: fixture.repo.path, agents: [.codex], scope: .user, + environment: fixture.environment)) + #expect(result.result?.hasChanges == false) + #expect(try fixture.snapshot() == before) + #expect(try producer.bytes(producerManifest) == upstream) + } +} diff --git a/Tests/AgentsUpdatesTests/IntegratedConsumerRegressionTests.swift b/Tests/AgentsUpdatesTests/IntegratedConsumerRegressionTests.swift new file mode 100644 index 0000000..e153bcf --- /dev/null +++ b/Tests/AgentsUpdatesTests/IntegratedConsumerRegressionTests.swift @@ -0,0 +1,114 @@ +import AgentsCore +import AgentsInstructions +import AgentsManifest +import AgentsUpdates +import Foundation +import StateTestSupport +import Testing + +struct IntegratedConsumerRegressionTests { + @Test func preciseRootMCPRemovalPreservesUnrelatedYAML() throws { + let f = try UpdateFixture() + try f.write( + """ + # Keep this declaration comment. + version: 1 + components: + - kind: mcpServer + name: first + transport: {kind: stdio, executable: never-run} + agents: [claude-code] + # Keep the remaining component comment. + - kind: mcpServer + name: second + transport: {kind: stdio, executable: never-run} + agents: [claude-code] + """, to: f.store.declarationURL) + _ = try f.apply() + let inspected = try UpdateOperations.inspect(environment: f.environment) + let selected = try #require(inspected.components.first { $0.name == "first" }) + let request = UpdateRequest(operation: .remove, selections: [selected.selection]) + let preview = try UpdateOperations.preview(request, environment: f.environment) + _ = try UpdateOperations.withPreparedUpdate(request, environment: f.environment) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + let after = try UpdateOperations.inspect(environment: f.environment) + #expect(after.components.map(\.name) == ["second"]) + let text = try String(contentsOf: f.store.declarationURL, encoding: .utf8) + #expect(text.contains("# Keep this declaration comment.")) + #expect(text.contains("# Keep the remaining component comment.")) + } + + @Test func publicPromptUsesCurrentConsumerAppendAndLockedSectionOrder() throws { + let f = try UpdateFixture() + try f.declare(agents: [.claudeCode]) + var declaration = try f.store.loadDeclaration() + for index in declaration.components.indices { + if case .instructions(var selection) = declaration.components[index] { + selection.prompts[0].prompt.append = "append.md" + declaration.components[index] = .instructions(selection) + } + } + try f.store.save(declaration: declaration, ledger: ResolvedLedger()) + _ = try f.apply() // An absent consumer file must not prevent publication. + try f.write("First appendix", to: f.root.appendingPathComponent("append.md")) + let first = try InstructionOperations.renderChatGPT( + prompt: "weekly", environment: f.environment) + try f.write("Current appendix", to: f.root.appendingPathComponent("append.md")) + let before = try FileHash.folderHash(f.root) + let current = try InstructionOperations.renderChatGPT( + prompt: "weekly", environment: f.environment) + #expect(String(decoding: first, as: UTF8.self).contains("First appendix")) + #expect(String(decoding: current, as: UTF8.self).contains("Current appendix")) + #expect(!String(decoding: current, as: UTF8.self).contains("First appendix")) + #expect(try FileHash.folderHash(f.root) == before) + } +} + +extension IntegratedConsumerRegressionTests { + @Test func documentedNativeImportKeepsUnavailableUpstreamRevisionNil() throws { + let f = try UpdateFixture() + let input = f.root.appendingPathComponent("native-input") + try f.write("{}", to: input.appendingPathComponent("settings.json")) + let before = try FileHash.folderHash(f.root) + let report = try SourceImportOperations.inspect( + format: "claudeSettingsV1", root: input, document: "settings.json") + #expect(report.producerRevision == nil) + #expect(report.specificationStatus.contains("Documented Claude Code format")) + #expect(try FileHash.folderHash(f.root) == before) + } +} + +extension IntegratedConsumerRegressionTests { + @Test func authoredNodeRemovalSelectsOneDirectOccurrenceAndRejectsReuse() throws { + let f = try UpdateFixture() + try f.write( + """ + # Keep authored occurrence order. + version: 1 + components: + - {kind: mcpServer, name: repeated, transport: {kind: stdio, executable: first}, agents: [claude-code]} + - {kind: mcpServer, name: repeated, transport: {kind: stdio, executable: second}, agents: [gemini-cli]} + """, to: f.store.declarationURL) + _ = try f.apply() + let snapshot = try UpdateOperations.inspect(environment: f.environment) + let document = try #require(snapshot.document) + let node = try #require(document.node(at: "/components/1")) + #expect(document.editability(of: node) == .direct) + let request = UpdateRequest( + operation: .edit([.removeComponent(node)]), expectedDeclarationDigest: document.digest) + let preview = try UpdateOperations.preview(request, environment: f.environment) + _ = try UpdateOperations.withPreparedUpdate(request, environment: f.environment) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + let remaining = try UpdateOperations.inspect(environment: f.environment) + #expect(remaining.components.count == 1) + #expect(remaining.components[0].recipients == [.claudeCode]) + #expect( + try String(contentsOf: f.store.declarationURL, encoding: .utf8).contains( + "# Keep authored occurrence order.")) + #expect(throws: (any Error).self) { + try UpdateOperations.preview(request, environment: f.environment) + } + } +} diff --git a/Tests/AgentsUpdatesTests/LifecycleCompositionTests.swift b/Tests/AgentsUpdatesTests/LifecycleCompositionTests.swift new file mode 100644 index 0000000..495c4b7 --- /dev/null +++ b/Tests/AgentsUpdatesTests/LifecycleCompositionTests.swift @@ -0,0 +1,448 @@ +import AgentsCore +import AgentsInstructions +import AgentsManifest +import AgentsSkills +import Foundation +import StateTestSupport +import Synchronization +import Testing + +@testable import AgentsUpdates + +@Suite("Ledger lifecycle composition") +struct LifecycleCompositionTests { + @Test(arguments: [InstallMode.copy, .link]) + func exactColdRestoreKeepsFrozenOwnInstructionsAndSkillResources(_ mode: InstallMode) throws { + let fixture = try UpdateFixture() + let source = fixture.root.appendingPathComponent("local-skills") + try fixture.write( + "---\nname: frozen\ndescription: Frozen\n---\nOriginal skill\n", + to: source.appendingPathComponent("frozen/SKILL.md")) + let script = source.appendingPathComponent("frozen/run") + try fixture.write("#!/bin/sh\nexit 0\n", to: script) + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: script.path) + try fixture.write( + "---\ndescription: Frozen\n---\n# Frozen\n\nOriginal instructions\n", + to: fixture.root.appendingPathComponent(".agent/instructions/frozen.md")) + try fixture.store.save( + declaration: Declaration( + sources: ["local": .init(kind: .local, location: source.path)], + skills: ["local": .init(select: .all, agents: [.claudeCode], mode: mode)], + instructions: .init(agents: [.codex], sections: ["frozen"])), ledger: ResolvedLedger()) + _ = try fixture.apply() + let instruction = try fixture.bytes(fixture.instruction()) + let skill = try fixture.bytes( + fixture.target(.claudeCode).deletingLastPathComponent().appendingPathComponent( + "frozen/SKILL.md")) + let cold = fixture.root.appendingPathComponent("cold") + var environment = fixture.environment + environment.projectDirectory = cold + let store = StateStore(scope: .project, environment: environment) + try FileManager.default.createDirectory(at: store.directory, withIntermediateDirectories: true) + try fixture.bytes(fixture.store.declarationURL).write(to: store.declarationURL) + let locked = try fixture.bytes(fixture.store.resolvedURL) + try locked.write(to: store.resolvedURL) + try FileManager.default.removeItem(at: source) + try FileManager.default.removeItem( + at: fixture.root.appendingPathComponent(".agent/instructions")) + _ = try UpdateOperations.restore(environment: environment) + #expect(try Data(contentsOf: cold.appendingPathComponent("AGENTS.md")) == instruction) + let restored = cold.appendingPathComponent(".claude/skills/frozen") + #expect(try Data(contentsOf: restored.appendingPathComponent("SKILL.md")) == skill) + let flags = + try FileManager.default.attributesOfItem(atPath: restored.appendingPathComponent("run").path)[ + .posixPermissions] as? NSNumber + #expect((flags?.intValue ?? 0) & 0o111 != 0) + #expect(try Data(contentsOf: store.resolvedURL) == locked) + #expect( + try store.loadResolved().skills["frozen"]?.installs == [AgentID.claudeCode.rawValue: mode]) + } + + @Test func purePreviewAndStableFingerprintUseNoPersistentSourceWrites() throws { + let fixture = try UpdateFixture() + try fixture.declare(agents: [.claudeCode]) + let before = try FileHash.folderHash(fixture.root) + let first = try fixture.preview() + let second = try fixture.preview() + #expect(first.displayedFingerprint == second.displayedFingerprint) + #expect(try FileHash.folderHash(fixture.root) == before) + #expect(!FileManager.default.fileExists(atPath: fixture.store.cacheDirectory.path)) + _ = try fixture.apply() + let installed = try FileHash.folderHash(fixture.root) + let request = UpdateRequest(operation: .restore) + let a = try UpdateOperations.preview(request, environment: fixture.environment) + let b = try UpdateOperations.preview(request, environment: fixture.environment) + #expect(a.displayedFingerprint == b.displayedFingerprint) + #expect(try FileHash.folderHash(fixture.root) == installed) + #expect(try JSONSerialization.jsonObject(with: JSONEncoder().encode(a)) is [String: Any]) + } + + @Test func directSkillPinUpdatePreservesRecordedInstructionPinAndLastRemovalRetention() throws { + let fixture = try UpdateFixture() + try fixture.install(agents: [.claudeCode]) + let old = try fixture.store.loadResolved() + let bytes = try fixture.bytes(fixture.instruction(.claudeCode)) + try fixture.advance() + _ = try SkillOperations.updateInstalled(environment: fixture.environment, apply: true) + let updated = try fixture.store.loadResolved() + #expect(updated.skills["demo"]?.revision != old.skills["demo"]?.revision) + #expect(updated.instructions == old.instructions) + #expect(try fixture.bytes(fixture.instruction(.claudeCode)) == bytes) + _ = try SkillOperations.watchOperations().add("fixture", environment: fixture.environment) + _ = try SkillOperations.remove(skillNames: ["demo"], environment: fixture.environment) + #expect(try SkillOperations.listManaged(environment: fixture.environment).isEmpty) + #expect(try fixture.store.loadResolved().instructions == old.instructions) + #expect(try fixture.bytes(fixture.instruction(.claudeCode)) == bytes) + _ = try SkillOperations.watchOperations().status(environment: fixture.environment) + _ = try SkillOperations.doctor(environment: fixture.environment) + _ = try InstructionOperations.doctor(environment: fixture.environment) + _ = try InstructionOperations.renderChatGPT(prompt: "weekly", environment: fixture.environment) + _ = try InstructionOperations.installResolvedReport(environment: fixture.environment) + } + + @Test func nativeSiblingsStayPrivateAndEqualUnmanagedValuesAreNotAdopted() throws { + let fixture = try UpdateFixture() + let declaration = Declaration(components: [ + .mcpServer( + name: "server", transport: .stdio(.init(executable: "fixture-server")), + agents: [.claudeCode]) + ]) + try fixture.store.save(declaration: declaration, ledger: ResolvedLedger()) + let native = fixture.root.appendingPathComponent(".mcp.json") + try fixture.write("{\"unmanaged\":{\"secret\":\"private sibling sentinel\"}}\n", to: native) + let report = try fixture.preview() + #expect( + !String(decoding: try JSONEncoder().encode(report), as: UTF8.self).contains( + "private sibling sentinel")) + _ = try fixture.apply() + let owned = try fixture.bytes(native) + #expect(String(decoding: owned, as: UTF8.self).contains("private sibling sentinel")) + let original = try fixture.preview().displayedFingerprint + try fixture.write( + String(decoding: owned, as: UTF8.self).replacingOccurrences( + of: "private sibling sentinel", with: "rotated private sibling"), to: native) + #expect(try fixture.preview().displayedFingerprint == original) + try UpdateOperations.withPreparedUpdate(environment: fixture.environment) { prepared in + try fixture.write(String(decoding: owned, as: UTF8.self), to: native) + #expect(throws: UpdateApplyError.self) { try prepared.apply() } + } + try FileManager.default.removeItem(at: fixture.store.resolvedURL) + let before = try FileHash.folderHash(fixture.root) + #expect(throws: (any Error).self) { try fixture.preview() } + #expect(try FileHash.folderHash(fixture.root) == before) + } + + @Test func combinedFaultRollsBackSkillInstructionAndNativeOwnedKey() throws { + let fixture = try UpdateFixture() + try fixture.declare(agents: [.claudeCode]) + var declaration = try fixture.store.loadDeclaration() + declaration.components.append( + .mcpServer( + name: "server", transport: .stdio(.init(executable: "before")), agents: [.claudeCode])) + try fixture.store.save(declaration: declaration, ledger: ResolvedLedger()) + _ = try fixture.apply() + let native = fixture.root.appendingPathComponent(".mcp.json") + let oldNative = try fixture.bytes(native) + let before = try fixture.snapshot() + try fixture.advance() + declaration.components[declaration.components.count - 1] = .mcpServer( + name: "server", transport: .stdio(.init(executable: "after")), agents: [.claudeCode]) + try fixture.store.save(declaration: declaration, ledger: fixture.store.loadLedger()) + let state = try fixture.snapshot() + struct Interrupted: Error {} + var interrupted = false + #expect(throws: UpdateApplyError.self) { + try UpdateOperations.withPreparedUpdate( + environment: fixture.environment, + checkpoint: { _ in + if !interrupted, (try? fixture.bytes(native)) != oldNative { + interrupted = true + throw Interrupted() + } + }, { try $0.apply() }) + } + #expect(interrupted) + #expect(try fixture.snapshot() == state) + #expect(try fixture.bytes(native) == oldNative) + #expect( + before[fixture.instruction(.claudeCode).path] == state[fixture.instruction(.claudeCode).path]) + _ = try fixture.apply() + #expect(try fixture.bytes(native) != oldNative) + } +} + +private final class FixtureBindings: RuntimeBindingProvider { + private let state = Mutex((calls: 0, value: "private literal sentinel")) + var calls: Int { state.withLock { $0.calls } } + var value: String { + get { state.withLock { $0.value } } + set { state.withLock { $0.value = newValue } } + } + func value(for binding: String, environment: RuntimeEnvironment) throws -> Data { + state.withLock { + $0.calls += 1 + return Data($0.value.utf8) + } + } +} + +extension LifecycleCompositionTests { + @Test func literalBindingsStayInsidePrivateStagingAndDoNotChangeDisplayIdentity() throws { + let fixture = try UpdateFixture() + try fixture.store.save( + declaration: Declaration(components: [ + .mcpServer( + name: "bound", + transport: .stdio( + .init(executable: "fixture-server", environment: ["TOKEN": .secret("fixture-token")])), + agents: [.claudeCode]) + ]), ledger: ResolvedLedger()) + var environment = fixture.environment + environment.environment["CLAUDE_CONFIG_DIR"] = nil + let provider = FixtureBindings() + let request = UpdateRequest() + try UpdateOperations.prepare( + request, scope: .project, environment: environment, checkpoint: { _ in }, + provider: provider, + { prepared in + #expect(provider.calls == 0) + let json = String(decoding: try JSONEncoder().encode(prepared.report), as: UTF8.self) + #expect(!json.contains(provider.value)) + _ = try prepared.apply() + }) + #expect(provider.calls == 1) + let native = environment.homeDirectory.appendingPathComponent(".claude.json") + #expect(String(decoding: try fixture.bytes(native), as: UTF8.self).contains(provider.value)) + #expect( + !String(decoding: try fixture.bytes(fixture.store.resolvedURL), as: UTF8.self).contains( + provider.value)) + let a = try UpdateOperations.preview(environment: environment).displayedFingerprint + provider.value = "rotated private literal" + try UpdateOperations.prepare( + request, scope: .project, environment: environment, checkpoint: { _ in }, + provider: provider, + { prepared in + #expect(prepared.report.displayedFingerprint == a) + #expect(provider.calls == 1) + _ = try prepared.apply() + }) + #expect(provider.calls == 2) + #expect(try UpdateOperations.preview(environment: environment).displayedFingerprint == a) + let mode = + try FileManager.default.attributesOfItem(atPath: native.path)[.posixPermissions] as? NSNumber + #expect(mode?.intValue == 0o600) + } + + @Test(arguments: [false, true]) + func producerOwnedSkillCannotBeRemovedAndChangedProtectedGroupRequiresCombinedUpdate( + nonCanonical: Bool + ) throws { + let fixture = try UpdateFixture() + if nonCanonical { + try fixture.write( + "---\nname: Demo Skill\ndescription: Producer skill\n---\nOriginal\n", + to: fixture.repo.appendingPathComponent("skills/demo/SKILL.md")) + } + try fixture.write( + """ + version: 1 + components: [] + groups: + skills: + components: [{kind: skills, source: ., select: all, mode: copy, agents: [claude-code]}] + tools: + components: [{kind: mcpServer, name: server, transport: {kind: stdio, executable: before}, agents: [claude-code]}] + exports: [skills, tools] + """, to: fixture.repo.appendingPathComponent(".agent/agents.yaml")) + try fixture.commit() + try fixture.write( + """ + version: 1 + sources: + producer: {path: \(fixture.repo.path)} + uses: + - {source: producer, group: skills} + - {source: producer, group: tools} + """, to: fixture.store.declarationURL) + _ = try fixture.apply() + let before = try fixture.snapshot() + #expect { + try SkillOperations.remove( + skillNames: [nonCanonical ? "demo-skill" : "demo"], environment: fixture.environment) + } throws: { error in + guard case CoreError.invalidState(let reason) = error else { return false } + return reason.contains("notEditableHere") && reason.contains(fixture.repo.path) + && reason.contains("#skills") + } + #expect(try fixture.snapshot() == before) + let manifest = fixture.repo.appendingPathComponent(".agent/agents.yaml") + let changed = try String(contentsOf: manifest, encoding: .utf8).replacingOccurrences( + of: "executable: before", with: "executable: after") + try fixture.write(changed, to: manifest) + try fixture.writeSource("new producer skill") + try fixture.commit() + do { + _ = try SkillOperations.updateInstalled(environment: fixture.environment, apply: true) + Issue.record("protected producer group was changed by skill-only update") + } catch let error as CoreError { + #expect(error.description.contains("requiresCombinedUpdate")) + } + #expect(try fixture.snapshot() == before) + } + + @Test func completeYAMLEditPreservesUnusedIntentAndChangesItsDisplayIdentity() throws { + let fixture = try UpdateFixture() + try fixture.write( + """ + # retained preamble + version: 1 + components: + - {kind: mcpServer, name: inactive, transport: {kind: stdio, executable: fixture}, agents: [], native: {claude-code: {value: !!float 1.00}}} + groups: + unused: + components: [{kind: ignore, name: unused, patterns: [build], condition: {platforms: []}}] + """, to: fixture.store.declarationURL) + let before = try fixture.bytes(fixture.store.declarationURL) + let a = try fixture.preview().displayedFingerprint + let document = try #require(try fixture.store.loadManifest()) + let request = UpdateRequest( + operation: .edit([.setDefaultAgents([.claudeCode])]), + expectedDeclarationDigest: document.digest) + _ = try UpdateOperations.withPreparedUpdate(request, environment: fixture.environment) { + try $0.apply() + } + let after = try fixture.bytes(fixture.store.declarationURL) + let text = String(decoding: after, as: UTF8.self) + #expect(text.contains("# retained preamble") && text.contains("!!float 1.00")) + #expect(text.contains("unused:") && text.contains("platforms: []")) + #expect(after != before) + #expect(try fixture.preview().displayedFingerprint != a) + #expect(try fixture.store.loadDeclaration().groups.count == 1) + } +} + +extension LifecycleCompositionTests { + @Test func nonGitSeparateGroupsSharingAProducerProtectActualNativeSemantics() throws { + let fixture = try UpdateFixture() + let producer = fixture.root.appendingPathComponent("producer") + try fixture.write( + "---\nname: demo\ndescription: Local\n---\nBefore\n", + to: producer.appendingPathComponent("skills/demo/SKILL.md")) + try fixture.write( + """ + version: 1 + groups: + skills: + components: [{kind: skills, source: ., select: [demo], mode: copy, agents: [claude-code]}] + tools: + components: [{kind: mcpServer, name: stable, transport: {kind: stdio, executable: fixture-server}, agents: [claude-code]}] + exports: [skills, tools] + """, to: producer.appendingPathComponent(".agent/agents.yaml")) + try fixture.write( + """ + version: 1 + sources: {producer: {path: \(producer.path)}} + uses: [{source: producer, group: skills}, {source: producer, group: tools}] + """, to: fixture.store.declarationURL) + _ = try fixture.apply() + let native = fixture.root.appendingPathComponent(".mcp.json") + let bytes = try fixture.bytes(native) + try fixture.write( + "---\nname: demo\ndescription: Local\n---\nAfter\n", + to: producer.appendingPathComponent("skills/demo/SKILL.md")) + _ = try SkillOperations.updateInstalled(environment: fixture.environment, apply: true) + #expect(try fixture.bytes(native) == bytes) + #expect( + String( + decoding: try fixture.bytes(fixture.target(.claudeCode).appendingPathComponent("SKILL.md")), + as: UTF8.self + ).contains("After")) + } +} + +extension LifecycleCompositionTests { + @Test func sameSkillNameFromDisjointSourcesKeepsSeparatePublicInventoryAndReport() throws { + let fixture = try UpdateFixture() + let second = fixture.root.appendingPathComponent("second") + try fixture.write( + "---\nname: demo\ndescription: Other\n---\nSecond\n", + to: second.appendingPathComponent("skills/demo/SKILL.md")) + try fixture.store.save( + declaration: Declaration( + sources: [ + "first": .init(kind: .local, location: fixture.repo.path), + "second": .init(kind: .local, location: second.path), + ], + components: [ + .skills(source: "first", .init(select: .all, agents: [.codex], mode: .copy)), + .skills(source: "second", .init(select: .all, agents: [.claudeCode], mode: .copy)), + ]), ledger: ResolvedLedger()) + let report = try fixture.preview() + #expect(report.skills.count == 2) + #expect(Set(report.skills.map(\.sourceIdentity)).count == 2) + _ = try fixture.apply() + let inventory = try SkillOperations.listManaged(environment: fixture.environment) + #expect(Set(inventory.compactMap(\.sourceIdentity)).count == 2) + #expect(Set(inventory.map(\.agent)) == [.codex, .claudeCode]) + #expect( + try fixture.store.loadLedger().components.values.filter { $0.kind == "skills" }.count == 2) + } +} + +extension LifecycleCompositionTests { + @Test func forwardingSiblingsStayPrivateWhileFreshnessRemainsStrict() throws { + let fixture = try UpdateFixture() + try fixture.declare(agents: [.claudeCode]) + let file = fixture.root.appendingPathComponent("CLAUDE.md") + try fixture.write("# Private sibling sentinel\n", to: file) + let report = try fixture.preview() + #expect( + !String(decoding: try JSONEncoder().encode(report), as: UTF8.self).contains( + "Private sibling sentinel")) + _ = try fixture.apply() + let before = try fixture.bytes(file) + let fingerprint = try fixture.preview().displayedFingerprint + try fixture.write( + String(decoding: before, as: UTF8.self).replacingOccurrences( + of: "Private sibling sentinel", with: "Rotated sibling"), to: file) + #expect(try fixture.preview().displayedFingerprint == fingerprint) + try UpdateOperations.withPreparedUpdate(environment: fixture.environment) { update in + try before.write(to: file) + #expect(throws: UpdateApplyError.self) { try update.apply() } + } + } +} + +extension LifecycleCompositionTests { + @Test func unusedDeclarationEditsInvalidateASelectedSkillPreparation() throws { + let fixture = try UpdateFixture() + try fixture.install(agents: [.codex]) + let authored = + String(decoding: try fixture.bytes(fixture.store.declarationURL), as: UTF8.self) + + "\ngroups:\n unused: {components: [{kind: ignore, name: draft, patterns: [build]}]}\n" + try fixture.write(authored, to: fixture.store.declarationURL) + try fixture.advance() + let ledger = try fixture.bytes(fixture.store.resolvedURL) + let target = try FileHash.folderHash(fixture.target()) + var edited = Data() + try UpdateOperations.withPreparedUpdate( + UpdateRequest(kinds: [.skills]), environment: fixture.environment + ) { prepared in + edited = Data( + authored.replacingOccurrences(of: "patterns: [build]", with: "patterns: [cache]").utf8) + try edited.write(to: fixture.store.declarationURL) + #expect { try prepared.apply() } throws: { error in + guard let failure = error as? UpdateApplyError, + case .unchanged = failure.disposition, + case CoreError.invalidState(let reason) = failure.underlyingError + else { return false } + return reason.contains("changed during preparation") + } + } + #expect(try fixture.bytes(fixture.store.declarationURL) == edited) + #expect(try fixture.bytes(fixture.store.resolvedURL) == ledger) + #expect(try FileHash.folderHash(fixture.target()) == target) + #expect(try fixture.store.loadDeclaration().groups.count == 1) + #expect(try fixture.store.loadLedger().version == 2) + } +} diff --git a/Tests/AgentsUpdatesTests/MCPConnectionOperationsTests.swift b/Tests/AgentsUpdatesTests/MCPConnectionOperationsTests.swift new file mode 100644 index 0000000..542873a --- /dev/null +++ b/Tests/AgentsUpdatesTests/MCPConnectionOperationsTests.swift @@ -0,0 +1,448 @@ +import AgentsCore +import AgentsUpdates +import Foundation +import Testing + +private final class MCPFacadeBundle: NSObject {} + +/// Only the call list mutates, under lock; values are immutable fixture input. +final class MCPBindingSpy: RuntimeBindingProvider, @unchecked Sendable { + private let lock = NSLock() + private var names: [String] = [] + let values: [String: Data] + let delay: TimeInterval + init(_ values: [String: Data] = [:], delay: TimeInterval = 0) { + self.values = values + self.delay = delay + } + var calls: [String] { lock.withLock { names } } + func value(for binding: String, environment: RuntimeEnvironment) throws -> Data { + lock.withLock { names.append(binding) } + if delay > 0 { Thread.sleep(forTimeInterval: delay) } + guard let value = values[binding] else { throw MCPConnectionPreparationError.invalidSelection } + return value + } +} + +private struct MCPRemovingDirectoryProvider: RuntimeBindingProvider { + let directory: URL + func value(for binding: String, environment: RuntimeEnvironment) throws -> Data { + try FileManager.default.removeItem(at: directory) + return Data("unused-after-path-removal".utf8) + } +} + +final class MCPFacadeFixture { + let root: URL + let observation: URL + let environment: RuntimeEnvironment + static var executable: URL { + var directory = Bundle(for: MCPFacadeBundle.self).bundleURL + for _ in 0..<8 { + let candidate = directory.appendingPathComponent("MCPTestProcess") + if FileManager.default.isExecutableFile(atPath: candidate.path) { return candidate } + directory.deleteLastPathComponent() + } + return directory.appendingPathComponent("MCPTestProcess") + } + init() throws { + root = FileManager.default.temporaryDirectory.appendingPathComponent( + "mcp-facade-" + UUID().uuidString) + observation = root.appendingPathComponent("observed") + environment = RuntimeEnvironment( + projectDirectory: root, homeDirectory: root.appendingPathComponent("home"), + environment: [ + "PATH": Self.executable.deletingLastPathComponent().path + ":/usr/bin:/bin", + "SELECTED_ENV": "environment-canary", + ]) + try FileManager.default.createDirectory(at: observation, withIntermediateDirectories: true) + try FileManager.default.createDirectory( + at: root.appendingPathComponent(".agent"), withIntermediateDirectories: true) + try Data("untouched declaration".utf8).write( + to: root.appendingPathComponent(".agent/agents.yaml")) + try Data("untouched ledger".utf8).write( + to: root.appendingPathComponent(".agent/agents.resolved")) + } + func snapshot( + _ mode: String = "normal", selection: String = "source-a/same-name", + values: [String: RuntimeBinding] = [:] + ) throws -> MCPConnectionSnapshot { + try MCPConnectionOperations.snapshot( + selectionID: selection, + transport: .stdio( + .init( + executable: "MCPTestProcess", arguments: [mode, observation.path], environment: values)), + workingDirectory: .live(root)) + } + func text(_ path: String) -> String? { + try? String(contentsOf: observation.appendingPathComponent(path), encoding: .utf8) + } + func waitFor(_ predicate: () -> Bool) async -> Bool { + let deadline = ContinuousClock.now + .seconds(3) + while !predicate() { + if ContinuousClock.now >= deadline { return false } + try? await Task.sleep(for: .milliseconds(2)) + } + return true + } + func unchanged() throws { + #expect( + try String(contentsOf: root.appendingPathComponent(".agent/agents.yaml"), encoding: .utf8) + == "untouched declaration") + #expect( + try String(contentsOf: root.appendingPathComponent(".agent/agents.resolved"), encoding: .utf8) + == "untouched ledger") + } + deinit { try? FileManager.default.removeItem(at: root) } +} + +@Suite(.serialized) struct MCPConnectionOperationsTests { + @Test func describeIsPureAndExactSelectionUsesOnlyNecessaryBindings() async throws { + let fixture = try MCPFacadeFixture() + let spy = MCPBindingSpy([ + "wanted": Data("provider-canary".utf8), "controlled": Data("control-\ncanary".utf8), + ]) + let selected = try fixture.snapshot( + "facade", + values: [ + "FACADE_SECRET": .secret("wanted"), "SECOND_SECRET": .secret("wanted"), + "FACADE_LITERAL": .literal("literal-canary"), "FACADE_ENV": .environment("SELECTED_ENV"), + "FACADE_CONTROLLED": .secret("controlled"), + ]) + let other = try fixture.snapshot( + "wrong-version", selection: "source-b/same-name", values: ["UNUSED": .secret("unused")]) + let before = try FileManager.default.contentsOfDirectory(atPath: fixture.root.path).sorted() + let description = MCPConnectionOperations.describe(selected) + #expect(description.snapshotID == selected.id && selected.id != other.id) + #expect(description.startsOwnedProcess) + #expect(description.requiredBindings == ["controlled", "wanted"]) + #expect(description.environmentBindings == ["SELECTED_ENV"]) + #expect(spy.calls.isEmpty && fixture.text("pid") == nil) + #expect( + try FileManager.default.contentsOfDirectory(atPath: fixture.root.path).sorted() == before) + #expect(Mirror(reflecting: selected).children.isEmpty) + #expect(!String(reflecting: selected).contains("literal-canary")) + let result = await MCPConnectionOperations.test( + selected, environment: fixture.environment, bindings: spy) + #expect(result.snapshotID == selected.id) + #expect(result.outcome == .discovered && result.issue == nil) + #expect(result.cleanupComplete && result.startedAt <= result.finishedAt) + #expect(result.elapsed >= 0 && result.transport == .stdio) + #expect(result.tools.map(\.name) == ["first", "second"]) + #expect(spy.calls == ["controlled", "wanted"]) + let encoded = String(decoding: try JSONEncoder().encode(result), as: UTF8.self) + for secret in [ + "provider-canary", "control-canary", "literal-canary", "environment-canary", + fixture.root.path, + ] { + #expect(!encoded.contains(secret)) + } + #expect(result.tools.allSatisfy { $0.description?.contains("[redacted]") == true }) + #expect( + result.tools.allSatisfy { + $0.description?.unicodeScalars.contains(where: CharacterSet.controlCharacters.contains) + == false + }) + let pid = try #require(Int32(fixture.text("pid") ?? "")) + #expect(kill(pid, 0) == -1 && errno == ESRCH) + try fixture.unchanged() + } + + @Test func confirmationShowsFixedCommandAndSafeEndpointWithoutEffects() throws { + let fixture = try MCPFacadeFixture() + let live = try MCPConnectionResource.live(fixture.root) + let snapshot = try MCPConnectionOperations.snapshot( + selectionID: "description-only", + transport: .stdio( + .init( + executable: "safe-command", arguments: ["--mode", "read-only", "literal-\ncanary", "é"], + environment: ["TOKEN": .literal("literal-canary"), "SECRET": .secret("named-secret")])), + workingDirectory: live) + let before = try FileHash.folderHash(fixture.root) + let description = MCPConnectionOperations.describe(snapshot) + #expect(description.executable == "safe-command") + #expect(description.arguments == ["--mode", "read-only", "[redacted]", "é"]) + #expect(description.workingDirectory == fixture.root.path) + #expect(!description.workingDirectoryIsCaptured && !description.executableIsCaptured) + #expect(description.endpoint == nil && description.startsOwnedProcess) + #expect(description.requiredBindings == ["named-secret"]) + #expect(description.readDependencies == snapshot.readDependencies) + #expect(snapshot.readDependencies.contains { $0.url.path == fixture.root.path }) + #expect(snapshot.readDependencies.allSatisfy { if case .entry = $0 { true } else { false } }) + let encoded = try JSONEncoder().encode(description) + #expect(try JSONDecoder().decode(MCPConnectionDescription.self, from: encoded) == description) + let object = try #require(JSONSerialization.jsonObject(with: encoded) as? [String: Any]) + #expect(object["readLocations"] == nil) + let dependencies = try #require(object["readDependencies"] as? [[String: [String: String]]]) + #expect( + dependencies == description.readDependencies.map { ["entry": ["_0": $0.url.absoluteString]] }) + #expect(try FileHash.folderHash(fixture.root) == before && fixture.text("pid") == nil) + for transport: MCPTransportDeclaration in [ + .sse( + url: "http://127.0.0.1:1/private-path?token=query-canary", + headers: [ + "Authorization": .literal("header-canary"), "X-Secret": .secret("remote-secret"), + ]), + .streamableHTTP(url: "http://127.0.0.1:1/private-path?token=query-canary", headers: [:]), + ] { + // Projection only. No test() call is admitted for these endpoint values. + let remote = try MCPConnectionOperations.snapshot(selectionID: "remote", transport: transport) + let info = MCPConnectionOperations.describe(remote) + #expect(info.endpoint == "http://127.0.0.1:1/[redacted]") + #expect(!info.startsOwnedProcess && info.executable == nil && info.arguments == nil) + #expect(info.workingDirectory == nil && info.readDependencies.isEmpty) + let text = String(decoding: try JSONEncoder().encode(info), as: UTF8.self) + for hidden in ["private-path", "query-canary", "header-canary"] { + #expect(!text.contains(hidden)) + } + } + let credentialInOrigin = try MCPConnectionOperations.snapshot( + selectionID: "header-redaction-only", + transport: .sse( + url: "http://127.0.0.1:1/mcp", + headers: [ + "Authorization": .literal("Bearer 127.0.0.1") + ])) + #expect( + MCPConnectionOperations.describe(credentialInOrigin).endpoint + == "http://[redacted]:1/[redacted]") + let long = try MCPConnectionOperations.snapshot( + selectionID: "bounded", + transport: .stdio( + .init( + executable: "safe-command", arguments: ["a" + String(repeating: "é", count: 20_000)])), + workingDirectory: live) + let projected = try #require(MCPConnectionOperations.describe(long).arguments?.first) + #expect(projected.utf8.count == 4095 && projected.hasPrefix("a")) + #expect(String(data: Data(projected.utf8), encoding: .utf8) != nil) + #expect(fixture.text("pid") == nil) + try FileManager.default.removeItem(at: fixture.root) + #expect(MCPConnectionOperations.describe(snapshot) == description) + } + + @Test func confirmationIdentifiesSelectedExecutableResourceInsteadOfDeclaration() throws { + let fixture = try MCPFacadeFixture() + let file = fixture.root.appendingPathComponent("selected-executable") + try Data("description-only resource".utf8).write(to: file) + try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: file.path) + let cwd = try MCPConnectionResource.live(fixture.root) + let declared = "/declared/different-executable" + let live = try MCPConnectionOperations.snapshot( + selectionID: "live-resource", + transport: .stdio(.init(executable: declared, arguments: ["fixed-argument"])), + workingDirectory: cwd, executable: .live(file)) + let captured = try MCPConnectionOperations.snapshot( + selectionID: "captured-resource", + transport: .stdio(.init(executable: declared)), workingDirectory: cwd, + executable: .capture( + sourceRoot: fixture.root, path: "selected-executable", + expectedHash: "sha256:" + FileHash.sha256Hex(file: file), + expectedExecutableFiles: [".": true])) + let before = try FileHash.folderHash(fixture.root) + let liveDescription = MCPConnectionOperations.describe(live) + #expect(liveDescription.executable == file.path && !liveDescription.executableIsCaptured) + #expect(liveDescription.arguments == ["fixed-argument"]) + #expect(liveDescription.readDependencies.contains { $0.url.path == file.path }) + let capturedDescription = MCPConnectionOperations.describe(captured) + #expect(capturedDescription.executable == "selected-executable") + #expect(capturedDescription.executableIsCaptured) + #expect(!capturedDescription.readDependencies.contains { $0.url.path == file.path }) + let path = try MCPConnectionOperations.snapshot( + selectionID: "path-command", transport: .stdio(.init(executable: "path-command")), + workingDirectory: cwd) + #expect(MCPConnectionOperations.describe(path).executable == "path-command") + #expect(try FileHash.folderHash(fixture.root) == before && fixture.text("pid") == nil) + try FileManager.default.removeItem(at: file) + #expect(MCPConnectionOperations.describe(live) == liveDescription) + #expect(MCPConnectionOperations.describe(captured) == capturedDescription) + } + + @Test func invalidOptionsAndUnavailableEnvironmentDoNotConsultProvider() async throws { + let fixture = try MCPFacadeFixture() + let spy = MCPBindingSpy() + let snapshot = try fixture.snapshot(values: ["TOKEN": .secret("unused")]) + var options = MCPConnectionTestOptions() + options.totalTimeout = .infinity + let invalid = await MCPConnectionOperations.test( + snapshot, options: options, environment: fixture.environment, bindings: spy) + #expect(invalid.issue == .invalidInput && invalid.cleanupComplete) + let missing = try fixture.snapshot(values: [ + "TOKEN": .secret("unused"), "MISSING": .environment("MISSING"), + ]) + let unavailable = await MCPConnectionOperations.test( + missing, environment: fixture.environment, bindings: spy) + #expect(unavailable.issue == .bindingUnavailable && unavailable.cleanupComplete) + #expect(spy.calls.isEmpty && fixture.text("pid") == nil) + let cancelled = Task { [environment = fixture.environment] in + withUnsafeCurrentTask { $0?.cancel() } + return await MCPConnectionOperations.test( + snapshot, environment: environment, bindings: spy) + } + #expect(await cancelled.value.issue == .cancelled) + #expect(spy.calls.isEmpty) + // This bounded synchronous provider deliberately consumes the total budget. + let slow = MCPBindingSpy(["unused": Data("deadline-canary".utf8)], delay: 0.03) + options.totalTimeout = 0.001 + let expired = await MCPConnectionOperations.test( + snapshot, options: options, environment: fixture.environment, bindings: slow) + #expect(expired.issue == .timeout && expired.cleanupComplete) + #expect(slow.calls == ["unused"] && fixture.text("pid") == nil) + try fixture.unchanged() + } + + @Test func invalidHeaderBindingsFailBeforeNetworkWithoutLeakingValues() async throws { + let fixture = try MCPFacadeFixture() + let snapshot = try MCPConnectionOperations.snapshot( + selectionID: "fixed-remote", + transport: .streamableHTTP( + url: "http://127.0.0.1:1/mcp", headers: ["Authorization": .secret("token")])) + let spy = MCPBindingSpy(["token": Data("credential-canary\r\nInjected: value".utf8)]) + let result = await MCPConnectionOperations.test( + snapshot, environment: fixture.environment, bindings: spy) + #expect(result.issue == .invalidBinding && result.cleanupComplete) + #expect(spy.calls == ["token"]) + #expect( + !String(decoding: try JSONEncoder().encode(result), as: UTF8.self).contains( + "credential-canary")) + #expect(throws: MCPConnectionPreparationError.invalidConfiguration) { + try MCPConnectionOperations.snapshot( + selectionID: "invalid", + transport: .sse(url: "http://127.0.0.1/mcp", headers: ["bad\nkey": .secret("unused")])) + } + for headers: [String: RuntimeBinding] in [ + ["MCP-Session-ID": .secret("unused")], + ["Authorization": .secret("one"), "authorization": .secret("two")], + ["Authorization": .secret("")], + ] { + #expect(throws: MCPConnectionPreparationError.invalidConfiguration) { + try MCPConnectionOperations.snapshot( + selectionID: "invalid", transport: .sse(url: "http://127.0.0.1/mcp", headers: headers)) + } + } + try fixture.unchanged() + } + + @Test func capturedBorrowedResourcesSurviveCancellationUntilOwnedCleanup() async throws { + let fixture = try MCPFacadeFixture() + let borrowed = fixture.root.appendingPathComponent("borrowed") + try FileManager.default.createDirectory(at: borrowed, withIntermediateDirectories: false) + let tool = borrowed.appendingPathComponent("tool") + try FileManager.default.copyItem(at: MCPFacadeFixture.executable, to: tool) + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: tool.path) + let content = borrowed.appendingPathComponent("content") + try FileManager.default.createDirectory(at: content, withIntermediateDirectories: false) + try Data("required-support".utf8).write(to: content.appendingPathComponent("support")) + let directoryLink = borrowed.appendingPathComponent("cwd") + try FileManager.default.createSymbolicLink( + atPath: directoryLink.path, withDestinationPath: "content") + let executable = try MCPConnectionResource.capture( + sourceRoot: borrowed, path: "tool", + expectedHash: "sha256:" + FileHash.sha256Hex(file: tool), expectedExecutableFiles: [".": true] + ) + let cwd = try MCPConnectionResource.capture( + sourceRoot: borrowed, path: "cwd", + expectedHash: "sha256:" + FileHash.folderHash(directoryLink), + expectedExecutableFiles: FileHash.executableFlags(directoryLink)) + let snapshot = try MCPConnectionOperations.snapshot( + selectionID: "fixed-source/entry", + transport: .stdio( + .init(executable: "./tool", arguments: ["stubborn", fixture.observation.path])), + workingDirectory: cwd, executable: executable) + try FileManager.default.removeItem(at: borrowed) + let spy = MCPBindingSpy() + let task = Task { [environment = fixture.environment] in + await MCPConnectionOperations.test(snapshot, environment: environment, bindings: spy) + } + let ready = await fixture.waitFor { fixture.text("stubborn-ready") != nil } + #expect(ready) + let records = (fixture.text("wire.jsonl") ?? "").split(separator: "\n").compactMap { + (try? JSONSerialization.jsonObject(with: Data($0.utf8))) as? [String: Any] + } + let staged = records.first?["cwd"] as? String + if let staged { + #expect(FileManager.default.fileExists(atPath: staged + "/support")) + #expect(!staged.hasPrefix(borrowed.path)) + } else { + Issue.record("Missing owned resource working directory") + } + task.cancel() + let result = await task.value + #expect(result.issue == .cancelled && result.cleanupComplete) + #expect(result.outcome == .incomplete) + if let staged { #expect(!FileManager.default.fileExists(atPath: staged)) } + let pid = try #require(Int32(fixture.text("pid") ?? "")) + #expect(kill(pid, 0) == -1 && errno == ESRCH) + #expect(spy.calls.isEmpty) + try fixture.unchanged() + } + + @Test func liveAliasChildrenStayLiveAndRetargetingRefusesBeforeBinding() async throws { + let fixture = try MCPFacadeFixture() + let logical = fixture.root.appendingPathComponent("live-alias") + let first = fixture.root.appendingPathComponent("physical-first").resolvingSymlinksInPath() + let second = fixture.root.appendingPathComponent("physical-second").resolvingSymlinksInPath() + for directory in [first, second] { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false) + } + try FileManager.default.createSymbolicLink(at: logical, withDestinationURL: first) + let marker = first.appendingPathComponent("live-marker") + try Data("before".utf8).write(to: marker) + let snapshot = try MCPConnectionOperations.snapshot( + selectionID: "live-alias", + transport: .stdio( + .init( + executable: "MCPTestProcess", + arguments: ["normal", fixture.observation.path], + environment: ["TOKEN": .secret("wanted")])), workingDirectory: .live(logical)) + #expect(Set(snapshot.readDependencies.map { $0.url.path }) == Set([logical.path, first.path])) + #expect(snapshot.readDependencies.allSatisfy { if case .entry = $0 { true } else { false } }) + try Data("after".utf8).write(to: marker) + let spy = MCPBindingSpy(["wanted": Data("value".utf8)]) + let live = await MCPConnectionOperations.test( + snapshot, environment: fixture.environment, bindings: spy) + #expect(live.outcome == .discovered && live.cleanupComplete && spy.calls == ["wanted"]) + let wire = try String( + contentsOf: fixture.observation.appendingPathComponent("wire.jsonl"), encoding: .utf8) + let startup = try #require(wire.split(separator: "\n").first) + let record = try #require( + JSONSerialization.jsonObject(with: Data(startup.utf8)) as? [String: Any]) + #expect(record["liveMarker"] as? String == "after") + try FileManager.default.removeItem(at: logical) + try FileManager.default.createSymbolicLink(at: logical, withDestinationURL: second) + let forbidden = MCPBindingSpy(["wanted": Data("unused".utf8)]) + let stale = await MCPConnectionOperations.test( + snapshot, environment: fixture.environment, bindings: forbidden) + #expect(stale.issue == .resourceChanged && stale.cleanupComplete && forbidden.calls.isEmpty) + try fixture.unchanged() + } + + @Test func replacedLiveDirectoryRequiresNewSnapshotBeforeBinding() async throws { + let fixture = try MCPFacadeFixture() + let live = fixture.root.appendingPathComponent("live") + try FileManager.default.createDirectory(at: live, withIntermediateDirectories: false) + let snapshot = try MCPConnectionOperations.snapshot( + selectionID: "live-entry", + transport: .stdio( + .init( + executable: "MCPTestProcess", arguments: ["normal", fixture.observation.path], + environment: ["TOKEN": .secret("unused")])), workingDirectory: .live(live)) + try FileManager.default.moveItem(at: live, to: fixture.root.appendingPathComponent("old-live")) + try FileManager.default.createDirectory(at: live, withIntermediateDirectories: false) + let spy = MCPBindingSpy() + let result = await MCPConnectionOperations.test( + snapshot, environment: fixture.environment, bindings: spy) + #expect(result.issue == .resourceChanged && result.cleanupComplete) + #expect(spy.calls.isEmpty && fixture.text("pid") == nil) + let selected = try MCPConnectionOperations.snapshot( + selectionID: "live-entry", + transport: .stdio( + .init(executable: "MCPTestProcess", environment: ["TOKEN": .secret("remove-directory")])), + workingDirectory: .live(live)) + let removedDuringBinding = await MCPConnectionOperations.test( + selected, environment: fixture.environment, + bindings: MCPRemovingDirectoryProvider(directory: live)) + #expect(removedDuringBinding.issue == .resourceChanged && removedDuringBinding.cleanupComplete) + #expect(!FileManager.default.fileExists(atPath: live.path) && fixture.text("pid") == nil) + try fixture.unchanged() + } +} diff --git a/Tests/AgentsUpdatesTests/MCPManagedSelectionTests.swift b/Tests/AgentsUpdatesTests/MCPManagedSelectionTests.swift new file mode 100644 index 0000000..f3f9a49 --- /dev/null +++ b/Tests/AgentsUpdatesTests/MCPManagedSelectionTests.swift @@ -0,0 +1,298 @@ +import AgentsCore +import AgentsManifest +import Components +import Foundation +import Testing + +@testable import AgentsUpdates + +private struct ManagedMCPFixture { + let fixture: MCPFacadeFixture + let store: StateStore + let producer: URL + var ledger: ResolvedLedger + + init(remote: Bool) throws { + fixture = try MCPFacadeFixture() + store = StateStore(scope: .project, environment: fixture.environment) + producer = fixture.root.appendingPathComponent("producer") + let fm = FileManager.default + try fm.createDirectory( + at: producer.appendingPathComponent(".agent"), withIntermediateDirectories: true) + try fm.createDirectory( + at: producer.appendingPathComponent("cwd"), withIntermediateDirectories: true) + try fm.copyItem(at: MCPFacadeFixture.executable, to: producer.appendingPathComponent("tool")) + try fm.setAttributes( + [.posixPermissions: 0o755], ofItemAtPath: producer.appendingPathComponent("tool").path) + try Data("fixed support".utf8).write(to: producer.appendingPathComponent("cwd/support")) + try Data( + """ + version: 1 + groups: + tools: + components: + - kind: mcpServer + name: selected + transport: + kind: stdio + executable: ./tool + arguments: [managed, \(fixture.observation.path)] + workingDirectory: {path: cwd} + environment: {TOKEN: {secret: wanted}} + agents: [] + exports: [tools] + """.utf8 + ).write(to: producer.appendingPathComponent(".agent/agents.yaml")) + let bytes = Data( + """ + version: 1 + sources: {producer: {path: \(producer.path)}} + uses: [{source: producer, group: tools}] + """.utf8) + try bytes.write(to: store.declarationURL) + let document = try DeclarationDocument( + bytes: Array(bytes), identity: DocumentIdentity(store.declarationURL.path)) + let declaration = try ManifestProjection.declaration( + of: document, environment: fixture.environment) + #if os(macOS) + let platform = DeclarationPlatform.macOS + #else + let platform = DeclarationPlatform.linux + #endif + let selectedStore = store + ledger = try ComponentLinker.withLinkedComponents( + document: document, store: selectedStore, platform: platform + ) { linked, session in + try LedgerFreeze.freeze( + linked, session: session, + locations: .init( + sources: UpdatePlan.sourceLocations( + linked, declaration: declaration, store: selectedStore)), limits: .standard) + } + if remote { + let id = try #require(ledger.groups.first?.source) + let revision = String(repeating: "a", count: 40) + ledger.sources[id] = .init( + kind: .git, transport: "https://fixture.invalid/producer.git", revision: revision) + let root = SourceCache(store: store).materializedURL( + sourceID: try ledger.sourceIdentity(id, roots: store.ledgerRoots), revision: revision) + try fm.createDirectory( + at: root.deletingLastPathComponent(), withIntermediateDirectories: true) + try fm.copyItem(at: producer, to: root) + for key in ledger.resources.keys { + ledger.resources[key]!.kind = .git + ledger.resources[key]!.entries = ledger.resources[key]!.entries.map { + var e = $0 + e.object = nil + return e + } + ledger.resources[key]!.support = ledger.resources[key]!.support.map { + var e = $0 + e.object = nil + return e + } + } + ledger.contentObjects = [:] + } + try ResolvedLedgerCodec.encode(ledger, limits: .standard).write(to: store.resolvedURL) + } + func save(_ value: ResolvedLedger) throws { + try ResolvedLedgerCodec.encode(value, limits: .standard).write(to: store.resolvedURL) + } + func inspection() throws -> ComponentInspection { + try #require(UpdateOperations.inspect(environment: fixture.environment).components.first) + } +} + +@Suite(.serialized) struct MCPManagedSelectionTests { + @Test(arguments: [false, true]) + func exactGroupSelectionOwnsResourcesAcrossSourceLossAndConcurrentTests(_ remote: Bool) + async throws + { + let f = try ManagedMCPFixture(remote: remote) + let selected = try f.inspection() + #expect(selected.group == "tools" && selected.kind == .mcpServer) + #expect( + remote ? selected.source == "fixture.invalid/producer" : selected.source.hasPrefix("local:")) + let before = try FileHash.folderHash(f.store.directory) + if remote { try FileManager.default.removeItem(at: f.producer) } + let snapshot = try MCPConnectionOperations.snapshot( + selection: selected.occurrences[0].selection, scope: .project, + environment: f.fixture.environment) + let description = MCPConnectionOperations.describe(snapshot) + #expect(description.executable == "tool" && description.executableIsCaptured) + #expect(description.workingDirectory == "cwd" && description.workingDirectoryIsCaptured) + #expect(snapshot.readDependencies.contains(.subtree(f.store.declarationURL))) + #expect(snapshot.readDependencies.contains(.subtree(f.store.resolvedURL))) + #expect(snapshot.readDependencies.contains(.subtree(f.store.watchURL))) + #expect(description.readDependencies == snapshot.readDependencies) + #expect(snapshot.readDependencies.allSatisfy { if case .subtree = $0 { true } else { false } }) + let encoded = try JSONEncoder().encode(description) + #expect(try JSONDecoder().decode(MCPConnectionDescription.self, from: encoded) == description) + let object = try #require(JSONSerialization.jsonObject(with: encoded) as? [String: Any]) + let dependencies = try #require(object["readDependencies"] as? [[String: [String: String]]]) + #expect( + dependencies + == description.readDependencies.map { ["subtree": ["_0": $0.url.absoluteString]] }) + if !remote { + #expect( + snapshot.readDependencies.contains { + if case .subtree(let url) = $0 { url.path == f.producer.path } else { false } + }) + } + #expect(!snapshot.readDependencies.contains { $0.url.path.contains("agents-mcp-capture-") }) + let spy = MCPBindingSpy(["wanted": Data("provider-canary".utf8)]) + #expect(MCPConnectionOperations.describe(snapshot).requiredBindings == ["wanted"]) + #expect(spy.calls.isEmpty) + #expect(try FileManager.default.contentsOfDirectory(atPath: f.fixture.observation.path).isEmpty) + #expect(try FileHash.folderHash(f.store.directory) == before) + if !remote { try FileManager.default.removeItem(at: f.producer) } + if remote { try FileManager.default.removeItem(at: f.store.cacheDirectory) } + let environment = f.fixture.environment + async let first = MCPConnectionOperations.test( + snapshot, environment: environment, bindings: spy) + async let second = MCPConnectionOperations.test( + snapshot, environment: environment, bindings: spy) + let results = await [first, second] + #expect(results.allSatisfy { $0.outcome == .discovered && $0.cleanupComplete }) + #expect(spy.calls == ["wanted", "wanted"]) + let children = try FileManager.default.contentsOfDirectory( + at: f.fixture.observation, includingPropertiesForKeys: nil) + #expect(children.count == 2) + var directories = Set() + for child in children { + let pid = try #require( + Int32(String(contentsOf: child.appendingPathComponent("pid"), encoding: .utf8))) + #expect(kill(pid, 0) == -1 && errno == ESRCH) + let wire = try String(contentsOf: child.appendingPathComponent("wire.jsonl"), encoding: .utf8) + let startup = try #require(wire.split(separator: "\n").first) + let record = try #require( + JSONSerialization.jsonObject(with: Data(startup.utf8)) as? [String: Any]) + let cwd = try #require(record["cwd"] as? String) + directories.insert(cwd) + #expect(!FileManager.default.fileExists(atPath: cwd)) + } + #expect(directories.count == 2) + } + + @Test func staleWrongKindOccurrenceAndAmbiguousSelectionsRefusePreparation() throws { + let f = try ManagedMCPFixture(remote: false) + let selected = try f.inspection() + let environment = f.fixture.environment + let wrong = ComponentSelection( + identity: selected.selection.identity, occurrence: 99999, + generation: selected.selection.generation) + #expect(throws: MCPConnectionPreparationError.invalidSelection) { + try MCPConnectionOperations.snapshot( + selection: wrong, scope: .project, environment: environment) + } + let unknown = ComponentSelection( + identity: "not-the-selected-source", occurrence: nil, + generation: selected.selection.generation) + #expect(throws: MCPConnectionPreparationError.invalidSelection) { + try MCPConnectionOperations.snapshot( + selection: unknown, scope: .project, environment: environment) + } + var ledger = f.ledger + let key = try #require(ledger.components.keys.first) + ledger.components[key]!.kind = "ignore" + try f.save(ledger) + #expect(throws: MCPConnectionPreparationError.invalidSelection) { + try MCPConnectionOperations.snapshot( + selection: selected.selection, scope: .project, environment: environment) + } + let wrongKind = try f.inspection().selection + #expect(throws: MCPConnectionPreparationError.invalidSelection) { + try MCPConnectionOperations.snapshot( + selection: wrongKind, scope: .project, environment: environment) + } + try f.save(f.ledger) + var declaration = try Data(contentsOf: f.store.declarationURL) + declaration.append(Data("\n# changed generation\n".utf8)) + try declaration.write(to: f.store.declarationURL) + #expect(throws: MCPConnectionPreparationError.invalidSelection) { + try MCPConnectionOperations.snapshot( + selection: selected.selection, scope: .project, environment: environment) + } + ledger = f.ledger + ledger.components["duplicate"] = ledger.components[key] + try f.save(ledger) + let ambiguous = try f.inspection().selection + #expect(throws: MCPConnectionPreparationError.invalidSelection) { + try MCPConnectionOperations.snapshot( + selection: ambiguous, scope: .project, environment: environment) + } + #expect(try FileManager.default.contentsOfDirectory(atPath: f.fixture.observation.path).isEmpty) + } + + @Test func defaultLocalContextStaysLiveAndReplacedIdentityRefusesLaunch() async throws { + let f = try ManagedMCPFixture(remote: false) + var ledger = f.ledger + let key = try #require(ledger.components.keys.first) + var payload = ledger.components[key]!.payload.object! + payload["transport"] = .init(object: [ + "kind": .init("stdio"), + "run": .init(object: [ + "executable": .init("MCPTestProcess"), + "arguments": .init(array: [LedgerValue("normal"), .init(f.fixture.observation.path)]), + "environment": .init(object: [:]), + ]), + ]) + ledger.components[key]!.payload = .init(object: payload) + ledger.components[key]!.resources = [] + try f.save(ledger) + let marker = f.fixture.root.appendingPathComponent("live-marker") + try Data("before".utf8).write(to: marker) + let selection = try f.inspection().selection + let snapshot = try MCPConnectionOperations.snapshot( + selection: selection, scope: .project, environment: f.fixture.environment) + #expect( + snapshot.readDependencies.contains { + if case .entry(let url) = $0 { url.path == f.fixture.root.path } else { false } + }) + #expect( + snapshot.readDependencies.contains { + if case .subtree(let url) = $0 { url.path == f.producer.path } else { false } + }) + try Data("after".utf8).write(to: marker) + let spy = MCPBindingSpy() + let result = await MCPConnectionOperations.test( + snapshot, environment: f.fixture.environment, bindings: spy) + #expect(result.outcome == .discovered && result.cleanupComplete) + let wire = try String( + contentsOf: f.fixture.observation.appendingPathComponent("wire.jsonl"), encoding: .utf8) + let startup = try #require(wire.split(separator: "\n").first) + let record = try #require( + JSONSerialization.jsonObject(with: Data(startup.utf8)) as? [String: Any]) + #expect(record["liveMarker"] as? String == "after") + let displaced = f.fixture.root.appendingPathExtension("displaced") + defer { try? FileManager.default.removeItem(at: displaced) } + try FileManager.default.moveItem(at: f.fixture.root, to: displaced) + try FileManager.default.createDirectory(at: f.fixture.root, withIntermediateDirectories: false) + let stale = await MCPConnectionOperations.test( + snapshot, environment: f.fixture.environment, bindings: spy) + #expect(stale.issue == .resourceChanged && stale.cleanupComplete && spy.calls.isEmpty) + #expect(try FileManager.default.contentsOfDirectory(atPath: f.fixture.root.path).isEmpty) + } + + @Test func changedOrMissingRetainedRemoteBytesNeverRefreshTheSource() throws { + let f = try ManagedMCPFixture(remote: true) + let selected = try f.inspection().selection + let id = try #require(f.ledger.groups.first?.source) + let root = SourceCache(store: f.store).materializedURL( + sourceID: try f.ledger.sourceIdentity(id, roots: f.store.ledgerRoots), + revision: f.ledger.sources[id]!.revision) + try Data("changed retained executable".utf8).write(to: root.appendingPathComponent("tool")) + #expect(throws: (any Error).self) { + try MCPConnectionOperations.snapshot( + selection: selected, scope: .project, environment: f.fixture.environment) + } + try FileManager.default.removeItem(at: root) + #expect(throws: (any Error).self) { + try MCPConnectionOperations.snapshot( + selection: selected, scope: .project, environment: f.fixture.environment) + } + #expect(!FileManager.default.fileExists(atPath: root.path)) + #expect(try FileManager.default.contentsOfDirectory(atPath: f.fixture.observation.path).isEmpty) + } +} diff --git a/Tests/AgentsUpdatesTests/MCPRegistryTests.swift b/Tests/AgentsUpdatesTests/MCPRegistryTests.swift new file mode 100644 index 0000000..97d278f --- /dev/null +++ b/Tests/AgentsUpdatesTests/MCPRegistryTests.swift @@ -0,0 +1,903 @@ +import AgentsCore +import Foundation +import StateTestSupport +import Testing + +@testable import AgentsUpdates + +@Suite struct MCPRegistryTests { + @Test func configuredRegistryKeepsTheOperatorPrefixAndRejectsInvalidSettings() throws { + var environment = RuntimeEnvironment(environment: [:]) + #expect( + try MCPRegistry.configured(environment: environment).endpoint == MCPRegistry.official.endpoint + ) + environment.environment["MCP_REGISTRY_URL"] = "https://packages.example.invalid/team/registry" + let registry = try MCPRegistry.configured(environment: environment) + #expect(registry.endpoint.absoluteString == "https://packages.example.invalid/team/registry") + environment.environment["MCP_REGISTRY_URL"] = "registry.invalid/path" + #expect(throws: MCPRegistryError.invalidEndpoint) { + try MCPRegistry.configured(environment: environment) + } + } + + @Test func discoveryPaginatesAndLooksUpAnExactVersionWithoutChangingScope() async throws { + let fixture = try await RegistryFixture.start() + let registry = try fixture.registry("/private") + let before = try fixture.scopeContents() + let page = try await registry.search( + "fixture +&/", limit: 1, credentials: fixture.credentials, environment: fixture.environment) + let entry = try #require(page.servers.first) + #expect(page.servers.count == 1) + #expect(entry.name == "dev.example/fixture") + #expect(entry.title == "Fixture tools") + #expect(entry.version == "1.2.3+build") + #expect(entry.status == "active") + #expect(entry.registry == registry.endpoint) + #expect(entry.choices.map(\.transport).prefix(2) == ["streamable-http", "sse"]) + let cursor = try #require(page.nextCursor) + #expect(cursor == "dev.example/fixture:1.2.3+build & next=%") + let next = try await registry.search( + "fixture +&/", limit: 1, cursor: cursor, credentials: fixture.credentials, + environment: fixture.environment) + #expect(next.servers.isEmpty && next.nextCursor == nil) + + let exact = try await registry.server( + named: entry.name, version: entry.version, credentials: fixture.credentials, + environment: fixture.environment) + #expect(exact.version == entry.version) + let latest = try await registry.server( + named: entry.name, credentials: fixture.credentials, environment: fixture.environment) + #expect(latest.version == exact.version) + await #expect(throws: MCPRegistryError.invalidResponse) { + try await registry.server( + named: entry.name, version: "wrong-version", credentials: fixture.credentials, + environment: fixture.environment) + } + await #expect(throws: MCPRegistryError.httpStatus(401)) { + try await registry.search() + } + + let requests = try fixture.requests() + #expect(requests[0].target.contains("search=fixture%20%2B%26%2F")) + #expect(requests[0].target.contains("version=latest")) + #expect( + requests[1].target.contains("cursor=dev.example%2Ffixture%3A1.2.3%2Bbuild%20%26%20next%3D%25") + ) + #expect( + requests[2].target == "/private/v0.1/servers/dev.example%2Ffixture/versions/1.2.3%2Bbuild") + #expect(requests[3].target.hasSuffix("/versions/latest")) + #expect(requests.dropLast().allSatisfy { $0.authorization && $0.apiKey }) + #expect(requests.last?.authorization == false && requests.last?.apiKey == false) + #expect(requests.allSatisfy { !$0.cookie }) + #expect(try fixture.scopeContents() == before) + } + + @Test func requestsAdmitExplicitCredentialsAndRejectRedirectsBeforeForwarding() async throws { + let fixture = try await RegistryFixture.start() + for path in ["/cross-origin", "/same-origin"] { + let registry = try fixture.registry(path) + await #expect(throws: MCPRegistryError.redirectRejected) { + try await registry.search( + credentials: fixture.credentials, environment: fixture.environment) + } + } + #expect( + try fixture.requests().map(\.target) == [ + "/cross-origin/v0.1/servers?limit=20&version=latest", + "/same-origin/v0.1/servers?limit=20&version=latest", + ]) + let registry = try fixture.registry("/public") + await #expect(throws: MCPRegistryError.invalidCredentials) { + try await registry.search(credentials: ["Host": "other.example.invalid"]) + } + await #expect(throws: MCPRegistryError.invalidCredentials) { + try await registry.search(credentials: ["X-Key": "one\r\nInjected: two"]) + } + let unsecured = try MCPRegistry(endpoint: URL(string: "http://registry.example.invalid")!) + await #expect(throws: MCPRegistryError.invalidCredentials) { + try await unsecured.search(credentials: fixture.credentials, environment: fixture.environment) + } + #expect(throws: MCPRegistryError.invalidEndpoint) { + try MCPRegistry(endpoint: URL(string: "https://user:password@registry.example.invalid")!) + } + #expect(throws: MCPRegistryError.invalidEndpoint) { + try MCPRegistry(endpoint: URL(string: "https://registry.example.invalid/?key=one")!) + } + let page = try await registry.search(version: nil) + #expect(page.servers.count == 1) + let last = try #require(fixture.requests().last) + #expect(last.target == "/public/v0.1/servers?limit=20") + #expect(!last.authorization && !last.apiKey && !last.cookie) + } + + @Test func rejectsOversizeAndCancelsAnInFlightRequest() async throws { + let fixture = try await RegistryFixture.start() + let oversize = try fixture.registry("/large") + await #expect(throws: MCPRegistryError.responseTooLarge) { + try await oversize.search() + } + let slow = try fixture.registry("/slow") + let request = Task { try await slow.search() } + defer { request.cancel() } + let clock = ContinuousClock() + let deadline = clock.now + .seconds(3) + while try !fixture.requests().contains(where: { $0.target.hasPrefix("/slow/") }) { + try #require(clock.now < deadline) + try await Task.sleep(for: .milliseconds(10)) + } + request.cancel() + await #expect(throws: CancellationError.self) { try await request.value } + } + + @Test func selectedRemoteBecomesAProjectMCPDeclarationWithAReference() async throws { + let fixture = try await RegistryFixture.start() + let registry = try fixture.registry("/private") + let entry = try await registry.server( + named: "dev.example/fixture", credentials: fixture.credentials, + environment: fixture.environment) + let remote = try #require(entry.choices.first) + guard case .remote(let endpoint) = remote.source else { + Issue.record("Expected a remote choice") + return + } + #expect(endpoint?.absoluteString == "https://tools.example.invalid/v2/mcp") + #expect(remote.bindings.map(\.name) == ["Authorization", "X-Mode", "X-Profile"]) + #expect(remote.bindings.first?.isRequired == true && remote.bindings.first?.isSecret == true) + #expect(remote.bindings[1].defaultValue == "steady") + #expect(remote.bindings[2].defaultValue == "safe") + #expect(remote.bindings[2].choices == ["fast", "safe"]) + let environment = fixture.environment + let destination = try UpdateOperations.inspect(environment: environment) + #expect(throws: MCPRegistryError.missingBinding("Authorization")) { + try remote.select(named: "fixture", agents: [.codex], in: destination) + } + #expect(throws: MCPRegistryError.invalidBinding("Authorization")) { + try remote.select( + named: "fixture", agents: [.codex], in: destination, + bindings: ["Authorization": .environment("Bearer raw-token")]) + } + let defaults = ["Authorization": MCPRegistryBinding.environment("FIXTURE_SERVICE_AUTH")] + #expect(throws: MCPRegistryError.missingBinding("X-Profile")) { + try remote.compatibleAgents(in: .project, bindings: defaults) + } + #expect(throws: MCPRegistryError.invalidBinding("X-Profile")) { + try remote.compatibleAgents( + in: .project, + bindings: defaults.merging(["X-Profile": .choice("unknown")]) { _, new in new } + ) + } + let defaultRequest = try remote.select( + named: "fixture-default", agents: [.codex], in: destination, + bindings: defaults.merging(["X-Profile": .choice("safe")]) { _, new in new } + ).updateRequest() + let defaultPreview = try UpdateOperations.preview(defaultRequest, environment: environment) + #expect(defaultPreview.components.first?.symbolicAfter?.contains("steady") == true) + + let references: [String: MCPRegistryBinding] = [ + "Authorization": .environment("FIXTURE_SERVICE_AUTH"), "X-Profile": .choice("fast"), + "X-Mode": .environment("FIXTURE_MODE"), + ] + #expect( + Set(try remote.compatibleAgents(in: .project, bindings: references)) + == [.codex, .claudeCode, .geminiCLI]) + #expect(throws: (any Error).self) { + try remote.select( + named: "fixture", agents: [.opencode], in: destination, bindings: references) + } + let sse = try #require(entry.choices.first { $0.transport == "sse" }) + #expect(Set(try sse.compatibleAgents(in: .project)) == [.claudeCode, .geminiCLI]) + let sseRequest = try sse.select(named: "legacy", agents: [.claudeCode], in: destination) + .updateRequest() + let ssePreview = try UpdateOperations.preview(sseRequest, environment: environment) + #expect(ssePreview.components.first?.symbolicAfter?.contains("sse") == true) + + // A registry response can change after selection. Publication uses the captured choice. + let discovery = try remote.select( + named: "fixture", agents: [.codex, .claudeCode], in: destination, + bindings: references) + let request = discovery.updateRequest() + let requestsBefore = try fixture.requests().count + let before = try fixture.scopeContents() + try fixture.replaceRegistryEndpoint(with: "https://replacement.example.invalid") + let refreshed = try await registry.server( + named: entry.name, version: entry.version, credentials: fixture.credentials, + environment: fixture.environment) + #expect( + try #require(refreshed.choices.first).sourceEndpoint?.host == "replacement.example.invalid") + let report = try UpdateOperations.preview(request, environment: environment) + #expect(report.hasChanges && report.components.count == 2) + #expect( + report.components.allSatisfy { + $0.name == "fixture" && !$0.privateMaterialization + && $0.symbolicAfter?.contains("FIXTURE_SERVICE_AUTH") == true + }) + #expect(try fixture.scopeContents() == before) + + _ = try UpdateOperations.withPreparedUpdate(request, environment: environment) { + try $0.apply(ifUnchangedFrom: report.displayedFingerprint) + } + let state = try UpdateOperations.inspect(environment: environment) + let transport = MCPTransportDeclaration.streamableHTTP( + url: "https://tools.example.invalid/v2/mcp", + headers: [ + "Authorization": .environment("FIXTURE_SERVICE_AUTH"), "X-Schema": .literal("2"), + "X-Mode": .environment("FIXTURE_MODE"), "X-Profile": .literal("fast"), + ]) + let evidence = try #require(state.components.first?.mcpRegistry) + #expect( + state.declaration?.components == [ + .mcpServer( + name: "fixture", transport: transport, agents: [.codex, .claudeCode], registry: evidence) + ]) + #expect(evidence.registry == registry.endpoint.absoluteString) + #expect(evidence.server == entry.name && evidence.version == entry.version) + #expect(evidence.origin == "https://tools.example.invalid" && evidence.package == nil) + #expect(try evidence.portableLiteralBindings(in: transport) == ["X-Schema", "X-Profile"]) + #expect(state.components.first?.version == entry.version) + let exportedPackage = BundlePackage(name: "shared-remote", version: "1.0.0") + #expect(throws: CoreError.self) { + try BundleOperations.export( + exportedPackage, selections: state.components.map(\.selection), scope: .project, + environment: environment, registrySchemas: [refreshed]) + } + let portable = try BundleOperations.inspect( + BundleOperations.export( + exportedPackage, selections: state.components.map(\.selection), scope: .project, + environment: environment, registrySchemas: [entry])) + #expect( + portable.components.first?.transport + == .streamableHTTP( + url: "https://tools.example.invalid/v2/mcp", + headers: [ + "Authorization": .environment("FIXTURE_SERVICE_AUTH"), "X-Schema": .literal("2"), + "X-Mode": .environment("FIXTURE_MODE"), "X-Profile": .literal("fast"), + ])) + let home = environment.homeDirectory + #expect( + !FileManager.default.fileExists( + atPath: home.appendingPathComponent(".codex/config.toml").path)) + let codex = try fixture.text("project/.codex/config.toml") + #expect(codex.contains("https://tools.example.invalid/v2/mcp")) + #expect(codex.contains("env_http_headers") && codex.contains("FIXTURE_SERVICE_AUTH")) + let claude = try fixture.text("project/.mcp.json") + #expect(claude.contains("\"Authorization\": \"${FIXTURE_SERVICE_AUTH}\"")) + #expect(try fixture.requests().count == requestsBefore + 1) + try fixture.checkPublishedValues(scope: .project, native: [codex, claude]) + } + + @Test func scopePolicyChecksTheRegistryAndSelectedEndpointThroughReplay() async throws { + let fixture = try await RegistryFixture.start() + let registry = try fixture.registry("/public") + let environment = fixture.environment + let store = StateStore(scope: .project, environment: environment) + let projectPolicy = SourcePolicyOperations.policyURL(scope: .project, environment: environment) + let userPolicy = SourcePolicyOperations.policyURL(scope: .user, environment: environment) + let registryOrigin = try SourceOrigin.http(registry.endpoint.absoluteString) + let endpointOrigin = try SourceOrigin.http("https://tools.example.invalid") + try fixture.writePolicy("deny: [{http: '\(registry.endpoint.absoluteString)'}]", to: userPolicy) + await #expect(throws: SourcePolicyFailure.self) { + try await registry.server(named: "dev.example/fixture", environment: environment) + } + #expect(try fixture.requests().isEmpty) + try FileManager.default.removeItem(at: userPolicy) + let entry = try await registry.server( + named: "dev.example/fixture", environment: fixture.environment) + let remote = try #require(entry.choices.first) + let destination = try UpdateOperations.inspect(environment: environment) + let bindings: [String: MCPRegistryBinding] = [ + "Authorization": .environment("FIXTURE_SERVICE_AUTH"), "X-Profile": .choice("safe"), + ] + try fixture.writePolicy( + "allow: [inline, {http: '\(registry.endpoint.absoluteString)'}]\n" + + "deny: [{http: 'https://tools.example.invalid'}]", to: projectPolicy) + let before = try fixture.scopeContents() + do { + _ = try remote.select(named: "fixture", agents: [.codex], in: destination, bindings: bindings) + Issue.record("Selected a server with a denied endpoint") + } catch let failure as SourcePolicyFailure { + #expect(failure.violations.map(\.origin) == [endpointOrigin]) + #expect(failure.violations.map(\.reason) == [.denied]) + } + #expect(try fixture.scopeContents() == before) + let allowed = + "allow: [{http: '\(registry.endpoint.absoluteString)'}, " + + "{http: 'https://tools.example.invalid'}]" + try fixture.writePolicy(allowed, to: projectPolicy) + let request = try remote.select( + named: "fixture", agents: [.codex], in: destination, bindings: bindings + ).updateRequest() + let preview = try UpdateOperations.preview(request, environment: environment) + try fixture.writePolicy("deny: [{http: '\(registry.endpoint.absoluteString)'}]", to: userPolicy) + do { + _ = try UpdateOperations.withPreparedUpdate(request, environment: environment) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + Issue.record("Published a selection after its registry was denied") + } catch let failure as SourcePolicyFailure { + #expect(failure.violations.map(\.origin) == [registryOrigin]) + #expect(failure.violations.map(\.scope) == [.user]) + } + #expect(try fixture.snapshot(environment: environment).isEmpty) + try FileManager.default.removeItem(at: userPolicy) + _ = try UpdateOperations.withPreparedUpdate(request, environment: environment) { update in + try update.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + let ledger = try store.loadLedger() + let component = try #require(ledger.components.values.first) + #expect(component.version == entry.version) + #expect(component.mcpRegistry?.registry == registry.endpoint.absoluteString) + #expect(component.mcpRegistry?.origin == endpointOrigin.identity) + #expect(try SourcePolicyOperations.audit(environment: environment).violations.isEmpty) + + var restricted = environment + let organization = fixture.root.appendingPathComponent("team-policy.yaml") + try fixture.writePolicy("deny: [{http: 'https://tools.example.invalid'}]", to: organization) + restricted.organizationSourcePolicyURL = organization + let audit = try SourcePolicyOperations.audit(environment: restricted) + #expect(audit.violations.map(\.scope) == [.organization]) + #expect(audit.violations.map(\.origin) == [endpointOrigin]) + let installed = try fixture.snapshot(environment: restricted) + #expect(throws: SourcePolicyFailure.self) { + try UpdateOperations.preview(environment: restricted) + } + #expect(throws: SourcePolicyFailure.self) { + try UpdateOperations.restore(environment: restricted) + } + #expect(try fixture.snapshot(environment: restricted) == installed) + #expect(try fixture.requests().count == 1) + } + + @Test func forwardedRegistryBundleAndLocalTeamCatalogRetainOriginalOrigins() async throws { + let fixture = try await RegistryFixture.start() + let registry = try fixture.registry("/public") + let publisher = fixture.environment + let entry = try await registry.server( + named: "dev.example/fixture", environment: fixture.environment) + let choice = try #require(entry.choice(packageType: "npm")) + let request = try choice.select( + named: "team-server", agents: [.codex], in: UpdateOperations.inspect(environment: publisher), + bindings: [ + "FIXTURE_PACKAGE_TOKEN": .environment("FIXTURE_PACKAGE_TOKEN"), + "FIXTURE_LOG_LEVEL": .choice("info"), + ] + ).updateRequest() + _ = try UpdateOperations.withPreparedUpdate(request, environment: publisher) { try $0.apply() } + let publisherScope = try UpdateOperations.inspect(environment: publisher) + let evidence = try #require(publisherScope.components.first?.mcpRegistry) + #expect(evidence.package == "@fixture/tools@2.0.0") + let package = BundlePackage(name: "team-kit", version: "1.0.0") + let offlineExport = try BundleOperations.export( + package, selections: publisherScope.components.map(\.selection), scope: .project, + environment: publisher) + let bytes = try BundleOperations.export( + package, selections: publisherScope.components.map(\.selection), scope: .project, + environment: publisher, registrySchemas: [entry]) + try fixture.replaceRegistryEndpoint( + "https://npm.example.invalid", with: "https://npm.example.invalid/other-index") + let otherIndex = try await registry.server( + named: entry.name, version: entry.version, + environment: publisher) + #expect(throws: CoreError.self) { + try BundleOperations.export( + package, selections: publisherScope.components.map(\.selection), scope: .project, + environment: publisher, registrySchemas: [otherIndex]) + } + #expect(offlineExport == bytes) + let bundle = try BundleOperations.inspect(bytes) + let member = try #require(bundle.components.first) + #expect(member.mcpRegistry == evidence) + guard case .stdio(let run) = member.transport else { + Issue.record("Expected a captured stdio server") + return + } + #expect(run.environment["FIXTURE_LOG_LEVEL"] == .literal("info")) + #expect(run.environment["FIXTURE_PACKAGE_TOKEN"] == .environment("FIXTURE_PACKAGE_TOKEN")) + let authorCapture = try AuthorPackageOperations.preview( + .init( + package: package, lockedMembers: [.init(kind: .mcpServer, name: "team-server")]), + environment: publisher) + #expect(authorCapture.inspection.components.first?.transport == member.transport) + #expect(authorCapture.warnings.isEmpty) + let reviewFile = fixture.root.appendingPathComponent("author-review.bundle") + try AuthorPackageOperations.write(authorCapture, to: reviewFile, environment: publisher) + let reread = try AuthorPackageOperations.readArchive( + at: reviewFile, expectedDigest: authorCapture.digest, environment: publisher) + #expect(reread.archive == authorCapture.archive) + #expect( + Set(member.sources.compactMap(\.origin)) + == Set( + try [ + SourceOrigin.http(registry.endpoint.absoluteString), SourceOrigin.http(evidence.origin), + ])) + + let consumer = try fixture.consumer("consumer") + let projectPolicy = SourcePolicyOperations.policyURL(scope: .project, environment: consumer) + let selections = [BundleImportSelection(componentID: member.id, targets: [.codex])] + try fixture.writePolicy( + "allow: [inline, local, {http: '\(registry.endpoint.absoluteString)'}]\n" + + "deny: [{http: '\(evidence.origin)'}]", to: projectPolicy) + #expect(throws: SourcePolicyFailure.self) { + try BundleOperations.previewImport( + bundle, selections: selections, scope: .project, environment: consumer) + } + #expect(try fixture.snapshot(environment: consumer).isEmpty) + + let catalog = fixture.root.appendingPathComponent("catalog") + try FileManager.default.createDirectory(at: catalog, withIntermediateDirectories: false) + let registration = try MarketplaceRegistration( + name: "team", origin: .init(kind: .directory, location: catalog.path)) + let release = try MarketplaceOperations.publishBundle( + bytes, to: catalog, environment: publisher) + let catalogOrigin = try #require(SourceOrigin.local(at: catalog).identity) + try fixture.writePolicy("deny: [{local: '\(catalogOrigin)'}]", to: projectPolicy) + do { + _ = try MarketplaceOperations.acquire(release, environment: consumer) + Issue.record("Acquired a release from a denied catalog") + } catch let failure as SourcePolicyFailure { + #expect(failure.violations.map(\.origin) == [.local(at: catalog)]) + #expect(failure.violations.map(\.reason) == [.denied]) + } + let allow = + "allow: [{local: '\(catalogOrigin)'}, " + + "{http: '\(registry.endpoint.absoluteString)'}, {http: '\(evidence.origin)'}]" + try fixture.writePolicy(allow, to: projectPolicy) + let listing = try MarketplaceOperations.browse(registration, environment: consumer) + let acquired = try MarketplaceOperations.acquire( + listing.select(package: package.name), environment: consumer) + #expect(acquired.archive == bytes) + let consumerStore = StateStore(scope: .project, environment: consumer) + try BundleInstallation.withStagedSources( + BundleOperations.inspect(acquired.archive), selections: selections, store: consumerStore + ) { installation in + var request = UpdateRequest() + request.bundleInstallation = installation + request = try acquired.bindingImport( + request, as: "team", sourceAliases: installation.members.map(\.alias)) + let preview = try UpdateOperations.preview(request, environment: consumer) + let denied = allow + "\ndeny: [{http: '\(evidence.origin)'}]" + try fixture.writePolicy(denied, to: projectPolicy) + #expect(throws: SourcePolicyFailure.self) { + try UpdateOperations.withPreparedUpdate(request, environment: consumer) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + } + #expect(try fixture.snapshot(environment: consumer).isEmpty) + try fixture.writePolicy(allow, to: projectPolicy) + _ = try UpdateOperations.withPreparedUpdate(request, environment: consumer) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + } + let installed = try UpdateOperations.inspect(environment: consumer) + #expect(installed.marketplacePackages.first?.catalogOrigin == .local(at: catalog)) + #expect(installed.components.first?.mcpRegistry == evidence) + let resourceSource = try #require(installed.components.first?.sourceRecord) + let sealed = try #require(consumerStore.loadLedger().sources[resourceSource]?.bundleSources) + #expect(sealed.contains { $0.origin == .local(at: catalog) }) + #expect(try SourcePolicyOperations.audit(environment: consumer).violations.isEmpty) + #expect(try !UpdateOperations.preview(environment: consumer).hasChanges) + + let forwarded = try BundleOperations.inspect( + BundleOperations.export( + .init(name: "forwarded-kit", version: "1.0.0"), + selections: installed.components.map(\.selection), + scope: .project, environment: consumer, registrySchemas: [entry])) + let forwardedMember = try #require(forwarded.components.first) + #expect(forwardedMember.mcpRegistry == evidence) + #expect(Set(member.sources).isSubset(of: Set(forwardedMember.sources))) + #expect(forwardedMember.sources.contains { $0.origin == .local(at: catalog) }) + #expect( + forwardedMember.sources.contains { + $0.packageName == package.name && $0.version == package.version + && $0.revision == bundle.archiveDigest && $0.origin == .local(at: catalog) + }) + + let second = try fixture.consumer("second") + let secondPolicy = SourcePolicyOperations.policyURL(scope: .project, environment: second) + let forwardedSelections = [ + BundleImportSelection( + componentID: forwardedMember.id, targets: [.codex]) + ] + try fixture.writePolicy(allow + "\ndeny: [{local: '\(catalogOrigin)'}]", to: secondPolicy) + #expect(throws: SourcePolicyFailure.self) { + try BundleOperations.previewImport( + forwarded, selections: forwardedSelections, scope: .project, environment: second) + } + #expect(try fixture.snapshot(environment: second).isEmpty) + try fixture.writePolicy(allow, to: secondPolicy) + let org = fixture.root.appendingPathComponent("recipient-organization.yaml") + var deniedRecipient = second + deniedRecipient.projectOrganizationPolicy = .init(.local(org)) + try fixture.writePolicy( + "enforcement: block\ndependencies: {deny: ['_local/team-kit']}", to: org) + #expect(throws: OrganizationPolicyFailure.self) { + try BundleOperations.previewImport( + forwarded, selections: forwardedSelections, scope: .project, environment: deniedRecipient) + } + let reinstallation = try BundleOperations.previewImport( + forwarded, selections: forwardedSelections, scope: .project, environment: second) + _ = try BundleOperations.withPreparedImport(reinstallation) { try $0.apply() } + let before = try fixture.snapshot(environment: second) + try fixture.writePolicy(allow + "\ndeny: [{http: '\(evidence.origin)'}]", to: secondPolicy) + let violations = try SourcePolicyOperations.audit(environment: second).violations + #expect(Set(violations.map(\.origin)) == [try SourceOrigin.http(evidence.origin)]) + #expect(throws: SourcePolicyFailure.self) { try UpdateOperations.preview(environment: second) } + #expect(throws: SourcePolicyFailure.self) { try UpdateOperations.restore(environment: second) } + #expect(try fixture.snapshot(environment: second) == before) + #expect(!FileManager.default.fileExists(atPath: fixture.launchMarker.path)) + #expect(try fixture.requests().count == 2) + } + + @Test func selectedPackageRegistersInUserScopeWithoutLaunchingTheDeclaredCommand() async throws { + let fixture = try await RegistryFixture.start() + let registry = try fixture.registry("/public") + let entry = try await registry.server( + named: "dev.example/fixture", environment: fixture.environment) + let npm = try #require(entry.choice(packageType: "npm")) + let region = try #require(npm.bindings.first { $0.name == "FIXTURE_REGION" }) + let logLevel = try #require(npm.bindings.first { $0.name == "FIXTURE_LOG_LEVEL" }) + #expect(region.defaultValue == "us") + #expect(logLevel.choices == ["warn", "info"]) + #expect(throws: MCPRegistryError.missingBinding("FIXTURE_LOG_LEVEL")) { + try npm.compatibleAgents( + in: .user, bindings: ["FIXTURE_PACKAGE_TOKEN": .environment("FIXTURE_PACKAGE_TOKEN")]) + } + let references: [String: MCPRegistryBinding] = [ + "FIXTURE_PACKAGE_TOKEN": .environment("FIXTURE_PACKAGE_TOKEN"), + "FIXTURE_REGION": .environment("FIXTURE_REGION"), + "FIXTURE_LOG_LEVEL": .choice("info"), + ] + #expect( + Set(try npm.compatibleAgents(in: .user, bindings: references)) + == [.codex, .claudeCode, .geminiCLI]) + #expect( + Set( + try npm.compatibleAgents( + in: .user, + bindings: [ + "FIXTURE_PACKAGE_TOKEN": .environment("RENAMED_TOKEN"), + "FIXTURE_LOG_LEVEL": .choice("warn"), + ])) + == [.claudeCode, .geminiCLI]) + + let environment = fixture.environment + let destination = try UpdateOperations.inspect(scope: .user, environment: environment) + let discovery = try npm.select( + named: "pkg", agents: [.codex], in: destination, bindings: references) + let request = discovery.updateRequest() + #expect(throws: (any Error).self) { + try UpdateOperations.preview(request, scope: .project, environment: environment) + } + var changed = request + changed.operation = .declaration(.init()) + #expect(throws: (any Error).self) { + try UpdateOperations.preview(changed, scope: .user, environment: environment) + } + let report = try UpdateOperations.preview(request, scope: .user, environment: environment) + #expect(report.components.first?.symbolicAfter?.contains("@fixture/tools@2.0.0") == true) + #expect(try fixture.scopeContents().allSatisfy { $0.hasPrefix("launcher/") }) + _ = try UpdateOperations.withPreparedUpdate(request, scope: .user, environment: environment) { + try $0.apply(ifUnchangedFrom: report.displayedFingerprint) + } + let config = try fixture.text("home/.codex/config.toml") + #expect(config.contains("npx") && config.contains("@fixture/tools@2.0.0")) + #expect(config.contains("--port=8080") && config.contains("stdio-start")) + #expect(config.contains("FIXTURE_PACKAGE_TOKEN") && config.contains("env_vars")) + #expect(config.contains("FIXTURE_REGION") && config.contains("FIXTURE_LOG_LEVEL")) + #expect(config.contains("\"info\"")) + #expect( + !FileManager.default.fileExists( + atPath: environment.projectDirectory.appendingPathComponent(".codex/config.toml").path)) + #expect(!FileManager.default.fileExists(atPath: fixture.launchMarker.path)) + try fixture.checkPublishedValues(scope: .user, native: [config]) + #expect(!(try UpdateOperations.preview(scope: .user, environment: environment)).hasChanges) + } + + @Test func packageChoicesPreserveExactCoordinatesAndReportUnsupportedVariants() async throws { + let fixture = try await RegistryFixture.start() + let entry = try await fixture.registry("/public").server( + named: "dev.example/fixture", environment: fixture.environment) + let environment = fixture.environment + let destination = try UpdateOperations.inspect(environment: environment) + let python = try #require(entry.choice(packageType: "pypi")) + #expect(python.requiresPackageCommand) + #expect(throws: MCPRegistryError.missingPackageCommand) { + try python.compatibleAgents(in: .project) + } + #expect(throws: MCPRegistryError.invalidPackageCommand) { + try python.compatibleAgents(in: .project, packageCommand: "../fixture-weather") + } + for (type, command, expected) in [ + ("pypi", Optional("fixture-weather"), ["uvx", "fixture_tools==2.3.0", "fixture-weather"]), + ("oci", nil, ["docker", "ghcr.io/fixture/registry-mcp:3.5.0", "-i"]), + ] { + let selected = try #require(entry.choice(packageType: type)) + for scope in [InstallScope.project, .user] { + #expect( + try selected.compatibleAgents(in: scope, packageCommand: command).contains(.antigravity)) + } + let request = try selected.select( + named: type, agents: [.codex], in: destination, packageCommand: command + ).updateRequest() + let report = try UpdateOperations.preview(request, environment: environment) + let rendered = try #require(report.components.first?.symbolicAfter) + #expect(expected.allSatisfy { rendered.contains($0) }) + } + #expect(entry.choice(packageType: "mcpb")?.unavailableReason?.contains("checksum") == true) + #expect(entry.choices.filter { $0.unavailableReason != nil }.count == 5) + let interactive = try #require( + entry.choices.first { + if case .package(let package) = $0.source { + return package.identifier == "@fixture/interactive" + } + return false + }) + #expect(interactive.unavailableReason?.contains("argument") == true) + #expect(!FileManager.default.fileExists(atPath: fixture.launchMarker.path)) + } +} + +extension MCPRegistryChoice { + fileprivate var sourceEndpoint: URL? { + if case .remote(let endpoint) = source { return endpoint } + return nil + } +} + +extension MCPRegistryServer { + fileprivate func choice(packageType: String) -> MCPRegistryChoice? { + choices.first { + if case .package(let package) = $0.source { return package.registryType == packageType } + return false + } + } +} + +private final class RegistryFixture { + struct Request: Decodable { + let target: String + let authorization: Bool + let apiKey: Bool + let cookie: Bool + } + + let root: URL + let environment: RuntimeEnvironment + let launchMarker: URL + let credentials = [ + "Authorization": "Bearer registry-request-canary", "X-Registry-Key": "registry-key-canary", + ] + private let process = Process() + private var port: Int? + + private init() throws { + root = FileManager.default.temporaryDirectory.appendingPathComponent( + "mcp-registry-" + UUID().uuidString) + let launcher = root.appendingPathComponent("launcher") + launchMarker = launcher.appendingPathComponent("started") + environment = RuntimeEnvironment( + projectDirectory: root.appendingPathComponent("project"), + homeDirectory: root.appendingPathComponent("home"), + environment: [ + "PATH": launcher.path + ":/usr/bin:/bin", + "FIXTURE_SERVICE_AUTH": "Bearer service-runtime-canary", + "FIXTURE_PACKAGE_TOKEN": "package-runtime-canary", + "FIXTURE_REGION": "region-runtime-canary", + ]) + for directory in [launcher, environment.projectDirectory, environment.homeDirectory] { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + } + for command in ["npx", "uvx", "docker"] { + let executable = launcher.appendingPathComponent(command) + try Data("#!/bin/sh\ntouch '\(launchMarker.path)'\n".utf8).write(to: executable) + try FileManager.default.setAttributes( + [.posixPermissions: 0o755], ofItemAtPath: executable.path) + } + try Data(Self.response.utf8).write(to: root.appendingPathComponent("response.json")) + try Data().write(to: root.appendingPathComponent("requests.jsonl")) + } + + static func start() async throws -> RegistryFixture { + let fixture = try RegistryFixture() + fixture.process.executableURL = URL(fileURLWithPath: "/usr/bin/env") + fixture.process.arguments = ["python3", "-c", server, fixture.root.path] + fixture.process.standardOutput = FileHandle.nullDevice + fixture.process.standardError = FileHandle.nullDevice + try fixture.process.run() + let clock = ContinuousClock() + let deadline = clock.now + .seconds(3) + while fixture.process.isRunning { + if let value = try? fixture.text("port"), let port = Int(value), (1...65535).contains(port) { + fixture.port = port + return fixture + } + // A resumed test may observe a readiness file published while it was suspended. + guard clock.now < deadline else { break } + try await Task.sleep(for: .milliseconds(10)) + } + throw CoreError.invalidState("registry HTTP fixture did not start") + } + + deinit { + if process.isRunning { + do { try ProcessWait.terminate(process, timeout: 3) } catch { Issue.record(error) } + } + try? FileManager.default.removeItem(at: root) + } + + func consumer(_ name: String) throws -> RuntimeEnvironment { + let environment = RuntimeEnvironment( + projectDirectory: root.appendingPathComponent(name), + homeDirectory: root.appendingPathComponent(name + "-home"), environment: [:]) + for directory in [environment.projectDirectory, environment.homeDirectory] { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false) + } + return environment + } + + func writePolicy(_ rules: String, to url: URL) throws { + try FileManager.default.createDirectory( + at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data(("version: 1\n" + rules + "\n").utf8).write(to: url, options: .atomic) + } + + func snapshot(environment: RuntimeEnvironment) throws -> [URL: Data] { + let store = StateStore(scope: .project, environment: environment) + let files = [ + store.declarationURL, store.resolvedURL, + environment.projectDirectory.appendingPathComponent(".codex/config.toml"), + ] + return try Dictionary( + uniqueKeysWithValues: files.compactMap { url in + FileManager.default.fileExists(atPath: url.path) ? (url, try Data(contentsOf: url)) : nil + }) + } + + func registry(_ path: String) throws -> MCPRegistry { + try MCPRegistry(endpoint: URL(string: "http://127.0.0.1:\(try #require(port))" + path)!) + } + + func text(_ path: String) throws -> String { + try String(contentsOf: root.appendingPathComponent(path), encoding: .utf8) + } + + func requests() throws -> [Request] { + try text("requests.jsonl").split(separator: "\n").map { + try JSONDecoder().decode(Request.self, from: Data($0.utf8)) + } + } + + func scopeContents() throws -> [String] { + try ["project", "home", "launcher"].flatMap { prefix in + let contents = try FileManager.default.subpathsOfDirectory( + atPath: root.appendingPathComponent(prefix).path) + return contents.sorted().map { prefix + "/" + $0 } + } + } + + func replaceRegistryEndpoint( + _ original: String = "https://tools.example.invalid", with replacement: String + ) throws { + let modified = Self.response.replacingOccurrences( + of: original, with: replacement) + try Data(modified.utf8).write( + to: root.appendingPathComponent("response.json"), options: .atomic) + } + + func checkPublishedValues(scope: InstallScope, native: [String]) throws { + let store = StateStore(scope: scope, environment: environment) + let texts = + try native + + [store.declarationURL, store.resolvedURL].map { + try String(contentsOf: $0, encoding: .utf8) + } + for canary in [ + "registry-request-canary", "registry-key-canary", "service-runtime-canary", + "package-runtime-canary", "region-runtime-canary", "publisher-has-secret", + ] { + #expect(!texts.contains(where: { $0.contains(canary) })) + } + } + + private static let response = #""" + { + "server": { + "name": "dev.example/fixture", "title": "Fixture tools", + "description": "An independently authored v0.1 fixture.", "version": "1.2.3+build", + "remotes": [ + {"type": "streamable-http", "url": "https://tools.example.invalid/{route}/mcp", + "variables": {"route": {"value": "v2"}}, + "headers": [ + {"name": "Authorization", "isRequired": true, "isSecret": true, + "value": "Bearer {token}", "variables": {"token": {"default": "publisher-has-secret", "isSecret": true}}}, + {"name": "X-Schema", "value": "2"}, + {"name": "X-Mode", "default": "steady", "isRequired": true}, + {"name": "X-Profile", "default": "safe", "choices": ["fast", "safe"]} + ]}, + {"type": "sse", "url": "https://tools.example.invalid/events"}, + {"type": "streamable-http", "url": "https://tools.example.invalid/mcp?api_key=publisher-has-secret"}, + {"type": "streamable-http", "url": "https://{tenant}.example.invalid/mcp", + "variables": {"tenant": {"isRequired": true, "default": "can-change"}}} + ], + "packages": [ + {"registryType": "npm", "identifier": "@fixture/tools", "version": "2.0.0", + "runtimeHint": "npx", "registryBaseUrl": "https://npm.example.invalid", + "transport": {"type": "stdio"}, + "packageArguments": [{"type": "positional", "value": "stdio-start"}, + {"type": "named", "name": "--port", "value": "{port}", + "variables": {"port": {"value": "8080"}}}], + "environmentVariables": [{"name": "FIXTURE_PACKAGE_TOKEN", "isRequired": true, "isSecret": true, + "value": "publisher-has-secret"}, + {"name": "FIXTURE_REGION", "default": "us"}, + {"name": "FIXTURE_LOG_LEVEL", "choices": ["warn", "info"]}]}, + {"registryType": "npm", "identifier": "@fixture/interactive", "version": "2.0.0", + "transport": {"type": "stdio"}, + "packageArguments": [{"type": "named", "name": "--port", "isRequired": true, "default": "8080"}]}, + {"registryType": "pypi", "identifier": "fixture_tools", "version": "2.3.0", + "transport": {"type": "stdio"}}, + {"registryType": "oci", "identifier": "ghcr.io/fixture/registry-mcp:3.5.0", + "transport": {"type": "stdio"}}, + {"registryType": "oci", "identifier": ":", "transport": {"type": "stdio"}}, + {"registryType": "mcpb", "identifier": "https://tools.example.invalid/tools.mcpb", + "fileSha256": "80084795b3b4df6264cc2d2ace29f4b04ce1451a83d66cd22c8792f24f4bff63", + "transport": {"type": "stdio"}} + ] + }, + "_meta": {"io.modelcontextprotocol.registry/official": {"status": "active", "isLatest": true}} + } + """# + + private static let server = #""" + import http.server, json, pathlib, sys, threading, time, urllib.parse + root = pathlib.Path(sys.argv[1]) + + class Handler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + path = urllib.parse.urlsplit(self.path) + auth = self.headers.get("Authorization") == "Bearer registry-request-canary" + api = self.headers.get("X-Registry-Key") == "registry-key-canary" + cookie = self.headers.get("Cookie") is not None + with (root / "requests.jsonl").open("a") as records: + records.write(json.dumps(dict(target=self.path, authorization=auth, apiKey=api, cookie=cookie)) + "\n") + if path.path.startswith("/cross-origin/"): + return self.reply(302, Location=f"http://127.0.0.1:{sink.server_port}/sink") + if path.path.startswith("/same-origin/"): + return self.reply(307, Location="/sink") + if path.path == "/sink": + return self.reply(200, b'{"servers":[]}') + if path.path.startswith("/large/"): + self.send_response(200) + self.end_headers() + for part in range(9): + self.wfile.write(b"x" * (1024 * 1024)) + return + if path.path.startswith("/slow/"): + time.sleep(15) + return + if path.path.startswith("/private/") and not (auth and api): + return self.reply(401, b'{"error":"Credentials are needed"}') + entry = json.loads((root / "response.json").read_text()) + if "/v0.1/servers/" in path.path: + result = entry + else: + cursor = urllib.parse.parse_qs(path.query).get("cursor") + result = {"servers": [] if cursor else [entry], "metadata": { + "nextCursor": "" if cursor else "dev.example/fixture:1.2.3+build & next=%" + }} + self.reply(200, json.dumps(result).encode(), **{"Set-Cookie": "ambient=ignored; Path=/"}) + + def reply(self, status, body=b"", **headers): + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + for name, value in headers.items(): + self.send_header(name, value) + self.end_headers() + self.wfile.write(body) + + sink = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) + main = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) + threading.Thread(target=sink.serve_forever, daemon=True).start() + (root / "port").write_text(str(main.server_port)) + main.serve_forever() + """# +} diff --git a/Tests/AgentsUpdatesTests/MarketplaceDirectoryTests.swift b/Tests/AgentsUpdatesTests/MarketplaceDirectoryTests.swift new file mode 100644 index 0000000..ef2ebed --- /dev/null +++ b/Tests/AgentsUpdatesTests/MarketplaceDirectoryTests.swift @@ -0,0 +1,39 @@ +import AgentsCore +import AgentsUpdates +import Foundation +import Testing + +@Suite struct MarketplaceDirectoryTests { + @Test func scopedCatalogsResolveAtTheirOwnerAndRevealInheritedRegistrationOnRemoval() throws { + let f = try UpdateFixture() + let env = f.environment + let user = try MarketplaceRegistration( + name: "tools", origin: .init(kind: .directory, location: "team")) + let project = try MarketplaceRegistration( + name: "tools", + origin: .init(kind: .git, location: "./producer", ref: "stable", subpath: "market")) + #expect(try MarketplaceDirectory.list(scope: .project, environment: env).isEmpty) + #expect(!FileManager.default.fileExists(atPath: f.store.directory.path)) + try MarketplaceDirectory.register(user, scope: .user, environment: env) + let inherited = try MarketplaceDirectory.lookup("tools", scope: .project, environment: env) + #expect(inherited.origin.location == env.homeDirectory.appendingPathComponent("team").path) + try MarketplaceDirectory.register(project, scope: .project, environment: env) + #expect( + try MarketplaceDirectory.list(scope: .project, environment: env).map(\.scope) == [.project]) + #expect(try MarketplaceDirectory.lookup("tools", scope: .project, environment: env) == project) + try MarketplaceDirectory.register(project, scope: .project, environment: env) + #expect(throws: MarketplaceError.self) { + try MarketplaceDirectory.register(user, scope: .project, environment: env) + } + try MarketplaceDirectory.unregister("tools", scope: .project, environment: env) + #expect( + try MarketplaceDirectory.lookup("tools", scope: .project, environment: env) == inherited) + #expect(!FileManager.default.fileExists(atPath: f.store.resolvedURL.path)) + let file = f.store.directory.appendingPathComponent("marketplaces.yaml") + try Data("tools: {git: https://example.com/a/b, ref: main, unknown: true}\n".utf8).write( + to: file) + #expect(throws: MarketplaceError.self) { + try MarketplaceDirectory.list(scope: .project, environment: env) + } + } +} diff --git a/Tests/AgentsUpdatesTests/MarketplaceResolutionTests.swift b/Tests/AgentsUpdatesTests/MarketplaceResolutionTests.swift new file mode 100644 index 0000000..8a22645 --- /dev/null +++ b/Tests/AgentsUpdatesTests/MarketplaceResolutionTests.swift @@ -0,0 +1,939 @@ +import AgentsCore +import AgentsManifest +import AgentsUpdates +import Foundation +import Testing + +@Suite("Marketplace dependency resolution") +struct MarketplaceResolutionTests { + @Test func verifiesEveryCatalogArchiveWithoutInstalling() throws { + let market = try GraphCatalog() + let first = try market.publish("handbook", "1.0.0") + try market.publish("handbook", "1.1.0") + let consumer = try UpdateFixture() + let registration = try MarketplaceRegistration(name: "team", origin: market.origin) + let report = try MarketplaceOperations.verifyCatalog( + registration, environment: consumer.environment) + #expect(report.releases.map(\.coordinate.version) == ["1.1.0", "1.0.0"]) + let file = market.catalog.appendingPathComponent(first.coordinate.releasePath) + .appendingPathComponent("package.bundle") + var bytes = try Data(contentsOf: file) + bytes[bytes.startIndex] ^= 1 + try bytes.write(to: file) + #expect(throws: MarketplaceError.self) { + try MarketplaceOperations.verifyCatalog(registration, environment: consumer.environment) + } + #expect(!FileManager.default.fileExists(atPath: consumer.store.directory.path)) + } + + @Test func lockOnlyFreezesSelectedRecipientsAndDeploysInIndependentScopeWithoutCatalog() throws { + let market = try GraphCatalog() + try market.publish("shared", "1.0.0") + try market.publish("starter", "1.0.0", ["shared": .exact("1.0.0")]) + let project = try UpdateFixture() + let root = try market.root("main", package: "starter", recipient: .codex) + let preview = try MarketplaceOperations.previewLockOnly( + .install(root), environment: project.environment) + #expect(!FileManager.default.fileExists(atPath: project.store.directory.path)) + #expect(preview.report.deployedGraph == nil) + let firstGraph = try #require(preview.report.pendingDeployment.graph) + let member = try #require(firstGraph.nodes.first { $0.id.package == "shared" }?.members.first) + #expect(member.targets == [.codex]) + #expect(member.producerResource != nil) + + try MarketplaceOperations.writeLockOnly(preview) + let state = try UpdateOperations.inspect(environment: project.environment) + #expect(state.marketplaceIssue == nil) + #expect(state.marketplaceGraph == nil) + #expect(state.deployments.isEmpty) + #expect(state.pendingMarketplaceDeployment?.graph == firstGraph) + #expect(!FileManager.default.fileExists(atPath: project.target().path)) + #expect( + !FileManager.default.fileExists( + atPath: project.store.directory.appendingPathComponent("bundles").path)) + let audit = try OrganizationPolicyOperations.audit(environment: project.environment) + #expect(audit.pendingMarketplaceDeployment) + #expect(audit.closureIssue == nil) + #expect(audit.isBlocked) + #expect(throws: MarketplaceError.pendingDeployment) { + try UpdateOperations.restore(environment: project.environment) + } + + let extra = try market.root("extra", package: "starter", recipient: .antigravity) + let revised = try MarketplaceOperations.previewLockOnly( + .install(extra), environment: project.environment) + let desired = try #require(revised.report.pendingDeployment.graph) + #expect( + Set(desired.nodes.first { $0.id.package == "shared" }?.members.first?.targets ?? []) + == [.codex, .antigravity]) + try MarketplaceOperations.writeLockOnly(revised) + #expect(!FileManager.default.fileExists(atPath: project.target(.antigravity).path)) + + let independent = try UpdateFixture() + for file in [project.store.declarationURL, project.store.resolvedURL] { + try independent.write( + String(contentsOf: file, encoding: .utf8), + to: independent.store.directory.appendingPathComponent(file.lastPathComponent)) + } + try FileManager.default.removeItem(at: market.catalog) + let deploy = try MarketplaceOperations.previewFrozenDeployment( + environment: independent.environment) + #expect(deploy.ownershipConflict == nil) + #expect(deploy.report.marketplaceGraphChange?.after == desired) + _ = try MarketplaceOperations.deployFrozen(deploy) + let result = try UpdateOperations.inspect(environment: independent.environment) + #expect(result.pendingMarketplaceDeployment == nil) + #expect(result.marketplaceGraph == desired) + let deployed = try #require( + result.deployments.first { + $0.location == independent.target() && $0.recipients.contains(.codex) + }) + #expect(deployed.status == .current) + #expect(result.marketplaceOwners(of: deployed).map(\.root) == ["main"]) + let extraTarget = try #require( + result.deployments.first { + $0.location == independent.target(.antigravity) && $0.recipients.contains(.antigravity) + }) + #expect(extraTarget.status == .current) + #expect(result.marketplaceOwners(of: extraTarget).map(\.root) == ["extra"]) + #expect(try !OrganizationPolicyOperations.audit(environment: independent.environment).isBlocked) + } + + @Test func lockOnlyUpgradeAndRemovalPreserveActualOwnershipUntilFrozenDeploy() throws { + let market = try GraphCatalog() + let range = SourceRequirement.upToNextMajor(from: "1.0.0") + try market.publish("shared", "1.0.0") + try market.publish("left", "1.0.0", ["shared": range]) + try market.publish("right", "1.0.0", ["shared": range]) + let project = try UpdateFixture() + let first = try market.root("one", package: "left", recipient: .codex) + let second = try market.root("two", package: "right", recipient: .claudeCode) + try apply(.install(first), project) + try apply(.install(second), project) + let deployed = try project.store.loadLedger() + let codex = project.target().appendingPathComponent("SKILL.md") + let claude = project.target(.claudeCode).appendingPathComponent("SKILL.md") + let old = try project.bytes(codex) + let manual = project.target().deletingLastPathComponent().appendingPathComponent("manual") + try project.write("personal", to: manual) + + try market.author.advance() + _ = try market.author.apply() + let producer = try UpdateOperations.inspect(environment: market.author.environment) + let refreshedSelection = try #require( + producer.components.first { $0.kind == .skills }?.selection) + let archive = try BundleOperations.export( + .init(name: "shared", version: "1.1.0"), selections: [refreshedSelection], + scope: .project, environment: market.author.environment) + try MarketplaceOperations.publishBundle(archive, to: market.catalog) + let upgrade = try MarketplaceOperations.previewLockOnly( + .upgrade("one"), environment: project.environment) + #expect(upgrade.report.marketplaceGraphChange?.affectedRoots == ["one", "two"]) + try MarketplaceOperations.writeLockOnly(upgrade) + var actual = try project.store.loadLedger() + actual.pendingDeployment = nil + #expect(actual == deployed) + #expect(try project.bytes(codex) == old) + #expect(try project.bytes(claude) == old) + #expect( + try UpdateOperations.inspect(environment: project.environment).deployments.allSatisfy { + $0.status == .current + }) + + let deployment = try MarketplaceOperations.previewFrozenDeployment( + environment: project.environment) + _ = try MarketplaceOperations.deployFrozen(deployment) + #expect(try project.bytes(codex) != old) + #expect(try project.bytes(codex) == project.bytes(claude)) + try FileManager.default.removeItem(at: market.catalog) + let removal = try MarketplaceOperations.previewLockOnly( + .remove("one"), environment: project.environment) + try MarketplaceOperations.writeLockOnly(removal) + #expect(FileManager.default.fileExists(atPath: codex.path)) + #expect(FileManager.default.fileExists(atPath: claude.path)) + let originalLink = try FileManager.default.destinationOfSymbolicLink( + atPath: project.target().path) + try FileManager.default.removeItem(at: project.target()) + try project.write("unmanaged replacement", to: codex) + let occupied = try MarketplaceOperations.previewFrozenDeployment( + environment: project.environment) + #expect(occupied.ownershipConflict != nil) + #expect(throws: CoreError.self) { try MarketplaceOperations.deployFrozen(occupied) } + #expect(try project.bytes(codex) == Data("unmanaged replacement".utf8)) + try FileManager.default.removeItem(at: project.target()) + try FileManager.default.createSymbolicLink( + atPath: project.target().path, withDestinationPath: originalLink) + let removeFirst = try MarketplaceOperations.previewFrozenDeployment( + environment: project.environment) + _ = try MarketplaceOperations.deployFrozen(removeFirst) + #expect(!FileManager.default.fileExists(atPath: codex.path)) + #expect(FileManager.default.fileExists(atPath: claude.path)) + + let removeLast = try MarketplaceOperations.previewLockOnly( + .remove("two"), environment: project.environment) + try MarketplaceOperations.writeLockOnly(removeLast) + let beforeLast = try UpdateOperations.inspect(environment: project.environment) + #expect(beforeLast.pendingMarketplaceDeployment != nil) + #expect(beforeLast.pendingMarketplaceDeployment?.graph == nil) + #expect(beforeLast.marketplaceGraph?.roots.map(\.intent.name) == ["two"]) + #expect(FileManager.default.fileExists(atPath: claude.path)) + let deployLast = try MarketplaceOperations.previewFrozenDeployment( + environment: project.environment) + _ = try MarketplaceOperations.deployFrozen(deployLast) + #expect(!FileManager.default.fileExists(atPath: claude.path)) + #expect(try project.bytes(manual) == Data("personal".utf8)) + #expect(try project.store.loadLedger().marketplaceGraph == nil) + } + + @Test func lockAndDeployRejectChangedGenerationAndPolicyBeforePublication() throws { + let market = try GraphCatalog() + try market.publish("shared", "1.0.0") + let project = try UpdateFixture() + let request = try MarketplaceResolutionRequest.install( + market.root("main", package: "shared", recipient: .codex)) + let policy = project.root.appendingPathComponent("org.yaml") + var environment = project.environment + environment.userOrganizationPolicy = .init(.local(policy)) + try project.write("enforcement: block", to: policy) + let allowed = try MarketplaceOperations.previewLockOnly(request, environment: environment) + try project.write("enforcement: block\nsources: {deny: [local]}", to: policy) + #expect(throws: OrganizationPolicyFailure.self) { + try MarketplaceOperations.writeLockOnly(allowed) + } + #expect(!FileManager.default.fileExists(atPath: project.store.directory.path)) + + try project.write("enforcement: block", to: policy) + try market.publish("shared", "1.1.0") + #expect(throws: CoreError.self) { try MarketplaceOperations.writeLockOnly(allowed) } + #expect(!FileManager.default.fileExists(atPath: project.store.directory.path)) + + let lock = try MarketplaceOperations.previewLockOnly(request, environment: environment) + try project.write("version: 1\n# changed\n", to: project.store.declarationURL) + let changed = try project.snapshot() + #expect(throws: CoreError.self) { try MarketplaceOperations.writeLockOnly(lock) } + #expect(try project.snapshot() == changed) + #expect( + !FileManager.default.fileExists( + atPath: project.store.directory.appendingPathComponent(".agents.lock").path)) + + try MarketplaceOperations.writeLockOnly( + MarketplaceOperations.previewLockOnly(request, environment: environment)) + let frozen = try MarketplaceOperations.previewFrozenDeployment(environment: environment) + let pending = try project.snapshot() + try project.write("enforcement: block\nsources: {deny: [local]}", to: policy) + #expect(throws: OrganizationPolicyFailure.self) { + try MarketplaceOperations.deployFrozen(frozen) + } + #expect(try project.snapshot() == pending) + try project.write("enforcement: block", to: policy) + let bytes = try String(contentsOf: project.store.declarationURL, encoding: .utf8) + try project.write(bytes + "\n# changed since review\n", to: project.store.declarationURL) + let stale = try project.snapshot() + #expect(throws: MarketplaceError.changedPendingDeclaration) { + try MarketplaceOperations.deployFrozen(frozen) + } + #expect(try project.snapshot() == stale) + let state = try UpdateOperations.inspect(environment: environment) + #expect(state.pendingMarketplaceDeployment != nil) + #expect(state.marketplaceIssue == .changedPendingDeclaration) + #expect(state.deployments.isEmpty) + } + + @Test func changesPendingRootsOfflineAfterRollbackWithoutTouchingOtherDeployments() throws { + enum Injected: Error { case publication } + let market = try GraphCatalog() + try market.publish("shared", "1.0.0") + let project = try UpdateFixture() + let untouched = project.repo.appendingPathComponent("skills/untouched") + try FileManager.default.moveItem( + at: project.repo.appendingPathComponent("skills/demo"), to: untouched) + let authoredSkill = untouched.appendingPathComponent("SKILL.md") + let authoredText = try String(contentsOf: authoredSkill, encoding: .utf8) + try project.write( + authoredText.replacingOccurrences(of: "name: demo", with: "name: untouched"), + to: authoredSkill) + try project.commit() + try project.install(agents: [.antigravity]) + let existing = project.target(.antigravity).deletingLastPathComponent() + .appendingPathComponent("untouched/SKILL.md") + let originalBytes = try project.bytes(existing) + let policy = project.root.appendingPathComponent("org.yaml") + try project.write("security: {audit: {fail_on_drift: true}}", to: policy) + var environment = project.environment + environment.userOrganizationPolicy = .init(.local(policy)) + let one = try market.root("one", package: "shared", recipient: .codex) + let two = try market.root("two", package: "shared", recipient: .claudeCode) + let preview = try MarketplaceOperations.previewLockOnly(.install(one), environment: environment) + let before = try project.snapshot() + do { + _ = try MarketplaceOperations.writeLockOnly(preview) { point in + if point == "publish.0.synced" { throw Injected.publication } + } + Issue.record("Expected lock publication to roll back.") + } catch let error as UpdateApplyError { + #expect(error.disposition == .unchanged) + #expect(error.underlyingError is Injected) + } + #expect(try project.snapshot() == before) + #expect(!(try UpdateOperations.inspect(environment: environment).recovery.pending)) + try MarketplaceOperations.writeLockOnly( + MarketplaceOperations.previewLockOnly(.install(one), environment: environment)) + try MarketplaceOperations.writeLockOnly( + MarketplaceOperations.previewLockOnly(.install(two), environment: environment)) + #expect(try project.bytes(existing) == originalBytes) + try FileManager.default.removeItem(at: market.catalog) + try MarketplaceOperations.writeLockOnly( + MarketplaceOperations.previewLockOnly(.remove("one"), environment: environment)) + let modified = originalBytes + Data("\nLocally edited deployment.\n".utf8) + try modified.write(to: existing) + let inspection = try UpdateOperations.inspect(environment: environment) + #expect(inspection.pendingMarketplaceDeployment?.graph?.roots.map(\.intent.name) == ["two"]) + #expect(inspection.marketplaceIssue == nil) + #expect( + inspection.deployments.contains { + $0.location.path == existing.deletingLastPathComponent().path && $0.status == .drifted + }) + let audit = try OrganizationPolicyOperations.audit(environment: environment) + #expect(audit.pendingMarketplaceDeployment) + #expect(audit.organization.findings.contains { $0.rule == "workspace-drift" }) + + let deploy = try MarketplaceOperations.previewFrozenDeployment(environment: environment) + _ = try MarketplaceOperations.deployFrozen(deploy) + #expect(!FileManager.default.fileExists(atPath: project.target().path)) + #expect(FileManager.default.fileExists(atPath: project.target(.claudeCode).path)) + #expect(try project.bytes(existing) == modified) + #expect( + !(try OrganizationPolicyOperations.audit(environment: environment) + .pendingMarketplaceDeployment)) + } + + @Test func bothSourceAllowlistsGateLockAndFrozenDeploy() throws { + let market = try GraphCatalog() + try market.publish("shared", "1.0.0") + let project = try UpdateFixture() + let request = try MarketplaceResolutionRequest.install( + market.root("main", package: "shared", recipient: .codex)) + let initial = try MarketplaceOperations.previewLockOnly( + request, environment: project.environment) + let userPolicy = SourcePolicyOperations.policyURL( + scope: .user, environment: project.environment) + let projectPolicy = SourcePolicyOperations.policyURL( + scope: .project, environment: project.environment) + try project.write("version: 1\ndeny: [local]\n", to: userPolicy) + #expect(throws: SourcePolicyFailure.self) { try MarketplaceOperations.writeLockOnly(initial) } + #expect(!FileManager.default.fileExists(atPath: project.store.directory.path)) + try FileManager.default.removeItem(at: userPolicy) + try MarketplaceOperations.writeLockOnly( + MarketplaceOperations.previewLockOnly(request, environment: project.environment)) + let deploy = try MarketplaceOperations.previewFrozenDeployment(environment: project.environment) + let previous = try project.snapshot() + try project.write("version: 1\ndeny: [local]\n", to: projectPolicy) + #expect(throws: SourcePolicyFailure.self) { try MarketplaceOperations.deployFrozen(deploy) } + #expect(try project.snapshot() == previous) + } + + @Test func frozenRemovalPreservesOtherRegionsInSharedNativeFile() throws { + let market = try GraphCatalog() + let component = ComponentDeclaration.mcpServer( + name: "marketplace", transport: .stdio(.init(executable: "never-run-marketplace")), + agents: [.claudeCode]) + let authorRequest = UpdateRequest(operation: .declaration(.init(components: [component]))) + try UpdateOperations.withPreparedUpdate(authorRequest, environment: market.author.environment) { + _ = try $0.apply() + } + let authorState = try UpdateOperations.inspect(environment: market.author.environment) + let item = try #require(authorState.components.first { $0.kind == .mcpServer }) + let archive = try BundleOperations.export( + .init(name: "servers", version: "1.0.0"), selections: [item.selection], + scope: .project, environment: market.author.environment) + try MarketplaceOperations.publishBundle(archive, to: market.catalog) + let root = try MarketplaceRoot( + name: "servers", catalog: market.origin, package: "servers", requirement: .exact("1.0.0"), + selections: [ + .init( + package: "servers", member: .init(kind: .mcpServer, name: "marketplace"), + targets: [.claudeCode]) + ]) + + let project = try UpdateFixture() + let config = project.root.appendingPathComponent(".mcp.json") + let manual = #""manual" : {"command": "never-run-manual"}"# + try project.write("{\"mcpServers\":{\(manual)}}\n", to: config) + let adjacent = ComponentDeclaration.mcpServer( + name: "adjacent", transport: .stdio(.init(executable: "never-run-adjacent")), + agents: [.claudeCode]) + let localRequest = UpdateRequest(operation: .declaration(.init(components: [adjacent]))) + try UpdateOperations.withPreparedUpdate(localRequest, environment: project.environment) { + _ = try $0.apply() + } + try apply(.install(root), project) + let installed = try project.bytes(config) + let original = try project.store.loadLedger() + #expect(original.nativeAuthorities?.isEmpty == false) + #expect(String(decoding: installed, as: UTF8.self).contains("never-run-marketplace")) + try FileManager.default.removeItem(at: market.catalog) + try MarketplaceOperations.writeLockOnly( + MarketplaceOperations.previewLockOnly(.remove("servers"), environment: project.environment)) + #expect(try project.bytes(config) == installed) + #expect(try project.store.loadLedger().nativeAuthorities == original.nativeAuthorities) + let preview = try MarketplaceOperations.previewFrozenDeployment( + environment: project.environment) + _ = try MarketplaceOperations.deployFrozen(preview) + let text = try String(contentsOf: config, encoding: .utf8) + #expect(text.contains(manual)) + #expect(text.contains("never-run-adjacent")) + #expect(!text.contains("never-run-marketplace")) + let deployed = try UpdateOperations.inspect(environment: project.environment) + #expect(deployed.deployments.count == 1) + #expect(deployed.deployments.first?.status == .current) + #expect(deployed.pendingMarketplaceDeployment == nil) + } + + @Test func rootedDiamondBacktracksAndRemovesOnlyEachRootsTargets() throws { + let market = try GraphCatalog() + let v1 = SourceRequirement.exact("1.0.0") + let range = SourceRequirement.range(from: "1.0.0", to: "3.0.0") + try market.publish("shared", "1.0.0") + try market.publish("shared", "2.0.0") + try market.publish("left", "1.0.0", ["shared": range]) + try market.publish("left", "2.0.0", ["shared": .exact("2.0.0")]) + try market.publish("right", "1.0.0", ["shared": v1]) + try market.publish("starter", "1.0.0", ["left": range, "right": v1]) + + let project = try UpdateFixture() + let one = try market.root("one", package: "starter", recipient: .codex) + let two = try market.root("two", package: "right", recipient: .claudeCode) + let plan = try MarketplaceOperations.resolve(.install(one), environment: project.environment) + #expect( + plan.nodes.first { $0.versions.node.package == "left" }?.versions.eligible.version == "1.0.0") + #expect( + plan.nodes.first { $0.versions.node.package == "left" }?.versions.latest?.version == "2.0.0") + #expect(plan.nodes.first { $0.versions.node.package == "shared" }?.availableMembers?.count == 1) + try apply(.install(one), project) + let second = try apply(.install(two), project) + let graph = try #require(second.marketplaceGraphChange?.after) + let shared = try #require(graph.nodes.first { $0.id.package == "shared" }) + #expect(graph.nodes.count == 4) + #expect(graph.rootsRequiring(shared.id) == ["one", "two"]) + #expect(graph.incoming(to: shared.id).map(\.parent.package) == ["left", "right"]) + #expect(Set(try #require(shared.members.first).targets) == [.codex, .claudeCode]) + #expect(FileManager.default.fileExists(atPath: project.target().path)) + #expect(FileManager.default.fileExists(atPath: project.target(.claudeCode).path)) + let scope = try UpdateOperations.inspect(environment: project.environment) + for (agent, alias) in [(AgentID.codex, "one"), (.claudeCode, "two")] { + let deployment = try #require( + scope.deployments.first { $0.location.path == project.target(agent).path }) + #expect(scope.marketplaceOwners(of: deployment).map(\.root) == [alias]) + } + let inventory = try #require( + JSONSerialization.jsonObject(with: scope.cycloneDXInventory()) as? [String: Any]) + #expect((inventory["dependencies"] as? [[String: Any]])?.count == 3) + + try FileManager.default.removeItem(at: market.catalog) + let removed = try apply(.remove("one"), project) + #expect(removed.marketplaceGraphChange?.affectedRoots == ["one"]) + #expect(!FileManager.default.fileExists(atPath: project.target().path)) + #expect(FileManager.default.fileExists(atPath: project.target(.claudeCode).path)) + let last = try apply(.remove("two"), project) + #expect(last.marketplaceGraphChange?.after == nil) + #expect(!FileManager.default.fileExists(atPath: project.target(.claudeCode).path)) + #expect(try project.store.loadLedger().marketplaceGraph == nil) + let producers = project.store.directory.appendingPathComponent("bundles") + #expect(try FileManager.default.contentsOfDirectory(atPath: producers.path).isEmpty) + } + + @Test func reportsRequirementConflictAndCyclesWithoutWritingDestination() throws { + let market = try GraphCatalog() + let v1 = SourceRequirement.exact("1.0.0") + try market.publish("shared", "1.0.0") + try market.publish("shared", "2.0.0") + try market.publish("left", "1.0.0", ["shared": v1]) + try market.publish("right", "1.0.0", ["shared": .exact("2.0.0")]) + try market.publish("conflict", "1.0.0", ["left": v1, "right": v1]) + try market.publish("loop-a", "1.0.0", ["loop-b": v1]) + try market.publish("loop-b", "1.0.0", ["loop-a": v1]) + + let project = try UpdateFixture() + for package in ["conflict", "loop-a"] { + let root = try market.root("start", package: package) + do { + _ = try MarketplaceOperations.previewResolution( + .install(root), environment: project.environment) + Issue.record("Expected resolution failure for \(package)") + } catch MarketplaceError.unsatisfiable(let detail) { + #expect(package == "conflict") + #expect(detail.contains("left") && detail.contains("right") && detail.contains("shared")) + } catch MarketplaceError.dependencyCycle(let detail) { + #expect(package == "loop-a") + #expect(detail.contains("loop-a") && detail.contains("loop-b")) + } + } + #expect(!FileManager.default.fileExists(atPath: project.store.directory.path)) + } + + @Test func upgradesSharedNodeAndReplaysPriorGraphInIndependentProject() throws { + let market = try GraphCatalog() + let sharedRange = SourceRequirement.upToNextMajor(from: "1.0.0") + try market.publish("shared", "1.0.0") + try market.publish("left", "1.0.0", ["shared": sharedRange]) + try market.publish("right", "1.0.0", ["shared": sharedRange]) + let project = try UpdateFixture() + let cold = try UpdateFixture() + try apply(.install(market.root("one", package: "left", recipient: .codex)), project) + try apply(.install(market.root("two", package: "right", recipient: .claudeCode)), project) + for name in ["agents.yaml", "agents.resolved"] { + try cold.write( + String(contentsOf: project.store.directory.appendingPathComponent(name), encoding: .utf8), + to: cold.store.directory.appendingPathComponent(name)) + } + let oldLock = try cold.bytes(cold.store.resolvedURL) + let old = try #require(cold.store.loadLedger().marketplaceGraph) + #expect(old.nodes.first { $0.id.package == "shared" }?.coordinate.version == "1.0.0") + try market.publish("shared", "1.1.0") + let upgrade = try MarketplaceOperations.previewResolution( + .upgrade("one"), environment: project.environment) + #expect(upgrade.report.marketplaceGraphChange?.affectedRoots == ["one", "two"]) + let versions = try #require( + upgrade.resolution.nodes.first { $0.versions.node.package == "shared" }?.versions) + #expect(versions.locked?.version == "1.0.0") + #expect(versions.eligible.version == "1.1.0") + #expect(versions.latest?.version == "1.1.0") + + try market.publish("shared", "1.2.0") + #expect(throws: CoreError.self) { + try MarketplaceOperations.withPreparedResolution(upgrade) { try $0.apply() } + } + let updated = try apply(.upgrade("one"), project) + #expect( + updated.marketplaceGraphChange?.after?.nodes.first { $0.id.package == "shared" }?.coordinate + .version == "1.2.0") + try FileManager.default.removeItem(at: market.catalog) + _ = try UpdateOperations.restore(environment: cold.environment) + #expect(try cold.bytes(cold.store.resolvedURL) == oldLock) + #expect( + try cold.bytes(cold.target().appendingPathComponent("SKILL.md")) + == project.bytes(project.target().appendingPathComponent("SKILL.md"))) + #expect(try UpdateOperations.inspect(environment: cold.environment).marketplaceGraph == old) + try apply(.remove("one"), cold) + #expect(!FileManager.default.fileExists(atPath: cold.target().path)) + #expect(FileManager.default.fileExists(atPath: cold.target(.claudeCode).path)) + } + + @Test func requiresReconciliationForAuthoredDriftAndMissingLock() throws { + let market = try GraphCatalog() + try market.publish("shared", "1.0.0") + let project = try UpdateFixture() + let root = try market.root("shared", package: "shared") + try project.write( + """ + version: 1 + packages: + shared: + catalog: {kind: directory, location: "\(market.catalog.path)"} + package: shared + requirement: {exact: "1.0.0"} + """, + to: project.store.declarationURL) + #expect(try project.store.loadDeclaration().marketplaceRoots == [root]) + #expect( + try UpdateOperations.inspect(environment: project.environment).marketplaceIssue + == .missingPin("shared")) + #expect(throws: MarketplaceError.missingPin("shared")) { + try UpdateOperations.restore(environment: project.environment) + } + let reconciled = try apply(.reconcile, project) + #expect(reconciled.marketplaceGraphChange?.after?.roots.first?.intent == root) + #expect(try UpdateOperations.inspect(environment: project.environment).marketplaceIssue == nil) + let manifest = try String(contentsOf: project.store.declarationURL, encoding: .utf8) + try project.write( + manifest.replacingOccurrences(of: "1.0.0", with: "2.0.0"), to: project.store.declarationURL) + let drifted = try UpdateOperations.inspect(environment: project.environment) + #expect(drifted.marketplaceIssue == .selectionMismatch("shared")) + #expect(throws: MarketplaceError.selectionMismatch("shared")) { + try drifted.cycloneDXInventory() + } + #expect(throws: MarketplaceError.selectionMismatch("shared")) { + try UpdateOperations.restore(environment: project.environment) + } + } + + @Test func stalePolicyAndMutableCatalogNeverPublishPreview() throws { + let market = try GraphCatalog() + try market.publish("shared", "1.0.0") + let project = try UpdateFixture() + let root = try market.root("one", package: "shared", recipient: .codex) + let request = MarketplaceResolutionRequest.install(root) + let preview = try MarketplaceOperations.previewResolution( + request, environment: project.environment) + let policy = SourcePolicyOperations.policyURL(scope: .project, environment: project.environment) + + try project.write("version: 1\ndeny: [local]\n", to: policy) + #expect(throws: SourcePolicyFailure.self) { + try MarketplaceOperations.withPreparedResolution(preview) { try $0.apply() } + } + try FileManager.default.removeItem(at: policy) + let lateRelease = try market.archive("shared", "2.0.0") + #expect(throws: UpdateApplyError.self) { + try MarketplaceOperations.withPreparedResolution(preview) { + try MarketplaceOperations.publishBundle(lateRelease, to: market.catalog) + return try $0.apply() + } + } + #expect(!FileManager.default.fileExists(atPath: project.target().path)) + #expect(!FileManager.default.fileExists(atPath: project.store.resolvedURL.path)) + #expect( + !FileManager.default.fileExists( + atPath: project.store.directory.appendingPathComponent("bundles").path)) + } + + @Test func interruptedGraphPublicationRollsBackTheWholeCandidate() throws { + let market = try GraphCatalog() + try market.publish("shared", "1.0.0") + let project = try UpdateFixture() + let root = try market.root("one", package: "shared", recipient: .codex) + let request = MarketplaceResolutionRequest.install(root) + let preview = try MarketplaceOperations.previewResolution( + request, environment: project.environment) + struct Interrupted: Error {} + let checkpoint: (String) throws -> Void = { point in + if point == "publish.0.created" { throw Interrupted() } + } + #expect(throws: UpdateApplyError.self) { + try MarketplaceOperations.prepareResolution(preview, checkpoint: checkpoint) { + try $0.apply() + } + } + #expect(!FileManager.default.fileExists(atPath: project.target().path)) + #expect(!FileManager.default.fileExists(atPath: project.store.declarationURL.path)) + #expect(!FileManager.default.fileExists(atPath: project.store.resolvedURL.path)) + let producers = project.store.directory.appendingPathComponent("bundles") + if FileManager.default.fileExists(atPath: producers.path) { + #expect(try FileManager.default.contentsOfDirectory(atPath: producers.path).isEmpty) + } + _ = try apply(request, project) + #expect(FileManager.default.fileExists(atPath: project.target().path)) + } + + @Test func incorporatesExactPortableInstallWhenANewRootSharesIt() throws { + let market = try GraphCatalog() + let release = try market.publish("shared", "1.0.0") + try market.publish("starter", "1.0.0", ["shared": .exact("1.0.0")]) + let project = try UpdateFixture() + let verified = try MarketplaceOperations.acquire(release, environment: project.environment) + let component = try #require(verified.inspectBundle().components.first) + let original = try verified.previewImport( + as: "original", selections: [.init(componentID: component.id, targets: [.codex])], + scope: .project, environment: project.environment) + _ = try BundleOperations.withPreparedImport(original) { try $0.apply() } + #expect(try MarketplaceOperations.installed(environment: project.environment).count == 1) + + let report = try apply( + .install(market.root("next", package: "starter", recipient: .claudeCode)), project) + let graph = try #require(report.marketplaceGraphChange?.after) + let shared = try #require(graph.nodes.first { $0.id.package == "shared" }) + #expect(graph.rootsRequiring(shared.id) == ["next", "original"]) + #expect(Set(try #require(shared.members.first).targets) == [.codex, .claudeCode]) + #expect(try MarketplaceOperations.installed(environment: project.environment).isEmpty) + #expect(FileManager.default.fileExists(atPath: project.target().path)) + try apply(.remove("next"), project) + #expect(FileManager.default.fileExists(atPath: project.target().path)) + #expect(!FileManager.default.fileExists(atPath: project.target(.claudeCode).path)) + } + + @Test func catalogIdentityDistinguishesSameNamedReleasesAndRejectsRebinding() throws { + let first = try GraphCatalog() + let second = try GraphCatalog() + try first.publish("shared", "1.0.0") + try second.publish("shared", "1.0.0") + let project = try UpdateFixture() + let one = try first.root("one", package: "shared") + try apply(.install(one), project) + let two = try second.root("two", package: "shared") + let report = try apply(.install(two), project) + let graph = try #require(report.marketplaceGraphChange?.after) + #expect(graph.nodes.count == 2) + #expect(graph.nodes[0].id != graph.nodes[1].id) + #expect(graph.nodes.allSatisfy { $0.id.package == "shared" }) + let rebound = try second.root("one", package: "shared") + #expect(throws: MarketplaceError.originConflict("one")) { + try MarketplaceOperations.resolve(.install(rebound), environment: project.environment) + } + } + + @Test func upgradesWithReviewedSelectionsForNewAndRemovedMembers() throws { + let market = try GraphCatalog() + try market.publish("starter", "1.0.0") + let project = try UpdateFixture() + let root = try MarketplaceRoot( + name: "root", catalog: market.origin, package: "starter", + requirement: .upToNextMajor(from: "1.0.0")) + try apply(.install(root), project) + try market.publish("extra", "1.0.0") + try market.publish("starter", "1.1.0", ["extra": .exact("1.0.0")]) + let plan = try MarketplaceOperations.resolve(.upgrade("root"), environment: project.environment) + let extra = try #require(plan.nodes.first { $0.versions.node.package == "extra" }) + let member = try #require(extra.availableMembers?.first?.marketplaceKey) + let selection = try MarketplaceMemberSelection( + package: "extra", member: member, targets: [.codex]) + try apply(.upgrade("root", selections: [selection]), project) + #expect(FileManager.default.fileExists(atPath: project.target().path)) + + try market.publish("starter", "1.2.0") + let next = try MarketplaceOperations.resolve(.upgrade("root"), environment: project.environment) + #expect(next.nodes.first?.versions.eligible.version == "1.2.0") + #expect(throws: MarketplaceError.selectionMismatch("root / demo")) { + try MarketplaceOperations.previewResolution( + .upgrade("root"), environment: project.environment) + } + try apply(.upgrade("root", selections: []), project) + #expect(!FileManager.default.fileExists(atPath: project.target().path)) + } + + @Test func resolvesGitSubpathsAndRelativeUserCatalogs() throws { + let market = try GraphCatalog() + try market.publish("shared", "1.0.0") + let user = try UpdateFixture(scope: .user) + for name in ["docs", "tools"] { + try FileManager.default.copyItem( + at: market.catalog, to: user.repo.appendingPathComponent(name)) + } + try user.commit() + let commit = try user.git(["rev-parse", "HEAD"]) + func root(_ name: String, subpath: String, ref: String? = "main") throws -> MarketplaceRoot { + try MarketplaceRoot( + name: name, + catalog: MarketplaceOrigin(kind: .git, location: "../source", ref: ref, subpath: subpath), + package: "shared", requirement: .exact("1.0.0")) + } + try apply(.install(root("docs", subpath: "docs")), user) + let installed = try apply(.install(root("tools", subpath: "tools")), user) + let graph = try #require(installed.marketplaceGraphChange?.after) + #expect(graph.nodes.compactMap(\.id.catalog.subpath) == ["docs", "tools"]) + #expect(graph.nodes.allSatisfy { $0.catalogCommit == commit }) + #expect(throws: MarketplaceError.self) { + let conflicting = try root("another", subpath: "docs", ref: nil) + _ = try MarketplaceOperations.resolve( + .install(conflicting), scope: .user, environment: user.environment) + } + } + + @Test func pinOnlyUpdateReportsLockAndLatestWithoutNativeTargets() throws { + let market = try GraphCatalog() + try market.publish("shared", "1.0.0") + let project = try UpdateFixture() + let root = try MarketplaceRoot( + name: "root", catalog: market.origin, package: "shared", + requirement: .upToNextMajor(from: "1.0.0")) + try apply(.install(root), project) + try market.publish("shared", "1.1.0+one") + try market.publish("shared", "1.1.0+two") + try market.publish("shared", "1.2.0-rc.1") + try market.publish("shared", "2.0.0") + let updated = try MarketplaceOperations.previewResolution( + .upgrade("root"), environment: project.environment) + let versions = try #require(updated.resolution.nodes.first?.versions) + #expect(versions.locked?.version == "1.0.0") + #expect(versions.eligible.version == "1.1.0+two") + #expect(versions.latest?.version == "2.0.0") + #expect(updated.report.hasChanges && updated.report.components.isEmpty) + let receipt = MarketplaceOperations.performResolution(updated) { try $0.apply() } + #expect(receipt.disposition == .committed) + _ = try receipt.result.get() + #expect(try project.store.loadLedger().deployments.isEmpty) + + let exact = try MarketplaceRoot( + name: "root", catalog: market.origin, package: "shared", + requirement: .exact("1.1.0+one")) + let plan = try MarketplaceOperations.resolve(.install(exact), environment: project.environment) + #expect(plan.nodes.first?.versions.eligible.version == "1.1.0+one") + } + + @Test func deniesAnExplicitPortableCatalogBeforeDiscovery() throws { + let market = try GraphCatalog() + let denied = try MarketplaceOrigin(kind: .git, location: "https://blocked.invalid/catalog") + let dependency = try MarketplacePackageRequirement( + package: "shared", requirement: .exact("1.0.0"), catalog: denied) + try market.publish("starter", "1.0.0", dependencies: [dependency]) + let project = try UpdateFixture() + let policy = SourcePolicyOperations.policyURL(scope: .project, environment: project.environment) + try project.write("version: 1\nallow: [local]\n", to: policy) + let root = try market.root("one", package: "starter") + #expect(throws: SourcePolicyFailure.self) { + try MarketplaceOperations.resolve(.install(root), environment: project.environment) + } + #expect(!FileManager.default.fileExists(atPath: project.store.resolvedURL.path)) + } + + @discardableResult + private func apply(_ request: MarketplaceResolutionRequest, _ consumer: UpdateFixture) throws + -> CombinedUpdateReport + { + let preview = try MarketplaceOperations.previewResolution( + request, scope: consumer.store.scope, environment: consumer.environment) + #expect(preview.ownershipConflict == nil) + return try MarketplaceOperations.withPreparedResolution(preview) { + try $0.apply(ifUnchangedFrom: preview.report.displayedFingerprint).report + } + } +} + +struct GraphCatalog { + let author: UpdateFixture + let catalog: URL + let origin: MarketplaceOrigin + let selection: ComponentSelection + + init() throws { + let author = try UpdateFixture() + try author.install() + catalog = author.root.appendingPathComponent("catalog") + try FileManager.default.createDirectory(at: catalog, withIntermediateDirectories: false) + origin = try MarketplaceOrigin(kind: .directory, location: catalog.path) + let state = try UpdateOperations.inspect(environment: author.environment) + selection = try #require(state.components.first { $0.kind == .skills }?.selection) + self.author = author + } + + @discardableResult + func publish( + _ package: String, _ version: String, _ dependencies: [String: SourceRequirement] = [:] + ) + throws -> MarketplaceRelease + { + let edges = try dependencies.keys.sorted().map { + try MarketplacePackageRequirement(package: $0, requirement: dependencies[$0]!) + } + return try publish(package, version, dependencies: edges) + } + + @discardableResult + func publish(_ package: String, _ version: String, dependencies: [MarketplacePackageRequirement]) + throws -> MarketplaceRelease + { + try MarketplaceOperations.publishBundle( + archive(package, version, dependencies: dependencies), to: catalog) + } + + func archive( + _ package: String, _ version: String, dependencies: [MarketplacePackageRequirement] = [] + ) throws -> Data { + try BundleOperations.export( + .init(name: package, version: version, dependencies: dependencies), selections: [selection], + scope: .project, environment: author.environment) + } + + func root(_ name: String, package: String, recipient: AgentID? = nil) throws -> MarketplaceRoot { + let selections = + try recipient.map { target in + [ + try MarketplaceMemberSelection( + package: "shared", member: .init(kind: .skills, name: "demo"), targets: [target]) + ] + } ?? [] + return try MarketplaceRoot( + name: name, catalog: origin, package: package, requirement: .exact("1.0.0"), + selections: selections) + } +} + +extension MarketplaceResolutionTests { + @Test func organizationChecksNewAndRetainedTransitiveEdgesBeforeAcquisition() throws { + let market = try GraphCatalog() + try market.publish("leaf", "1.0.0") + try market.publish("starter", "1.0.0", ["leaf": .exact("1.0.0")]) + let root = try market.root("main", package: "starter") + let consumer = try UpdateFixture() + let policy = consumer.root.appendingPathComponent("org.yaml") + var environment = consumer.environment + environment.userOrganizationPolicy = .init(.local(policy)) + + try consumer.write("enforcement: block\ndependencies: {max_depth: 1}", to: policy) + do { + _ = try MarketplaceOperations.previewResolution(.install(root), environment: environment) + Issue.record("A depth-two dependency was admitted.") + } catch let error as OrganizationPolicyFailure { + let depth = try #require(error.report.findings.first { $0.rule == "dependency-depth" }) + #expect(depth.dependencyPath.count == 2) + #expect(depth.dependencyPath.last?.hasSuffix("#leaf") == true) + } + #expect(!FileManager.default.fileExists(atPath: consumer.store.directory.path)) + + try consumer.write("enforcement: warn\ndependencies: {max_depth: 1}", to: policy) + let preview = try MarketplaceOperations.previewResolution( + .install(root), environment: environment) + #expect( + preview.report.organizationPolicy?.findings.contains { $0.rule == "dependency-depth" } == true + ) + _ = try MarketplaceOperations.withPreparedResolution(preview) { try $0.apply() } + + let denied = "local:" + market.catalog.resolvingSymlinksInPath().path + "#leaf" + try consumer.write("enforcement: block\ndependencies: {deny: ['\(denied)']}", to: policy) + let previous = try FileHash.folderHash(consumer.root) + #expect(throws: OrganizationPolicyFailure.self) { + _ = try MarketplaceOperations.previewResolution(.reconcile, environment: environment) + } + try FileManager.default.removeItem(at: market.catalog) + let audit = try OrganizationPolicyOperations.audit(environment: environment) + #expect(audit.isBlocked) + #expect( + audit.organization.findings.contains { + $0.rule == "package-deny" && $0.matchedPattern == denied + }) + #expect(throws: OrganizationPolicyFailure.self) { + _ = try UpdateOperations.restore(environment: environment) + } + #expect(try FileHash.folderHash(consumer.root) == previous) + } + + @Test func organizationVersionConflictModesKeepAuthoredAndResolvedEvidence() throws { + let market = try GraphCatalog() + try market.publish("tools", "1.0.0") + try market.publish("tools", "2.0.0") + let consumer = try UpdateFixture() + let root = try MarketplaceRoot( + name: "tools", catalog: market.origin, package: "tools", requirement: .exact("1.0.0"), + selections: [ + .init(package: "tools", member: .init(kind: .skills, name: "demo"), targets: [.codex]) + ]) + let policy = consumer.root.appendingPathComponent("org.yaml") + let identity = "local:" + market.catalog.resolvingSymlinksInPath().path + "#tools" + var environment = consumer.environment + environment.userOrganizationPolicy = .init(.local(policy)) + func rules(_ resolution: String) -> String { + """ + enforcement: block + dependencies: + require_resolution: \(resolution) + require: [{identity: '\(identity)', exact: '2.0.0'}] + """ + } + try consumer.write(rules("project-wins"), to: policy) + let project = try MarketplaceOperations.previewResolution( + .install(root), environment: environment) + #expect(project.resolution.nodes.first?.versions.eligible.version == "1.0.0") + try consumer.write(rules("block"), to: policy) + #expect(throws: OrganizationPolicyFailure.self) { + _ = try MarketplaceOperations.previewResolution(.install(root), environment: environment) + } + + try consumer.write(rules("policy-wins"), to: policy) + let organization = try MarketplaceOperations.previewResolution( + .install(root), environment: environment) + #expect(organization.resolution.nodes.first?.versions.eligible.version == "2.0.0") + #expect(organization.resolution.roots.first?.intent.requirement == root.requirement) + _ = try MarketplaceOperations.withPreparedResolution(organization) { try $0.apply() } + #expect(try !OrganizationPolicyOperations.audit(environment: environment).isBlocked) + try FileManager.default.removeItem(at: market.catalog) + _ = try UpdateOperations.restore(environment: environment) + + try consumer.write("enforcement: off", to: policy) + let stale = try OrganizationPolicyOperations.audit(environment: environment) + #expect( + stale.organization.findings.contains { + $0.rule == "dependency-policy-override" && $0.outcome == .block + }) + #expect(throws: OrganizationPolicyFailure.self) { + _ = try UpdateOperations.restore(environment: environment) + } + } +} diff --git a/Tests/AgentsUpdatesTests/MarketplaceTests.swift b/Tests/AgentsUpdatesTests/MarketplaceTests.swift new file mode 100644 index 0000000..0d3e52b --- /dev/null +++ b/Tests/AgentsUpdatesTests/MarketplaceTests.swift @@ -0,0 +1,483 @@ +import AgentsCore +import AgentsManifest +import AgentsSkills +import AgentsUpdates +import Foundation +import Testing + +@Suite("Versioned team marketplace") +struct MarketplaceTests { + @Test func publishesIdempotentlyAndVerifiesSelectedBytes() throws { + let fixture = try MarketplaceFixture() + let first = try fixture.publish(version: "1.0.0", content: "alpha") + #expect(first == (try fixture.publish(version: "1.0.0", content: "alpha"))) + #expect(throws: MarketplaceError.publicationConflict("team-kit@1.0.0")) { + try fixture.publish(version: "1.0.0", content: "other") + } + let abandoned = fixture.catalog.appendingPathComponent("releases/team-kit/.stage-interrupted") + try FileManager.default.createDirectory(at: abandoned, withIntermediateDirectories: false) + try Data("partial".utf8).write(to: abandoned.appendingPathComponent("package.bundle")) + let catalog = try fixture.browse() + #expect(catalog.search("TEAM GUIDE").map(\.coordinate) == [first.coordinate]) + #expect(catalog.search("absent").isEmpty) + let selected = try catalog.select(package: "team-kit", version: "1.0.0") + let acquired = try fixture.acquire(selected) + #expect(try fixture.decode(acquired.archive).content == "alpha") + + let archive = fixture.catalog.appendingPathComponent(first.coordinate.releasePath) + .appendingPathComponent("package.bundle") + var tampered = acquired.archive + tampered[tampered.startIndex] ^= 1 + try tampered.write(to: archive) + #expect(throws: MarketplaceError.integrityMismatch("team-kit@1.0.0")) { + try fixture.acquire(selected) + } + #expect(throws: MarketplaceError.integrityMismatch("team-kit@1.0.0")) { + try fixture.publish(version: "1.0.0", content: "alpha") + } + } + + @Test func publishedCatalogKeepsEachConcurrentReleaseComplete() async throws { + let fixture = try MarketplaceFixture() + let directory = fixture.catalog + let environment = fixture.environment + let first = MarketplaceFixture.Archive(package: "team-kit", version: "1.0.0", content: "one") + let conflicting = MarketplaceFixture.Archive( + package: "team-kit", version: "1.0.0", content: "three") + let second = MarketplaceFixture.Archive(package: "team-kit", version: "2.0.0", content: "two") + + let outcomes = await withTaskGroup(of: Bool.self, returning: [Bool].self) { group in + for archive in [first, conflicting, second] { + group.addTask { + do { + try MarketplaceFixture.publish(archive, to: directory, environment: environment) + return true + } catch MarketplaceError.publicationConflict { + return false + } catch { + Issue.record(error) + return false + } + } + } + var outcomes: [Bool] = [] + for await outcome in group { outcomes.append(outcome) } + return outcomes + } + + #expect(outcomes.filter { $0 }.count == 2) + let catalog = try fixture.browse() + #expect(catalog.releases.map(\.coordinate.version) == ["2.0.0", "1.0.0"]) + for release in catalog.releases { + let archive = try fixture.decode(fixture.acquire(release).archive) + #expect(archive.version == release.coordinate.version) + let names = try FileManager.default.contentsOfDirectory( + atPath: directory.appendingPathComponent(release.coordinate.releasePath) + .deletingLastPathComponent().path) + #expect(names.allSatisfy { !$0.hasPrefix(".stage-") }) + } + } + + @Test func distinctProjectsAdvanceIndependentlyAndRestoreWithoutProducer() throws { + let fixture = try MarketplaceFixture() + let one = try fixture.project("one") + let two = try fixture.project("two") + let initial = try fixture.publish(version: "1.0.0", content: "first version") + let v1 = try fixture.acquire(fixture.browse().select(package: initial.coordinate.package)) + try fixture.install(v1, in: one) + try fixture.install(v1, in: two) + #expect(try one.skillText().contains("first version")) + #expect(try two.skillText().contains("first version")) + #expect(try one.executable()) + #expect(try two.executable()) + let pin = try #require(try MarketplaceOperations.installed(environment: two.environment).first) + #expect(pin.archiveDigest == v1.release.archiveDigest) + #expect(pin.dependency.catalog.location == "../catalog") + #expect(pin.dependency.coordinate.version == "1.0.0") + #expect(pin.componentRecords.count == 1) + + try fixture.publish(version: "1.2.0", content: "second version") + let available = try fixture.browse().updates(for: pin) + #expect(available.map(\.coordinate.version) == ["1.2.0"]) + let v2 = try fixture.acquire(try #require(available.first)) + let request = try fixture.importRequest(v2, in: one) + let preview = try UpdateOperations.preview(request, environment: one.environment) + #expect(preview.hasChanges) + let packageChange = try #require(preview.marketplaceChanges?.first) + #expect(packageChange.before?.dependency.coordinate.version == "1.0.0") + #expect(packageChange.after?.dependency.coordinate.version == "1.2.0") + #expect(packageChange.after?.archiveDigest == v2.release.archiveDigest) + #expect(try one.skillText().contains("first version")) + _ = try UpdateOperations.withPreparedUpdate(request, environment: one.environment) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + #expect(try one.skillText().contains("second version")) + #expect(try two.skillText().contains("first version")) + #expect(try MarketplaceOperations.installed(environment: two.environment) == [pin]) + let inspection = try UpdateOperations.inspect(environment: two.environment) + #expect(inspection.marketplacePackages == [pin]) + let inventory = String(decoding: try inspection.cycloneDXInventory(), as: UTF8.self) + #expect(inventory.contains(pin.archiveDigest)) + #expect(inventory.contains("agents:marketplace-origin")) + let spdx = try #require( + try JSONSerialization.jsonObject(with: inspection.inventory(format: .spdx)) + as? [String: Any]) + let packages = try #require(spdx["packages"] as? [[String: Any]]) + let release = try #require(packages.first { $0["checksums"] != nil }) + let ownedItem = try #require( + packages.first { + ($0["sourceInfo"] as? String)?.contains("agents:kind skills") == true + }) + let relationships = try #require(spdx["relationships"] as? [[String: String]]) + #expect(release["versionInfo"] as? String == "1.0.0") + #expect( + relationships.contains { + $0["relationshipType"] == "CONTAINS" + && $0["spdxElementId"] == release["SPDXID"] as? String + && $0["relatedSpdxElement"] == ownedItem["SPDXID"] as? String + }) + + let cold = try fixture.project("cold") + try cold.copyState(from: two) + let committed = try Data(contentsOf: cold.store.resolvedURL) + try FileManager.default.removeItem(at: fixture.catalog) + try FileManager.default.removeItem(at: two.environment.projectDirectory) + _ = try UpdateOperations.restore(environment: cold.environment) + #expect(try cold.skillText().contains("first version")) + #expect(try cold.executable()) + #expect(try MarketplaceOperations.installed(environment: cold.environment) == [pin]) + #expect(try Data(contentsOf: cold.store.resolvedURL) == committed) + + let removal = MarketplaceOperations.removalRequest(for: "starter") + let removalPreview = try UpdateOperations.preview(removal, environment: one.environment) + _ = try UpdateOperations.withPreparedUpdate(removal, environment: one.environment) { + try $0.apply(ifUnchangedFrom: removalPreview.displayedFingerprint) + } + #expect(!FileManager.default.fileExists(atPath: one.skillDirectory.path)) + #expect(try MarketplaceOperations.installed(environment: one.environment).isEmpty) + #expect(try cold.skillText().contains("first version")) + } + + @Test func restoreRejectsMissingPinAndDivergentManifestBeforeDeploying() throws { + let fixture = try MarketplaceFixture() + let project = try fixture.project("first") + try fixture.publish(version: "1.0.0", content: "sealed") + let selected = try fixture.browse().select(package: "team-kit") + try fixture.install(fixture.acquire(selected), in: project) + + let cold = try fixture.project("cold") + try cold.copyState(from: project) + let declaration = try Data(contentsOf: cold.store.declarationURL) + let lock = try Data(contentsOf: cold.store.resolvedURL) + try Data("{broken".utf8).write(to: cold.store.declarationURL) + #expect(throws: (any Error).self) { + try SkillOperations.installResolvedReport(environment: cold.environment) + } + #expect(!FileManager.default.fileExists(atPath: cold.skillDirectory.path)) + #expect(try Data(contentsOf: cold.store.resolvedURL) == lock) + try declaration.write(to: cold.store.declarationURL) + try FileManager.default.removeItem(at: cold.store.resolvedURL) + #expect(throws: MarketplaceError.missingPin("starter")) { + try UpdateOperations.restore(environment: cold.environment) + } + #expect(!FileManager.default.fileExists(atPath: cold.skillDirectory.path)) + + try lock.write(to: cold.store.resolvedURL) + let wrongVersion = String(decoding: declaration, as: UTF8.self) + .replacingOccurrences(of: "1.0.0", with: "2.0.0") + try Data(wrongVersion.utf8).write(to: cold.store.declarationURL) + #expect(throws: MarketplaceError.selectionMismatch("starter")) { + try UpdateOperations.restore(environment: cold.environment) + } + #expect(!FileManager.default.fileExists(atPath: cold.skillDirectory.path)) + let audit = try UpdateOperations.inspect(environment: cold.environment) + #expect(audit.marketplaceIssue == .selectionMismatch("starter")) + #expect(throws: MarketplaceError.selectionMismatch("starter")) { + try audit.cycloneDXInventory() + } + + try declaration.write(to: cold.store.declarationURL) + let wrongDigest = String(decoding: lock, as: UTF8.self).replacingOccurrences( + of: selected.archiveDigest, with: "sha256:" + String(repeating: "a", count: 64)) + try Data(wrongDigest.utf8).write(to: cold.store.resolvedURL) + #expect(throws: MarketplaceError.contributionMismatch("starter")) { + try UpdateOperations.restore(environment: cold.environment) + } + #expect(!FileManager.default.fileExists(atPath: cold.skillDirectory.path)) + + try lock.write(to: cold.store.resolvedURL) + let wrongSource = String(decoding: declaration, as: UTF8.self) + .replacingOccurrences(of: ".agent/imported/", with: ".agent/changed/") + try Data(wrongSource.utf8).write(to: cold.store.declarationURL) + #expect(throws: MarketplaceError.contributionMismatch("starter")) { + try UpdateOperations.restore(environment: cold.environment) + } + #expect(!FileManager.default.fileExists(atPath: cold.skillDirectory.path)) + } + + @Test func gitCatalogUsesCommittedSnapshotAndPinsEachPackageIndependently() throws { + let fixture = try MarketplaceFixture() + let project = try fixture.project("git-consumer") + try fixture.git(["init", "--initial-branch=main"]) + try fixture.git(["config", "user.name", "Fixture"]) + try fixture.git(["config", "user.email", "fixture@example.invalid"]) + try fixture.git(["config", "gc.auto", "0"]) + try fixture.git(["config", "maintenance.auto", "false"]) + try fixture.publish(version: "1.0.0", content: "first team package") + let firstCommit = try fixture.commitCatalog() + let observed = try fixture.browse(kind: .git) + let first = try observed.select(package: "team-kit") + #expect(observed.catalogCommit == firstCommit) + #expect(first.catalogCommit == firstCommit) + + try fixture.publish(package: "extra", version: "2.0.0", content: "second team package") + #expect(try fixture.browse(kind: .git).releases.count == 1) + let secondCommit = try fixture.commitCatalog() + let now = try fixture.browse(kind: .git) + let second = try now.select(package: "extra") + #expect(now.catalogCommit == secondCommit) + #expect(first.catalogCommit != second.catalogCommit) + let a = try fixture.acquire(first) + let b = try fixture.acquire(second) + try fixture.install(a, in: project) + try fixture.install(b, as: "extra", in: project) + let pins = try MarketplaceOperations.installed(environment: project.environment) + #expect(pins.map(\.catalogCommit) == [firstCommit, secondCommit]) + let reacquired = try MarketplaceOperations.acquire( + try #require(pins.first), environment: project.environment) + #expect(reacquired.release.catalogCommit == firstCommit) + #expect(reacquired.archive == a.archive) + #expect(try project.skillText().contains("first team package")) + #expect(try project.skillText(for: "extra").contains("second team package")) + + let rebound = try fixture.browse() + #expect(throws: MarketplaceError.originConflict("starter")) { + try rebound.updates(for: try #require(pins.first)) + } + let reboundPackage = try fixture.acquire(rebound.select(package: "team-kit")) + let reboundRequest = try fixture.importRequest(reboundPackage, in: project) + #expect(throws: MarketplaceError.originConflict("starter")) { + try UpdateOperations.preview(reboundRequest, environment: project.environment) + } + } + + @Test func previewFingerprintRejectsAnInterveningPackageUpdate() throws { + let fixture = try MarketplaceFixture() + let project = try fixture.project("first") + for (version, content) in [("1.0.0", "first"), ("2.0.0", "second"), ("3.0.0", "third")] { + try fixture.publish(version: version, content: content) + } + let catalog = try fixture.browse() + func acquire(_ version: String) throws -> VerifiedMarketplacePackage { + try fixture.acquire(catalog.select(package: "team-kit", version: version)) + } + try fixture.install(acquire("1.0.0"), in: project) + let second = try fixture.importRequest(acquire("2.0.0"), in: project) + let preview = try UpdateOperations.preview(second, environment: project.environment) + try fixture.install(acquire("3.0.0"), in: project) + let refreshed = try fixture.importRequest(acquire("2.0.0"), in: project) + #expect(throws: (any Error).self) { + try UpdateOperations.withPreparedUpdate(refreshed, environment: project.environment) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + } + #expect(try project.skillText().contains("third")) + } +} + +private final class MarketplaceFixture { + struct Archive: Codable, Sendable { + let package: String + let version: String + let content: String + } + + struct Project { + let environment: RuntimeEnvironment + var store: StateStore { StateStore(scope: .project, environment: environment) } + var skillDirectory: URL { skillDirectory(for: "team-kit") } + + func skillDirectory(for name: String) -> URL { + environment.projectDirectory.appendingPathComponent(".agents/skills/" + name) + } + + func skillText(for name: String = "team-kit") throws -> String { + try String( + contentsOf: skillDirectory(for: name).appendingPathComponent("SKILL.md"), encoding: .utf8) + } + + func executable() throws -> Bool { + let attributes = try FileManager.default.attributesOfItem( + atPath: skillDirectory.appendingPathComponent("run.sh").path) + return try #require(attributes[.posixPermissions] as? NSNumber).intValue & 0o111 != 0 + } + + func copyState(from origin: Project) throws { + try FileManager.default.createDirectory( + at: store.directory, withIntermediateDirectories: true) + for (source, destination) in [ + (origin.store.declarationURL, store.declarationURL), + (origin.store.resolvedURL, store.resolvedURL), + ] { + try FileManager.default.copyItem(at: source, to: destination) + } + } + } + + let root: URL + let catalog: URL + let environment: RuntimeEnvironment + + init() throws { + root = FileManager.default.temporaryDirectory.appendingPathComponent( + "marketplace-tests-" + UUID().uuidString) + catalog = root.appendingPathComponent("catalog") + environment = RuntimeEnvironment( + projectDirectory: root.appendingPathComponent("producer"), + homeDirectory: root.appendingPathComponent("producer-home"), environment: [:]) + do { + for directory in [catalog, environment.projectDirectory, environment.homeDirectory] { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + } + } catch { + try? FileManager.default.removeItem(at: root) + throw error + } + } + + deinit { + do { try FileManager.default.removeItem(at: root) } catch { Issue.record(error) } + } + + func project(_ name: String) throws -> Project { + let project = root.appendingPathComponent(name) + let home = root.appendingPathComponent(name + "-home") + for directory in [project, home] { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + } + return Project( + environment: RuntimeEnvironment( + projectDirectory: project, homeDirectory: home, environment: [:])) + } + + @discardableResult + func publish(package: String = "team-kit", version: String, content: String) throws + -> MarketplaceRelease + { + try Self.publish( + Archive(package: package, version: version, content: content), + to: catalog, environment: environment) + } + + @discardableResult + static func publish( + _ fixture: Archive, to directory: URL, environment: RuntimeEnvironment + ) throws -> MarketplaceRelease { + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys] + return try MarketplaceOperations.publish( + encoder.encode(fixture), to: directory, summary: "Team guide", environment: environment + ) { bytes in + let archive = try JSONDecoder().decode(Archive.self, from: bytes) + return try MarketplaceCoordinate(package: archive.package, version: archive.version) + } + } + + func browse(kind: MarketplaceOrigin.Kind = .directory) throws -> MarketplaceCatalog { + let origin = try MarketplaceOrigin(kind: kind, location: "../catalog") + return try MarketplaceOperations.browse( + MarketplaceRegistration(name: "team", origin: origin), environment: environment) + } + + func acquire(_ release: MarketplaceRelease) throws -> VerifiedMarketplacePackage { + try MarketplaceOperations.acquire(release, environment: environment) + } + + func decode(_ data: Data) throws -> Archive { try JSONDecoder().decode(Archive.self, from: data) } + + func install( + _ package: VerifiedMarketplacePackage, as name: String = "starter", in project: Project + ) + throws + { + let request = try importRequest(package, as: name, in: project) + let preview = try UpdateOperations.preview(request, environment: project.environment) + _ = try UpdateOperations.withPreparedUpdate(request, environment: project.environment) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + } + + /// Exercises the archive owner's integration contract with an independently written fixture. + func importRequest( + _ package: VerifiedMarketplacePackage, as name: String = "starter", in project: Project + ) throws -> UpdateRequest { + let archive = try decode(package.archive) + let coordinate = try MarketplaceCoordinate(package: archive.package, version: archive.version) + guard coordinate == package.release.coordinate else { + throw MarketplaceError.integrityMismatch(archive.package) + } + let key = String(package.release.archiveDigest.dropFirst("sha256:".count)) + let alias = "fixture-" + key + let relative = ".agent/imported/" + key + let producer = project.environment.projectDirectory.appendingPathComponent(relative) + let skill = producer.appendingPathComponent("skills/" + archive.package) + let manifest = producer.appendingPathComponent(".agent/agents.yaml") + for directory in [skill, manifest.deletingLastPathComponent()] { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + } + try Data( + """ + version: 1 + groups: + release: + components: + - kind: skills + source: "." + mode: copy + select: ["\(archive.package)"] + agents: ["codex"] + exports: ["release"] + """.utf8 + ).write(to: manifest) + try Data( + """ + --- + name: \(archive.package) + description: fixture + --- + + \(archive.content) + """.utf8 + ).write(to: skill.appendingPathComponent("SKILL.md")) + let executable = skill.appendingPathComponent("run.sh") + try Data("#!/bin/sh\ntrue\n".utf8).write(to: executable) + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: executable.path) + + var declaration = try project.store.loadDeclaration() + if declaration.sources[alias] == nil { + declaration.sourceDeclarations.append( + .init( + name: alias, source: SourceDeclaration(kind: .local, location: relative))) + declaration.uses.append(GroupUseDeclaration(name: "release", source: alias)) + } + let document = try project.store.loadManifest() + return try package.bindingImport( + UpdateRequest( + operation: .declaration(declaration), + expectedDeclarationDigest: document?.digest ?? "absent"), + as: name, sourceAliases: [alias]) + } + + @discardableResult + func git(_ args: [String]) throws -> String { + try ProcessRunner.run( + "/usr/bin/env", arguments: ["git", "-C", catalog.path, "-c", "commit.gpgsign=false"] + args + ).stdout.trimmingCharacters(in: .whitespacesAndNewlines) + } + + func commitCatalog() throws -> String { + try git(["add", "."]) + try git(["commit", "-m", "test catalog"]) + return try git(["rev-parse", "HEAD"]) + } +} diff --git a/Tests/AgentsUpdatesTests/NativeAuthorityIntegrationTests.swift b/Tests/AgentsUpdatesTests/NativeAuthorityIntegrationTests.swift new file mode 100644 index 0000000..201179d --- /dev/null +++ b/Tests/AgentsUpdatesTests/NativeAuthorityIntegrationTests.swift @@ -0,0 +1,512 @@ +import Foundation +import Testing + +@testable import AgentsCore +@testable import AgentsUpdates + +struct NativeAuthorityIntegrationTests { + private struct Bindings: RuntimeBindingProvider { + let value: String + func value(for binding: String, environment: RuntimeEnvironment) throws -> Data { + Data(value.utf8) + } + } + private struct Refuse: RuntimeBindingProvider { + func value(for binding: String, environment: RuntimeEnvironment) throws -> Data { + throw CoreError.invalidState("unselected provider called") + } + } + + @Test func equalHooksKeepDistinctAuthorityAndRemoveOnlySelectedOccurrence() throws { + let f = try UpdateFixture() + let file = f.root.appendingPathComponent(".claude/settings.json") + try f.write( + #"{"hooks":{"SessionStart":[{"hooks":[{"type":"command","command":"same"}]}]}}"#, to: file) + try f.store.save( + declaration: Declaration( + components: ["first", "second"].map { + .hook( + name: $0, event: .native("SessionStart"), run: .init(executable: "same"), + agents: [.claudeCode]) + }), ledger: ResolvedLedger()) + _ = try f.apply() + let snapshot = try UpdateOperations.inspect(environment: f.environment) + #expect(snapshot.deployments.allSatisfy { $0.status == .current }) + let first = try #require(snapshot.components.first { $0.name == "first" }) + _ = try UpdateOperations.withPreparedUpdate( + .init(operation: .remove, selections: [first.selection]), environment: f.environment + ) { try $0.apply() } + var object = try #require( + JSONSerialization.jsonObject(with: Data(contentsOf: file)) as? [String: Any]) + var hooks = try #require(object["hooks"] as? [String: Any]) + #expect((hooks["SessionStart"] as? [Any])?.count == 2) + let remaining = try UpdateOperations.inspect(environment: f.environment) + #expect(remaining.deployments.allSatisfy { $0.status == .current }) + _ = try UpdateOperations.withPreparedUpdate( + .init(operation: .remove, selections: [try #require(remaining.components.first?.selection)]), + environment: f.environment + ) { try $0.apply() } + object = try #require( + JSONSerialization.jsonObject(with: Data(contentsOf: file)) as? [String: Any]) + hooks = try #require(object["hooks"] as? [String: Any]) + #expect((hooks["SessionStart"] as? [Any])?.count == 1) + } + + @Test func privateHookColdRestoreAndRemovalUseActualArrayEvidence() throws { + let f = try UpdateFixture() + try f.store.save( + declaration: Declaration(components: [ + .hook( + name: "check", event: .native("SessionStart"), + run: .init(executable: "never-run", environment: ["TOKEN": .secret("token")]), + agents: [.claudeCode]) + ]), ledger: ResolvedLedger()) + let preview = try f.preview() + _ = try UpdateOperations.withPreparedUpdate( + environment: f.environment, bindingProvider: Bindings(value: "actual-private-array-canary") + ) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + let file = f.root.appendingPathComponent(".claude/settings.json") + #expect(try String(contentsOf: file, encoding: .utf8).contains("actual-private-array-canary")) + let bytes = try Data(contentsOf: f.store.resolvedURL) + let text = String(decoding: bytes, as: UTF8.self) + #expect(!text.contains("actual-private-array-canary")) + #expect(text.contains("privateArray")) + #expect(!text.contains("semanticDigest")) + let snapshot = try UpdateOperations.inspect(environment: f.environment) + try FileManager.default.removeItem(at: file) + _ = try UpdateOperations.withPreparedUpdate( + .init(operation: .restore), environment: f.environment, + bindingProvider: Bindings(value: "restored-private-array-canary") + ) { try $0.apply() } + #expect(try String(contentsOf: file, encoding: .utf8).contains("restored-private-array-canary")) + let restored = try UpdateOperations.inspect(environment: f.environment) + #expect(restored.deployments.allSatisfy { $0.status == .current }) + _ = snapshot + _ = try UpdateOperations.withPreparedUpdate( + .init(operation: .remove, selections: [try #require(restored.components.first?.selection)]), + environment: f.environment, bindingProvider: Refuse() + ) { try $0.apply() } + let object = try #require( + JSONSerialization.jsonObject(with: Data(contentsOf: file)) as? [String: Any]) + #expect(object["hooks"] == nil) + #expect(try f.store.readLedger().nativeAuthorities == nil) + } + + @Test func pruneRightsRetireWhenUnmanagedContainerContentRemains() throws { + let f = try UpdateFixture() + try f.store.save( + declaration: Declaration(components: [ + .command( + name: "review", description: "Review", prompt: .literal("Body"), agents: [.opencode]) + ]), ledger: ResolvedLedger()) + _ = try f.apply() + let file = f.root.appendingPathComponent("opencode.json") + var object = try #require( + JSONSerialization.jsonObject(with: Data(contentsOf: file)) as? [String: Any]) + var commands = try #require(object["commands"] as? [String: Any]) + commands["user"] = ["template": "unmanaged"] + object["commands"] = commands + try JSONSerialization.data(withJSONObject: object).write(to: file) + let snapshot = try UpdateOperations.inspect(environment: f.environment) + _ = try UpdateOperations.withPreparedUpdate( + .init(operation: .remove, selections: [try #require(snapshot.components.first?.selection)]), + environment: f.environment + ) { try $0.apply() } + #expect(try f.store.readLedger().nativeAuthorities == nil) + #expect(try String(contentsOf: file, encoding: .utf8).contains("unmanaged")) + try f.store.save( + declaration: Declaration(components: [ + .command( + name: "review", description: "Review", prompt: .literal("Again"), agents: [.opencode]) + ]), ledger: try f.store.readLedger()) + _ = try f.apply() + #expect( + try f.store.readLedger().nativeAuthorities?.flatMap(\.createdContainers).isEmpty == true) + } + + @Test func independentScopeSiblingEditRetainsPrivateArrayTokenAndFreshRemoval() throws { + let f = try UpdateFixture(scope: .user) + try f.store.save( + declaration: Declaration(components: [ + .hook( + name: "private", event: .native("SessionStart"), + run: .init(executable: "never-run", environment: ["TOKEN": .secret("token")]), + agents: [.claudeCode]) + ]), ledger: ResolvedLedger()) + _ = try UpdateOperations.withPreparedUpdate( + scope: .user, environment: f.environment, + bindingProvider: Bindings(value: "cross-scope-private-canary") + ) { try $0.apply() } + func receipt(_ store: StateStore) throws -> MaterializationReceipt { + try store.withLock(footprint: [.claudeSettingsUser]) { + let target = try store.nativeTarget(for: .claudeSettingsUser) + return try #require(try store.materializationReceipt(for: target)) + } + } + let before = try receipt(f.store) + let ledgerBytes = try Data(contentsOf: f.store.resolvedURL) + var other = f.environment + other.homeDirectory = f.root.appendingPathComponent("other-home") + try FileManager.default.createDirectory( + at: other.homeDirectory, withIntermediateDirectories: true) + let store = StateStore(scope: .user, environment: other) + try store.save( + declaration: Declaration(components: [ + .permissions( + name: "read", rules: [], agents: [.claudeCode], + native: ["claude-code": ["allow": .array([.string("Read")])]]) + ]), ledger: ResolvedLedger()) + _ = try UpdateOperations.withPreparedUpdate( + scope: .user, environment: other, bindingProvider: Refuse() + ) { try $0.apply() } + let after = try receipt(f.store) + #expect(before.generation != after.generation) + #expect(before.nativeArrays == after.nativeArrays) + #expect(try Data(contentsOf: f.store.resolvedURL) == ledgerBytes) + let current = try UpdateOperations.inspect(scope: .user, environment: f.environment) + #expect(current.deployments.allSatisfy { $0.status == .current }) + _ = try UpdateOperations.withPreparedUpdate( + .init(operation: .remove, selections: [try #require(current.components.first?.selection)]), + scope: .user, environment: f.environment, bindingProvider: Refuse() + ) { try $0.apply() } + let file = try f.store.withLock(footprint: [.claudeSettingsUser]) { + try f.store.nativeTarget(for: .claudeSettingsUser).url + } + let text = try String(contentsOf: file, encoding: .utf8) + #expect(!text.contains("cross-scope-private-canary")) + #expect(text.contains("Read")) + } + + @Test func staleArrayAuthorityDoesNotBlockAnIndependentSelectedSibling() throws { + let f = try UpdateFixture(scope: .user) + func declaration(_ allowed: String) -> Declaration { + Declaration(components: [ + .hook( + name: "private", event: .native("SessionStart"), + run: .init(executable: "never-run", environment: ["TOKEN": .secret("token")]), + agents: [.claudeCode]), + .permissions( + name: "read", rules: [], agents: [.claudeCode], + native: ["claude-code": ["allow": .array([.string(allowed)])]]), + ]) + } + try f.store.save(declaration: declaration("Read"), ledger: ResolvedLedger()) + _ = try UpdateOperations.withPreparedUpdate( + scope: .user, environment: f.environment, + bindingProvider: Bindings(value: "stale-array-private-canary") + ) { try $0.apply() } + var other = f.environment + other.homeDirectory = f.root.appendingPathComponent("other-home") + try FileManager.default.createDirectory( + at: other.homeDirectory, withIntermediateDirectories: true) + let otherStore = StateStore(scope: .user, environment: other) + try otherStore.save( + declaration: Declaration(components: [ + .hook( + name: "foreign", event: .native("SessionStart"), + run: .init(executable: "foreign-never-run"), agents: [.claudeCode]) + ]), ledger: ResolvedLedger()) + _ = try UpdateOperations.withPreparedUpdate( + scope: .user, environment: other, bindingProvider: Refuse() + ) { try $0.apply() } + let ledger = try f.store.readLedger() + try f.store.save(declaration: declaration("Write"), ledger: ledger) + _ = try UpdateOperations.withPreparedUpdate( + .init(kinds: [.permissions], names: ["read"]), scope: .user, environment: f.environment, + bindingProvider: Refuse() + ) { try $0.apply() } + #expect(throws: (any Error).self) { + try UpdateOperations.withPreparedUpdate( + .init(kinds: [.hook], names: ["private"]), scope: .user, environment: f.environment, + bindingProvider: Refuse() + ) { try $0.apply() } + } + let file = try f.store.withLock(footprint: [.claudeSettingsUser]) { + try f.store.nativeTarget(for: .claudeSettingsUser).url + } + let text = try String(contentsOf: file, encoding: .utf8) + #expect(text.contains("stale-array-private-canary")) + #expect(text.contains("foreign-never-run")) + #expect(text.contains("Write")) + } + + @Test func privateArrayRollbackRestoresTargetLedgerAndReceiptTogether() throws { + let f = try UpdateFixture() + func declaration(_ command: String) -> Declaration { + Declaration(components: [ + .hook( + name: "check", event: .native("SessionStart"), + run: .init(executable: command, environment: ["TOKEN": .secret("token")]), + agents: [.claudeCode]) + ]) + } + try f.store.save(declaration: declaration("before"), ledger: ResolvedLedger()) + _ = try UpdateOperations.withPreparedUpdate( + environment: f.environment, bindingProvider: Bindings(value: "before-private") + ) { try $0.apply() } + let file = f.root.appendingPathComponent(".claude/settings.json") + let before = try Data(contentsOf: file) + let ledger = try Data(contentsOf: f.store.resolvedURL) + let receipt = try Data(contentsOf: f.store.materializationReceiptURL) + try f.store.save(declaration: declaration("after"), ledger: try f.store.readLedger()) + var reached = false + var receiptIndex: Int? + let result = UpdateOperations.perform( + environment: f.environment, bindingProvider: Bindings(value: "after-private"), + checkpoint: { point in + if point == TransactionCheckpoint.phase(.preparing).name { + let journal = try #require( + JSONSerialization.jsonObject( + with: Data(contentsOf: f.store.directory.appendingPathComponent("transaction.json"))) + as? [String: Any]) + let entries = try #require(journal["entries"] as? [[String: Any]]) + receiptIndex = try #require( + entries.firstIndex { ($0["path"] as? String) == "state/materializations.json" }) + } + if let receiptIndex, point == TransactionCheckpoint.progress(receiptIndex, .applied).name { + reached = true + throw CoreError.invalidState("injected native publication failure") + } + }, { try $0.apply() }) + #expect(reached) + #expect(result.disposition == .rolledBack) + #expect(!result.recovery.pending) + #expect(try Data(contentsOf: file) == before) + #expect(try Data(contentsOf: f.store.resolvedURL) == ledger) + #expect(try Data(contentsOf: f.store.materializationReceiptURL) == receipt) + } + + @Test func deferredLedgerNoopPreservesCapturedEncodingDuringColdRestore() throws { + let f = try UpdateFixture() + try f.store.save( + declaration: Declaration(components: [ + .command( + name: "review", description: "Review", prompt: .literal("Frozen body"), + agents: [.claudeCode]) + ]), ledger: ResolvedLedger()) + _ = try f.apply() + var original = try Data(contentsOf: f.store.resolvedURL) + original.append(Data("\n \n".utf8)) + try original.write(to: f.store.resolvedURL) + let inspection = try UpdateOperations.inspect(environment: f.environment) + let target = try #require(inspection.deployments.first?.location) + let output = try Data(contentsOf: target) + try FileManager.default.removeItem(at: target) + _ = try UpdateOperations.restore(environment: f.environment) + #expect(try Data(contentsOf: target) == output) + #expect(try Data(contentsOf: f.store.resolvedURL) == original) + } + + @Test func generatedPrivatePluginUsesProductionBindingsAndRetainsFrozenTree() throws { + let f = try UpdateFixture() + let source = f.root.appendingPathComponent("bundle") + try f.write( + #"{"name":"upstream","mcpServers":{"native":{"command":"${CLAUDE_PLUGIN_ROOT}/bin/server","env":{"TOKEN":"source-private-canary"}}}}"#, + to: source.appendingPathComponent(".claude-plugin/plugin.json")) + try f.write( + "#!/bin/sh\n# fixture source; never executed\n", + to: source.appendingPathComponent("bin/server")) + try FileManager.default.setAttributes( + [.posixPermissions: 0o755], ofItemAtPath: source.appendingPathComponent("bin/server").path) + try f.store.save( + declaration: Declaration(components: [ + .plugin( + name: "selected", path: "bundle", source: ".", mode: .components, agents: [.claudeCode]), + .command( + name: "independent", description: "Independent", prompt: .literal("Body"), + agents: [.claudeCode]), + ]), ledger: ResolvedLedger()) + let before = try FileHash.folderHash(f.root) + let preview = try f.preview() + #expect(try FileHash.folderHash(f.root) == before) + let text = try #require(preview.components.first { $0.kind == "plugin" }?.symbolicAfter) + #expect(text.contains("mcpServers")) + #expect(text.contains("«binding:")) + #expect(!text.contains("source-private-canary")) + #expect(!text.contains("actual-generated-private-canary")) + _ = try UpdateOperations.withPreparedUpdate( + environment: f.environment, + bindingProvider: Bindings(value: "actual-generated-private-canary") + ) { try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) } + let snapshot = try UpdateOperations.inspect(environment: f.environment) + #expect(snapshot.deployments.allSatisfy { $0.status == .current }) + let plugin = try #require(snapshot.components.first { $0.kind == .plugin }) + let tree = try #require( + snapshot.deployments.first { $0.ownerRecords.contains(plugin.record) }?.location) + let manifest = tree.appendingPathComponent(".claude-plugin/plugin.json") + #expect( + try String(contentsOf: manifest, encoding: .utf8).contains("actual-generated-private-canary")) + #expect( + !String(decoding: try Data(contentsOf: f.store.resolvedURL), as: UTF8.self).contains( + "actual-generated-private-canary")) + #expect( + !String(decoding: try Data(contentsOf: f.store.resolvedURL), as: UTF8.self).contains( + "source-private-canary")) + _ = try UpdateOperations.withPreparedUpdate( + .init(kinds: [.command], names: ["independent"]), environment: f.environment, + bindingProvider: Refuse() + ) { try $0.apply() } + try FileManager.default.removeItem(at: source) + try FileManager.default.removeItem(at: tree) + _ = try UpdateOperations.withPreparedUpdate( + .init(operation: .restore), environment: f.environment, + bindingProvider: Bindings(value: "cold-generated-private-canary") + ) { try $0.apply() } + #expect( + try String(contentsOf: manifest, encoding: .utf8).contains("cold-generated-private-canary")) + } + + @Test func generatedGeminiAuthoredVersionOverridesProducerAndSurvivesColdRestore() throws { + let f = try UpdateFixture(scope: .user) + let source = f.store.directory.appendingPathComponent("bundle") + try f.write( + #"{"name":"upstream","version":"1.2.3"}"#, + to: source.appendingPathComponent("gemini-extension.json")) + try f.store.save( + declaration: Declaration(components: [ + .plugin( + name: "selected", path: "bundle", source: ".", mode: .components, + agents: [.geminiCLI], native: ["gemini-cli": ["version": .string("9.8.7")]]) + ]), ledger: ResolvedLedger()) + let preview = try f.preview() + #expect(preview.components.first?.symbolicAfter?.contains("9.8.7") == true) + _ = try UpdateOperations.withPreparedUpdate(scope: .user, environment: f.environment) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + let installed = try UpdateOperations.inspect(scope: .user, environment: f.environment) + let tree = try #require(installed.deployments.first?.location) + try FileManager.default.removeItem(at: source) + try FileManager.default.removeItem(at: tree) + _ = try UpdateOperations.restore(scope: .user, environment: f.environment) + let manifest = try #require( + JSONSerialization.jsonObject( + with: Data(contentsOf: tree.appendingPathComponent("gemini-extension.json"))) + as? [String: Any]) + #expect(manifest["version"] as? String == "9.8.7") + } + + @Test(arguments: [AgentID.claudeCode, .cursor, .geminiCLI], [false, true]) + func generatedPluginPublishesOnlySelectedMembersAndColdRestores( + _ agent: AgentID, _ supportingLink: Bool + ) throws { + let f = try UpdateFixture(scope: .user) + let root = f.store.directory.appendingPathComponent("bundle") + let manifest: String + let command: String + switch agent { + case .claudeCode: + manifest = ".claude-plugin/plugin.json" + command = "commands/review.md" + case .cursor: + manifest = ".cursor-plugin/plugin.json" + command = "commands/review.md" + default: + manifest = "gemini-extension.json" + command = "commands/review.toml" + } + try f.write( + #"{"name":"upstream","version":"1.2.3"}"#, to: root.appendingPathComponent(manifest)) + try f.write( + agent == .geminiCLI + ? "description = \"Review\"\nprompt = \"Frozen member\"\n" + : (agent == .cursor ? "Frozen member\n" : "---\ndescription: Review\n---\nFrozen member\n"), + to: root.appendingPathComponent(command) + ) + try f.write( + "---\nname: helper\ndescription: Helper\n---\nFrozen skill\n", + to: root.appendingPathComponent("skills/helper/SKILL.md")) + if supportingLink { + try f.write("Frozen supporting resource", to: root.appendingPathComponent("shared/tool.txt")) + try FileManager.default.createSymbolicLink( + atPath: root.appendingPathComponent("skills/helper/reference.txt").path, + withDestinationPath: "../../shared/tool.txt") + } + try f.store.save(declaration: Declaration(), ledger: ResolvedLedger()) + try f.write( + """ + version: 1 + components: + - kind: plugin + name: selected + source: "." + path: bundle + agents: ["\(agent.rawValue)"] + - kind: mcpServer + name: independent + transport: {kind: stdio, executable: fixture-command} + agents: ["\(agent.rawValue)"] + """, to: f.store.declarationURL) + let preview = try f.preview() + _ = try UpdateOperations.withPreparedUpdate(scope: .user, environment: f.environment) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + let memberPreview = try #require( + preview.components.first { $0.kind == "plugin" }?.symbolicAfter) + #expect(memberPreview.contains("Target: ")) + #expect(memberPreview.contains(command)) + #expect(memberPreview.contains("Frozen member")) + #expect(memberPreview.contains("skills/helper/SKILL.md")) + #expect(memberPreview.contains("Frozen skill")) + #expect(!memberPreview.contains("\"kind\":\"object\"")) + let ledger = try f.store.readLedger() + #expect(ledger.lowerings.filter { $0.format.hasSuffix("-generated-plugin@1") }.count == 1) + #expect(ledger.deployments.filter { $0.route == "agents/skill@1" }.isEmpty) + #expect(ledger.deployments.count == 2) + let snapshot = try UpdateOperations.inspect(scope: .user, environment: f.environment) + #expect(snapshot.deployments.allSatisfy { $0.status == .current }) + let plugin = try #require(snapshot.components.first { $0.kind == .plugin }) + let tree = try #require( + snapshot.deployments.first { $0.ownerRecords.contains(plugin.record) }?.location) + #expect( + try String(contentsOf: tree.appendingPathComponent(command), encoding: .utf8).contains( + "Frozen member")) + #expect( + try String(contentsOf: tree.appendingPathComponent("skills/helper/SKILL.md"), encoding: .utf8) + .contains("Frozen skill")) + if supportingLink { + #expect( + try String( + contentsOf: tree.appendingPathComponent("skills/helper/reference.txt"), encoding: .utf8) + == "Frozen supporting resource") + } + let unmanaged = tree.appendingPathComponent("unmanaged-empty") + try FileManager.default.createDirectory(at: unmanaged, withIntermediateDirectories: true) + #expect( + try UpdateOperations.inspect(scope: .user, environment: f.environment).deployments.contains { + $0.location == tree && $0.status == .drifted + }) + #expect(throws: (any Error).self) { try f.preview() } + try FileManager.default.removeItem(at: unmanaged) + try FileManager.default.removeItem(at: root) + try FileManager.default.removeItem(at: tree) + _ = try UpdateOperations.restore(scope: .user, environment: f.environment) + #expect( + try String(contentsOf: tree.appendingPathComponent(command), encoding: .utf8).contains( + "Frozen member")) + let restored = try UpdateOperations.inspect(scope: .user, environment: f.environment) + #expect(restored.deployments.allSatisfy { $0.status == .current }) + if agent == .geminiCLI { + let native = try #require( + JSONSerialization.jsonObject(with: Data(contentsOf: tree.appendingPathComponent(manifest))) + as? [String: Any]) + #expect(native["version"] as? String == "1.2.3") + } + if supportingLink { + #expect( + try String( + contentsOf: tree.appendingPathComponent("skills/helper/reference.txt"), encoding: .utf8) + == "Frozen supporting resource") + } + _ = try UpdateOperations.withPreparedUpdate( + .init( + operation: .remove, + selections: [try #require(restored.components.first { $0.kind == .plugin }?.selection)]), + scope: .user, environment: f.environment + ) { try $0.apply() } + #expect(!FileManager.default.fileExists(atPath: tree.path)) + #expect( + try UpdateOperations.inspect(scope: .user, environment: f.environment).deployments.count == 1) + } +} diff --git a/Tests/AgentsUpdatesTests/NativeCompositionIntegrationTests.swift b/Tests/AgentsUpdatesTests/NativeCompositionIntegrationTests.swift new file mode 100644 index 0000000..fac5cb2 --- /dev/null +++ b/Tests/AgentsUpdatesTests/NativeCompositionIntegrationTests.swift @@ -0,0 +1,336 @@ +import AgentsCore +import AgentsUpdates +import Foundation +import StateTestSupport +import Testing + +struct NativeCompositionIntegrationTests { + @Test(arguments: [AgentID.claudeCode, .geminiCLI, .cursor, .opencode]) + func concreteCommandLifecycleUsesPublicOperations(_ agent: AgentID) throws { + let f = try UpdateFixture() + try f.store.save( + declaration: Declaration(components: [ + .command( + name: "review", description: agent == .cursor ? "" : "Review sources", + prompt: .literal("Review exact sources."), agents: [agent]) + ]), ledger: ResolvedLedger()) + let before = try FileHash.folderHash(f.root) + let preview = try f.preview() + #expect(preview.components.first?.kind == "command") + #expect(try FileHash.folderHash(f.root) == before) + _ = try UpdateOperations.withPreparedUpdate(environment: f.environment) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + let inspection = try UpdateOperations.inspect(environment: f.environment) + let deployment = try #require(inspection.deployments.first) + #expect(deployment.status == .current) + let bytes = try Data(contentsOf: deployment.location) + #expect(String(decoding: bytes, as: UTF8.self).contains("Review exact sources.")) + try FileManager.default.removeItem(at: deployment.location) + _ = try UpdateOperations.restore(environment: f.environment) + #expect(try Data(contentsOf: deployment.location) == bytes) + let current = try UpdateOperations.inspect(environment: f.environment) + let selection = try #require(current.components.first?.selection) + _ = try UpdateOperations.withPreparedUpdate( + .init(operation: .remove, selections: [selection]), environment: f.environment + ) { try $0.apply() } + #expect(try UpdateOperations.inspect(environment: f.environment).components.isEmpty) + } + + @Test func codexRoleAndMCPShareOnePhysicalDocumentWithoutLosingSiblings() throws { + let f = try UpdateFixture() + let config = f.root.appendingPathComponent(".codex/config.toml") + try f.write("# Preserve this native setting.\ntheme = 'fixture'\n", to: config) + try f.store.save( + declaration: Declaration(components: [ + .subagent( + name: "researcher", description: "Research sources", prompt: .literal("Read sources."), + agents: [.codex]), + .mcpServer(name: "db", transport: .stdio(.init(executable: "never-run")), agents: [.codex]), + ]), ledger: ResolvedLedger()) + _ = try f.apply() + let contents = try String(contentsOf: config, encoding: .utf8) + #expect(contents.hasPrefix("# Preserve this native setting.\ntheme = 'fixture'\n")) + #expect(contents.contains("researcher")) + #expect(contents.contains("db")) + let inspection = try UpdateOperations.inspect(environment: f.environment) + #expect(inspection.deployments.filter { $0.location == config }.count == 2) + let role = try #require(inspection.components.first { $0.kind == .subagent }) + let request = UpdateRequest(operation: .remove, selections: [role.selection]) + let preview = try UpdateOperations.preview(request, environment: f.environment) + _ = try UpdateOperations.withPreparedUpdate(request, environment: f.environment) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + let after = try String(contentsOf: config, encoding: .utf8) + #expect(after.contains("theme = 'fixture'")) + #expect(after.contains("db")) + #expect(!after.contains("researcher")) + #expect( + !FileManager.default.fileExists( + atPath: f.root.appendingPathComponent(".codex/agents/researcher.toml").path)) + } + + @Test func nativePermissionCategoriesPreserveUnselectedCategoriesAndSettings() throws { + let f = try UpdateFixture() + let settings = f.root.appendingPathComponent(".claude/settings.json") + try f.write("{\"telemetry\":false,\"permissions\":{\"deny\":[\"Bash(rm *)\"]}}", to: settings) + try f.store.save( + declaration: Declaration(components: [ + .permissions( + name: "read", rules: [], agents: [.claudeCode], + native: ["claude-code": ["allow": .array([.string("Read")])]]) + ]), ledger: ResolvedLedger()) + _ = try f.apply() + let value = try JSONSerialization.jsonObject(with: Data(contentsOf: settings)) as? [String: Any] + #expect(value?["telemetry"] as? Bool == false) + #expect((value?["permissions"] as? [String: Any])?["deny"] as? [String] == ["Bash(rm *)"]) + let inspected = try UpdateOperations.inspect(environment: f.environment) + _ = try UpdateOperations.withPreparedUpdate( + .init(operation: .remove, selections: [try #require(inspected.components.first?.selection)]), + environment: f.environment + ) { try $0.apply() } + let after = try JSONSerialization.jsonObject(with: Data(contentsOf: settings)) as? [String: Any] + #expect((after?["permissions"] as? [String: Any])?["allow"] == nil) + #expect((after?["permissions"] as? [String: Any])?["deny"] as? [String] == ["Bash(rm *)"]) + } + + @Test(arguments: [AgentID.geminiCLI, .cursor]) + func ignoreBlockPreservesUnmanagedPatternsThroughRemoval(_ agent: AgentID) throws { + let f = try UpdateFixture() + let file = f.root.appendingPathComponent(agent == .cursor ? ".cursorignore" : ".geminiignore") + let custom = "# Preserve user patterns.\nuser-local\n" + try f.write(custom, to: file) + try f.store.save( + declaration: Declaration(components: [ + .ignore(name: "generated", patterns: ["build", "!build/keep"], agents: [agent]) + ]), ledger: ResolvedLedger()) + _ = try f.apply() + #expect(try String(contentsOf: file, encoding: .utf8).hasPrefix(custom)) + let current = try UpdateOperations.inspect(environment: f.environment) + _ = try UpdateOperations.withPreparedUpdate( + .init(operation: .remove, selections: [try #require(current.components.first?.selection)]), + environment: f.environment + ) { try $0.apply() } + #expect(try String(contentsOf: file, encoding: .utf8) == custom) + } +} + +extension NativeCompositionIntegrationTests { + @Test func opaqueNativePluginRetainsItsWholeFrozenTreeAndExecutionBits() throws { + let f = try UpdateFixture() + let source = f.root.appendingPathComponent("plugin-source") + let tree = source.appendingPathComponent("plugins/demo-plugin") + try f.write( + "{\"name\":\"demo-plugin\",\"version\":\"1.0.0\"}", + to: tree.appendingPathComponent(".claude-plugin/plugin.json")) + try f.write("#!/bin/sh\n# Never executed.\n", to: tree.appendingPathComponent("scripts/check")) + try FileManager.default.setAttributes( + [.posixPermissions: 0o755], ofItemAtPath: tree.appendingPathComponent("scripts/check").path) + try f.store.save( + declaration: Declaration( + sources: ["producer": .init(kind: .local, location: source.path)], + components: [ + .plugin( + name: "demo-plugin", path: "plugins/demo-plugin", source: "producer", mode: .native, + agents: [.claudeCode]) + ]), ledger: ResolvedLedger()) + _ = try f.apply() + let snapshot = try UpdateOperations.inspect(environment: f.environment) + let deployment = try #require(snapshot.deployments.first) + #expect(deployment.status == .current) + let hash = try FileHash.folderHash(deployment.location) + let flags = try FileHash.executableFlags(deployment.location) + try FileManager.default.removeItem(at: source) + try FileManager.default.removeItem(at: f.store.cacheDirectory) + try FileManager.default.removeItem(at: deployment.location) + _ = try UpdateOperations.restore(environment: f.environment) + #expect(try FileHash.folderHash(deployment.location) == hash) + #expect(try FileHash.executableFlags(deployment.location) == flags) + try f.write("Unmanaged child", to: deployment.location.appendingPathComponent("user-child")) + #expect(throws: (any Error).self) { + try UpdateOperations.withPreparedUpdate( + .init(operation: .remove, selections: [try #require(snapshot.components.first?.selection)]), + environment: f.environment + ) { try $0.apply() } + } + #expect( + try String( + contentsOf: deployment.location.appendingPathComponent("user-child"), encoding: .utf8) + == "Unmanaged child") + } + + @Test func normalLSPProgramUsesProductionStagedConversion() throws { + let f = try UpdateFixture() + try f.store.save( + declaration: Declaration(components: [ + .lspServer( + name: "language", run: .init(executable: "never-run"), languages: [:], agents: [.opencode] + ) + ]), ledger: ResolvedLedger()) + _ = try f.apply() + let snapshot = try UpdateOperations.inspect(environment: f.environment) + #expect(snapshot.deployments.allSatisfy { $0.status == .current }) + } +} + +extension NativeCompositionIntegrationTests { + @Test(arguments: [false, true]) + func createdNativeContainerPruningPreservesPreexistingContainers(_ existingContainer: Bool) throws + { + let f = try UpdateFixture() + let config = f.root.appendingPathComponent("opencode.json") + if existingContainer { try f.write("{\"commands\":{},\"userSetting\":false}", to: config) } + try f.store.save( + declaration: Declaration(components: [ + .command( + name: "review", description: "Review", prompt: .literal("Review sources."), + agents: [.opencode]) + ]), ledger: ResolvedLedger()) + _ = try f.apply() + let snapshot = try UpdateOperations.inspect(environment: f.environment) + _ = try UpdateOperations.withPreparedUpdate( + .init(operation: .remove, selections: [try #require(snapshot.components.first?.selection)]), + environment: f.environment + ) { try $0.apply() } + let object = try JSONSerialization.jsonObject(with: Data(contentsOf: config)) as? [String: Any] + #expect((object?["commands"] != nil) == existingContainer) + if existingContainer { #expect(object?["userSetting"] as? Bool == false) } + } + + @Test func normalHookPreservesExistingUnmanagedOccurrence() throws { + let f = try UpdateFixture() + let config = f.root.appendingPathComponent(".claude/settings.json") + try f.write( + "{\"hooks\":{\"SessionStart\":[{\"hooks\":[{\"type\":\"command\",\"command\":\"user-hook\"}]}]}}", + to: config) + try f.store.save( + declaration: Declaration(components: [ + .hook( + name: "check", event: .native("SessionStart"), run: .init(executable: "never-run"), + agents: [.claudeCode]) + ]), ledger: ResolvedLedger()) + _ = try f.apply() + let text = try String(contentsOf: config, encoding: .utf8) + #expect(text.contains("user-hook")) + #expect(text.contains("never-run")) + } +} + +extension NativeCompositionIntegrationTests { + @Test( + arguments: [AgentID.claudeCode, .codex, .cursor, .geminiCLI, .opencode], + [InstallScope.project, .user]) + func concreteSubagentUsesRegisteredScopeAndColdRestore(_ agent: AgentID, _ scope: InstallScope) + throws + { + let f = try UpdateFixture(scope: scope) + try f.store.save( + declaration: Declaration(components: [ + .subagent( + name: "researcher", description: "Research exact sources", + prompt: .literal("Read exact sources."), agents: [agent]) + ]), ledger: ResolvedLedger()) + let preview = try f.preview() + _ = try UpdateOperations.withPreparedUpdate(scope: scope, environment: f.environment) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + let snapshot = try UpdateOperations.inspect(scope: scope, environment: f.environment) + #expect(!snapshot.deployments.isEmpty) + #expect(snapshot.deployments.allSatisfy { $0.status == .current }) + let before = try snapshot.deployments.map { try Data(contentsOf: $0.location) } + let locked = try Data(contentsOf: f.store.resolvedURL) + for deployment in snapshot.deployments { + try FileManager.default.removeItem(at: deployment.location) + } + _ = try UpdateOperations.restore(scope: scope, environment: f.environment) + #expect(try snapshot.deployments.map { try Data(contentsOf: $0.location) } == before) + #expect(try Data(contentsOf: f.store.resolvedURL) == locked) + _ = try UpdateOperations.withPreparedUpdate( + .init(operation: .remove, selections: [try #require(snapshot.components.first?.selection)]), + scope: scope, environment: f.environment + ) { try $0.apply() } + #expect( + try UpdateOperations.inspect(scope: scope, environment: f.environment).components.isEmpty) + } +} + +extension NativeCompositionIntegrationTests { + @Test func ordinaryRoleEditPreservesAnUnselectedPrivateMCPRegionWithoutProviderReplay() throws { + struct InitialBindings: RuntimeBindingProvider { + func value(for binding: String, environment: RuntimeEnvironment) throws -> Data { + Data("private-native-sibling-canary".utf8) + } + } + struct NoReplay: RuntimeBindingProvider { + func value(for binding: String, environment: RuntimeEnvironment) throws -> Data { + throw CoreError.invalidState("unselected provider was replayed") + } + } + let f = try UpdateFixture() + func declaration(_ body: String) -> Declaration { + Declaration(components: [ + .mcpServer( + name: "private", + transport: .stdio( + .init(executable: "never-run", environment: ["TOKEN": .secret("token")])), + agents: [.codex]), + .subagent( + name: "researcher", description: "Research sources", prompt: .literal(body), + agents: [.codex]), + ]) + } + try f.store.save(declaration: declaration("Before."), ledger: ResolvedLedger()) + _ = try UpdateOperations.withPreparedUpdate( + environment: f.environment, bindingProvider: InitialBindings() + ) { try $0.apply() } + let request = UpdateRequest(operation: .declaration(declaration("After.")), kinds: [.subagent]) + let preview = try UpdateOperations.preview(request, environment: f.environment) + #expect( + !String(decoding: try JSONEncoder().encode(preview), as: UTF8.self).contains( + "private-native-sibling-canary")) + _ = try UpdateOperations.withPreparedUpdate( + request, environment: f.environment, bindingProvider: NoReplay() + ) { try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) } + let config = f.root.appendingPathComponent(".codex/config.toml") + #expect( + try String(contentsOf: config, encoding: .utf8).contains("private-native-sibling-canary")) + let mode = + try FileManager.default.attributesOfItem(atPath: config.path)[.posixPermissions] as? NSNumber + #expect((mode?.intValue ?? 0) & 0o777 == 0o600) + #expect( + try UpdateOperations.inspect(environment: f.environment).deployments.allSatisfy { + $0.status == .current + }) + } +} + +extension NativeCompositionIntegrationTests { + @Test func existingOpenCodeJSONCIsOneRecordedPhysicalTargetForMCPAndCommands() throws { + let f = try UpdateFixture() + let config = f.root.appendingPathComponent("opencode.jsonc") + try f.write("// User comment\n{\"userSetting\":true,}\n", to: config) + try f.store.save( + declaration: Declaration(components: [ + .command( + name: "review", description: "Review", prompt: .literal("Review sources."), + agents: [.opencode]), + .mcpServer( + name: "db", transport: .stdio(.init(executable: "never-run")), agents: [.opencode]), + ]), ledger: ResolvedLedger()) + _ = try f.apply() + let snapshot = try UpdateOperations.inspect(environment: f.environment) + #expect(snapshot.deployments.allSatisfy { $0.location == config && $0.status == .current }) + #expect( + !FileManager.default.fileExists(atPath: f.root.appendingPathComponent("opencode.json").path)) + let bytes = try Data(contentsOf: config) + #expect(String(decoding: bytes, as: UTF8.self).hasPrefix("// User comment\n")) + let locked = try Data(contentsOf: f.store.resolvedURL) + try FileManager.default.removeItem(at: config) + _ = try UpdateOperations.restore(environment: f.environment) + let restored = try UpdateOperations.inspect(environment: f.environment) + #expect(restored.deployments.allSatisfy { $0.location == config && $0.status == .current }) + #expect(try Data(contentsOf: f.store.resolvedURL) == locked) + #expect( + !FileManager.default.fileExists(atPath: f.root.appendingPathComponent("opencode.json").path)) + } +} diff --git a/Tests/AgentsUpdatesTests/NativePluginExportTests.swift b/Tests/AgentsUpdatesTests/NativePluginExportTests.swift new file mode 100644 index 0000000..32536d8 --- /dev/null +++ b/Tests/AgentsUpdatesTests/NativePluginExportTests.swift @@ -0,0 +1,154 @@ +import AgentsCore +import AgentsUpdates +import Foundation +import Testing + +@Suite("Native plugin export") +struct NativePluginExportTests { + private let package = BundlePackage( + name: "plugin-workbench", version: "1.0.0", + description: "Discoverable author description", author: "Fixture Author") + + @Test(arguments: NativePluginTarget.allCases) + func checkedTreePreservesFilesAndWiresTheLocalListing(_ target: NativePluginTarget) throws { + let fixture = try UpdateFixture() + let project = fixture.root.appendingPathComponent("author") + var environment = fixture.environment + environment.projectDirectory = project + let scaffold = try AuthorPackageOperations.scaffold( + package, at: project, environment: environment) + let skill = project.appendingPathComponent(scaffold.skills[0]) + let assets = skill.appendingPathComponent("assets") + try FileManager.default.createDirectory( + at: assets.appendingPathComponent("empty"), withIntermediateDirectories: true) + let bytes = Data([0, 255, 22, 4]) + try bytes.write(to: assets.appendingPathComponent("bytes.bin")) + try FileManager.default.createSymbolicLink( + atPath: assets.appendingPathComponent("linked.bin").path, withDestinationPath: "bytes.bin") + let script = skill.appendingPathComponent("run.sh") + try fixture.write("#!/bin/sh\ntouch never-created\n", to: script) + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: script.path) + try fixture.write( + """ + version: 1 + components: + - kind: mcpServer + name: docs + transport: {kind: streamableHTTP, url: 'https://example.invalid/mcp'} + """, + to: project.appendingPathComponent(".agent/agents.yaml")) + let artifact = try AuthorPackageOperations.preview( + .init(package: package, skills: scaffold.skills, mcpServers: ["docs"]), + environment: environment) + let marketplace = NativePluginMarketplace(name: "example-team", category: "Productivity") + let before = try FileHash.folderHash(fixture.root) + let checked = try NativePluginOperations.preview( + artifact, for: target, marketplace: marketplace, environment: environment) + #expect(try FileHash.folderHash(fixture.root) == before) + let repeated = try NativePluginOperations.preview( + artifact, for: target, marketplace: marketplace, environment: environment) + #expect(repeated.digest == checked.digest) + let (manifest, listing): (String, String) + switch target { + case .claudeCode: + (manifest, listing) = (".claude-plugin/plugin.json", ".claude-plugin/marketplace.json") + case .codex: + (manifest, listing) = (".codex-plugin/plugin.json", ".agents/plugins/marketplace.json") + } + let prefix = "plugins/plugin-workbench/" + let metadata = try json(checked, prefix + manifest) + #expect(metadata["description"] as? String == package.description) + #expect(metadata["skills"] as? String == "./skills/") + #expect(metadata["mcpServers"] as? String == "./.mcp.json") + let mcp = try json(checked, prefix + ".mcp.json") + let servers = try #require(mcp["mcpServers"] as? [String: [String: String]]) + #expect(servers["docs"]?["url"] == "https://example.invalid/mcp") + let catalog = try json(checked, listing) + let entries = try #require(catalog["plugins"] as? [[String: Any]]) + let entry = try #require(entries.first) + if target == .codex { + #expect((entry["source"] as? [String: String])?["path"] == "./plugins/plugin-workbench") + #expect( + (metadata["interface"] as? [String: String])?["longDescription"] == package.description) + } else { + #expect(entry["source"] as? String == "./plugins/plugin-workbench") + #expect(entry["description"] as? String == package.description) + } + + let destination = fixture.root.appendingPathComponent("distribution") + try FileManager.default.removeItem(at: project) + #expect(throws: CoreError.self) { + try NativePluginOperations.write( + checked, to: destination, expectedDigest: artifact.digest, environment: fixture.environment) + } + #expect(!FileManager.default.fileExists(atPath: destination.path)) + try NativePluginOperations.write( + checked, to: destination, expectedDigest: checked.digest, environment: fixture.environment) + try NativePluginOperations.write(checked, to: destination, environment: fixture.environment) + let copied = destination.appendingPathComponent(prefix + "skills/getting-started") + #expect(try fixture.bytes(copied.appendingPathComponent("assets/linked.bin")) == bytes) + #expect( + FileManager.default.fileExists(atPath: copied.appendingPathComponent("assets/empty").path)) + let mode = try #require( + FileManager.default.attributesOfItem(atPath: copied.appendingPathComponent("run.sh").path)[ + .posixPermissions] as? NSNumber) + #expect(mode.intValue & 0o111 != 0) + #expect( + !FileManager.default.fileExists(atPath: copied.appendingPathComponent("never-created").path)) + let extra = destination.appendingPathComponent("occupied") + try fixture.write("Preserve me", to: extra) + #expect(throws: CoreError.self) { + try NativePluginOperations.write(checked, to: destination, environment: fixture.environment) + } + #expect(try fixture.bytes(extra) == Data("Preserve me".utf8)) + } + + @Test func claudePreservesSymbolicBindingsAndItsBundledProgramWithoutLaunchingIt() throws { + let fixture = try UpdateFixture() + let program = fixture.root.appendingPathComponent("mcp/fixture") + try fixture.write("#!/bin/sh\ntouch never-created\n", to: program) + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: program.path) + try fixture.write( + """ + version: 1 + components: + - kind: mcpServer + name: fixture + transport: + kind: stdio + executable: ./mcp/fixture + arguments: ['--token=redact-me', serve] + environment: + REGION: {env: FIXTURE_REGION} + TOKEN: {secret: fixture_token} + """, + to: fixture.store.declarationURL) + let artifact = try AuthorPackageOperations.preview( + .init(package: package, mcpServers: ["fixture"]), environment: fixture.environment) + #expect(artifact.warnings.map(\.count) == [1]) + let plugin = try NativePluginOperations.preview( + artifact, for: .claudeCode, environment: fixture.environment) + let mcp = try json(plugin, ".mcp.json") + let servers = try #require(mcp["mcpServers"] as? [String: [String: Any]]) + let fields = try #require(servers["fixture"]) + #expect( + fields["command"] as? String == "${CLAUDE_PLUGIN_ROOT}/mcp-resources/fixture/mcp/fixture") + #expect( + fields["env"] as? [String: String] == [ + "REGION": "${FIXTURE_REGION}", "TOKEN": "${user_config.fixture_token}", + ]) + #expect(fields["args"] as? [String] == ["serve"]) + #expect(try plugin.contents(at: "mcp-resources/fixture/mcp/fixture") == fixture.bytes(program)) + let manifest = try json(plugin, ".claude-plugin/plugin.json") + let config = try #require(manifest["userConfig"] as? [String: [String: Any]]) + #expect(config["fixture_token"]?["sensitive"] as? Bool == true) + #expect( + !String(decoding: try #require(plugin.contents(at: ".mcp.json")), as: UTF8.self).contains( + "redact-me")) + } + + private func json(_ artifact: NativePluginArtifact, _ path: String) throws -> [String: Any] { + let data = try #require(artifact.contents(at: path)) + return try #require(JSONSerialization.jsonObject(with: data) as? [String: Any]) + } +} diff --git a/Tests/AgentsUpdatesTests/OrganizationPolicyTests.swift b/Tests/AgentsUpdatesTests/OrganizationPolicyTests.swift new file mode 100644 index 0000000..cc179d1 --- /dev/null +++ b/Tests/AgentsUpdatesTests/OrganizationPolicyTests.swift @@ -0,0 +1,434 @@ +import AgentsCore +import AgentsInstructions +import Foundation +import Testing + +@testable import AgentsUpdates + +struct OrganizationPolicyTests { + @Test func hostEnvironmentSelectsRequiredPoliciesByScope() throws { + let fixture = try UpdateFixture() + let user = fixture.root.appendingPathComponent("team.yaml") + try fixture.write("enforcement: warn", to: user) + let environment = RuntimeEnvironment( + projectDirectory: fixture.environment.projectDirectory, + homeDirectory: fixture.environment.homeDirectory, + environment: [ + "AGENTS_USER_ORGANIZATION_POLICY": user.path, + "AGENTS_PROJECT_ORGANIZATION_POLICY": "project-relative.yaml", + ]) + let project = try OrganizationPolicyOperations.status(scope: .project, environment: environment) + #expect(project.policies.map(\.outcome) == [.loaded, .unavailable]) + #expect(project.isBlocked) + let global = try OrganizationPolicyOperations.status(scope: .user, environment: environment) + #expect(global.policies.map(\.outcome) == [.loaded]) + #expect(!global.isBlocked) + #expect(throws: OrganizationPolicyFailure.self) { + try UpdateOperations.withPreparedUpdate(request(fixture), environment: environment) { + try $0.apply() + } + } + #expect(!FileManager.default.fileExists(atPath: fixture.store.directory.path)) + } + + @Test func hardSourceDenialStillRefusesWithOrganizationOff() throws { + let fixture = try UpdateFixture() + var environment = try configured(fixture, "enforcement: off") + let user = SourcePolicyOperations.policyURL(scope: .user, environment: environment) + try fixture.write("version: 1\ndeny: [local]\n", to: user) + let project = fixture.root.appendingPathComponent("project-policy.yaml") + try fixture.write("enforcement: off\nsources: {allow: [local]}", to: project) + environment.projectOrganizationPolicy = .init(.local(project)) + let report = try OrganizationPolicyOperations.status(environment: environment) + #expect(report.policies.map(\.mode) == [.off, .off]) + #expect(throws: SourcePolicyFailure.self) { + try UpdateOperations.withPreparedUpdate(request(fixture), environment: environment) { + try $0.apply() + } + } + #expect(!FileManager.default.fileExists(atPath: fixture.store.directory.path)) + } + + @Test func parentAndIndependentUserAuthorityKeepTheirRestrictions() throws { + let fixture = try UpdateFixture() + let parent = fixture.root.appendingPathComponent("parent.yaml") + try fixture.write( + "enforcement: block\nsources: {allow: [], deny: []}", to: parent) + var environment = try configured( + fixture, "extends: parent.yaml\nenforcement: off\nsources: {allow: null}") + let project = fixture.root.appendingPathComponent("project-policy.yaml") + try fixture.write("enforcement: warn\nsources: {deny: [local]}", to: project) + environment.projectOrganizationPolicy = .init(.local(project)) + let status = try OrganizationPolicyOperations.status(environment: environment) + #expect(status.policies.map(\.mode) == [.block, .warn]) + #expect( + status.policies[0].documents.map(\.url.lastPathComponent) == ["parent.yaml", "org.yaml"]) + do { + _ = try UpdateOperations.preview(request(fixture), environment: environment) + Issue.record("An empty parent allow list admitted a source.") + } catch let error as OrganizationPolicyFailure { + #expect( + error.report.findings.contains { + $0.authority == .user && $0.rule == "source-allow" && $0.document == parent + && $0.outcome == .block + }) + #expect( + error.report.findings.contains { + $0.authority == .project && $0.rule == "source-deny" && $0.outcome == .warn + }) + } + #expect(!FileManager.default.fileExists(atPath: fixture.store.directory.path)) + } + + @Test func warningInstallsAndReadOnlyAuditKeepsAttribution() throws { + let fixture = try UpdateFixture() + let environment = try configured(fixture, "enforcement: warn\nsources: {deny: [local]}") + let report = try UpdateOperations.preview(request(fixture), environment: environment) + let advisory = try #require(report.organizationPolicy) + #expect(!advisory.isBlocked) + #expect(advisory.findings.contains { $0.rule == "source-deny" && $0.outcome == .warn }) + _ = try UpdateOperations.withPreparedUpdate(request(fixture), environment: environment) { + try $0.apply(ifUnchangedFrom: report.displayedFingerprint) + } + #expect(FileManager.default.fileExists(atPath: fixture.target().path)) + let before = try FileHash.folderHash(fixture.root) + let audit = try OrganizationPolicyOperations.audit(environment: environment) + #expect(audit.hasLock && !audit.isBlocked) + let previewAttribution = try #require(advisory.findings.first { $0.rule == "source-deny" }) + #expect(audit.organization.findings.contains(previewAttribution)) + #expect(try FileHash.folderHash(fixture.root) == before) + } + + @Test func directInstallDenialsCreateNoScopeOrTargetArtifacts() throws { + let early = try UpdateFixture() + let first = try configured( + early, "enforcement: block\ndependencies: {require_pinned_constraint: true}") + let remote = SourceDeclaration( + kind: .git, location: "https://never-contact.invalid/example/repo", + requirement: .branch("main")) + let moving = UpdateRequest( + operation: .declaration( + Declaration( + sources: ["remote": remote], skills: ["remote": .init(select: .names(["demo"]))]))) + let initial = try FileHash.folderHash(early.root) + do { + _ = try UpdateOperations.withPreparedUpdate(moving, environment: first) { try $0.apply() } + Issue.record("A moving authored branch was admitted.") + } catch let error as OrganizationPolicyFailure { + #expect(error.report.findings.map(\.rule) == ["dependency-pinned-constraint"]) + } + #expect(try FileHash.folderHash(early.root) == initial) + #expect(!FileManager.default.fileExists(atPath: early.store.directory.path)) + + let late = try UpdateFixture() + let run = late.repo.appendingPathComponent("skills/demo/run.sh") + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: run.path) + try late.commit() + let second = try configured(late, "enforcement: block\nexecutables: {deny_all: true}") + let before = try FileHash.folderHash(late.root) + do { + _ = try UpdateOperations.withPreparedUpdate(request(late), environment: second) { + try $0.apply() + } + Issue.record("Resolved executable was admitted.") + } catch let error as OrganizationPolicyFailure { + #expect(error.report.findings.contains { $0.rule == "executables-deny" }) + } + #expect(try FileHash.folderHash(late.root) == before) + #expect(!FileManager.default.fileExists(atPath: late.store.directory.path)) + #expect(!FileManager.default.fileExists(atPath: late.target().path)) + } + + @Test func policyChangeDuringConfirmationRefusesBeforePublication() throws { + let fixture = try UpdateFixture() + let environment = try configured(fixture, "enforcement: warn\nsources: {deny: [local]}") + let selection = try #require(environment.userOrganizationPolicy) + guard case .local(let url) = selection.source else { return } + let report = try UpdateOperations.preview(request(fixture), environment: environment) + #expect(throws: UpdateApplyError.self) { + try UpdateOperations.withPreparedUpdate(request(fixture), environment: environment) { + update in + try fixture.write("enforcement: block\nsources: {deny: [local]}", to: url) + return try update.apply(ifUnchangedFrom: report.displayedFingerprint) + } + } + #expect(!FileManager.default.fileExists(atPath: fixture.store.resolvedURL.path)) + #expect(!FileManager.default.fileExists(atPath: fixture.target().path)) + #expect(!FileManager.default.fileExists(atPath: fixture.store.cacheDirectory.path)) + } + + @Test func requiredMCPDistinguishesIntentFromDeploymentAndCIStartsNoProgram() throws { + let fixture = try UpdateFixture() + let marker = fixture.root.appendingPathComponent("execution-marker") + let transport = MCPTransportDeclaration.stdio( + .init(executable: "touch", arguments: [marker.path])) + let absent = Declaration(components: [ + .mcpServer( + name: "tools", transport: transport, agents: [.codex], condition: .init(scopes: [.user])) + ]) + let environment = try configured( + fixture, + """ + enforcement: block + mcp: + require: [inline/tools] + transport: {allow: [stdio]} + """) + let intentOnly = UpdateRequest(operation: .declaration(absent)) + do { + _ = try UpdateOperations.preview(intentOnly, environment: environment) + Issue.record("A server outside the selected scope satisfied deployment.") + } catch let error as OrganizationPolicyFailure { + #expect(error.report.findings.contains { $0.rule == "mcp-required-deployment" }) + #expect(!error.report.findings.contains { $0.rule == "mcp-required-declaration" }) + } + try fixture.write( + "---\ndescription: Rules\n---\n# Rules\n", + to: fixture.root.appendingPathComponent(".agent/instructions/rules.md")) + let present = Declaration(components: [ + .mcpServer(name: "tools", transport: transport, agents: [.codex]), + .instructions(.init(agents: [.codex], sections: ["rules"])), + ]) + try fixture.store.save(declaration: present, ledger: ResolvedLedger()) + do { + _ = try InstructionOperations.previewOutputs(environment: environment) + Issue.record("Instruction preview admitted an undeployed required server.") + } catch let error as OrganizationPolicyFailure { + #expect(error.report.findings.contains { $0.rule == "mcp-required-deployment" }) + } + let update = try UpdateOperations.withPreparedUpdate(environment: environment) { + try $0.apply() + } + let beforePreview = try FileHash.folderHash(fixture.root) + let preview = try InstructionOperations.previewOutputs(environment: environment) + #expect(preview.organizationPolicy?.isBlocked == false) + #expect(preview.instructions.outputs.count == 1) + #expect(preview.instructions.outputs == update.report.instructions.outputs) + #expect(try FileHash.folderHash(fixture.root) == beforePreview) + #expect(!(try OrganizationPolicyOperations.audit(environment: environment)).isBlocked) + #expect(!FileManager.default.fileExists(atPath: marker.path)) + + try fixture.write("version: 1\n", to: fixture.store.declarationURL) + let before = try FileHash.folderHash(fixture.root) + let stale = try OrganizationPolicyOperations.audit(environment: environment) + #expect(stale.isBlocked) + #expect(stale.organization.findings.contains { $0.rule == "mcp-required-declaration" }) + #expect(try FileHash.folderHash(fixture.root) == before) + } + + @Test func instructionPreviewEnforcesContentPolicyOnCopyProducts() throws { + let fixture = try UpdateFixture() + let environment = try configured( + fixture, "enforcement: block\nmanifest: {content_types: {allow: [skills]}}") + try fixture.write( + """ + version: 1 + sources: {fixture: {path: ./source}} + components: + - kind: instructions + sections: [{name: rules, source: fixture, recipients: [chatgpt-app]}] + """, to: fixture.store.declarationURL) + let before = try fixture.snapshot() + do { + _ = try InstructionOperations.previewOutputs(environment: environment) + Issue.record("Instruction preview admitted a prohibited copy product.") + } catch let error as OrganizationPolicyFailure { + #expect(error.report.findings.contains { $0.rule == "manifest-content-types" }) + } + #expect(try fixture.snapshot() == before) + } + + @Test func unmanagedAndDriftUsePassiveWorkspaceEvidence() throws { + let fixture = try UpdateFixture() + _ = try UpdateOperations.withPreparedUpdate(request(fixture), environment: fixture.environment) + { + try $0.apply() + } + let rogue = fixture.root.appendingPathComponent(".agents/skills/rogue/SKILL.md") + try fixture.write("unmanaged content", to: rogue) + try fixture.write("changed deployment", to: fixture.target().appendingPathComponent("SKILL.md")) + let environment = try configured( + fixture, + """ + enforcement: block + unmanaged_files: {action: deny, directories: [.agents/skills]} + security: {audit: {fail_on_drift: true}, integrity: {require_hashes: true}} + """) + let before = try FileHash.folderHash(fixture.root) + let audit = try OrganizationPolicyOperations.audit(environment: environment) + #expect(audit.organization.findings.contains { $0.rule == "workspace-drift" }) + #expect( + audit.organization.findings.contains { + $0.rule == "workspace-unmanaged" && $0.identity == ".agents/skills/rogue/SKILL.md" + }) + #expect( + !audit.organization.findings.contains { + $0.rule == "workspace-unmanaged" && $0.identity.contains("/demo/") + }) + #expect(try FileHash.folderHash(fixture.root) == before) + } + + @Test func boundedHTTPSCacheRequiresAnEligibleCompleteChain() throws { + let fixture = try UpdateFixture() + let leaf = try #require(URL(string: "https://policy.example/leaf")) + let parent = try #require(URL(string: "https://policy.example/parent")) + let foreign = try #require(URL(string: "https://other.example/parent")) + var environment = fixture.environment + environment.userOrganizationPolicy = .init(.https(leaf)) + let store = StateStore(scope: .project, environment: environment) + let time = Date(timeIntervalSince1970: 4_000_000) + var calls: [URL] = [] + let first = try OrganizationPolicySnapshot(store: store, now: time) { url in + calls.append(url) + let policy = + url == leaf + ? "extends: https://policy.example/parent\nenforcement: warn\ncache: {ttl: 10}" + : "enforcement: block\nfetch_failure: block\ncache: {ttl: 5}" + return .init(status: 200, url: url, bytes: Data(policy.utf8)) + } + #expect(calls == [leaf, parent]) + #expect(first.statuses.first?.mode == .block) + let cache = environment.homeDirectory.appendingPathComponent( + ".cache/agents/organization-policies") + #expect(!FileManager.default.fileExists(atPath: cache.path)) + calls.removeAll() + let reviewed = try OrganizationPolicySnapshot( + store: store, now: time.addingTimeInterval(4), offlineObservations: first + ) { url in + calls.append(url) + throw OrganizationPolicyLoader.Offline() + } + #expect(calls.isEmpty) + #expect(reviewed.fingerprint == first.fingerprint) + #expect(reviewed.statuses.first?.mode == .block) + #expect(!FileManager.default.fileExists(atPath: cache.path)) + + first.rememberVerifiedPolicies() + + calls.removeAll() + let fresh = try OrganizationPolicySnapshot(store: store, now: time.addingTimeInterval(4)) { + url in + calls.append(url) + throw OrganizationPolicyLoader.Offline() + } + #expect(calls.isEmpty) + #expect(fresh.statuses.first?.documents.allSatisfy { !$0.stale } == true) + let stale = try OrganizationPolicySnapshot(store: store, now: time.addingTimeInterval(6)) { + url in + calls.append(url) + throw OrganizationPolicyLoader.Offline() + } + #expect(calls == [leaf, parent]) + #expect(stale.statuses.first?.documents.allSatisfy(\.stale) == true) + let expired = try OrganizationPolicySnapshot( + store: store, now: time.addingTimeInterval(7 * 86_400 + 1) + ) { _ in throw OrganizationPolicyLoader.Offline() } + #expect(expired.report().isBlocked) + #expect(expired.statuses.first?.documents.isEmpty == true) + + let redirected = try OrganizationPolicySnapshot(store: store, now: time.addingTimeInterval(50)) + { + url in + .init( + status: 200, url: url == parent ? foreign : url, + bytes: Data( + (url == leaf ? "extends: https://policy.example/parent" : "enforcement: off").utf8)) + } + #expect(redirected.report().isBlocked) + #expect(redirected.statuses.first?.outcome == .unavailable) + + let auth = try OrganizationPolicySnapshot(store: store, now: time.addingTimeInterval(80)) { + url in .init(status: 403, url: url, bytes: Data()) + } + #expect(auth.report().isBlocked) + #expect(auth.statuses.first?.outcome == .unavailable) + } + + @Test func discoversAnOrganizationFromTheCallerRemoteAndCanRequirePresence() throws { + let fixture = try UpdateFixture() + let absent = try OrganizationPolicyOperations.status(environment: fixture.environment) + #expect(absent.policies.map(\.outcome) == [.absent]) + let mandatory = try OrganizationPolicyOperations.audit( + environment: fixture.environment, requireOrganizationPolicy: true) + #expect(mandatory.isBlocked) + #expect(mandatory.organization.findings.map(\.rule) == ["policy-required"]) + + var environment = fixture.environment + environment.userOrganizationPolicy = .init( + .organization(gitRemote: "git@github.com:Team/Main.git")) + let store = StateStore(scope: .project, environment: environment) + var requests: [String] = [] + let status = try OrganizationPolicySnapshot(store: store) { url in + requests.append(url.path) + return .init( + status: url.path.contains("/.github-private/") ? 404 : 200, + url: url, bytes: Data("enforcement: block".utf8)) + } + #expect( + requests == [ + "/team/.github-private/HEAD/agents-policy.yaml", "/team/.github/HEAD/agents-policy.yaml", + ]) + #expect(status.statuses.first?.mode == .block) + #expect(!status.report().isBlocked) + #expect(!FileManager.default.fileExists(atPath: fixture.store.directory.path)) + } + + @Test func stableManifestRulesInspectPresentFieldsAndSelection() throws { + let fixture = try UpdateFixture() + let environment = try configured( + fixture, + """ + enforcement: block + manifest: + required_fields: [version, components] + require_explicit_includes: true + content_types: {allow: [skills]} + """) + let request = UpdateRequest( + operation: .declaration( + .init( + sources: ["demo": .init(kind: .local, location: fixture.repo.path)], + skills: ["demo": .init(select: .all, agents: [.codex], mode: .copy)]))) + do { + _ = try UpdateOperations.preview(request, environment: environment) + Issue.record("An implicit selection was admitted.") + } catch let error as OrganizationPolicyFailure { + #expect(error.report.findings.contains { $0.rule == "manifest-explicit-includes" }) + #expect(!error.report.findings.contains { $0.rule == "manifest-required-field" }) + } + } + + @Test func invalidParentAndCyclesNeverApplyAPartialPolicy() throws { + let fixture = try UpdateFixture() + let environment = try configured(fixture, "enforcement: warn\nextends: parent.yaml") + let parent = fixture.root.appendingPathComponent("parent.yaml") + for yaml in ["enforcement: [block]", "extends: org.yaml"] { + try fixture.write(yaml, to: parent) + let status = try OrganizationPolicyOperations.status(environment: environment) + #expect(status.isBlocked && status.policies.first?.documents.isEmpty == true) + } + for index in 0..<5 { + let url = fixture.root.appendingPathComponent("level-\(index).yaml") + try fixture.write( + index < 4 ? "extends: level-\(index + 1).yaml" : "enforcement: block", to: url) + } + try fixture.write("extends: level-0.yaml", to: parent) + #expect(try OrganizationPolicyOperations.status(environment: environment).isBlocked) + } + + private func configured(_ fixture: UpdateFixture, _ yaml: String) throws -> RuntimeEnvironment { + let policy = fixture.root.appendingPathComponent("org.yaml") + try fixture.write(yaml, to: policy) + var environment = fixture.environment + environment.userOrganizationPolicy = .init(.local(policy)) + return environment + } + + private func request(_ fixture: UpdateFixture) -> UpdateRequest { + .init( + operation: .declaration( + .init( + sources: ["demo": .init(kind: .local, location: fixture.repo.path)], + skills: ["demo": .init(select: .names(["demo"]), agents: [.codex], mode: .copy)]))) + } +} diff --git a/Tests/AgentsUpdatesTests/PackageLifecycleTLSTests.swift b/Tests/AgentsUpdatesTests/PackageLifecycleTLSTests.swift new file mode 100644 index 0000000..34437da --- /dev/null +++ b/Tests/AgentsUpdatesTests/PackageLifecycleTLSTests.swift @@ -0,0 +1,242 @@ +#if os(macOS) + import AgentsCore + import AgentsManifest + import Darwin + import Foundation + import Testing + + @testable import AgentsUpdates + + @Suite("Package lifecycle loopback TLS") + struct PackageLifecycleTLSTests { + @Test(.enabled(if: ProcessInfo.processInfo.environment["AGENTS_TEST_LIFECYCLE_TLS"] == "1")) + func dispatchOrderingResponseWaitingAndRedaction() async throws { + let fixture = try LifecycleFixture() + let transport = try LifecycleLoopbackTLS(fixture: fixture) + try await fixture.withoutAdministratorFiles { + try await LifecycleHTTPClient.$loopbackTrustAnchorForTesting.withValue(transport.anchor) { + var environment = fixture.environment + environment.environment["FIXTURE_TOKEN"] = "synthetic-token-value" + environment.environment["FIXTURE_BUILD"] = "synthetic-build" + try fixture.write( + """ + version: 1 + lifecycle: + pre-install: + - type: http + url: \(transport.origin)/pre?private=synthetic-query + headers: {Authorization: 'Bearer ${FIXTURE_TOKEN}', X-Build: '$FIXTURE_BUILD'} + allowedEnvVars: [FIXTURE_TOKEN] + timeout: 5 + post-install: + - {type: http, url: "\(transport.origin)/redirect", timeout: 5} + pre-update: + - type: http + url: \(transport.origin)/wait + timeout: 5 + - type: command + run: 'printf second >> count' + pre-uninstall: + - type: http + url: \(transport.origin)/blocked + headers: {Authorization: 'Bearer ${FIXTURE_TOKEN}'} + post-uninstall: + - {type: http, url: "\(transport.origin)/lost", timeout: 2} + """) + _ = try await fixture.enable() + let req = UpdateRequest(operation: .edit([.setDefaultAgents([.codex])])) + let review = try UpdateOperations.previewLifecycle( + req, intent: .install, environment: environment) + #expect(!fixture.exists(transport.path("pre-hit"))) + let output = try fixture.completed( + await UpdateOperations.perform( + review, + onDispatch: { summary in + if summary.event == .preInstall { + #expect(!fixture.exists(fixture.store.resolvedURL)) + } + })) + _ = try output.package.result.get() + #expect(output.pre.map(\.disposition) == [.httpSucceeded]) + #expect(output.pre.map(\.httpStatus) == [202]) + #expect(output.post.map(\.disposition) == [.httpRejected]) + #expect(output.post.map(\.httpStatus) == [307]) + #expect(!fixture.exists(transport.path("never-hit"))) + #expect(try String(contentsOf: transport.path("pre-hit"), encoding: .utf8) == "verified") + let resultBytes = try JSONEncoder().encode(output.pre) + let report = String(decoding: resultBytes, as: UTF8.self) + #expect(!report.contains("synthetic-token-value")) + #expect(!report.contains("synthetic-query")) + #expect(!report.contains("synthetic-build")) + + let preview = LifecycleOperations.simulate(.preUpdate, environment: environment) + #expect(!fixture.exists(transport.path("wait-hit"))) + let running = Task { await LifecycleOperations.executeTest(preview) } + try await transport.awaitMarker("wait-hit") + #expect(!fixture.exists(fixture.counter)) + try Data().write(to: transport.path("wait-release")) + let tested = try fixture.completed(await running.value) + #expect(tested.map(\.disposition) == [.httpSucceeded, .commandSucceeded]) + #expect(try fixture.counterText() == "second") + + let blocked = LifecycleOperations.simulate(.preUninstall, environment: environment) + let refused = try fixture.completed(await LifecycleOperations.executeTest(blocked)) + #expect(refused.map(\.withholding) == [.headerExpansionRefused]) + #expect(!fixture.exists(transport.path("blocked-hit"))) + + let lost = LifecycleOperations.simulate(.postUninstall, environment: environment) + let unknown = try fixture.completed(await LifecycleOperations.executeTest(lost)) + #expect(unknown.map(\.disposition) == [.deliveryUnknown]) + #expect(unknown.map(\.dispatched) == [true]) + #expect(try String(contentsOf: transport.path("lost-hit"), encoding: .utf8) == "hit\n") + } + } + } + } + + private final class LifecycleLoopbackTLS: @unchecked Sendable { + let anchor: Data + private(set) var origin = "" + private let root: URL + private let server = Process() + private let exited = DispatchSemaphore(value: 0) + + init(fixture: LifecycleFixture) throws { + root = fixture.root + func path(_ name: String) -> URL { fixture.root.appendingPathComponent(name) } + let authority = path("authority.pem") + let authorityKey = path("authority.key") + let key = path("server.key") + let certificate = path("server.pem") + let request = path("server.csr") + let extensions = path("server.conf") + let certificateDER = path("authority.der") + try Self.openssl([ + "req", "-x509", "-newkey", "rsa:2048", "-days", "1", "-nodes", + "-subj", "/CN=Agents Synthetic Lifecycle", "-keyout", authorityKey.path, + "-out", authority.path, + ]) + try Self.openssl([ + "req", "-new", "-newkey", "rsa:2048", "-nodes", "-subj", "/CN=127.0.0.1", + "-keyout", key.path, "-out", request.path, + ]) + try Data( + """ + basicConstraints = critical,CA:FALSE + subjectAltName = IP:127.0.0.1 + extendedKeyUsage = serverAuth + """.utf8 + ).write(to: extensions) + try Self.openssl([ + "x509", "-req", "-in", request.path, "-CA", authority.path, "-CAkey", authorityKey.path, + "-CAcreateserial", "-days", "1", "-extfile", extensions.path, "-out", certificate.path, + ]) + try Self.openssl([ + "x509", "-in", authority.path, "-outform", "der", "-out", certificateDER.path, + ]) + anchor = try Data(contentsOf: certificateDER) + + server.executableURL = URL(fileURLWithPath: "/usr/bin/env") + server.arguments = ["python3", "-c", Self.handler, fixture.root.path, fixture.project.path] + server.standardOutput = FileHandle.nullDevice + let diagnostics = fixture.root.appendingPathComponent("tls-diagnostics") + FileManager.default.createFile(atPath: diagnostics.path, contents: nil) + server.standardError = try FileHandle(forWritingTo: diagnostics) + server.terminationHandler = { [exited] _ in exited.signal() } + try server.run() + let deadline = ContinuousClock.now + .seconds(5) + var selectedPort: Int? + while server.isRunning && ContinuousClock.now < deadline { + if let content = try? String(contentsOf: path("tls-port"), encoding: .utf8), + let port = Int(content) + { + selectedPort = port + break + } + Thread.sleep(forTimeInterval: 0.01) + } + guard let selectedPort else { + stop() + let detail = (try? String(contentsOf: diagnostics, encoding: .utf8)) ?? "" + throw CoreError.invalidState("Synthetic TLS server could not start: " + detail) + } + origin = "https://127.0.0.1:\(selectedPort)" + } + + deinit { stop() } + + private func stop() { + guard server.isRunning else { return } + server.terminate() + if exited.wait(timeout: .now() + .seconds(3)) == .timedOut { + _ = kill(server.processIdentifier, SIGKILL) + #expect(exited.wait(timeout: .now() + .seconds(3)) == .success) + } + } + + func path(_ name: String) -> URL { root.appendingPathComponent(name) } + + func awaitMarker(_ name: String) async throws { + let deadline = ContinuousClock.now + .seconds(5) + while !FileManager.default.fileExists(atPath: path(name).path), ContinuousClock.now < deadline + { + try await Task.sleep(for: .milliseconds(10)) + } + try #require(FileManager.default.fileExists(atPath: path(name).path)) + } + + private static func openssl(_ arguments: [String]) throws { + _ = try ProcessRunner.run("/usr/bin/openssl", arguments: arguments) + } + + private static let handler = """ + import http.server, json, pathlib, socket, ssl, sys, time, urllib.parse + root = pathlib.Path(sys.argv[1]) + project = pathlib.Path(sys.argv[2]) + class Handler(http.server.BaseHTTPRequestHandler): + def do_POST(self): + path = urllib.parse.urlsplit(self.path).path + body = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) + marker = root / (path.lstrip("/") + "-hit") + if path == "/lost": + with marker.open("a") as file: + file.write("hit\\n") + self.connection.shutdown(socket.SHUT_RDWR) + return + marker.touch() + status = 204 + if path == "/pre": + deadline = time.monotonic() + 4 + ledger = project / ".agent" / "agents.resolved" + while not ledger.exists() and time.monotonic() < deadline: + time.sleep(0.01) + valid = ( + ledger.exists() and body == {"version": 1, "event": "pre-install", "scope": "project", "test": False} + and self.headers.get("Authorization") == "Bearer synthetic-token-value" + and self.headers.get("X-Build") == "synthetic-build" + and self.headers.get("Cookie") is None + ) + if valid: + marker.write_text("verified") + status = 202 if valid else 422 + if path == "/wait": + deadline = time.monotonic() + 4 + while not (root / "wait-release").exists() and time.monotonic() < deadline: + time.sleep(0.01) + status = 204 if body["test"] and (root / "wait-release").exists() else 422 + if path == "/redirect": + self.send_response(307) + self.send_header("Location", "/never") + self.end_headers() + return + self.send_response(status) + self.end_headers() + server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) + context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + context.load_cert_chain(root / "server.pem", root / "server.key") + server.socket = context.wrap_socket(server.socket, server_side=True) + (root / "tls-port").write_text(str(server.server_port)) + server.serve_forever() + """ + } +#endif diff --git a/Tests/AgentsUpdatesTests/PackageLifecycleTests.swift b/Tests/AgentsUpdatesTests/PackageLifecycleTests.swift new file mode 100644 index 0000000..e12fc05 --- /dev/null +++ b/Tests/AgentsUpdatesTests/PackageLifecycleTests.swift @@ -0,0 +1,740 @@ +import AgentsInstructions +import AgentsManifest +import CPlatform +import Foundation +import StateTestSupport +import Testing + +@testable import AgentsCore +@testable import AgentsUpdates + +@Suite("Package-manager lifecycle", .serialized) +struct PackageLifecycleTests { + @Test func readOnlyPreviewAndCanonicalEdit() async throws { + let fixture = try LifecycleFixture() + try await fixture.withoutAdministratorFiles { + try fixture.write( + """ + version: 1 + # user formatting + lifecycle: + pre-install: + - type: command + run: 'echo fixture' + - {run: 'echo fixture', type: command} + """) + let before = try fixture.readDeclaration() + let preview = LifecycleOperations.simulate(.preInstall, environment: fixture.environment) + #expect(preview.inspection.actions.count == 2) + #expect(preview.inspection.actions.map(\.index) == [0, 1]) + #expect(preview.inspection.actions.allSatisfy { $0.withheld == .projectUntrusted }) + #expect(try fixture.readDeclaration() == before) + #expect(!fixture.exists(fixture.home.appendingPathComponent(".agents"))) + #expect(!fixture.exists(fixture.store.resolvedURL)) + + let grant = try await fixture.enable() + let snapshot = try fixture.store.loadManifest() + let document = try #require(snapshot) + let change = try document.preparing([.setDefaultAgents([.codex])]) + try Data(change.bytes).write(to: fixture.store.declarationURL) + let after = try fixture.readDeclaration() + #expect(after.contains("# user formatting")) + #expect(after.contains("run: 'echo fixture'")) + #expect( + LifecycleOperations.list(environment: fixture.environment).projectTrusted) + try fixture.write( + """ + # same lifecycle data + version: 1 + lifecycle: {pre-install: [{run: "echo fixture", type: command}, {type: command, run: "echo fixture"}]} + """) + let rereview = try LifecycleOperations.reviewEnable(environment: fixture.environment) + #expect(rereview.enablement.digest == grant.digest) + #expect(rereview.enablement.expectedRevision == 1) + try fixture.write( + """ + version: 1 + lifecycle: {pre-install: [{run: "echo edited", type: command}, {type: command, run: "echo fixture"}]} + """) + #expect( + !LifecycleOperations.list(environment: fixture.environment).projectTrusted) + } + } + + @Test func validationAggregatesFieldsAndAdministratorShape() async throws { + let fixture = try LifecycleFixture() + try await fixture.withoutAdministratorFiles { + try fixture.write( + """ + version: 1 + lifecycle: + bad-event: [] + pre-install: + - {type: command, command: echo one, bash: echo two, url: http://example.invalid} + - {type: http, url: https://me:password@example.invalid, headers: {X-Test: 7}} + - {type: other, timeout: 301} + post-install: {type: command} + """) + let errors = LifecycleOperations.validate(environment: fixture.environment) + #expect(errors.count == 8) + #expect(errors.allSatisfy { $0.source.file == fixture.store.declarationURL }) + #expect(errors.contains { $0.event == "bad-event" }) + #expect(errors.contains { $0.event == "pre-install" && $0.index == 1 && $0.field == "url" }) + #expect( + errors.contains { $0.event == "pre-install" && $0.index == 2 && $0.field == "timeout" }) + #expect(!errors.contains { $0.message.contains("password") }) + #expect(LifecycleOperations.list(environment: fixture.environment).actions.isEmpty) + } + + var discovery = LifecycleDiscovery() + let admin = LifecycleSource( + authority: .administrator, file: fixture.root.appendingPathComponent("a.json")) + try discovery.addAdmin( + input: ( + Data(#"{"version":2,"scripts":{"bad":[],"pre-compile":[{"type":"command"}]}}"#.utf8), + "fixture" + ), source: admin) + #expect(discovery.administratorInvalid) + #expect(discovery.actions.isEmpty) + #expect(discovery.diagnostics.count == 3) + var good = LifecycleDiscovery() + try good.addAdmin( + input: ( + Data( + #"{"version":1,"scripts":{"pre-compile":[{"type":"command","bash":"exit 7"},{"type":"command","bash":"exit 7"}]}}"# + .utf8), + "fixture" + ), source: admin) + #expect(!good.administratorInvalid) + #expect(good.actions.map { $0.value.index } == [0, 1]) + let declared = try #require(good.actions.first) + let opened = try DirectoryHandle.readDirectory(at: fixture.project) + let launched = try LifecycleCommand.spawn( + declared, in: opened, environment: fixture.environment) + let reported = await LifecycleCommand.finish( + launched, action: declared.summary(), payload: Data("{}".utf8)) + #expect(reported.disposition == .commandFailed) + #expect(reported.exitStatus == 7) + #expect(throws: (any Error).self) { + try good.addAdmin( + input: (Data(#"{"version":1,"version":1,"scripts":{}}"#.utf8), "fixture"), source: admin) + } + } + + @Test func confirmationClaimsOnceAndFreshReviewRunsAgain() async throws { + let fixture = try LifecycleFixture() + try await fixture.withoutAdministratorFiles { + try fixture.write( + """ + version: 1 + lifecycle: + pre-install: + - {type: command, run: 'printf "%s\\n" "pre:$APM_NO_SCRIPTS" >> count', env: {APM_NO_SCRIPTS: "0"}} + - {type: command, command: 'exit 7'} + post-install: + - {type: command, bash: 'test -f .agent/agents.resolved && printf "%s\\n" post >> count'} + """) + _ = try await fixture.enable() + let request = UpdateRequest(operation: .edit([.setDefaultAgents([.codex])])) + let review = try UpdateOperations.previewLifecycle( + request, intent: .install, environment: fixture.environment) + #expect(!fixture.exists(fixture.counter)) + let barrier = LifecycleBarrier() + let running = Task { + await LifecycleOperations.$checkpoint.withValue({ step in + if step == .confirmationClaimed { barrier.pause() } + }) { + await UpdateOperations.perform(review) + } + } + #expect(await barrier.wait()) + defer { barrier.release() } + guard case .alreadyRunning = await UpdateOperations.perform(review) else { + Issue.record("Duplicate confirmation was not recognized as running.") + return + } + barrier.release() + let initial = try fixture.completed(await running.value) + _ = try initial.package.result.get() + #expect(initial.pre.map(\.disposition) == [.commandSucceeded, .commandFailed]) + #expect(initial.pre.last?.exitStatus == 7) + #expect(initial.post.map(\.disposition) == [.commandSucceeded]) + #expect(try fixture.counterText() == "pre:1\npost\n") + let replay = try fixture.completed(await UpdateOperations.perform(review)) + #expect(replay.pre.count == initial.pre.count) + #expect(try fixture.counterText() == "pre:1\npost\n") + let next = try UpdateOperations.previewLifecycle( + request, intent: .install, environment: fixture.environment) + let again = try fixture.completed(await UpdateOperations.perform(next)) + _ = try again.package.result.get() + #expect(!next.report.hasChanges) + #expect(try fixture.counterText() == "pre:1\npost\npre:1\npost\n") + } + } + + @Test func eventPairsAndPreCompileAreExplicit() async throws { + let fixture = try LifecycleFixture() + try await fixture.withoutAdministratorFiles { + let authored = LifecycleEvent.allCases.map { event in + #" \#(event.rawValue): [{type: command, run: 'printf "%s\n" \#(event.rawValue) >> count'}]"# + }.joined(separator: "\n") + try fixture.write("version: 1\nlifecycle:\n" + authored + "\n") + _ = try await fixture.enable() + let intents: [LifecycleOperationIntent] = [.install, .update, .uninstall] + for intent in intents { + let view = try fixture.review(intent) + let result = try fixture.completed(await UpdateOperations.perform(view)) + _ = try result.package.result.get() + #expect(result.pre.map(\.action.event) == [intent.events.pre]) + let post = try #require(intent.events.post) + #expect(result.post.map(\.action.event) == [post]) + } + let compile = try InstructionOperations.previewCompilation(environment: fixture.environment) + let result = try fixture.completed(await UpdateOperations.perform(compile)) + _ = try result.package.result.get() + #expect(result.pre.map(\.action.event) == [.preCompile]) + #expect(result.post.isEmpty) + let lines = try fixture.counterText().split(separator: "\n").map(String.init) + #expect(lines == LifecycleEvent.allCases.map(\.rawValue)) + } + } + + @Test func receiptRevisionsArePerRootAndRevokeSurvivesReplacement() async throws { + let fixture = try LifecycleFixture() + try await fixture.withoutAdministratorFiles { + try fixture.write(LifecycleFixture.command) + try fixture.write(LifecycleFixture.command, project: fixture.secondProject) + let first = try LifecycleOperations.reviewEnable(environment: fixture.environment) + let secondEnvironment = fixture.environment(for: fixture.secondProject) + let second = try LifecycleOperations.reviewEnable(environment: secondEnvironment) + async let one = LifecycleOperations.enable(first) + async let two = LifecycleOperations.enable(second) + let granted = try await fixture.completed(one).get() + let other = try await fixture.completed(two).get() + #expect(granted.revision == 1 && other.revision == 1) + #expect(granted.project != other.project && granted.digest == other.digest) + let moved = fixture.root.appendingPathComponent("original-project") + try FileManager.default.moveItem(at: fixture.project, to: moved) + try fixture.write(LifecycleFixture.command) + #expect(!LifecycleOperations.list(environment: fixture.environment).projectTrusted) + let replacement = try await fixture.enable() + #expect(replacement.project != granted.project) + try FileManager.default.removeItem(at: moved) + let revoked = try LifecycleOperations.revoke( + granted.project, environment: fixture.environment) + #expect(revoked.revision == 2 && revoked.digest == nil) + #expect(LifecycleOperations.list(environment: fixture.environment).projectTrusted) + let records = try LifecycleOperations.storedTrust(environment: fixture.environment) + #expect(Set(records.map(\.project)) == [granted.project, other.project, replacement.project]) + let state = fixture.home.appendingPathComponent(".agents/lifecycle") + let directory = try FileManager.default.attributesOfItem(atPath: state.path) + let receipts = try FileManager.default.attributesOfItem( + atPath: state.appendingPathComponent("receipts.json").path) + #expect(directory[.posixPermissions] as? Int == 0o700) + #expect(receipts[.posixPermissions] as? Int == 0o600) + } + } + + @Test func saveThenEnableDetectsInterveningGrantAndRevocation() async throws { + let fixture = try LifecycleFixture() + try await fixture.withoutAdministratorFiles { + try fixture.write("version: 1\n# fixture\n") + let staged = try LifecycleOperations.previewDeclaration( + try LifecycleFixture.subtree(), environment: fixture.environment) + let barrier = LifecycleBarrier() + let task = Task { + await LifecycleOperations.$checkpoint.withValue({ step in + if step == .declarationSaved { barrier.pause() } + }) { + await LifecycleOperations.save(staged, enable: true) + } + } + #expect(await barrier.wait()) + defer { barrier.release() } + let first = try await fixture.enable() + _ = try LifecycleOperations.revoke(first.project, environment: fixture.environment) + barrier.release() + guard case .savedEnablementIncomplete = try fixture.completed(await task.value).get() else { + Issue.record("A stale enablement was accepted after grant and revoke.") + return + } + #expect(try fixture.readDeclaration().contains("# fixture")) + #expect(!LifecycleOperations.list(environment: fixture.environment).projectTrusted) + #expect( + try LifecycleOperations.storedTrust(environment: fixture.environment).first?.revision == 2) + } + } + + @Test func scaffoldRequiresForceAndPreservesOtherBytes() async throws { + let fixture = try LifecycleFixture() + try await fixture.withoutAdministratorFiles { + try fixture.write( + """ + version: 1 + # owner comment + lifecycle: + # inside subtree + pre-install: + - {type: command, run: 'exit 0'} # action note + defaultAgents: [codex] # target note + """) + #expect(throws: (any Error).self) { + try LifecycleOperations.previewScaffold(environment: fixture.environment) + } + let review = try LifecycleOperations.previewScaffold( + environment: fixture.environment, force: true) + guard case .saved = try fixture.completed(await LifecycleOperations.save(review)).get() else { + Issue.record("Scaffold should save without granting trust.") + return + } + let bytes = try fixture.readDeclaration() + #expect(bytes.contains("# owner comment")) + #expect(bytes.contains("defaultAgents: [codex] # target note")) + #expect(LifecycleOperations.list(environment: fixture.environment).actions.isEmpty) + #expect(!fixture.exists(fixture.home.appendingPathComponent(".agents"))) + } + } + + @Test func finalGateRejectsStaleTrustSourcePolicyAndDisable() async throws { + let fixture = try LifecycleFixture() + try await fixture.withoutAdministratorFiles { + try fixture.write(LifecycleFixture.command) + let grant = try await fixture.enable() + let beforeRevoke = LifecycleOperations.simulate(.preInstall, environment: fixture.environment) + _ = try LifecycleOperations.revoke(grant.project, environment: fixture.environment) + let revoked = try fixture.completed(await LifecycleOperations.executeTest(beforeRevoke)) + #expect(revoked.map(\.withholding) == [.trustChanged]) + + _ = try await fixture.enable() + let beforeSwap = LifecycleOperations.simulate(.preInstall, environment: fixture.environment) + let alternate = fixture.root.appendingPathComponent("alternate.yaml") + try Data(LifecycleFixture.command.utf8).write(to: alternate) + try FileManager.default.removeItem(at: fixture.store.declarationURL) + try FileManager.default.createSymbolicLink( + at: fixture.store.declarationURL, withDestinationURL: alternate) + let swapped = try fixture.completed(await LifecycleOperations.executeTest(beforeSwap)) + #expect(swapped.allSatisfy { !$0.dispatched }) + #expect(!LifecycleOperations.validate(environment: fixture.environment).isEmpty) + try FileManager.default.removeItem(at: fixture.store.declarationURL) + try fixture.write(LifecycleFixture.command) + + let policy = fixture.root.appendingPathComponent("organization.yaml") + try Data("enforcement: warn\n".utf8).write(to: policy) + var governed = fixture.environment + governed.projectOrganizationPolicy = .init(.local(policy)) + let beforePolicy = LifecycleOperations.simulate(.preInstall, environment: governed) + try Data("enforcement: warn\nexecutables: {deny_all: true}\n".utf8).write(to: policy) + let changed = try fixture.completed(await LifecycleOperations.executeTest(beforePolicy)) + #expect(changed.map(\.withholding) == [.policyDenied]) + try FileManager.default.removeItem(at: policy) + let unavailable = LifecycleOperations.simulate(.preInstall, environment: governed) + #expect(unavailable.inspection.allStartsWithheld == .policyUnavailable) + var disabled = fixture.environment + disabled.environment["APM_NO_SCRIPTS"] = "1" + let noScripts = LifecycleOperations.simulate(.preInstall, environment: disabled) + let rejected = try fixture.completed(await LifecycleOperations.executeTest(noScripts)) + #expect(rejected.map(\.withholding) == [.disabled]) + #expect(!fixture.exists(fixture.counter)) + } + } + + @Test func protectedUserSourceAndBadAdministratorDirectory() async throws { + let fixture = try LifecycleFixture() + try await fixture.withoutAdministratorFiles { + try fixture.write(LifecycleFixture.command) + _ = try await fixture.enable() + let user = StateStore(scope: .user, environment: fixture.environment) + let valid = """ + version: 1 + lifecycle: + pre-install: [{type: command, run: 'printf "%s\\n" user >> count'}] + """ + try Data(valid.utf8).write(to: user.declarationURL) + let listed = LifecycleOperations.list(environment: fixture.environment) + #expect(listed.actions.map(\.source.authority) == [.user, .project]) + let test = LifecycleOperations.simulate(.preInstall, environment: fixture.environment) + let result = try fixture.completed(await LifecycleOperations.executeTest(test)) + #expect(result.allSatisfy { $0.disposition == .commandSucceeded }) + #expect(try fixture.counterText() == "user\nproject\n") + let alias = fixture.root.appendingPathComponent("hardlink.yaml") + try FileManager.default.linkItem(at: user.declarationURL, to: alias) + let hardlink = LifecycleOperations.list(environment: fixture.environment) + #expect(hardlink.actions.map(\.source.authority) == [.project]) + #expect(hardlink.diagnostics.map(\.source.authority) == [.user]) + } + let admin = fixture.root.appendingPathComponent("administrator.d") + try FileManager.default.createDirectory(at: admin, withIntermediateDirectories: true) + try Data(#"{"version":1,"scripts":{}}"#.utf8).write( + to: admin.appendingPathComponent("010.json")) + await LifecycleOperations.$administratorDirectoryForTesting.withValue(admin) { + let view = LifecycleOperations.simulate(.preInstall, environment: fixture.environment) + #expect(view.inspection.allStartsWithheld == .administratorSourceInvalid) + #expect(view.inspection.diagnostics.contains { $0.source.file == admin }) + let result = try? fixture.completed(await LifecycleOperations.executeTest(view)) + #expect(result?.map(\.withholding) == [.administratorSourceInvalid]) + } + } + + @Test func userScopeActionsSurviveOrdinaryDeclarationPublication() async throws { + let fixture = try LifecycleFixture() + try await fixture.withoutAdministratorFiles { + let store = StateStore(scope: .user, environment: fixture.environment) + try FileManager.default.createDirectory( + at: store.directory, withIntermediateDirectories: true) + let source = """ + version: 1 + lifecycle: + pre-install: [{type: command, run: 'printf "%s\\n" pre >> count'}] + post-install: [{type: command, run: 'printf "%s\\n" post >> count'}] + """ + try Data(source.utf8).write(to: store.declarationURL) + let request = UpdateRequest(operation: .edit([.setDefaultAgents([.codex])])) + let review = try UpdateOperations.previewLifecycle( + request, intent: .install, scope: .user, environment: fixture.environment) + let result = try fixture.completed(await UpdateOperations.perform(review)) + _ = try result.package.result.get() + #expect(result.pre.first?.action.source.authority == .user) + #expect(result.post.first?.disposition == .commandSucceeded) + let count = fixture.home.appendingPathComponent("count") + #expect(try String(contentsOf: count, encoding: .utf8) == "pre\npost\n") + + #if os(macOS) + _ = try ProcessRunner.run( + "/bin/chmod", arguments: ["+a", "everyone allow write", store.declarationURL.path]) + #else + try FileManager.default.setAttributes( + [.posixPermissions: 0o664], ofItemAtPath: store.declarationURL.path) + #endif + let refused = LifecycleOperations.list(scope: .user, environment: fixture.environment) + #expect(refused.actions.isEmpty) + #expect(refused.diagnostics.first?.source.authority == .user) + } + } + + @Test func completedRevocationWaitsForHandoffAndWithholdsRemainingStarts() async throws { + let fixture = try LifecycleFixture() + try await fixture.withoutAdministratorFiles { + try fixture.write( + """ + version: 1 + lifecycle: + pre-install: + - {type: command, run: 'printf "%s\\n" one >> count'} + - {type: command, run: 'printf "%s\\n" two >> count'} + """) + let grant = try await fixture.enable() + let review = LifecycleOperations.simulate(.preInstall, environment: fixture.environment) + let handoff = LifecycleBarrier() + let running = Task { + await LifecycleOperations.$checkpoint.withValue({ point in + if point == .handedOff { handoff.pause() } + }) { + await LifecycleOperations.executeTest(review) + } + } + #expect(await handoff.wait()) + defer { handoff.release() } + let published = DispatchSemaphore(value: 0) + let returned = DispatchSemaphore(value: 0) + let revoking = Task { + try LifecycleOperations.$checkpoint.withValue({ point in + if point == .receiptPublished { published.signal() } + }) { + defer { returned.signal() } + return try LifecycleOperations.revoke(grant.project, environment: fixture.environment) + } + } + #expect(await waitForLifecycleSignal(published, for: .seconds(5)) == .success) + #expect(await waitForLifecycleSignal(returned, for: .milliseconds(50)) == .timedOut) + handoff.release() + #expect(try await revoking.value.revision == 2) + let actions = try fixture.completed(await running.value) + #expect(actions.map(\.dispatched) == [true, false]) + #expect(actions.last?.withholding == .trustChanged) + #expect(try fixture.counterText() == "one\n") + } + } + + @Test func lockOnlyThenFrozenDeploymentUsesOneReviewedPhasePairEach() async throws { + let fixture = try LifecycleFixture() + try await fixture.withoutAdministratorFiles { + let catalog = try GraphCatalog() + try catalog.publish("shared", "1.0.0") + let package = try catalog.root("main", package: "shared", recipient: .codex) + try fixture.write( + """ + version: 1 + lifecycle: + pre-install: [{type: command, run: 'printf "%s\\n" pre >> count'}] + post-install: [{type: command, run: 'printf "%s\\n" post >> count'}] + """) + _ = try await fixture.enable() + let review = try MarketplaceOperations.previewLockOnlyLifecycle( + .install(package), intent: .install, environment: fixture.environment) + #expect(!fixture.exists(fixture.counter)) + let lock = try fixture.completed(await UpdateOperations.perform(review)) + let pending = try lock.package.result.get() + #expect(pending.pendingDeployment.graph != nil) + #expect(lock.post.first?.disposition == .commandSucceeded) + #expect(try fixture.counterText() == "pre\npost\n") + try FileManager.default.removeItem(at: catalog.catalog) + + let frozen = try MarketplaceOperations.previewFrozenLifecycle( + intent: .install, environment: fixture.environment) + let applied = try fixture.completed(await UpdateOperations.perform(frozen)) + _ = try applied.package.result.get() + #expect(applied.post.first?.disposition == .commandSucceeded) + #expect(try fixture.counterText() == "pre\npost\npre\npost\n") + #expect( + try UpdateOperations.inspect(environment: fixture.environment).pendingMarketplaceDeployment + == nil) + } + } + + @Test func crashRecoveryDoesNotReplayEffects() async throws { + let fixture = try LifecycleFixture() + try await fixture.withoutAdministratorFiles { + try fixture.write( + """ + version: 1 + lifecycle: + pre-install: [{type: command, run: 'printf "%s\\n" pre >> count'}] + post-install: [{type: command, run: 'printf "%s\\n" post >> count'}] + """) + _ = try await fixture.enable() + var location = Bundle(for: LifecycleProbeBundle.self).bundleURL + while !FileManager.default.isExecutableFile( + atPath: location.appendingPathComponent("StateTestProcess").path), + location.path != "/" + { location.deleteLastPathComponent() } + let probe = Process() + probe.executableURL = location.appendingPathComponent("StateTestProcess") + probe.arguments = [ + fixture.project.path, "lifecycle-crash", + TransactionCheckpoint.persisted(.applying, .entry(0, .publishing), .renamed).name, + fixture.home.path, fixture.absentAdministratorDirectory.path, + ] + try probe.run() + defer { + if probe.isRunning { try? ProcessWait.terminate(probe, timeout: 3) } + } + try ProcessWait.exit(probe, root: fixture.project, timeout: 15) + try #require(probe.terminationReason == .uncaughtSignal && probe.terminationStatus == SIGKILL) + #expect(try fixture.counterText() == "pre\n") + + let pending = LifecycleOperations.simulate(.preInstall, environment: fixture.environment) + let result = try fixture.completed(await LifecycleOperations.executeTest(pending)) + #expect(result.map(\.withholding) == [.recoveryPending]) + let recovered = UpdateOperations.perform(environment: fixture.environment) { try $0.apply() } + #expect(recovered.recoveredBeforePreparation) + #expect(!recovered.recovery.pending) + #expect(try fixture.counterText() == "pre\n") + + let review = try fixture.review(.install) + let retry = try fixture.completed(await UpdateOperations.perform(review)) + _ = try retry.package.result.get() + #expect(try fixture.counterText() == "pre\npre\npost\n") + } + } + + @Test func rollbackReportsStartedPreActionsAndSuppressesPost() async throws { + let fixture = try LifecycleFixture() + try await fixture.withoutAdministratorFiles { + try fixture.write( + """ + version: 1 + lifecycle: + pre-install: [{type: command, run: 'cat > fixture-event.json'}] + post-install: [{type: command, run: 'touch count'}] + """) + _ = try await fixture.enable() + let request = UpdateRequest(operation: .edit([.setDefaultAgents([.codex])])) + let review = try UpdateOperations.previewLifecycle( + request, intent: .install, environment: fixture.environment) + let failAt = TransactionCheckpoint.progress(0, .applied).name + let submission = await LifecycleOperations.$transactionCheckpointForTesting.withValue({ + step in + if step == failAt { throw LifecycleFixtureAbort.rollback } + }) { + await UpdateOperations.perform(review) + } + let result = try fixture.completed(submission) + #expect(result.package.disposition == .rolledBack) + #expect(result.pre.first?.disposition == .commandSucceeded) + #expect(result.post.first?.withholding == .packageDidNotComplete) + #expect(!fixture.exists(fixture.counter)) + let file = try Data(contentsOf: fixture.project.appendingPathComponent("fixture-event.json")) + let event = try JSONSerialization.jsonObject(with: file) as? [String: Any] + #expect(event?["event"] as? String == "pre-install") + #expect(event?["version"] as? Int == 1) + #expect(event?["test"] as? Bool == false) + } + } + + @Test func childDeadlineCleanupAndOutputAreAdvisoryAndRedacted() async throws { + let fixture = try LifecycleFixture() + try await fixture.withoutAdministratorFiles { + try fixture.write( + """ + version: 1 + lifecycle: + pre-install: + - {type: command, run: 'sleep 10 & wait', timeout: 1} + - {type: command, run: 'printf "synthetic-private-value" >&2; exit 19'} + - {type: command, run: 'yes output'} + post-install: [{type: command, run: 'touch count'}] + """) + _ = try await fixture.enable() + let review = try fixture.review(.install) + let result = try fixture.completed(await UpdateOperations.perform(review)) + _ = try result.package.result.get() + #expect( + result.pre.map(\.disposition) == [.commandTimedOut, .commandFailed, .commandOutputLimit]) + #expect(result.pre.allSatisfy { $0.processGroupCleanedUp == true }) + #expect(fixture.exists(fixture.counter)) + let encoded = try JSONEncoder().encode(result.pre) + #expect(!String(decoding: encoded, as: UTF8.self).contains("synthetic-private-value")) + } + } + + @Test func staleApplyReportsPreStartsAndSuppressesPost() async throws { + let fixture = try LifecycleFixture() + try await fixture.withoutAdministratorFiles { + try fixture.write( + """ + version: 1 + lifecycle: + pre-update: [{type: command, run: 'printf "%s\\n" "# modified during pre" >> .agent/agents.yaml'}] + post-update: [{type: command, run: 'touch count'}] + """) + _ = try await fixture.enable() + let review = try fixture.review(.update) + let result = try fixture.completed(await UpdateOperations.perform(review)) + #expect(throws: (any Error).self) { try result.package.result.get() } + #expect(result.pre.first?.disposition == .commandSucceeded) + #expect(result.post.first?.withholding == .packageDidNotComplete) + #expect(!fixture.exists(fixture.counter)) + } + } +} + +private func waitForLifecycleSignal( + _ semaphore: DispatchSemaphore, for duration: DispatchTimeInterval +) async -> DispatchTimeoutResult { + await withCheckedContinuation { continuation in + DispatchQueue.global().async { + continuation.resume(returning: semaphore.wait(timeout: .now() + duration)) + } + } +} + +private enum LifecycleFixtureAbort: Error { case rollback } + +private final class LifecycleProbeBundle {} + +private final class LifecycleBarrier: @unchecked Sendable { + private let entered = DispatchSemaphore(value: 0) + private let permitted = DispatchSemaphore(value: 0) + + func pause() { + entered.signal() + if permitted.wait(timeout: .now() + .seconds(60)) == .timedOut { + Issue.record("Lifecycle barrier was not released.") + } + } + + func wait() async -> Bool { await waitForLifecycleSignal(entered, for: .seconds(60)) == .success } + func release() { permitted.signal() } +} + +final class LifecycleFixture: @unchecked Sendable { + let root: URL + let project: URL + let secondProject: URL + let home: URL + let absentAdministratorDirectory: URL + + init() throws { + let nonce = UUID().uuidString + root = FileManager.default.temporaryDirectory + .resolvingSymlinksInPath().appendingPathComponent("package-lifecycle-" + nonce) + project = root.appendingPathComponent("project") + secondProject = root.appendingPathComponent("project-two") + home = root.appendingPathComponent("home") + absentAdministratorDirectory = URL(fileURLWithPath: "/.agents-lifecycle-fixture-" + nonce) + do { + for url in [project, secondProject, home] { + try FileManager.default.createDirectory( + at: url, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700]) + } + } catch { + try? FileManager.default.removeItem(at: root) + throw error + } + } + + deinit { + do { try FileManager.default.removeItem(at: root) } catch { Issue.record(error) } + } + + var environment: RuntimeEnvironment { environment(for: project) } + var store: StateStore { .init(scope: .project, environment: environment) } + var counter: URL { project.appendingPathComponent("count") } + + func environment(for root: URL) -> RuntimeEnvironment { + RuntimeEnvironment( + projectDirectory: root, homeDirectory: home, + environment: ["HOME": home.path, "PATH": "/usr/bin:/bin"]) + } + + func write(_ text: String, project: URL? = nil) throws { + let store = StateStore(scope: .project, environment: environment(for: project ?? self.project)) + try FileManager.default.createDirectory( + at: store.directory, withIntermediateDirectories: true) + try Data(text.utf8).write(to: store.declarationURL) + } + + func readDeclaration() throws -> String { + try String(contentsOf: store.declarationURL, encoding: .utf8) + } + + func counterText() throws -> String { try String(contentsOf: counter, encoding: .utf8) } + func exists(_ url: URL) -> Bool { FileManager.default.fileExists(atPath: url.path) } + + func withoutAdministratorFiles(_ body: () async throws -> Void) async rethrows { + try await LifecycleOperations.$administratorDirectoryForTesting.withValue( + absentAdministratorDirectory + ) { + try await body() + } + } + + func enable() async throws -> LifecycleTrustRecord { + let review = try LifecycleOperations.reviewEnable(environment: environment) + return try completed(await LifecycleOperations.enable(review)).get() + } + + func review(_ intent: LifecycleOperationIntent) throws + -> LifecyclePackageReview + { + try UpdateOperations.previewLifecycle(intent: intent, environment: environment) + } + + func completed(_ submission: LifecycleSubmission) throws -> T { + switch submission { + case .completed(let result): result + case .alreadyRunning: throw CoreError.invalidState("Confirmation already running.") + } + } + + static let command = """ + version: 1 + lifecycle: + pre-install: [{type: command, run: 'printf "%s\\n" project >> count'}] + """ + + static func subtree() throws -> DeclarationValue { + let document = try DeclarationDocument(bytes: Array(command.utf8), identity: .init("fixture")) + return try #require(document.declaration.lifecycle) + } +} diff --git a/Tests/AgentsUpdatesTests/PortableBundleTests.swift b/Tests/AgentsUpdatesTests/PortableBundleTests.swift new file mode 100644 index 0000000..fd60dc7 --- /dev/null +++ b/Tests/AgentsUpdatesTests/PortableBundleTests.swift @@ -0,0 +1,487 @@ +import AgentsCore +import AgentsInstructions +import AgentsSkills +import AgentsUpdates +import Foundation +import Synchronization +import Testing + +@Suite("Portable bundles") +struct PortableBundleTests { + @Test func bundleOffersOnlyClientsThatCanRenderItsRemoteTransport() throws { + let publisher = try UpdateFixture() + try publisher.store.save( + declaration: Declaration(components: [ + .mcpServer( + name: "events", transport: .sse(url: "https://example.invalid/events"), + agents: [.claudeCode]), + .mcpServer( + name: "http", transport: .streamableHTTP(url: "https://example.invalid/mcp"), + agents: [.codex]), + ]), ledger: ResolvedLedger()) + _ = try UpdateOperations.withPreparedUpdate(environment: publisher.environment) { + try $0.apply() + } + let components = try UpdateOperations.inspect(environment: publisher.environment).components + let archive = try BundleOperations.export( + .init(name: "remote", version: "1.0.0"), + selections: components.map(\.selection), scope: .project, environment: publisher.environment) + let members = try BundleOperations.inspect(archive).components + let sse = try #require(members.first { $0.name == "events" }) + let http = try #require(members.first { $0.name == "http" }) + for scope in [InstallScope.project, .user] { + #expect(Set(sse.supportedTargets(in: scope)) == [.claudeCode, .geminiCLI]) + #expect( + Set(http.supportedTargets(in: scope)) == [ + .claudeCode, .geminiCLI, .codex, .opencode, .antigravity, + ]) + } + } + + @Test func freshClaudeUserInstallCreatesSharedInstructionAndSkillParents() throws { + let bundle = try BundleOperations.inspect(BundleFixture().export()) + let consumer = try UpdateFixture(scope: .user) + var environment = consumer.environment + environment.environment.removeValue(forKey: "CLAUDE_CONFIG_DIR") + let selections = bundle.components.filter { $0.kind != .mcpServer }.map { + BundleImportSelection(componentID: $0.id, targets: [.claudeCode]) + } + let root = environment.homeDirectory.appendingPathComponent(".claude") + let preview = try BundleOperations.previewImport( + bundle, selections: selections, scope: .user, environment: environment) + #expect(!FileManager.default.fileExists(atPath: root.path)) + let result = try BundleOperations.withPreparedImport(preview) { try $0.apply() } + #expect(result.report.displayedFingerprint == preview.report.displayedFingerprint) + #expect(FileManager.default.fileExists(atPath: root.appendingPathComponent("CLAUDE.md").path)) + #expect( + FileManager.default.fileExists( + atPath: root.appendingPathComponent("skills/demo/SKILL.md").path)) + } + + @Test(arguments: [InstallScope.project, .user]) + func lockedComponentsRoundTripAcrossIndependentHomes(_ scope: InstallScope) throws { + let publisher = try BundleFixture() + let bytes = try publisher.export() + let bundle = try BundleOperations.inspect(bytes) + #expect(bundle.formatVersion == 1) + #expect(bundle.package == .init(name: "fixture", version: "1.2.0")) + #expect(Set(bundle.components.map(\.kind)) == [.instructions, .skills, .mcpServer]) + let skill = try #require(bundle.components.first { $0.kind == .skills }) + let instruction = try #require(bundle.components.first { $0.kind == .instructions }) + #expect( + instruction.sources.contains { $0.revision == publisher.revision && $0.identity == nil }) + #expect(skill.entries.contains { $0.path.hasSuffix("/scripts/run.sh") && $0.executable }) + #expect(skill.entries.contains { $0.path.hasSuffix("/assets/empty") && $0.kind == .directory }) + let server = try #require(bundle.components.first { $0.kind == .mcpServer }) + let symbolic = try #require(server.configuration) + #expect(String(describing: symbolic).contains("bundle-token")) + let wire = String(decoding: bytes, as: UTF8.self) + #expect(!wire.contains(publisher.base.root.path)) + #expect(!wire.contains(publisher.provider.valueToSupply)) + + let consumer = try UpdateFixture(scope: scope) + let provider = BundleBindings() + let selections = bundle.components.map { component in + BundleImportSelection( + componentID: component.id, targets: [component.kind == .mcpServer ? .geminiCLI : .codex]) + } + let before = try FileHash.folderHash(consumer.root) + let preview = try BundleOperations.previewImport( + bundle, selections: selections, scope: scope, environment: consumer.environment) + #expect(preview.ownershipConflict == nil) + #expect(preview.report.hasChanges) + #expect(try FileHash.folderHash(consumer.root) == before) + #expect(provider.calls.withLock { $0 } == 0) + #expect(!FileManager.default.fileExists(atPath: consumer.store.directory.path)) + + // Transfer only archive bytes. The next update must be able to reconstruct its own graph. + try FileManager.default.removeItem(at: publisher.base.repo) + let receipt = try BundleOperations.withPreparedImport(preview, bindingProvider: provider) { + #expect($0.report == preview.report) + #expect(provider.calls.withLock { $0 } == 0) + return try $0.apply() + } + #expect(receipt.report == preview.report) + let instructionHealth = try InstructionOperations.doctor( + scope: scope, environment: consumer.environment) + #expect( + !instructionHealth.diagnostics.contains { + [.sourceUpdateAvailable, .sourceResolutionFailed, .uncommittedSource, .stateUnavailable] + .contains($0.kind) + }) + let skillHealth = try SkillOperations.doctor(scope: scope, environment: consumer.environment) + #expect( + !skillHealth.checks.contains { + ["source-update", "source-unavailable", "uncommitted-source"].contains($0.id) + }) + let target = consumer.target() + #expect( + try Data(contentsOf: target.appendingPathComponent("assets/nested/data.bin")) + == Data([0, 38, 128, 255])) + #expect( + try Data(contentsOf: target.appendingPathComponent("assets/data-link")) + == Data([0, 38, 128, 255])) + #expect( + FileManager.default.fileExists(atPath: target.appendingPathComponent("assets/empty").path)) + let mode = try #require( + FileManager.default.attributesOfItem( + atPath: target.appendingPathComponent("scripts/run.sh").path)[ + .posixPermissions] as? NSNumber) + #expect(mode.intValue & 0o111 != 0) + #expect( + String(decoding: try Data(contentsOf: consumer.instruction()), as: UTF8.self) + .contains("locked fixture text")) + #expect(!FileManager.default.fileExists(atPath: consumer.target(.claudeCode).path)) + + let installed = try UpdateOperations.inspect(scope: scope, environment: consumer.environment) + #expect(installed.components.count == 3) + #expect(installed.components.first { $0.kind == .skills }?.recipients == [.codex]) + let storedSources = consumer.store.directory.appendingPathComponent( + BundleSourceLocation.directory) + let producers = try FileManager.default.contentsOfDirectory( + at: storedSources, includingPropertiesForKeys: nil + ) + .map { container in + try String( + contentsOf: container.appendingPathComponent(BundleSourceLocation.tree) + .appendingPathComponent(".agent/agents.yaml"), encoding: .utf8) + } + #expect(producers.count == 3) + #expect(producers.filter { $0.contains("antigravity") }.count == 1) + let native = try #require(installed.deployments.first { $0.format.hasSuffix("-mcp@1") }) + let nativeText = String(decoding: try Data(contentsOf: native.location), as: UTF8.self) + #expect(nativeText.contains(provider.valueToSupply)) + #expect(nativeText.contains("BUNDLE_REGION")) + #expect(provider.calls.withLock { $0 } == 1) + let stored = String(decoding: try Data(contentsOf: consumer.store.resolvedURL), as: UTF8.self) + #expect(!stored.contains(provider.valueToSupply)) + #expect(!stored.contains(publisher.base.root.path)) + #expect( + !FileManager.default.fileExists( + atPath: consumer.environment.homeDirectory.appendingPathComponent("bundle-ran").path)) + let ordinaryPreview = try consumer.preview() + #expect(!ordinaryPreview.instructions.hasChanges) + #expect(ordinaryPreview.components.allSatisfy { $0.privateMaterialization }) + #expect(provider.calls.withLock { $0 } == 1) + + let forwarded = try BundleOperations.inspect( + BundleOperations.export( + bundle.package, selections: installed.components.map(\.selection), scope: scope, + environment: consumer.environment)) + let forwardedSkill = try #require(forwarded.components.first { $0.kind == .skills }) + #expect(forwardedSkill.sources == skill.sources) + #expect(forwarded.archiveDigest == bundle.archiveDigest) + } + + @Test(arguments: [InstallScope.project, .user]) + func antigravityBundleSelectionDeploysAllPortableKinds(_ scope: InstallScope) throws { + let publisher = try BundleFixture() + let bundle = try BundleOperations.inspect(publisher.export()) + let consumer = try UpdateFixture(scope: scope) + let selections = bundle.components.map { component in + #expect(component.supportedTargets(in: scope).contains(.antigravity)) + return BundleImportSelection(componentID: component.id, targets: [.antigravity]) + } + let preview = try BundleOperations.previewImport( + bundle, selections: selections, scope: scope, environment: consumer.environment) + #expect(preview.ownershipConflict == nil) + let region = "fixture-region" + let bindings = BundleBindings(region: region) + _ = try BundleOperations.withPreparedImport(preview, bindingProvider: bindings) { + try $0.apply() + } + let installed = try UpdateOperations.inspect(scope: scope, environment: consumer.environment) + #expect(installed.components.count == 3) + #expect(installed.components.allSatisfy { $0.recipients == [.antigravity] }) + #expect(installed.deployments.allSatisfy { $0.status == .current }) + #expect(installed.deployments.contains { $0.format == "agents/antigravity-rule@1" }) + let mcp = try #require(installed.deployments.first { $0.format == "agents/antigravity-mcp@1" }) + let native = String(decoding: try consumer.bytes(mcp.location), as: UTF8.self) + #expect(native.contains(region) && native.contains(bindings.valueToSupply)) + let lock = String(decoding: try consumer.bytes(consumer.store.resolvedURL), as: UTF8.self) + #expect(!lock.contains(region) && !lock.contains(bindings.valueToSupply)) + #expect(FileManager.default.fileExists(atPath: consumer.target(.antigravity).path)) + #expect(bindings.calls.withLock { $0 } == 2) + } + + @Test func marketplaceUpgradePreservesOtherProjectsLockedBundle() throws { + let author = try BundleFixture() + let catalog = author.base.root.appendingPathComponent("team-market") + try FileManager.default.createDirectory(at: catalog, withIntermediateDirectories: false) + let registration = try MarketplaceRegistration( + name: "team", + origin: MarketplaceOrigin(kind: .directory, location: catalog.path)) + let first = try UpdateFixture() + let second = try UpdateFixture() + func install(_ release: MarketplaceRelease, to project: UpdateFixture) throws { + let package = try MarketplaceOperations.acquire(release, environment: project.environment) + let selections = try package.inspectBundle().components.map { + BundleImportSelection( + componentID: $0.id, targets: [$0.kind == .mcpServer ? .geminiCLI : .codex]) + } + let preview = try package.previewImport( + as: "team-kit", selections: selections, + scope: .project, environment: project.environment) + #expect(preview.report.hasChanges) + #expect(preview.ownershipConflict == nil) + _ = try BundleOperations.withPreparedImport(preview, bindingProvider: author.provider) { + try $0.apply() + } + } + let old = try MarketplaceOperations.publishBundle(author.export(), to: catalog) + try install(old, to: first) + try install(old, to: second) + let previousLock = try Data(contentsOf: second.store.resolvedURL) + let content = "assets/nested/data.bin" + let newBytes = Data("new bundle payload".utf8) + try newBytes.write( + to: author.base.root.appendingPathComponent("authoring").appendingPathComponent(content)) + _ = try UpdateOperations.withPreparedUpdate( + environment: author.base.environment, bindingProvider: author.provider + ) { try $0.apply() } + _ = try MarketplaceOperations.publishBundle(author.export(version: "2.0.0"), to: catalog) + let pin = try #require(MarketplaceOperations.installed(environment: first.environment).first) + #expect(pin.dependency.catalog == registration.origin) + let upgrade = try #require( + MarketplaceOperations.availableUpdates( + for: pin, scope: .project, environment: first.environment + ).first) + let verified = try MarketplaceOperations.acquire(upgrade, environment: first.environment) + let bundle = try verified.inspectBundle() + let retained = try bundle.retainedSelections( + for: pin, in: UpdateOperations.inspect(environment: first.environment)) + for item in bundle.components { + let selection = try #require(retained.first { $0.componentID == item.id }) + #expect(selection.targets == [item.kind == .mcpServer ? .geminiCLI : .codex]) + } + let preview = try verified.previewImport( + as: pin.dependency.name, selections: retained, scope: .project, environment: first.environment + ) + #expect(preview.report.marketplaceChanges?.first?.before == pin) + #expect( + preview.report.marketplaceChanges?.first?.after?.dependency.coordinate.version == "2.0.0") + _ = try BundleOperations.withPreparedImport(preview, bindingProvider: author.provider) { + try $0.apply() + } + #expect(try Data(contentsOf: first.target().appendingPathComponent(content)) == newBytes) + #expect( + try MarketplaceOperations.installed(environment: first.environment).first?.dependency + .coordinate.version == "2.0.0") + try FileManager.default.removeItem(at: second.target()) + _ = try UpdateOperations.restore( + environment: second.environment, bindingProvider: author.provider) + #expect( + try Data(contentsOf: second.target().appendingPathComponent(content)) + == Data([0, 38, 128, 255])) + #expect(try Data(contentsOf: second.store.resolvedURL) == previousLock) + #expect(try MarketplaceOperations.installed(environment: second.environment) == [pin]) + } + + @Test func selectivelyImportsAndPreviewsSafeDestinationCollisions() throws { + let publisher = try BundleFixture() + let bundle = try BundleOperations.inspect(publisher.export()) + let instruction = try #require(bundle.components.first { $0.kind == .instructions }) + let skill = try #require(bundle.components.first { $0.kind == .skills }) + let consumer = try UpdateFixture() + try consumer.write("Handwritten instructions.\n", to: consumer.instruction()) + try consumer.write( + "Unmanaged skill.\n", to: consumer.target().appendingPathComponent("SKILL.md")) + let instructions = [BundleImportSelection(componentID: instruction.id, targets: [.codex])] + let skills = [BundleImportSelection(componentID: skill.id, targets: [.codex])] + let before = try FileHash.folderHash(consumer.root) + let collisions = try BundleOperations.previewImport( + bundle, selections: instructions, scope: .project, environment: consumer.environment) + #expect(collisions.ownershipConflict != nil) + #expect(collisions.report.instructions.targets.contains { $0.foreign }) + #expect(throws: CoreError.self) { + try BundleOperations.withPreparedImport(collisions) { try $0.apply() } + } + let skillCollision = try BundleOperations.previewImport( + bundle, selections: skills, scope: .project, environment: consumer.environment, replace: true) + #expect(skillCollision.ownershipConflict != nil) + #expect(throws: CoreError.self) { + try BundleOperations.withPreparedImport(skillCollision) { try $0.apply() } + } + #expect(try FileHash.folderHash(consumer.root) == before) + + let replacement = try BundleOperations.previewImport( + bundle, selections: instructions, scope: .project, environment: consumer.environment, + replace: true) + #expect(replacement.ownershipConflict == nil) + try consumer.write("Changed since preview.\n", to: consumer.instruction()) + #expect(throws: (any Error).self) { + try BundleOperations.withPreparedImport(replacement) { try $0.apply() } + } + #expect( + try String(contentsOf: consumer.instruction(), encoding: .utf8) == "Changed since preview.\n") + let fresh = try BundleOperations.previewImport( + bundle, selections: instructions, scope: .project, environment: consumer.environment, + replace: true) + _ = try BundleOperations.withPreparedImport(fresh) { try $0.apply() } + #expect( + try UpdateOperations.inspect(environment: consumer.environment).components.map(\.kind) + == [.instructions]) + #expect( + try String(contentsOf: consumer.target().appendingPathComponent("SKILL.md"), encoding: .utf8) + == "Unmanaged skill.\n") + } + + @Test func bindingFailureLeavesBundleSourceAndDeploymentsUnpublished() throws { + let publisher = try BundleFixture() + let bundle = try BundleOperations.inspect(publisher.export()) + let consumer = try UpdateFixture() + let server = try #require(bundle.components.first { $0.kind == .mcpServer }) + let preview = try BundleOperations.previewImport( + bundle, selections: [.init(componentID: server.id, targets: [.geminiCLI])], + scope: .project, environment: consumer.environment) + #expect { + try BundleOperations.withPreparedImport(preview) { try $0.apply() } + } throws: { error in + guard let failure = error as? UpdateApplyError, case .unchanged = failure.disposition else { + return false + } + return true + } + #expect(try consumer.store.loadDeclaration().uses.isEmpty) + #expect(try consumer.store.loadLedger().components.isEmpty) + #expect( + FileManager.default.enumerator(atPath: consumer.store.directory.path)? + .allObjects.contains(where: { ($0 as? String)?.hasSuffix("bundle-source.json") == true }) + == false) + #expect( + try UpdateOperations.inspect(environment: consumer.environment).deployments.isEmpty) + } + + @Test func alteredObjectsAndSealedTraversalFailBeforeImport() throws { + let publisher = try BundleFixture() + let bytes = try publisher.export() + var json = try #require(JSONSerialization.jsonObject(with: bytes) as? [String: Any]) + var objects = try #require(json["contentObjects"] as? [String: String]) + let canary = Data([0, 38, 128, 255]).base64EncodedString() + let key = try #require(objects.first { $0.value == canary }?.key) + objects[key] = Data([1, 38, 128, 255]).base64EncodedString() + json["contentObjects"] = objects + #expect(throws: CoreError.self) { try BundleOperations.inspect(canonical(json)) } + + json = try #require(JSONSerialization.jsonObject(with: bytes) as? [String: Any]) + var manifest = try #require(json["manifest"] as? [String: Any]) + var components = try #require(manifest["components"] as? [[String: Any]]) + let index = try #require(components.firstIndex { $0["kind"] as? String == "skills" }) + var entries = try #require(components[index]["entries"] as? [[String: Any]]) + let link = try #require(entries.firstIndex { $0["kind"] as? String == "symlink" }) + var escaping = entries + escaping[link]["link"] = "../../../../../outside" + entries[link]["path"] = "payload/../../outside" + for (invalid, expected) in [ + (entries, "bundle member path"), (escaping, "resource link escapes tree"), + ] { + components[index]["entries"] = invalid + manifest["components"] = components + json["manifest"] = manifest + json["manifestDigest"] = "sha256:" + FileHash.sha256Hex(data: try canonical(manifest)) + #expect { + try BundleOperations.inspect(canonical(json)) + } throws: { error in + String(describing: error).contains(expected) + } + } + } + + private func canonical(_ value: [String: Any]) throws -> Data { + var bytes = try JSONSerialization.data( + withJSONObject: value, options: [.sortedKeys, .withoutEscapingSlashes]) + bytes.append(10) + return bytes + } +} + +private final class BundleBindings: RuntimeBindingProvider { + let calls = Mutex(0) + let valueToSupply = "runtime-materialization-canary" + let region: String? + + init(region: String? = nil) { self.region = region } + + func value(for binding: String, environment: RuntimeEnvironment) throws -> Data { + calls.withLock { $0 += 1 } + if binding == "BUNDLE_REGION", let region { return Data(region.utf8) } + #expect(binding == "bundle-token") + return Data(valueToSupply.utf8) + } +} + +private struct BundleFixture { + let base: UpdateFixture + let revision: String + let provider: BundleBindings + + init() throws { + let base = try UpdateFixture() + let provider = BundleBindings() + let repo = base.repo + let skill = repo.appendingPathComponent("skills/demo") + try base.write( + "---\ndescription: Locked instructions.\n---\n# Bundle rules\n\nlocked fixture text\n", + to: repo.appendingPathComponent("instructions/rules.md")) + let assets = skill.appendingPathComponent("assets") + let data = assets.appendingPathComponent("nested/data.bin") + let fm = FileManager.default + try fm.createDirectory(at: data.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data([0, 38, 128, 255]).write(to: data) + try fm.createSymbolicLink( + atPath: assets.appendingPathComponent("data-link").path, + withDestinationPath: "nested/data.bin") + let run = skill.appendingPathComponent("scripts/run.sh") + try base.write("#!/bin/sh\nprintf fixture\n", to: run) + try fm.setAttributes([.posixPermissions: 0o755], ofItemAtPath: run.path) + let server = repo.appendingPathComponent("mcp/server.sh") + try base.write("#!/bin/sh\ntouch \"$HOME/bundle-ran\"\n", to: server) + try fm.setAttributes([.posixPermissions: 0o755], ofItemAtPath: server.path) + try base.write("package data\n", to: repo.appendingPathComponent("mcp/working/support")) + try base.commit() + let revision = try base.git(["rev-parse", "HEAD"]) + // Git preserves file and symlink content. A second local source contributes an empty directory. + let tree = base.root.appendingPathComponent("authoring") + try fm.copyItem(at: skill, to: tree) + try fm.createDirectory( + at: tree.appendingPathComponent("assets/empty"), withIntermediateDirectories: false) + try base.store.save( + declaration: Declaration( + sources: [ + "fixture": .init(kind: .local, location: repo.path, requirement: .revision(revision)), + "full-skill": .init(kind: .local, location: tree.path), + ], + skills: ["full-skill": .init(select: .names(["demo"]), agents: [.codex], mode: .copy)], + instructions: .init(agents: [.codex], sections: ["fixture:rules"]), + components: [ + .mcpServer( + name: "bundle-server", + transport: .stdio( + .init( + executable: "./mcp/server.sh", executableSource: "fixture", + environment: [ + "TOKEN": .secret("bundle-token"), "REGION": .environment("BUNDLE_REGION"), + ], + workingDirectory: .init(path: "mcp/working", source: "fixture"))), + agents: [.geminiCLI]) + ]), + ledger: ResolvedLedger()) + _ = try UpdateOperations.withPreparedUpdate( + environment: base.environment, bindingProvider: provider + ) { try $0.apply() } + try base.advance() + #expect( + !FileManager.default.fileExists( + atPath: base.environment.homeDirectory.appendingPathComponent("bundle-ran").path)) + self.base = base + self.provider = provider + self.revision = revision + } + + func export(version: String = "1.2.0") throws -> Data { + let state = try UpdateOperations.inspect(environment: base.environment) + return try BundleOperations.export( + .init(name: "fixture", version: version), selections: state.components.map(\.selection), + scope: .project, environment: base.environment) + } +} diff --git a/Tests/AgentsUpdatesTests/PrivateNativeCompositionTests.swift b/Tests/AgentsUpdatesTests/PrivateNativeCompositionTests.swift new file mode 100644 index 0000000..6c1c36b --- /dev/null +++ b/Tests/AgentsUpdatesTests/PrivateNativeCompositionTests.swift @@ -0,0 +1,375 @@ +import AgentsCore +import AgentsUpdates +import Foundation +import Synchronization +import Testing + +private final class NativeBindings: RuntimeBindingProvider { + let calls = Mutex(0) + let secret = "private-tree-materialization-canary" + func value(for binding: String, environment: RuntimeEnvironment) throws -> Data { + calls.withLock { $0 += 1 } + return Data(secret.utf8) + } +} + +private struct RefuseNativeBindings: RuntimeBindingProvider { + func value(for binding: String, environment: RuntimeEnvironment) throws -> Data { + throw CoreError.invalidState("an unselected binding must not be replayed") + } +} + +struct PrivateNativeCompositionTests { + @Test(arguments: [false, true]) + func generatedLSPContainerUsesProductionRenderingAndPrivatePublication(_ sensitive: Bool) throws { + let f = try UpdateFixture() + let provider = NativeBindings() + try f.store.save( + declaration: Declaration(components: [ + .lspServer( + name: "language", + run: .init( + executable: "fixture-language-server", + environment: sensitive ? ["TOKEN": .secret("token")] : [:]), + languages: [".swift": "swift"], agents: [.claudeCode]), + .command( + name: "review", description: "Review", prompt: .literal("Before"), agents: [.claudeCode]), + ]), ledger: ResolvedLedger()) + let inventory = try FileHash.folderHash(f.root) + let preview = try f.preview() + #expect(try FileHash.folderHash(f.root) == inventory) + #expect(provider.calls.withLock { $0 } == 0) + #expect( + !String(decoding: try JSONEncoder().encode(preview), as: UTF8.self).contains(provider.secret)) + _ = try UpdateOperations.withPreparedUpdate( + environment: f.environment, bindingProvider: provider + ) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + #expect(provider.calls.withLock { $0 } == (sensitive ? 1 : 0)) + let installed = try UpdateOperations.inspect(environment: f.environment) + #expect(installed.deployments.allSatisfy { $0.status == .current }) + let lsp = try #require(installed.components.first { $0.kind == .lspServer }) + let tree = try #require( + installed.deployments.first { $0.ownerRecords.contains(lsp.record) }?.location) + let manifest = tree.appendingPathComponent(".claude-plugin/plugin.json") + let bytes = try Data(contentsOf: manifest) + #expect(String(decoding: bytes, as: UTF8.self).contains("fixture-language-server")) + #expect(String(decoding: bytes, as: UTF8.self).contains(provider.secret) == sensitive) + #expect( + !String(decoding: try Data(contentsOf: f.store.resolvedURL), as: UTF8.self).contains( + provider.secret)) + if sensitive { + for url in [tree, manifest.deletingLastPathComponent(), manifest] { + let mode = + try FileManager.default.attributesOfItem(atPath: url.path)[.posixPermissions] as? NSNumber + #expect(mode?.intValue == (url == manifest ? 0o600 : 0o700)) + } + } + let committed = try f.snapshot() + let command = try #require( + installed.deployments.first { !$0.ownerRecords.contains(lsp.record) }?.location) + let oldCommand = try Data(contentsOf: command) + var failedDeclaration = try f.store.loadDeclaration() + failedDeclaration.components[0] = .lspServer( + name: "language", + run: .init( + executable: "fixture-language-server", arguments: ["new-generation"], + environment: sensitive ? ["TOKEN": .secret("token")] : [:]), + languages: [".swift": "swift"], agents: [.claudeCode]) + failedDeclaration.components[1] = .command( + name: "review", description: "Review", prompt: .literal("Interrupted"), agents: [.claudeCode]) + var interrupted = false + let failed = UpdateOperations.perform( + .init(operation: .declaration(failedDeclaration)), environment: f.environment, + bindingProvider: provider, + checkpoint: { _ in + if !interrupted, (try? Data(contentsOf: manifest)) != bytes { + interrupted = true + throw CoreError.invalidState("fixture interruption after container publication") + } + }, { try $0.apply() }) + #expect(interrupted && failed.disposition == .rolledBack && !failed.recovery.pending) + #expect(throws: (any Error).self) { try failed.result.get() } + #expect(try f.snapshot() == committed) + #expect(try Data(contentsOf: manifest) == bytes) + #expect(try Data(contentsOf: command) == oldCommand) + let callsBeforeEdit = provider.calls.withLock { $0 } + #expect(callsBeforeEdit == (sensitive ? 2 : 0)) + var declaration = try f.store.loadDeclaration() + declaration.components[1] = .command( + name: "review", description: "Review", prompt: .literal("After"), agents: [.claudeCode]) + let request = UpdateRequest(operation: .declaration(declaration), kinds: [.command]) + let edit = try UpdateOperations.preview(request, environment: f.environment) + _ = try UpdateOperations.withPreparedUpdate( + request, environment: f.environment, bindingProvider: RefuseNativeBindings() + ) { try $0.apply(ifUnchangedFrom: edit.displayedFingerprint) } + #expect(try Data(contentsOf: manifest) == bytes) + #expect(provider.calls.withLock { $0 } == callsBeforeEdit) + let cold = f.root.appendingPathComponent("cold-project") + var coldEnvironment = f.environment + coldEnvironment.projectDirectory = cold + let coldStore = StateStore(scope: .project, environment: coldEnvironment) + try FileManager.default.createDirectory( + at: coldStore.directory, withIntermediateDirectories: true) + let locked = try Data(contentsOf: f.store.resolvedURL) + try locked.write(to: coldStore.resolvedURL) + try Data("invalid: [".utf8).write(to: coldStore.declarationURL) + try FileManager.default.removeItem(at: tree) + _ = try UpdateOperations.withPreparedUpdate( + .init(operation: .restore), environment: coldEnvironment, bindingProvider: provider + ) { try $0.apply() } + #expect(try Data(contentsOf: coldStore.resolvedURL) == locked) + try Data(contentsOf: f.store.declarationURL).write(to: coldStore.declarationURL) + let current = try UpdateOperations.inspect(environment: coldEnvironment) + let restoredRecord = try #require(current.components.first { $0.kind == .lspServer }) + let restored = try #require( + current.deployments.first { $0.ownerRecords.contains(restoredRecord.record) }?.location) + #expect(restored.path.hasPrefix(cold.path + "/")) + #expect( + try Data(contentsOf: restored.appendingPathComponent(".claude-plugin/plugin.json")) == bytes) + #expect(try Data(contentsOf: coldStore.resolvedURL) == locked) + _ = try UpdateOperations.withPreparedUpdate( + .init(operation: .remove, selections: [restoredRecord.selection]), + environment: coldEnvironment, + bindingProvider: RefuseNativeBindings() + ) { try $0.apply() } + #expect(!FileManager.default.fileExists(atPath: restored.path)) + } +} + +extension PrivateNativeCompositionTests { + @Test(arguments: [false, true]) + func opaqueFrozenTreeRetainsPrivateClassificationWithoutProviderReplay(_ separateProducer: Bool) + throws + { + let f = try UpdateFixture() + let source = separateProducer ? f.root.appendingPathComponent("native-source") : f.root + let tree = source.appendingPathComponent("demo-plugin") + let manifest = Data("{\"name\":\"demo-plugin\",\"version\":\"1.0.0\"}".utf8) + let executable = Data("#!/bin/sh\n# Not executed.\n".utf8) + try f.write( + String(decoding: manifest, as: UTF8.self), + to: tree.appendingPathComponent(".claude-plugin/plugin.json")) + try f.write( + String(decoding: executable, as: UTF8.self), to: tree.appendingPathComponent("bin/check")) + try FileManager.default.setAttributes( + [.posixPermissions: 0o755], ofItemAtPath: tree.appendingPathComponent("bin/check").path) + try FileManager.default.createSymbolicLink( + atPath: tree.appendingPathComponent("current").path, withDestinationPath: "bin/check") + try f.store.save( + declaration: Declaration( + sources: ["producer": .init(kind: .local, location: source.path)], + components: [ + .plugin( + name: "demo-plugin", path: "demo-plugin", source: "producer", mode: .native, + agents: [.claudeCode]) + ]), ledger: ResolvedLedger()) + _ = try f.apply() + let installed = try UpdateOperations.inspect(environment: f.environment) + let location = try #require(installed.deployments.first?.location) + // A real previously materialized private generation is the input to this E continuity case. + let route = try NativeTargetRoute.named( + .claudeSkillPlugin, scope: .project, name: "demo-plugin") + try f.store.withLock(footprint: [route]) { + let target = try f.store.nativeTarget(for: route) + let prepared = try f.store.preparePrivateMaterialization(target, changingAccess: true) + let transaction = FileTransaction(store: f.store) + try transaction.replacePrivateTree( + prepared, + entries: [ + .init(".claude-plugin", content: .directory), + .init(".claude-plugin/plugin.json", content: .file(manifest)), + .init("bin", content: .directory), + .init("bin/check", content: .file(executable, executable: true)), + .init("current", content: .symlink("bin/check")), + ], provider: RefuseNativeBindings()) + try transaction.commit() + } + let bytes = try FileHash.folderHash(location) + let report = try f.preview() + #expect(report.components.first?.privateMaterialization == true) + _ = try UpdateOperations.withPreparedUpdate( + environment: f.environment, bindingProvider: RefuseNativeBindings() + ) { try $0.apply(ifUnchangedFrom: report.displayedFingerprint) } + #expect(try FileHash.folderHash(location) == bytes) + let current = try UpdateOperations.inspect(environment: f.environment) + #expect(current.deployments.first?.privateMaterialization == true) + #expect(current.deployments.first?.status == .current) + let mode = + try FileManager.default.attributesOfItem( + atPath: location.appendingPathComponent("bin/check").path)[.posixPermissions] as? NSNumber + #expect(mode?.intValue == 0o700) + #expect( + try FileManager.default.destinationOfSymbolicLink( + atPath: location.appendingPathComponent("current").path) == "bin/check") + // Exact locked replay must not consult a mutable producer or request a binding. + try FileManager.default.removeItem(at: tree) + try FileManager.default.removeItem(at: location) + _ = try UpdateOperations.restore( + environment: f.environment, bindingProvider: RefuseNativeBindings()) + #expect(try FileHash.folderHash(location) == bytes) + #expect( + try UpdateOperations.inspect(environment: f.environment).deployments.first?.status == .current + ) + _ = try UpdateOperations.withPreparedUpdate( + .init(operation: .remove, selections: [try #require(current.components.first?.selection)]), + environment: f.environment, bindingProvider: RefuseNativeBindings() + ) { try $0.apply() } + #expect(!FileManager.default.fileExists(atPath: location.path)) + } +} + +extension PrivateNativeCompositionTests { + @Test func addingBindingToOwnedContainerReportsExplicitMemberAccessChanges() throws { + let f = try UpdateFixture() + var declaration = Declaration(components: [ + .lspServer( + name: "language", run: .init(executable: "fixture-server"), languages: [".swift": "swift"], + agents: [.claudeCode]) + ]) + try f.store.save(declaration: declaration, ledger: ResolvedLedger()) + _ = try f.apply() + let installed = try UpdateOperations.inspect(environment: f.environment) + let tree = try #require(installed.deployments.first?.location) + for directory in [tree, tree.appendingPathComponent(".claude-plugin")] { + try FileManager.default.setAttributes( + [.posixPermissions: 0o755], ofItemAtPath: directory.path) + } + declaration.components[0] = .lspServer( + name: "language", + run: .init(executable: "fixture-server", environment: ["TOKEN": .secret("token")]), + languages: [".swift": "swift"], agents: [.claudeCode]) + var request = UpdateRequest(operation: .declaration(declaration)) + #expect(throws: (any Error).self) { + try UpdateOperations.preview(request, environment: f.environment) + } + request.changingAccess = true + let before = try FileHash.folderHash(f.root) + let preview = try UpdateOperations.preview(request, environment: f.environment) + let access = try #require(preview.components.first?.permissionChange) + #expect( + access.members.contains { $0.path == ".claude-plugin/plugin.json" && $0.afterMode == 0o600 }) + #expect(access.members.contains { $0.path == ".claude-plugin" && $0.afterMode == 0o700 }) + #expect(try FileHash.folderHash(f.root) == before) + let manifest = tree.appendingPathComponent(".claude-plugin/plugin.json") + let bytes = try Data(contentsOf: manifest) + try bytes.write(to: manifest, options: .atomic) + #expect( + try UpdateOperations.preview(request, environment: f.environment).displayedFingerprint + == preview.displayedFingerprint) + let provider = NativeBindings() + try UpdateOperations.withPreparedUpdate( + request, environment: f.environment, bindingProvider: provider + ) { prepared in + try bytes.write(to: manifest, options: .atomic) + #expect(throws: UpdateApplyError.self) { + try prepared.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + } + #expect(provider.calls.withLock { $0 } == 0) + try FileManager.default.setAttributes([.posixPermissions: 0o640], ofItemAtPath: manifest.path) + let changed = try UpdateOperations.preview(request, environment: f.environment) + #expect(changed.displayedFingerprint != preview.displayedFingerprint) + _ = try UpdateOperations.withPreparedUpdate( + request, environment: f.environment, bindingProvider: provider + ) { try $0.apply(ifUnchangedFrom: changed.displayedFingerprint) } + let current = try UpdateOperations.inspect(environment: f.environment) + #expect(current.deployments.allSatisfy { $0.privateMaterialization && $0.status == .current }) + } +} + +extension PrivateNativeCompositionTests { + @Test func differentSymbolicNativeOwnersCannotShareAProgramRegion() throws { + let f = try UpdateFixture() + try f.store.save( + declaration: Declaration(components: [ + .lspServer( + name: "language", + run: .init(executable: "fixture-server", environment: ["TOKEN": .secret("first")]), + languages: [:], agents: [.opencode]), + .lspServer( + name: "language", + run: .init(executable: "fixture-server", environment: ["TOKEN": .secret("second")]), + languages: [:], agents: [.opencode]), + ]), ledger: ResolvedLedger()) + let before = try FileHash.folderHash(f.root) + #expect(throws: (any Error).self) { try f.preview() } + #expect(try FileHash.folderHash(f.root) == before) + } +} + +extension PrivateNativeCompositionTests { + @Test func generatedEnvironmentValuesStayOutOfPreviewAndLedger() throws { + let f = try UpdateFixture() + var environment = f.environment + let canary = "private-native-environment-canary" + environment.environment["NATIVE_FIXTURE_VALUE"] = canary + try f.store.save( + declaration: Declaration(components: [ + .lspServer( + name: "language", + run: .init( + executable: "fixture-server", + environment: ["TOKEN": .environment("NATIVE_FIXTURE_VALUE")]), + languages: [".swift": "swift"], agents: [.claudeCode]) + ]), ledger: ResolvedLedger()) + let before = try FileHash.folderHash(f.root) + let preview = try UpdateOperations.preview(environment: environment) + #expect(!String(decoding: try JSONEncoder().encode(preview), as: UTF8.self).contains(canary)) + #expect(try FileHash.folderHash(f.root) == before) + _ = try UpdateOperations.withPreparedUpdate( + environment: environment, bindingProvider: RefuseNativeBindings() + ) { try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) } + let current = try UpdateOperations.inspect(environment: environment) + let tree = try #require(current.deployments.first?.location) + #expect(current.deployments.first?.privateMaterialization == true) + #expect( + try String( + contentsOf: tree.appendingPathComponent(".claude-plugin/plugin.json"), encoding: .utf8 + ).contains(canary)) + #expect( + !String(decoding: try Data(contentsOf: f.store.resolvedURL), as: UTF8.self).contains(canary)) + } +} + +extension PrivateNativeCompositionTests { + @Test func aPrivateReceiptDoesNotHideChangedGeneratedManifestSemantics() throws { + let f = try UpdateFixture() + try f.store.save( + declaration: Declaration(components: [ + .lspServer( + name: "language", + run: .init(executable: "fixture-server", environment: ["TOKEN": .secret("token")]), + languages: [".swift": "swift"], agents: [.claudeCode]) + ]), ledger: ResolvedLedger()) + _ = try UpdateOperations.withPreparedUpdate( + environment: f.environment, bindingProvider: NativeBindings() + ) { try $0.apply() } + let installed = try UpdateOperations.inspect(environment: f.environment) + let tree = try #require(installed.deployments.first?.location) + let manifest = tree.appendingPathComponent(".claude-plugin/plugin.json") + let original = try String(contentsOf: manifest, encoding: .utf8) + let changed = Data( + original.replacingOccurrences(of: "fixture-server", with: "different-server").utf8) + let route = try NativeTargetRoute.named(.claudeSkillPlugin, scope: .project, name: "language") + try f.store.withLock(footprint: [route]) { + let prepared = try f.store.preparePrivateMaterialization(f.store.nativeTarget(for: route)) + let transaction = FileTransaction(store: f.store) + try transaction.replacePrivateTree( + prepared, + entries: [ + .init(".claude-plugin", content: .directory), + .init(".claude-plugin/plugin.json", content: .file(changed)), + ], provider: RefuseNativeBindings()) + try transaction.commit() + } + let before = try FileHash.folderHash(f.root) + #expect( + try UpdateOperations.inspect(environment: f.environment).deployments.first?.status == .drifted + ) + #expect(throws: (any Error).self) { try f.preview() } + #expect(try FileHash.folderHash(f.root) == before) + #expect(try Data(contentsOf: manifest) == changed) + } +} diff --git a/Tests/AgentsUpdatesTests/ProducerPatchTests.swift b/Tests/AgentsUpdatesTests/ProducerPatchTests.swift new file mode 100644 index 0000000..942d6c3 --- /dev/null +++ b/Tests/AgentsUpdatesTests/ProducerPatchTests.swift @@ -0,0 +1,503 @@ +import AgentsManifest +import AgentsUpdates +import Foundation +import StateTestSupport +import Synchronization +import Testing + +@testable import AgentsCore + +@Suite("Producer patch export") +struct ProducerPatchTests { + @Test func appliesReviewedBytesToTheExactRepositoryCommit() throws { + let fixture = try UpdateFixture() + let package = "nested pack" + let skill = package + "/skills/demo" + let path = "assets/café file.md" + let source = fixture.repo.appendingPathComponent(skill) + let header = "" + let original = header + "\nold" + let edited = header + "\n\nnew" + try fixture.write("# Notes\n", to: source.appendingPathComponent("notes.md")) + try fixture.write(original, to: source.appendingPathComponent(path)) + try fixture.write("old\r\n", to: source.appendingPathComponent("crlf.md")) + try fixture.write("old\n", to: source.appendingPathComponent("gone.md")) + try fixture.write("old\n", to: source.appendingPathComponent("replaced.md")) + try fixture.write("$Format:%H$\n", to: source.appendingPathComponent("archive.md")) + try fixture.write( + "archive.md export-subst\n", to: source.appendingPathComponent(".gitattributes")) + try Data([0, 1, 2]).write(to: source.appendingPathComponent("binary")) + try fixture.write( + "---\nname: demo\ndescription: fixture\n---\n\nBody\n", + to: source.appendingPathComponent("SKILL.md")) + try fixture.write( + "---\ndescription: fixture\n---\n# Rule\n\nText\n", + to: fixture.repo.appendingPathComponent(package + "/instructions/rule.md")) + try fixture.commit() + let base = try fixture.git(["rev-parse", "HEAD"]) + let remote = try seedMirror(fixture, ref: base, location: "https://producer.invalid/team/tool") + var nested = remote + nested.path = package + let declaration = Declaration( + sources: ["nested": nested], + skills: ["nested": .init(select: .all, agents: [.codex, .claudeCode], mode: .copy)], + instructions: .init(agents: [.codex], sections: ["nested:rule"])) + try install(declaration, in: fixture) + + let target = fixture.target() + try fixture.write( + "\u{feff}" + edited.replacingOccurrences(of: "\n", with: "\r\n"), + to: target.appendingPathComponent(path)) + try fixture.write(edited, to: fixture.target(.claudeCode).appendingPathComponent(path)) + try fixture.write("# New notes\n", to: target.appendingPathComponent("notes.md")) + try fixture.write("new\n", to: target.appendingPathComponent("crlf.md")) + try FileManager.default.removeItem(at: target.appendingPathComponent("gone.md")) + let replaced = target.appendingPathComponent("replaced.md") + try FileManager.default.removeItem(at: replaced) + try FileManager.default.createSymbolicLink(at: replaced, withDestinationURL: source) + try fixture.write("archive edit\n", to: target.appendingPathComponent("archive.md")) + let instructions = String(decoding: try fixture.bytes(fixture.instruction()), as: UTF8.self) + let markerEnd = try #require(instructions.firstIndex(of: "\n")) + try fixture.write( + "" + instructions[markerEnd...], to: fixture.instruction()) + let cache = SourceCache(store: fixture.store) + let materialized = try cache.materializedURL( + sourceID: remote.identity(environment: fixture.environment), revision: base) + if FileManager.default.fileExists(atPath: materialized.path) { + try FileManager.default.removeItem(at: materialized) + } + + let baseline = try fixture.snapshot() + let preview = try UpdateOperations.previewProducerPatches(environment: fixture.environment) + let patch = try #require(preview.patches.first) + #expect(preview.patches.count == 1) + #expect(patch.producer.base == .git(commit: base)) + #expect(patch.producer.source == "producer.invalid/team/tool") + #expect(patch.producer.root == package) + #expect(patch.paths == [skill + "/" + path, skill + "/notes.md"]) + #expect(patch.content.contains("consumer-authored")) + #expect( + preview.skipped.contains { $0.path == fixture.instruction() && $0.reason == .transformed }) + #expect( + preview.skipped.contains { + $0.path == target.appendingPathComponent("archive.md") && $0.reason == .transformed + }) + let reasons = Set(preview.skipped.map(\.reason)) + #expect(reasons == [.transformed, .uncleanSource, .deleted, .binary, .nonRegular]) + let defaultOutput = fixture.root.appendingPathComponent("patches") + #expect(!FileManager.default.fileExists(atPath: defaultOutput.path)) + let encoded = try JSONSerialization.jsonObject(with: JSONEncoder().encode(preview)) + let fields = try #require(encoded as? [String: Any]) + #expect(Set(fields.keys) == ["patches", "skipped"]) + + // The local producer may move while the patch still names the reviewed commit. + try fixture.advance() + let checkout = fixture.root.appendingPathComponent("independent") + try fixture.git([ + "clone", "--no-local", "--no-checkout", "--", fixture.repo.path, checkout.path, + ]) + try git(["checkout", "--detach", base], at: checkout) + let exported = try UpdateOperations.exportProducerPatches(preview) + let output = try #require(exported.written.first) + #expect(exported.directory?.path == defaultOutput.path) + #expect(try fixture.bytes(output) == Data(patch.content.utf8)) + #expect(exported.failures.isEmpty) + try git(["apply", "--check", "--", output.path], at: checkout) + try git(["apply", "--", output.path], at: checkout) + #expect( + try fixture.bytes(checkout.appendingPathComponent(skill + "/" + path)) == Data(edited.utf8)) + #expect( + try fixture.bytes(checkout.appendingPathComponent(skill + "/notes.md")) + == Data("# New notes\n".utf8)) + #expect(try fixture.snapshot() == baseline) + #expect(try git(["rev-parse", "HEAD"], at: checkout) == base) + } + + @Test func comparesOverlappingPackagesBeforeChoosingAnOwner() throws { + let fixture = try UpdateFixture() + let package = "nested" + let source = fixture.repo.appendingPathComponent(package + "/skills/shared/SKILL.md") + let header = "---\nname: shared\ndescription: fixture\n---\n" + try fixture.write(header + "base\n", to: source) + try fixture.commit() + let base = try fixture.git(["rev-parse", "HEAD"]) + let remote = try seedMirror( + fixture, ref: base, location: "https://producer.invalid/team/overlap") + var nested = remote + nested.path = package + try install( + Declaration( + sources: ["root": remote, "nested": nested], + groups: [ + .init( + name: "outer", + components: [ + .skills( + source: "root", + .init(select: .names(["shared"]), path: package, agents: [.codex], mode: .copy)) + ]), + .init( + name: "inner", + components: [ + .skills(source: "nested", .init(select: .all, agents: [.claudeCode], mode: .copy)) + ]), + ], uses: [.init(name: "outer"), .init(name: "inner")]), + in: fixture) + let codex = installed("shared", on: .codex, in: fixture) + let claude = installed("shared", on: .claudeCode, in: fixture) + try fixture.write(header + "new\n", to: codex) + let oneEdit = try UpdateOperations.previewProducerPatches(environment: fixture.environment) + #expect(oneEdit.patches.count == 1) + try fixture.write(header + "different\n", to: claude) + let conflict = try UpdateOperations.previewProducerPatches(environment: fixture.environment) + #expect(conflict.patches.isEmpty) + #expect( + Set(conflict.skipped.filter { $0.reason == .conflictingEdits }.map(\.path)) == [ + codex, claude, + ]) + let empty = try UpdateOperations.exportProducerPatches(conflict) + #expect(empty.directory == nil) + #expect( + !FileManager.default.fileExists(atPath: fixture.root.appendingPathComponent("patches").path)) + + try fixture.write(header + "new\n", to: claude) + let agreed = try UpdateOperations.previewProducerPatches(environment: fixture.environment) + let patch = try #require(agreed.patches.first) + #expect(agreed.patches.count == 1) + #expect(patch.producer.root == ".") + #expect(patch.paths == [package + "/skills/shared/SKILL.md"]) + #expect(patch.selectors.contains { $0.contains(":outer:") }) + #expect(patch.selectors.contains { $0.contains(":inner:") }) + #expect(patch.content.components(separatedBy: "diff --git ").count == 2) + } + + @Test func usesRecordedOpaqueAndGeneratedPluginResourcePlacements() throws { + let fixture = try UpdateFixture() + let manifest = ".claude-plugin/plugin.json" + let resource = "skills/helper/SKILL.md" + let skillHeader = "---\nname: helper\ndescription: Help\n---\n" + for name in ["opaque", "composed"] { + let tree = fixture.repo.appendingPathComponent("plugins/" + name) + try fixture.write("{\"name\":\"\(name)\"}\n", to: tree.appendingPathComponent(manifest)) + try fixture.write(skillHeader + "Original\n", to: tree.appendingPathComponent(resource)) + } + try fixture.commit() + let base = try fixture.git(["rev-parse", "HEAD"]) + let remote = try seedMirror( + fixture, ref: base, location: "https://producer.invalid/team/plugins") + try install( + Declaration( + sources: ["producer": remote], + components: [ + .plugin( + name: "opaque", path: "plugins/opaque", source: "producer", mode: .native, + agents: [.claudeCode]), + .plugin( + name: "composed", path: "plugins/composed", source: "producer", agents: [.claudeCode]), + ]), in: fixture) + let state = try UpdateOperations.inspect(environment: fixture.environment) + let opaque = try #require(state.deployments.first { $0.location.lastPathComponent == "opaque" }) + let composed = try #require( + state.deployments.first { $0.location.lastPathComponent == "composed" }) + try fixture.write( + skillHeader + "Edited\n", to: opaque.location.appendingPathComponent(resource)) + try fixture.write( + skillHeader + "Edited\n", to: composed.location.appendingPathComponent(resource)) + try fixture.write( + "changed generated output\n", to: composed.location.appendingPathComponent(manifest)) + let report = try UpdateOperations.previewProducerPatches(environment: fixture.environment) + #expect( + report.patches.flatMap(\.paths).sorted() + == ["plugins/composed/" + resource, "plugins/opaque/" + resource]) + #expect(report.patches.allSatisfy { $0.producer.base == .git(commit: base) }) + #expect( + report.skipped.contains { + $0.path == composed.location.appendingPathComponent(manifest) && $0.reason == .transformed + }) + } + + @Test func staleAfterSelectionAndPoliciesCannotWrite() throws { + let fixture = try UpdateFixture() + let base = try fixture.git(["rev-parse", "HEAD"]) + let remote = try seedMirror(fixture, ref: base, location: "https://producer.invalid/team/tool") + try install(single(remote), in: fixture) + let copy = fixture.target().appendingPathComponent("run.sh") + try fixture.write("first\n", to: copy) + let first = try UpdateOperations.previewProducerPatches(environment: fixture.environment) + let output = fixture.root.appendingPathComponent("selected") + try fixture.write("second\n", to: copy) + #expect(throws: ProducerPatchError.stale) { + try UpdateOperations.exportProducerPatches(first, to: output) + } + #expect(!FileManager.default.fileExists(atPath: output.path)) + + let fresh = try UpdateOperations.previewProducerPatches(environment: fixture.environment) + #expect(fresh.patches.first?.content.contains("+second\n") == true) + let policy = SourcePolicyOperations.policyURL(scope: .project, environment: fixture.environment) + try fixture.write("version: 1\ndeny: [{git: producer.invalid/team/tool}]\n", to: policy) + #expect(throws: SourcePolicyFailure.self) { + try UpdateOperations.exportProducerPatches(fresh, to: output) + } + #expect(!FileManager.default.fileExists(atPath: output.path)) + + try FileManager.default.removeItem(at: policy) + let organization = fixture.root.appendingPathComponent("organization.yaml") + var environment = fixture.environment + environment.projectOrganizationPolicy = .init(.local(organization)) + try fixture.write("enforcement: block\n", to: organization) + let admitted = try UpdateOperations.previewProducerPatches(environment: environment) + try fixture.write( + "enforcement: block\nsources: {deny: [producer.invalid/team/tool]}\n", to: organization + ) + let denial = try #require(throws: OrganizationPolicyFailure.self) { + try UpdateOperations.exportProducerPatches(admitted, to: output) + } + #expect(denial.report.findings.contains { $0.rule == "source-deny" }) + #expect(!FileManager.default.fileExists(atPath: output.path)) + } + + @Test func localOnlySkipsReplayButMissingRemoteInputsFail() throws { + let local = try UpdateFixture() + try local.install(agents: [.codex]) + try FileManager.default.removeItem(at: local.store.cacheDirectory) + try FileManager.default.removeItem(at: local.repo) + let preview = try UpdateOperations.previewProducerPatches(environment: local.environment) + #expect(preview.patches.isEmpty) + #expect(!preview.skipped.isEmpty) + #expect(preview.skipped.allSatisfy { $0.reason == .locallyOwned }) + #expect(try UpdateOperations.exportProducerPatches(preview).directory == nil) + + let remote = try UpdateFixture() + let base = try remote.git(["rev-parse", "HEAD"]) + let declaration = try seedMirror( + remote, ref: base, location: "https://producer.invalid/team/tool") + try install(single(declaration), in: remote) + try FileManager.default.removeItem(at: remote.store.cacheDirectory) + #expect(throws: ProducerPatchError.lockedInputUnavailable) { + try UpdateOperations.previewProducerPatches(environment: remote.environment) + } + } + + @Test func pendingResolutionDoesNotInvalidateDeployedEdits() throws { + let fixture = try UpdateFixture() + let base = try fixture.git(["rev-parse", "HEAD"]) + let remote = try seedMirror(fixture, ref: base, location: "https://producer.invalid/team/tool") + try install(single(remote), in: fixture) + try fixture.write("edited\n", to: fixture.target().appendingPathComponent("run.sh")) + let preview = try UpdateOperations.previewProducerPatches(environment: fixture.environment) + let before = try fixture.store.loadLedger() + let catalog = try GraphCatalog() + try catalog.publish("preview", "1.0.0") + let pending = try MarketplaceOperations.previewLockOnly( + .install(catalog.root("future", package: "preview")), environment: fixture.environment) + try MarketplaceOperations.writeLockOnly(pending) + let after = try fixture.store.loadLedger() + #expect(after.pendingMarketplaceDeployment != nil) + #expect(after.deployments == before.deployments) + #expect(after.marketplaceGraph == before.marketplaceGraph) + let lock = try fixture.bytes(fixture.store.resolvedURL) + let result = try UpdateOperations.exportProducerPatches(preview) + #expect(result.written.count == 1) + #expect(try fixture.bytes(fixture.store.resolvedURL) == lock) + } + + @Test func portableGitClaimsDoNotAttributeARepublishedPath() throws { + let producer = try UpdateFixture() + let base = try producer.git(["rev-parse", "HEAD"]) + let remote = try seedMirror(producer, ref: base, location: "https://producer.invalid/team/tool") + try install(single(remote), in: producer) + let inspection = try UpdateOperations.inspect(environment: producer.environment) + let selection = try #require(inspection.components.first?.selection) + let archive = try BundleOperations.export( + .init(name: "forwarded", version: "1.0.0"), selections: [selection], scope: .project, + environment: producer.environment) + let bundle = try BundleOperations.inspect(archive) + let member = try #require(bundle.components.first) + #expect(member.sources.contains { $0.kind == .git && $0.revision == base }) + + let consumer = try UpdateFixture() + let imported = try BundleOperations.previewImport( + bundle, selections: [.init(componentID: member.id, targets: [.codex])], + scope: .project, environment: consumer.environment) + _ = try BundleOperations.withPreparedImport(imported) { try $0.apply() } + var declaration = try consumer.store.loadDeclaration() + let alias = try #require(declaration.sourceDeclarations.first?.name) + declaration.components.append( + .skills( + source: alias, + .init( + select: .names(["demo"]), path: "payload/skills/demo", agents: [.claudeCode], mode: .copy) + )) + _ = try UpdateOperations.withPreparedUpdate( + .init(operation: .declaration(declaration)), environment: consumer.environment + ) { try $0.apply() } + let copy = consumer.target(.claudeCode) + try consumer.write("edited\n", to: copy.appendingPathComponent("run.sh")) + let report = try UpdateOperations.previewProducerPatches(environment: consumer.environment) + #expect(report.patches.isEmpty) + #expect(report.skipped.contains { $0.path == copy && $0.reason == .missingPathAttribution }) + #expect( + report.skipped.contains { $0.path == consumer.target() && $0.reason == .linkedDeployment }) + } + + @Test func detectsEditAndDirectoryReplacementDuringPublication() throws { + let fixture = try UpdateFixture(scope: .user) + let base = try fixture.git(["rev-parse", "HEAD"]) + let remote = try seedMirror(fixture, ref: base, location: "https://producer.invalid/team/tool") + try install(single(remote), in: fixture) + let copy = fixture.target().appendingPathComponent("run.sh") + try fixture.write("first edit\n", to: copy) + let preview = try UpdateOperations.previewProducerPatches( + scope: .user, environment: fixture.environment) + let output = fixture.root.appendingPathComponent("missing/selected") + let parent = fixture.root + let observeEdit = onStaging(in: parent) { + try Data("second edit\n".utf8).write(to: copy) + } + #expect(throws: ProducerPatchError.stale) { + try DirectoryHandle.$synchronizationObserver.withValue(observeEdit) { + try UpdateOperations.exportProducerPatches(preview, to: output) + } + } + #expect(!FileManager.default.fileExists(atPath: parent.appendingPathComponent("missing").path)) + #expect( + try !FileManager.default.contentsOfDirectory(atPath: parent.path).contains { + $0.hasPrefix(".stage-") + }) + + let current = try UpdateOperations.previewProducerPatches( + scope: .user, environment: fixture.environment) + let selection = fixture.root.appendingPathComponent("existing") + let moved = fixture.root.appendingPathComponent("moved") + let elsewhere = fixture.root.appendingPathComponent("elsewhere") + for directory in [selection, elsewhere] { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false) + } + let swap = onStaging(in: selection) { + try FileManager.default.moveItem(at: selection, to: moved) + try FileManager.default.createSymbolicLink(at: selection, withDestinationURL: elsewhere) + } + let result = try DirectoryHandle.$synchronizationObserver.withValue(swap) { + try UpdateOperations.exportProducerPatches(current, to: selection) + } + #expect(result.written.isEmpty) + #expect(result.failures.map(\.reason) == [.destinationChanged]) + #expect(try FileManager.default.contentsOfDirectory(atPath: moved.path).isEmpty) + #expect(try FileManager.default.contentsOfDirectory(atPath: elsewhere.path).isEmpty) + } + + @Test func publicationKeepsCompetitorsAndSafeRetriesReusePriorFiles() throws { + let fixture = try UpdateFixture() + let base = try fixture.git(["rev-parse", "HEAD"]) + let one = try seedMirror(fixture, ref: base, location: "https://one.invalid/team/tool") + let two = try seedMirror(fixture, ref: base, location: "https://two.invalid/team/tool") + try install( + Declaration( + sources: [ + "one": one, "two": two, "local": .init(kind: .local, location: fixture.repo.path), + ], + skills: [ + "one": .init(select: .all, agents: [.codex], mode: .copy), + "two": .init(select: .all, agents: [.claudeCode], mode: .copy), + ]), in: fixture) + for agent in [AgentID.codex, .claudeCode] { + try fixture.write( + agent.rawValue + "\n", to: fixture.target(agent).appendingPathComponent("run.sh")) + } + let preview = try UpdateOperations.previewProducerPatches(environment: fixture.environment) + try #require(preview.patches.count == 2) + #expect(Set(preview.patches.map(\.filename)).count == 2) + #expect(preview.patches.allSatisfy { $0.filename.hasPrefix("tool@" + base.prefix(12)) }) + + let selection = fixture.root.appendingPathComponent("selected") + try FileManager.default.createDirectory(at: selection, withIntermediateDirectories: false) + let first = selection.appendingPathComponent(preview.patches[0].filename) + let competing = selection.appendingPathComponent(preview.patches[1].filename) + let unrelated = fixture.repo.appendingPathComponent("outside") + try fixture.write("competing bytes", to: unrelated) + let observer = onStaging(in: selection, after: first) { + try FileManager.default.createSymbolicLink(at: competing, withDestinationURL: unrelated) + } + let partial = try DirectoryHandle.$synchronizationObserver.withValue(observer) { + try UpdateOperations.exportProducerPatches(preview, to: selection) + } + #expect(partial.written == [first]) + #expect(partial.failures.map(\.reason) == [.occupied]) + #expect(try fixture.bytes(unrelated) == Data("competing bytes".utf8)) + let retry = try UpdateOperations.exportProducerPatches(preview, to: selection) + #expect(retry.reused == [first]) + #expect(retry.failures.map(\.file) == [competing]) + try FileManager.default.removeItem(at: competing) + let complete = try UpdateOperations.exportProducerPatches(preview, to: selection) + #expect(complete.reused == [first]) + #expect(complete.written == [competing]) + + let alias = fixture.root.appendingPathComponent("alias") + try FileManager.default.createSymbolicLink( + at: alias, withDestinationURL: fixture.store.cacheDirectory) + for path in [fixture.store.cacheDirectory, fixture.target(), fixture.repo, alias] { + #expect(throws: ProducerPatchError.unsafeDestination(path)) { + try UpdateOperations.exportProducerPatches(preview, to: path) + } + } + } + + private func onStaging( + in directory: URL, after previous: URL? = nil, _ action: @escaping @Sendable () throws -> Void + ) -> DirectoryHandle.SynchronizationObserver { + let injected = Mutex(false) + return .init { + guard previous.map({ FileManager.default.fileExists(atPath: $0.path) }) != false, + (try? FileManager.default.contentsOfDirectory(atPath: directory.path))?.contains( + where: { $0.hasPrefix(".stage-") }) == true + else { return } + injected.withLock { didInject in + guard !didInject else { return } + didInject = true + do { try action() } catch { Issue.record(error) } + } + } + } + + private func seedMirror(_ fixture: UpdateFixture, ref: String, location: String) throws + -> SourceDeclaration + { + let source = SourceDeclaration(kind: .git, location: location, requirement: .revision(ref)) + let cache = SourceCache(store: fixture.store) + let mirror = try cache.mirrorURL(sourceID: source.identity(environment: fixture.environment)) + try FileManager.default.createDirectory( + at: mirror.deletingLastPathComponent(), withIntermediateDirectories: true) + try fixture.git(["clone", "--mirror", "--no-local", "--", fixture.repo.path, mirror.path]) + try git(["config", "remote.origin.url", source.gitURL], at: mirror) + try git(["config", "maintenance.auto", "false"], at: mirror) + try git(["config", "gc.auto", "0"], at: mirror) + let lock = fixture.store.cacheDirectory.appendingPathComponent("locks") + .appendingPathComponent(mirror.deletingPathExtension().lastPathComponent + ".lock") + try FileLock.withLock(at: lock) {} + return source + } + + private func single(_ source: SourceDeclaration) -> Declaration { + Declaration( + sources: ["fixture": source], + skills: ["fixture": .init(select: .all, agents: [.codex], mode: .copy)]) + } + + private func install(_ declaration: Declaration, in fixture: UpdateFixture) throws { + try fixture.store.save(declaration: declaration, ledger: ResolvedLedger()) + _ = try fixture.apply() + } + + private func installed(_ name: String, on agent: AgentID, in fixture: UpdateFixture) -> URL { + AgentRegistry.installSkillsDirectory( + for: agent, scope: .project, environment: fixture.environment + ) + .appendingPathComponent(name + "/SKILL.md") + } + + @discardableResult + private func git(_ arguments: [String], at directory: URL) throws -> String { + try ProcessRunner.run("/usr/bin/env", arguments: ["git", "-C", directory.path] + arguments) + .stdout.trimmingCharacters(in: .whitespacesAndNewlines) + } +} diff --git a/Tests/AgentsUpdatesTests/PublicInspectionTests.swift b/Tests/AgentsUpdatesTests/PublicInspectionTests.swift new file mode 100644 index 0000000..0353f4d --- /dev/null +++ b/Tests/AgentsUpdatesTests/PublicInspectionTests.swift @@ -0,0 +1,415 @@ +import AgentsCore +import AgentsInstructions +import AgentsManifest +import AgentsSkills +import AgentsUpdates +import Foundation +import StateTestSupport +import Testing + +@Suite("Public rich lifecycle consumers") +struct PublicInspectionTests { + @Test func coherentInspectionCarriesDocumentGraphAndActualLocationsWithoutWrites() throws { + let f = try UpdateFixture() + try f.declare(agents: [.claudeCode]) + var declaration = try f.store.loadDeclaration() + declaration.components.append( + .mcpServer( + name: "metadata", transport: .stdio(.init(executable: "never-run")), agents: [.claudeCode])) + try f.store.save(declaration: declaration, ledger: ResolvedLedger()) + _ = try f.apply() + let before = try FileHash.folderHash(f.root) + let snapshot = try UpdateOperations.inspect(environment: f.environment) + #expect(try snapshot.document?.digest == f.store.loadManifest()?.digest) + #expect(snapshot.declaration == declaration) + #expect(snapshot.components.count == 4) + #expect(snapshot.components.allSatisfy { !$0.occurrences.isEmpty }) + #expect( + snapshot.components.allSatisfy { + !$0.selection.identity.contains(f.store.cacheDirectory.path) + }) + #expect(snapshot.sources.contains { $0.identity == "local:" + f.repo.path }) + #expect(snapshot.resources.allSatisfy { $0.location != nil }) + #expect(snapshot.readLocations.contains(f.store.watchURL)) + #expect(snapshot.readLocations.contains(f.root.appendingPathComponent(".mcp.json"))) + #expect(snapshot.deployments.allSatisfy { $0.status == .current }) + #expect(!snapshot.recovery.pending) + #expect(try FileHash.folderHash(f.root) == before) + try f.write("external drift", to: f.target(.claudeCode).appendingPathComponent("SKILL.md")) + let drift = try UpdateOperations.inspect(environment: f.environment) + #expect(drift.deployments.contains { $0.format == "agents/skill@1" && $0.status == .drifted }) + #expect(drift.generation == snapshot.generation) + } + + @Test func producerGroupInspectionPreservesRecordedJoinsAndProvenance() throws { + let f = try UpdateFixture() + try f.write( + """ + version: 1 + groups: + tools: + components: [{kind: mcpServer, name: group-tool, transport: {kind: stdio, executable: never-run}, agents: [claude-code]}] + exports: [tools] + """, to: f.repo.appendingPathComponent(".agent/agents.yaml")) + try f.commit() + try f.write( + """ + version: 1 + sources: {producer: {path: \(f.repo.path)}} + uses: [{source: producer, group: tools}] + """, to: f.store.declarationURL) + _ = try f.apply() + let snapshot = try UpdateOperations.inspect(environment: f.environment) + let group = try #require(snapshot.groups.first) + let component = try #require(snapshot.components.first) + let occurrence = try #require(component.occurrences.first) + let sourceRecords = Set(snapshot.sources.map(\.record)) + #expect(snapshot.groups.count == 1) + #expect(group.name == "tools") + #expect(sourceRecords.contains(group.sourceRecord)) + #expect(sourceRecords.contains(component.sourceRecord)) + #expect(sourceRecords.contains(component.declaringSourceRecord)) + #expect(occurrence.reference == group.id) + #expect(occurrence.manifestPath == ".agent/agents.yaml") + #expect(!occurrence.consumerEditable) + #expect(occurrence.dependencyRecords.allSatisfy(sourceRecords.contains)) + #expect(component.recipients == [.claudeCode]) + #expect(snapshot.deployments.first?.ownerRecords == [component.record]) + #expect(snapshot.deployments.first?.status == .current) + #expect(throws: (any Error).self) { + try UpdateOperations.preview( + .init(operation: .remove, selections: [component.selection]), environment: f.environment) + } + } + + @Test func preciseSelectionRemovesOneOfEqualNamesAndRejectsStaleOccurrence() throws { + let f = try UpdateFixture() + let a = f.root.appendingPathComponent("a") + let b = f.root.appendingPathComponent("b") + for root in [a, b] { + try f.write( + "---\nname: same\ndescription: Example\n---\nvalue\n", + to: root.appendingPathComponent("same/SKILL.md")) + } + try f.store.save( + declaration: Declaration( + sources: [ + "a": .init(kind: .local, location: a.path), "b": .init(kind: .local, location: b.path), + ], + components: [ + .skills(source: "a", .init(select: .all, agents: [.codex], mode: .copy)), + .skills(source: "b", .init(select: .all, agents: [.claudeCode], mode: .copy)), + ]), ledger: ResolvedLedger()) + _ = try f.apply() + let inspected = try UpdateOperations.inspect(environment: f.environment) + let selected = try #require(inspected.components.first { $0.source == "local:" + a.path }) + #expect(throws: (any Error).self) { + try UpdateOperations.preview( + .init(operation: .remove, kinds: [.skills], names: ["same"]), environment: f.environment) + } + let request = UpdateRequest(operation: .remove, selections: [selected.occurrences[0].selection]) + let preview = try UpdateOperations.preview(request, environment: f.environment) + #expect(preview.skills.count == 1) + #expect(preview.skills[0].sourceIdentity == "local:" + a.path) + _ = try UpdateOperations.withPreparedUpdate(request, environment: f.environment) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + let remaining = try UpdateOperations.inspect(environment: f.environment) + #expect(remaining.components.count == 1) + #expect(remaining.components[0].source == "local:" + b.path) + #expect(remaining.deployments.allSatisfy { $0.status == .current }) + #expect(throws: (any Error).self) { + try UpdateOperations.preview(request, environment: f.environment) + } + } + + @Test func preciseInstructionSelectionPreservesAnEqualNameFromAnotherSource() throws { + let f = try UpdateFixture() + let a = f.root.appendingPathComponent("instructions-a") + let b = f.root.appendingPathComponent("instructions-b") + for root in [a, b] { + try f.write( + "---\ndescription: Same name\n---\n# \(root.lastPathComponent)\n", + to: root.appendingPathComponent("instructions/rules.md")) + } + try f.store.save( + declaration: Declaration( + sources: [ + "a": .init(kind: .local, location: a.path), "b": .init(kind: .local, location: b.path), + ], + components: [ + .instructions(.init(agents: [.claudeCode], sections: ["a:rules"])), + .instructions(.init(agents: [.claudeCode], sections: ["b:rules"])), + ]), ledger: ResolvedLedger()) + _ = try f.apply() + let snapshot = try UpdateOperations.inspect(environment: f.environment) + let selected = try #require(snapshot.components.first { $0.source == "local:" + a.path }) + let request = UpdateRequest(operation: .remove, selections: [selected.selection]) + let preview = try UpdateOperations.preview(request, environment: f.environment) + _ = try UpdateOperations.withPreparedUpdate(request, environment: f.environment) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + let remaining = try UpdateOperations.inspect(environment: f.environment) + #expect(remaining.components.count == 1) + #expect(remaining.components[0].source == "local:" + b.path) + #expect(remaining.deployments.allSatisfy { $0.status == .current }) + } + + @Test(arguments: AgentID.allCases, [InstallScope.project, .user]) + func registeredMCPRouteAppliesAndColdRestoresWithoutRunningClient( + _ agent: AgentID, _ scope: InstallScope + ) throws { + let f = try UpdateFixture(scope: scope) + try f.store.save( + declaration: Declaration(components: [ + .mcpServer( + name: "quoted.server", + transport: .stdio(.init(executable: "never-run", arguments: ["fixed"])), agents: [agent]) + ]), ledger: ResolvedLedger()) + let preview = try f.preview() + #expect(preview.components.count == 1) + _ = try f.apply() + let snapshot = try UpdateOperations.inspect(scope: scope, environment: f.environment) + let deployed = try #require(snapshot.deployments.first) + #expect(deployed.status == .current) + let bytes = try Data(contentsOf: deployed.location) + let locked = try Data(contentsOf: f.store.resolvedURL) + try FileManager.default.removeItem(at: deployed.location) + _ = try UpdateOperations.restore(scope: scope, environment: f.environment) + #expect(try Data(contentsOf: deployed.location) == bytes) + #expect(try Data(contentsOf: f.store.resolvedURL) == locked) + } + + @Test func publicProviderAndOuterTerminalRetainPrivateBoundary() throws { + struct Provider: RuntimeBindingProvider { + func value(for binding: String, environment: RuntimeEnvironment) throws -> Data { + Data("private-canary".utf8) + } + } + let f = try UpdateFixture() + try f.store.save( + declaration: Declaration(components: [ + .mcpServer( + name: "private", + transport: .stdio( + .init(executable: "never-run", environment: ["TOKEN": .secret("token")])), + agents: [.claudeCode]) + ]), ledger: ResolvedLedger()) + try FileManager.default.createDirectory( + at: f.root.appendingPathComponent("configured-claude"), withIntermediateDirectories: true) + let preview = try f.preview() + #expect( + !String(decoding: try JSONEncoder().encode(preview), as: UTF8.self).contains("private-canary") + ) + let completion = UpdateOperations.perform( + environment: f.environment, bindingProvider: Provider() + ) { update in + try update.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + _ = try completion.result.get() + #expect(completion.disposition == .committed) + #expect(!completion.recovery.pending) + #expect( + !String(decoding: try Data(contentsOf: f.store.resolvedURL), as: UTF8.self).contains( + "private-canary")) + let snapshot = try UpdateOperations.inspect(environment: f.environment) + #expect(snapshot.deployments.allSatisfy { $0.status == .current }) + struct Cancelled: Error {} + let cancelled: UpdateCompletion = UpdateOperations.perform(environment: f.environment) { + _ in throw Cancelled() + } + #expect(cancelled.disposition == .unchanged) + #expect(throws: Cancelled.self) { try cancelled.result.get() } + } + + @Test func watchAcknowledgmentRejectsUndisplayedHead() throws { + let f = try UpdateFixture() + try f.declare() + let watch = SkillOperations.watchOperations() + _ = try watch.add("fixture", environment: f.environment) + let displayed = try #require(watch.status(environment: f.environment).first) + let previous = try f.store.loadWatch() + try f.advance() + #expect(throws: (any Error).self) { + try watch.seen(displayed, environment: f.environment) + } + #expect(try f.store.loadWatch() == previous) + let current = try #require(watch.status(environment: f.environment).first) + _ = try watch.seen(current, environment: f.environment) + #expect(try f.store.loadWatch().sources[current.sourceID]?.seen == current.current) + } + @Test func discoveryRetainsExactEvidenceAndRejectsAChangedSource() throws { + let f = try UpdateFixture() + try f.declare(agents: [.claudeCode]) + let declaration = try f.store.loadDeclaration() + let before = try FileHash.folderHash(f.root) + let discovery = try UpdateOperations.discover(declaration, environment: f.environment) + #expect(!discovery.components.isEmpty) + #expect( + discovery.sourceRevisions.values.flatMap { $0 }.contains(try f.git(["rev-parse", "HEAD"]))) + #expect(try FileHash.folderHash(f.root) == before) + #expect(discovery.readLocations.contains { $0.path == f.repo.path }) + let request = discovery.updateRequest() + let preview = try UpdateOperations.preview(request, environment: f.environment) + _ = try UpdateOperations.withPreparedUpdate(request, environment: f.environment) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + let current = try UpdateOperations.discover(declaration, environment: f.environment) + try f.advance() + #expect(throws: (any Error).self) { + try UpdateOperations.withPreparedUpdate(current.updateRequest(), environment: f.environment) { + _ in + Issue.record("changed discovery must fail before delivering the handle") + } + } + } + + @Test func watchAcknowledgmentRejectsAnAliasRedirectEvenWithTheSameCommit() throws { + let f = try UpdateFixture() + try f.declare() + let watch = SkillOperations.watchOperations() + _ = try watch.add("fixture", environment: f.environment) + let displayed = try #require(watch.status(environment: f.environment).first) + let other = f.root.appendingPathComponent("another-source") + try FileManager.default.copyItem(at: f.repo, to: other) + var declaration = try f.store.loadDeclaration() + declaration.sources["fixture"]?.location = other.path + try f.store.save(declaration: declaration, ledger: f.store.loadLedger()) + let before = try Data(contentsOf: f.store.watchURL) + #expect(throws: (any Error).self) { try watch.seen(displayed, environment: f.environment) } + #expect(try Data(contentsOf: f.store.watchURL) == before) + } + +} + +extension PublicInspectionTests { + @Test func importedAuthoringContentUsesProductionFreezeAndInputFreshness() throws { + let f = try UpdateFixture() + let input = f.root.appendingPathComponent("producer") + let document = input.appendingPathComponent("apm.yml") + let skill = input.appendingPathComponent(".apm/skills/review/SKILL.md") + try f.write("name: example\nversion: '1.0.0'\n", to: document) + try f.write("---\nname: review\ndescription: Review\n---\n# Review\n", to: skill) + let before = try FileHash.folderHash(f.root) + let proposal = try SourceImportOperations.inspect( + format: "apmManifest", root: input, document: "apm.yml") + #expect(!proposal.specificationStatus.isEmpty) + #expect(proposal.diagnostics.isEmpty) + #expect(proposal.components.count == 1) + #expect(proposal.resources.first?.requiresStandaloneSource == true) + #expect(try FileHash.folderHash(f.root) == before) + let scope = try UpdateOperations.inspect(environment: f.environment) + let request = try proposal.updateRequest(in: scope) + let preview = try UpdateOperations.preview(request, environment: f.environment) + _ = try UpdateOperations.withPreparedUpdate(request, environment: f.environment) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + let installed = try UpdateOperations.inspect(environment: f.environment) + #expect(installed.components.first?.name == "review") + #expect(installed.deployments.allSatisfy { $0.status == .current }) + let newProposal = try SourceImportOperations.inspect( + format: "apmManifest", root: input, document: "apm.yml") + let newRequest = try newProposal.updateRequest(in: installed) + try f.write("---\nname: review\ndescription: Review\n---\n# Changed\n", to: skill) + #expect(throws: (any Error).self) { + try UpdateOperations.withPreparedUpdate(newRequest, environment: f.environment) { _ in + Issue.record("stale imported resources must fail before delivering the handle") + } + } + let target = try #require(installed.deployments.first?.location) + let bytes = try Data(contentsOf: target.appendingPathComponent("SKILL.md")) + try FileManager.default.removeItem(at: input) + try FileManager.default.removeItem(at: f.store.cacheDirectory) + for deployment in installed.deployments { + try FileManager.default.removeItem(at: deployment.location) + } + _ = try UpdateOperations.restore(environment: f.environment) + #expect(try Data(contentsOf: target.appendingPathComponent("SKILL.md")) == bytes) + } + + @Test func importInputChangesDuringCallbackPreventPublication() throws { + let f = try UpdateFixture() + let input = f.root.appendingPathComponent("producer") + let document = input.appendingPathComponent("apm.yml") + try f.write("name: example\nversion: '1.0.0'\n", to: document) + try f.write( + "---\nname: review\ndescription: Review\n---\n# Review\n", + to: input.appendingPathComponent(".apm/skills/review/SKILL.md")) + let proposal = try SourceImportOperations.inspect( + format: "apmManifest", root: input, document: "apm.yml") + let request = try proposal.updateRequest( + in: UpdateOperations.inspect(environment: f.environment)) + let result = UpdateOperations.perform(request, environment: f.environment) { update in + try f.write("name: changed\n", to: document) + return try update.apply() + } + #expect(result.disposition == .unchanged) + #expect(throws: UpdateApplyError.self) { try result.result.get() } + #expect(!FileManager.default.fileExists(atPath: f.store.resolvedURL.path)) + } + @Test func importPreservesUnconvertedAndBindingDiagnostics() throws { + let f = try UpdateFixture() + let input = f.root.appendingPathComponent("producer") + try f.write( + "name: example\nversion: '1.0.0'\nscripts: {start: never-run}\n", + to: input.appendingPathComponent("apm.yml")) + let report = try SourceImportOperations.inspect( + format: "apmManifest", root: input, document: "apm.yml") + #expect(!report.diagnostics.isEmpty) + #expect(report.diagnostics.allSatisfy { !$0.document.isEmpty && !$0.message.isEmpty }) + #expect(throws: (any Error).self) { + try report.updateRequest(in: UpdateOperations.inspect(environment: f.environment)) + } + } + + @Test func ordinarySiblingUpdateKeepsTheWholeSharedFilePrivate() throws { + struct Provider: RuntimeBindingProvider { + func value(for binding: String, environment: RuntimeEnvironment) throws -> Data { + Data("shared-canary".utf8) + } + } + let f = try UpdateFixture() + try FileManager.default.createDirectory( + at: f.root.appendingPathComponent("configured-claude"), withIntermediateDirectories: true) + try f.store.save( + declaration: Declaration(components: [ + .mcpServer( + name: "private", + transport: .stdio( + .init(executable: "never-run", environment: ["TOKEN": .secret("token")])), + agents: [.claudeCode]) + ]), ledger: ResolvedLedger()) + _ = try UpdateOperations.withPreparedUpdate( + environment: f.environment, bindingProvider: Provider() + ) { try $0.apply() } + let user = StateStore(scope: .user, environment: f.environment) + try user.save( + declaration: Declaration(components: [ + .mcpServer( + name: "ordinary", transport: .stdio(.init(executable: "never-run")), agents: [.claudeCode] + ) + ]), ledger: ResolvedLedger()) + let preview = try UpdateOperations.preview(scope: .user, environment: f.environment) + #expect(preview.components.allSatisfy { $0.privateMaterialization }) + #expect( + !String(decoding: try JSONEncoder().encode(preview), as: UTF8.self).contains("shared-canary")) + _ = try UpdateOperations.withPreparedUpdate(scope: .user, environment: f.environment) { + try $0.apply() + } + let target = try #require( + UpdateOperations.inspect(scope: .user, environment: f.environment).deployments.first?.location + ) + #expect(String(decoding: try Data(contentsOf: target), as: UTF8.self).contains("shared-canary")) + let mode = + try FileManager.default.attributesOfItem(atPath: target.path)[.posixPermissions] as? NSNumber + #expect(mode?.intValue == 0o600) + #expect( + try UpdateOperations.inspect(environment: f.environment).deployments.allSatisfy { + $0.status == .current + }) + try FileManager.default.removeItem(at: target) + _ = try UpdateOperations.restore(environment: f.environment, bindingProvider: Provider()) + #expect(String(decoding: try Data(contentsOf: target), as: UTF8.self).contains("shared-canary")) + } + +} diff --git a/Tests/AgentsUpdatesTests/ReadFootprintIntegrationTests.swift b/Tests/AgentsUpdatesTests/ReadFootprintIntegrationTests.swift new file mode 100644 index 0000000..fa0dff8 --- /dev/null +++ b/Tests/AgentsUpdatesTests/ReadFootprintIntegrationTests.swift @@ -0,0 +1,62 @@ +import AgentsCore +import AgentsInstructions +import AgentsManifest +import AgentsUpdates +import Foundation +import Testing + +struct ReadFootprintIntegrationTests { + @Test func unsavedDeclarationAndAbsentExportInputsHaveDurableReadLocations() throws { + let f = try UpdateFixture() + try f.declare(agents: [.claudeCode]) + let own = f.root.appendingPathComponent(".agent/instructions/own.md") + let appendix = f.root.appendingPathComponent("future-append.md") + let unused = f.root.appendingPathComponent("future-source") + try f.write("---\ndescription: Own rules.\n---\n# Own\n\nCurrent own rules.", to: own) + var declaration = try f.store.loadDeclaration() + declaration.sources["unused"] = SourceDeclaration(kind: .local, location: unused.path) + for index in declaration.components.indices { + if case .instructions(var selection) = declaration.components[index] { + selection.sectionReferences.append(SectionDeclaration(name: "own")) + selection.prompts[0].prompt.append = "future-append.md" + declaration.components[index] = .instructions(selection) + } + } + let before = try FileHash.folderHash(f.root) + let report = try UpdateOperations.preview( + UpdateRequest(operation: .declaration(declaration)), environment: f.environment) + let discovery = try UpdateOperations.discover(declaration, environment: f.environment) + for locations in [report.readLocations, discovery.readLocations] { + let paths = Set(locations.map(\.path)) + #expect(paths.contains(unused.path)) + #expect(paths.contains(own.path)) + #expect(paths.contains(appendix.path)) + #expect(paths.contains(f.store.declarationURL.path)) + #expect( + !paths.contains { $0.contains("agents-replay-") || $0.contains("agents-resolution-") }) + } + #expect(try FileHash.folderHash(f.root) == before) + _ = try UpdateOperations.withPreparedUpdate( + UpdateRequest(operation: .declaration(declaration)), environment: f.environment + ) { + try $0.apply(ifUnchangedFrom: report.displayedFingerprint) + } + let inspected = try UpdateOperations.inspect(environment: f.environment) + #expect( + Set(inspected.readLocations.map(\.path)).isSuperset(of: [ + unused.path, own.path, appendix.path, + ])) + #expect(throws: (any Error).self) { + try InstructionOperations.inspectChatGPTExport(prompt: "weekly", environment: f.environment) + } + #expect(!FileManager.default.fileExists(atPath: appendix.path)) + try f.write("Live appendix", to: appendix) + let current = try InstructionOperations.inspectChatGPTExport( + prompt: "weekly", environment: f.environment) + #expect(String(decoding: current.bytes, as: UTF8.self).contains("Live appendix")) + #expect(current.readLocations.map(\.path).contains(appendix.path)) + let ownInspection = try InstructionOperations.inspectOwnInstructions(environment: f.environment) + #expect(ownInspection.units.map(\.record.name) == ["own"]) + #expect(ownInspection.readLocations.map(\.path).contains(own.deletingLastPathComponent().path)) + } +} diff --git a/Tests/AgentsUpdatesTests/RegistryAcquisitionTests.swift b/Tests/AgentsUpdatesTests/RegistryAcquisitionTests.swift new file mode 100644 index 0000000..b783429 --- /dev/null +++ b/Tests/AgentsUpdatesTests/RegistryAcquisitionTests.swift @@ -0,0 +1,553 @@ +import AgentsCore +import AgentsManifest +import Foundation +import Testing + +@testable import AgentsUpdates + +#if canImport(FoundationNetworking) + import FoundationNetworking +#endif + +@Suite struct RegistryAcquisitionTests { + @Test func proxyOnlyAdmitsTheConfiguredNamespaceAndRechecksWarmEntries() async throws { + let fixture = try RegistryAcquisitionFixture() + defer { fixture.remove() } + let base = "https://registry.example.invalid:8443/team/registry" + var environment = fixture.environment + environment.environment["MCP_REGISTRY_URL"] = base + "/" + environment.sourceAccess = .init(egress: .proxyOnly) + let registry = try MCPRegistry(endpoint: #require(URL(string: base))) + let reply = RegistryResponses([.init(headers: ["cache-control": "max-age=3600"])]) + try await RegistryAcquisition.$transport.withValue(reply.transport) { + let result = try await registry.search(environment: environment) + #expect(result.servers.first?.version == "1.0.0") + for other in [ + base + "-other", base + "/child", "https://registry.example.invalid/team/registry", + ] { + let sibling = try MCPRegistry(endpoint: #require(URL(string: other))) + await #expect(throws: SourceAccessError.egressDenied) { + try await sibling.search(environment: environment) + } + } + environment.environment["MCP_REGISTRY_URL"] = "https://registry.example.invalid/replacement" + await #expect(throws: SourceAccessError.egressDenied) { + try await registry.search(environment: environment) + } + #expect(await reply.calls.count == 1) + } + } + + @Test(arguments: [InstallScope.project, .user]) + func lockedServerRequiresItsOriginalRegistryInProxyOnlyMode(_ scope: InstallScope) async throws { + let fixture = try RegistryAcquisitionFixture() + defer { fixture.remove() } + let base = "https://registry.example.invalid:8443/team" + var environment = fixture.environment + for directory in [environment.projectDirectory, environment.homeDirectory] { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false) + } + environment.environment["MCP_REGISTRY_URL"] = base + let settings = try SourceAccessSettingsEditor(environment: environment) + try settings.save(settings.preview(Data("version: 1\negress: proxyOnly\n".utf8))) + environment.reloadSourceAccessSettings() + environment.userOrganizationPolicy = try fixture.registryOnlyPolicy() + let registry = try MCPRegistry.configured(environment: environment) + let transport: @Sendable (URLRequest) async throws -> RegistryHTTP.Response = { request in + let url = try #require(request.url) + #expect(url.absoluteString == base + "/v0.1/servers/test.example%2Ftool/versions/1.0.0") + let data = Data( + """ + {"server":{"name":"test.example/tool","version":"1.0.0","description":"fixture", + "remotes":[{"type":"streamable-http","url":"https://tools.example.invalid/mcp"}]}} + """.utf8) + return .init(url: url, status: 200, headers: [:], body: data) + } + let entry = try await RegistryAcquisition.$transport.withValue(transport) { + try await registry.server( + named: "test.example/tool", version: "1.0.0", environment: environment) + } + let selection = try #require(entry.choices.first) + let destination = try UpdateOperations.inspect(scope: scope, environment: environment) + let request = try selection.select(named: "team", agents: [.codex], in: destination) + .updateRequest() + _ = try UpdateOperations.withPreparedUpdate(request, scope: scope, environment: environment) { + try $0.apply() + } + _ = try UpdateOperations.restore(scope: scope, environment: environment) + #expect(try SourcePolicyOperations.audit(scope: scope, environment: environment).hasLock) + #expect( + !(try OrganizationPolicyOperations.audit( + scope: scope, environment: environment, requireOrganizationPolicy: true + )).isBlocked) + let root = scope == .project ? environment.projectDirectory : environment.homeDirectory + let output = root.appendingPathComponent(".codex/config.toml") + let installed = try Data(contentsOf: output) + let lock = StateStore(scope: scope, environment: environment).resolvedURL + let resolved = try Data(contentsOf: lock) + environment.environment["MCP_REGISTRY_URL"] = base + "/another-base" + #expect(throws: SourceAccessError.egressDenied) { + try UpdateOperations.restore(scope: scope, environment: environment) + } + #expect(throws: SourceAccessError.egressDenied) { + try SourcePolicyOperations.audit(scope: scope, environment: environment) + } + #expect(throws: SourceAccessError.egressDenied) { + try OrganizationPolicyOperations.audit(scope: scope, environment: environment) + } + environment.environment["MCP_REGISTRY_URL"] = base + "?invalid=1" + #expect(throws: SourceAccessError.invalidConfiguration) { + try UpdateOperations.restore(scope: scope, environment: environment) + } + #expect(throws: SourceAccessError.invalidConfiguration) { + try SourcePolicyOperations.audit(scope: scope, environment: environment) + } + #expect(throws: SourceAccessError.invalidConfiguration) { + try OrganizationPolicyOperations.audit(scope: scope, environment: environment) + } + environment.environment["MCP_REGISTRY_URL"] = base + try Data("version: 1\negress: unknown\n".utf8).write(to: settings.url) + environment.reloadSourceAccessSettings() + #expect(throws: SourceAccessSettingsError.self) { + try UpdateOperations.restore(scope: scope, environment: environment) + } + #expect(throws: SourceAccessSettingsError.self) { + try SourcePolicyOperations.audit(scope: scope, environment: environment) + } + #expect(throws: SourceAccessSettingsError.self) { + try OrganizationPolicyOperations.audit(scope: scope, environment: environment) + } + #expect(try Data(contentsOf: output) == installed) + #expect(try Data(contentsOf: lock) == resolved) + } + + @Test(arguments: ["npm", "pypi", "oci", "oci-digest", "http", "sse"]) + func registrySelectionBindsTheManifestInvocation(_ variant: String) async throws { + let fixture = try RegistryAcquisitionFixture() + defer { fixture.remove() } + var environment = try fixture.initializedEnvironment() + environment.userOrganizationPolicy = try fixture.registryOnlyPolicy() + let digest = String(repeating: "a", count: 64) + let definition = """ + {"server":{"name":"test.example/tool","version":"1.0.0","description":"fixture", + "remotes":[ + {"type":"streamable-http","url":"https://tools.example.invalid/stream"}, + {"type":"sse","url":"https://tools.example.invalid/events"}], + "packages":[ + {"registryType":"npm","identifier":"@fixture/tools","version":"2.0.0", + "registryBaseUrl":"https://packages.example.invalid/team","transport":{"type":"stdio"}, + "environmentVariables":[{"name":"FIXTURE_MODE","choices":["safe","fast"]}]}, + {"registryType":"pypi","identifier":"fixture-tools","version":"3.0.0", + "transport":{"type":"stdio"}}, + {"registryType":"oci","identifier":"fixture/tools","version":"4.0.0", + "transport":{"type":"stdio"}, + "environmentVariables":[{"name":"FIXTURE_ROLE","isRequired":true,"isSecret":true}]}, + {"registryType":"oci","identifier":"images.example.invalid/fixture/tools@sha256:\(digest)", + "transport":{"type":"stdio"}}]}} + """ + let entry = try await fixture.definition(definition, environment: environment) + let choice = try #require( + entry.choices.first { + switch $0.source { + case .package(let package): + if package.registryType == "oci" { + return variant == (package.identifier.contains("@sha256:") ? "oci-digest" : "oci") + } + return package.registryType == variant + case .remote: return $0.transport == (variant == "http" ? "streamable-http" : variant) + } + }) + let bindings: [String: MCPRegistryBinding] + let mutations: [(String, String)] + switch variant { + case "npm": + bindings = ["FIXTURE_MODE": .choice("safe")] + mutations = [ + (#""executable": "npx""#, #""executable": "echo""#), + ("@fixture/tools@2.0.0", "@fixture/tools@2.0.1"), + ("https://packages.example.invalid/team", "https://packages.example.invalid/other"), + ("safe", "fast"), + ] + case "pypi": + bindings = [:] + mutations = [("fixture-console", "different-console"), ("==3.0.0", "==3.0.1")] + case "oci": + bindings = ["FIXTURE_ROLE": .environment("FIXTURE_ROLE")] + mutations = [ + ("fixture/tools:4.0.0", "fixture/tools:4.1.0"), + (#""executable": "docker""#, #""executable": "echo""#), + ] + case "oci-digest": + bindings = [:] + mutations = [ + (digest, String(repeating: "b", count: 64)), + ("images.example.invalid", "alternate.example.invalid"), + ] + case "http": + bindings = [:] + mutations = [(#""kind": "streamableHTTP""#, #""kind": "sse""#), ("/stream", "/elsewhere")] + default: + bindings = [:] + mutations = [(#""kind": "sse""#, #""kind": "streamableHTTP""#)] + } + + let store = StateStore(scope: .project, environment: environment) + let destination = try UpdateOperations.inspect(environment: environment) + let request = try choice.select( + named: "selected", agents: [.claudeCode], in: destination, bindings: bindings, + packageCommand: variant == "pypi" ? "fixture-console" : nil + ).updateRequest() + let preview = try UpdateOperations.preview(request, environment: environment) + _ = try UpdateOperations.withPreparedUpdate(request, environment: environment) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + let original = try String(contentsOf: store.declarationURL, encoding: .utf8) + let originalLock = try Data(contentsOf: store.resolvedURL) + let native = environment.projectDirectory.appendingPathComponent(".mcp.json") + let expectedNative = try Data(contentsOf: native) + let component = try #require(store.loadDeclaration().components.first) + guard case .mcpServer(_, let transport, _, _, _, let recorded) = component else { + Issue.record("Expected a parsed MCP declaration") + return + } + let evidence = try #require(recorded) + #expect(evidence.invocationDigest?.hasPrefix("sha256:") == true) + #expect( + try evidence.portableLiteralBindings(in: transport) + == (variant == "npm" ? ["FIXTURE_MODE"] : [])) + #expect(!(try OrganizationPolicyOperations.audit(environment: environment)).isBlocked) + if variant == "npm" { + let state = try UpdateOperations.inspect(environment: environment) + let package = BundlePackage(name: "fixture-registry", version: "1.0.0") + let bytes = try BundleOperations.export( + package, selections: state.components.map(\.selection), scope: .project, + environment: environment) + let member = try #require(BundleOperations.inspect(bytes).components.first) + #expect(member.mcpRegistry == evidence) + } + for (initial, replacement) in mutations { + let edited = original.replacingOccurrences(of: initial, with: replacement) + try #require(edited != original) + try Data(edited.utf8).write(to: store.declarationURL) + #expect(throws: CoreError.self) { try store.loadDeclaration() } + #expect(throws: CoreError.self) { try UpdateOperations.preview(environment: environment) } + do { + _ = try OrganizationPolicyOperations.audit(environment: environment) + Issue.record("CI admitted a changed MCP declaration") + } catch let error as CoreError { + #expect(error.description.contains("does not match the configured invocation")) + #expect(error.description.contains("Reselect the exact MCP registry version")) + } + } + #expect(try Data(contentsOf: store.resolvedURL) == originalLock) + #expect(try Data(contentsOf: native) == expectedNative) + #expect( + !FileManager.default.fileExists(atPath: fixture.root.appendingPathComponent("launched").path)) + if variant == "pypi" { + try Data(original.utf8).write(to: store.declarationURL) + let alteredLock = String(decoding: originalLock, as: UTF8.self) + .replacingOccurrences(of: "fixture-console", with: "different-console") + try #require(Data(alteredLock.utf8) != originalLock) + try Data(alteredLock.utf8).write(to: store.resolvedURL) + #expect(throws: CoreError.self) { + try SourcePolicyOperations.audit(environment: environment) + } + #expect(throws: CoreError.self) { + try UpdateOperations.restore(environment: environment) + } + #expect(try Data(contentsOf: native) == expectedNative) + } + } + + @Test func legacyRegistryLockReplaysAndRequiresReselectionForRegistryOnlyPolicy() throws { + let fixture = try RegistryAcquisitionFixture() + defer { fixture.remove() } + var environment = try fixture.initializedEnvironment() + let store = StateStore(scope: .project, environment: environment) + try FileManager.default.createDirectory(at: store.directory, withIntermediateDirectories: true) + let original = """ + version: 1 + components: + - kind: mcpServer + name: selected + agents: [claude-code] + transport: + kind: stdio + executable: uvx + arguments: [--default-index, 'https://pypi.org/simple', --from, 'fixture-tools==3.0.0', --, fixture-console] + environment: {FIXTURE_PROFILE: safe} + registry: + registry: https://registry.example.invalid + server: test.example/tool + version: 1.0.0 + origin: https://pypi.org + package: 'fixture-tools==3.0.0' + + """ + try Data(original.utf8).write(to: store.declarationURL) + _ = try UpdateOperations.withPreparedUpdate(environment: environment) { try $0.apply() } + _ = try UpdateOperations.restore(environment: environment) + let item = try #require(UpdateOperations.inspect(environment: environment).components.first) + let evidence = try #require(item.mcpRegistry) + #expect(evidence.package == "fixture-tools==3.0.0") + #expect(evidence.invocationDigest == nil) + let component = try #require(store.loadDeclaration().components.first) + guard case .mcpServer(_, let transport, _, _, _, _) = component else { + Issue.record("Expected a parsed MCP declaration") + return + } + do { + _ = try evidence.portableLiteralBindings(in: transport) + Issue.record("Legacy literal was classified without Registry selection evidence") + } catch let error as CoreError { + #expect(error.description.contains("Reselect the exact MCP registry version")) + } + environment.userOrganizationPolicy = try fixture.registryOnlyPolicy() + let audit = try OrganizationPolicyOperations.audit(environment: environment) + #expect(audit.isBlocked) + let findings = audit.organization.findings.filter { $0.rule == "mcp-registry-evidence" } + #expect(findings.contains { $0.message.contains("Reselect the exact MCP registry version") }) + #expect(throws: OrganizationPolicyFailure.self) { + try UpdateOperations.restore(environment: environment) + } + + let mismatched = original.replacingOccurrences( + of: "--from, 'fixture-tools==3.0.0'", with: "--from, 'different-tools==3.0.0'") + try #require(mismatched != original) + try Data(mismatched.utf8).write(to: store.declarationURL) + #expect(throws: CoreError.self) { try store.loadDeclaration() } + } + + @Test func cacheSeparatesQueriesAndProjectsAndChecksPolicyBeforeReuse() async throws { + let fixture = try RegistryAcquisitionFixture() + defer { fixture.remove() } + let reply = RegistryResponses([ + .init(headers: ["cache-control": "max-age=3600", "vary": "Accept"], version: "1.0.0"), + .init(headers: ["cache-control": "max-age=3600"], version: "2.0.0"), + .init(headers: ["cache-control": "max-age=3600"], version: "3.0.0"), + ]) + try await RegistryAcquisition.$transport.withValue(reply.transport) { + let first = try await fixture.registry.search("a+b", environment: fixture.environment) + #expect(first.servers.first?.version == "1.0.0") + var independent = fixture.environment + independent.projectDirectory = fixture.root.appendingPathComponent("second") + let warm = try await fixture.registry.search("a+b", environment: independent) + #expect(warm.servers.first?.version == "1.0.0") + #expect(await reply.calls.count == 1) + var proxyOnly = independent + proxyOnly.sourceAccess = .init(egress: .proxyOnly) + await #expect(throws: SourceAccessError.egressDenied) { + _ = try await fixture.registry.search("a+b", environment: proxyOnly) + } + #expect(await reply.calls.count == 1) + let other = try await fixture.registry.search("a b", environment: independent) + #expect(other.servers.first?.version == "2.0.0") + let refreshed = try await fixture.registry.search( + "a+b", environment: independent, refresh: true) + #expect(refreshed.servers.first?.version == "3.0.0") + let policy = SourcePolicyOperations.policyURL(scope: .project, environment: independent) + try FileManager.default.createDirectory( + at: policy.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data("version: 1\ndeny: [{http: 'https://registry.example.invalid'}]\n".utf8) + .write(to: policy) + await #expect(throws: SourcePolicyFailure.self) { + try await fixture.registry.search("a+b", environment: independent) + } + #expect(await reply.calls.count == 3) + #expect(try fixture.cache.inspect().entries.map(\.store) == [.http, .http]) + } + } + + @Test func staleEntriesRevalidateAndNoStoreOn304EvictsImmediately() async throws { + let fixture = try RegistryAcquisitionFixture() + defer { fixture.remove() } + let reply = RegistryResponses([ + .init(headers: ["cache-control": "max-age=0", "etag": "\"v1\""]), + .init(status: 304, headers: ["cache-control": "max-age=60, no-store", "etag": "\"v1\""]), + ]) + try await RegistryAcquisition.$transport.withValue(reply.transport) { + _ = try await fixture.registry.search(environment: fixture.environment) + #expect(try fixture.cache.inspect().entries.count == 1) + let revalidated = try await fixture.registry.search(environment: fixture.environment) + #expect(revalidated.servers.first?.version == "1.0.0") + #expect(await reply.calls.last?.value(forHTTPHeaderField: "If-None-Match") == "\"v1\"") + #expect(try fixture.cache.inspect().entries.isEmpty) + await #expect(throws: MCPRegistryError.requestFailed) { + try await fixture.registry.search(environment: fixture.environment) + } + #expect(await reply.calls.last?.value(forHTTPHeaderField: "If-None-Match") == nil) + } + } + + @Test(arguments: [ + ["cache-control": "max-age=3600, no-cache", "etag": "\"v1\""], + ["cache-control": "max-age=3600, private"], + ["cache-control": "max-age=3600", "vary": "Accept-Language"], + ["cache-control": "max-age=3600", "vary": "*"], + ["cache-control": "max-age=3600", "set-cookie": "session=fixture"], + ]) + func ineligibleResponsesAlwaysFetchAndFailOffline(headers: [String: String]) async throws { + let fixture = try RegistryAcquisitionFixture() + defer { fixture.remove() } + let reply = RegistryResponses([ + .init(headers: headers, version: "1.0.0"), + .init(headers: headers, version: "2.0.0"), + ]) + try await RegistryAcquisition.$transport.withValue(reply.transport) { + let first = try await fixture.registry.search(environment: fixture.environment) + #expect(first.servers.first?.version == "1.0.0") + let other = try await fixture.registry.search(environment: fixture.environment) + #expect(other.servers.first?.version == "2.0.0") + await #expect(throws: MCPRegistryError.requestFailed) { + try await fixture.registry.search(environment: fixture.environment) + } + #expect(await reply.calls.count == 3) + #expect(try fixture.cache.inspect().entries.isEmpty) + } + } + + @Test func changedVaryForcesAnUnconditionalFetchAndCredentialsCannotReadPublicEntries() + async throws + { + let fixture = try RegistryAcquisitionFixture() + defer { fixture.remove() } + let reply = RegistryResponses([ + .init(headers: ["cache-control": "max-age=0", "etag": "\"v1\""]), + .init(status: 304, headers: ["vary": "Accept-Language"]), + .init(headers: ["cache-control": "max-age=3600"], version: "2.0.0"), + .init(headers: ["cache-control": "max-age=3600"], version: "8.0.0"), + ]) + try await RegistryAcquisition.$transport.withValue(reply.transport) { + _ = try await fixture.registry.search(environment: fixture.environment) + let fresh = try await fixture.registry.search(environment: fixture.environment) + #expect(fresh.servers.first?.version == "2.0.0") + let privateResult = try await fixture.registry.search( + credentials: ["X-Key": "fixture-key"], environment: fixture.environment) + #expect(privateResult.servers.first?.version == "8.0.0") + let warm = try await fixture.registry.search(environment: fixture.environment) + #expect(warm.servers.first?.version == "2.0.0") + let calls = await reply.calls + #expect( + calls.map { $0.value(forHTTPHeaderField: "If-None-Match") } == [ + nil, "\"v1\"", nil, nil, + ]) + #expect(calls.last?.value(forHTTPHeaderField: "X-Key") == "fixture-key") + #expect(try fixture.cache.inspect().entries.count == 1) + } + } + + @Test func validatorsRefreshFreshnessOnceAndStaleErrorsRemainExplicit() async throws { + let fixture = try RegistryAcquisitionFixture() + defer { fixture.remove() } + let reply = RegistryResponses([ + .init(headers: ["cache-control": "max-age=20", "age": "21", "etag": "\"v1\""]), + .init(status: 304, headers: ["cache-control": "max-age=120", "etag": "\"v1\""]), + ]) + try await RegistryAcquisition.$transport.withValue(reply.transport) { + _ = try await fixture.registry.search(environment: fixture.environment) + _ = try await fixture.registry.search(environment: fixture.environment) + _ = try await fixture.registry.search(environment: fixture.environment) + #expect(await reply.calls.count == 2) + await #expect(throws: MCPRegistryError.requestFailed) { + try await fixture.registry.search(environment: fixture.environment, refresh: true) + } + } + let stale = RegistryResponses([ + .init(headers: [ + "cache-control": "max-age=0", "last-modified": "Tue, 24 Nov 2026 08:00:00 GMT", + ]) + ]) + try await RegistryAcquisition.$transport.withValue(stale.transport) { + _ = try await fixture.registry.search("stale", environment: fixture.environment) + await #expect(throws: MCPRegistryError.requestFailed) { + try await fixture.registry.search("stale", environment: fixture.environment) + } + #expect( + await stale.calls.last?.value(forHTTPHeaderField: "If-Modified-Since") + == "Tue, 24 Nov 2026 08:00:00 GMT") + } + } +} + +private struct RegistryAcquisitionFixture { + let root: URL + let registry: MCPRegistry + let environment: RuntimeEnvironment + var cache: AcquisitionCache { AcquisitionCache(environment: environment) } + + init() throws { + root = FileManager.default.temporaryDirectory.appendingPathComponent( + "agents-registry-acquisition-" + UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: false) + registry = try MCPRegistry(endpoint: URL(string: "https://registry.example.invalid")!) + environment = RuntimeEnvironment( + projectDirectory: root.appendingPathComponent("project"), + homeDirectory: root.appendingPathComponent("home"), environment: [:], + acquisitionCacheRoot: root.appendingPathComponent("cache")) + } + + func initializedEnvironment() throws -> RuntimeEnvironment { + for directory in [environment.projectDirectory, environment.homeDirectory] { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false) + } + let launcher = root.appendingPathComponent("bin", isDirectory: true) + try FileManager.default.createDirectory(at: launcher, withIntermediateDirectories: false) + for command in ["npx", "uvx", "docker"] { + let program = launcher.appendingPathComponent(command) + try Data("#!/bin/sh\n/usr/bin/touch '\(root.appendingPathComponent("launched").path)'\n".utf8) + .write(to: program) + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: program.path) + } + var runtime = environment + runtime.environment["PATH"] = launcher.path + ":/usr/bin:/bin" + return runtime + } + + func registryOnlyPolicy() throws -> OrganizationPolicySelection { + let file = root.appendingPathComponent("organization.yaml") + try Data("enforcement: block\nmcp: {self_defined: deny}\n".utf8).write(to: file) + return .init(.local(file)) + } + + func definition(_ json: String, environment: RuntimeEnvironment) async throws -> MCPRegistryServer + { + let transport: @Sendable (URLRequest) async throws -> RegistryHTTP.Response = { request in + .init(url: request.url!, status: 200, headers: [:], body: Data(json.utf8)) + } + return try await RegistryAcquisition.$transport.withValue(transport) { + try await registry.server( + named: "test.example/tool", version: "1.0.0", environment: environment) + } + } + + func remove() { try? FileManager.default.removeItem(at: root) } +} + +private actor RegistryResponses { + struct Reply: Sendable { + var status = 200 + var headers: [String: String] + var version = "1.0.0" + } + + private let responses: [Reply] + private(set) var calls: [URLRequest] = [] + + init(_ responses: [Reply]) { self.responses = responses } + + nonisolated var transport: @Sendable (URLRequest) async throws -> RegistryHTTP.Response { + { try await self.request($0) } + } + + func request(_ request: URLRequest) throws -> RegistryHTTP.Response { + calls.append(request) + guard calls.count <= responses.count else { throw MCPRegistryError.requestFailed } + let reply = responses[calls.count - 1] + let body = """ + {"servers":[{"server":{"name":"test.example/tool","version":"\(reply.version)","description":"fixture"}}]} + """ + return .init( + url: request.url!, status: reply.status, headers: reply.headers, + body: reply.status == 200 ? Data(body.utf8) : Data()) + } +} diff --git a/Tests/AgentsUpdatesTests/RequirementUpdateTests.swift b/Tests/AgentsUpdatesTests/RequirementUpdateTests.swift new file mode 100644 index 0000000..4b22e85 --- /dev/null +++ b/Tests/AgentsUpdatesTests/RequirementUpdateTests.swift @@ -0,0 +1,70 @@ +import AgentsCore +import AgentsInstructions +import AgentsManifest +import AgentsSkills +import Foundation +import StateTestSupport +import Testing + +@testable import AgentsUpdates + +@Suite("Semantic requirement updates") +struct RequirementUpdateTests { + @Test func skillInstructionAndCombinedUpdatesKeepPinsAndOriginalLedgerBytes() throws { + let fixture = try UpdateFixture() + try fixture.git(["tag", "1.2.0"]) + try fixture.declare(agents: [.codex]) + var declaration = try fixture.store.loadDeclaration() + declaration.agents = [.codex] + try declaration.updateInstructions { $0?.agents = nil } + declaration.sources["fixture"]?.requirement = .upToNextMajor(from: "1.2.0") + try fixture.store.save(declaration: declaration, ledger: fixture.store.loadLedger()) + _ = try fixture.apply() + let original = try fixture.store.loadResolved() + var object = try #require( + JSONSerialization.jsonObject(with: fixture.bytes(fixture.store.resolvedURL)) as? [String: Any] + ) + var sourceUses = try #require(object["sourceUses"] as? [[String: Any]]) + let id = try #require(sourceUses.indices.first { sourceUses[$0]["requirement"] != nil }) + sourceUses[id]["requirement"] = ["from": "v1.2.0+lower", "to": "2.0.0+upper"] + object["sourceUses"] = sourceUses + let recordedBytes = try JSONSerialization.data( + withJSONObject: object, options: [.sortedKeys, .withoutEscapingSlashes]) + try recordedBytes.write(to: fixture.store.resolvedURL) + let beforeAttributes = try FileManager.default.attributesOfItem( + atPath: fixture.store.resolvedURL.path) + #expect(try !fixture.preview().hasChanges) + let skills = try SkillOperations.updateInstalled(environment: fixture.environment, apply: true) + #expect(skills.allSatisfy { !$0.changed }) + let instructions = try InstructionOperations.updateInstalled( + environment: fixture.environment, apply: true) + #expect(!instructions.hasChanges) + let combined = try fixture.apply() + #expect(!combined.report.hasChanges) + #expect(try fixture.bytes(fixture.store.resolvedURL) == recordedBytes) + #expect(try fixture.store.loadResolved() == original) + let afterAttributes = try FileManager.default.attributesOfItem( + atPath: fixture.store.resolvedURL.path) + #expect( + beforeAttributes[.systemFileNumber] as? UInt64 == afterAttributes[.systemFileNumber] + as? UInt64) + #expect( + beforeAttributes[.modificationDate] as? Date == afterAttributes[.modificationDate] as? Date) + let intentOnly = try InstructionOperations.updateInstalled( + agents: [.codex], environment: fixture.environment, apply: true) + #expect(intentOnly.hasChanges) + #expect(try fixture.store.loadDeclaration().instructions?.agents == [.codex]) + #expect(try fixture.bytes(fixture.store.resolvedURL) == recordedBytes) + try fixture.advance() + try fixture.git(["tag", "1.3.0"]) + _ = try fixture.apply() + let changed = try fixture.bytes(fixture.store.resolvedURL) + #expect(changed != recordedBytes) + let rewritten = try #require(JSONSerialization.jsonObject(with: changed) as? [String: Any]) + let rewrittenSources = try #require(rewritten["sourceUses"] as? [[String: Any]]) + #expect(rewrittenSources[id]["requirement"] as? [String: String] == ["from": "1.2.0"]) + #expect( + try fixture.store.loadResolved().skills["demo"]?.revision + == fixture.git(["rev-parse", "HEAD"])) + } +} diff --git a/Tests/AgentsUpdatesTests/SkillPathReadLocationsTests.swift b/Tests/AgentsUpdatesTests/SkillPathReadLocationsTests.swift new file mode 100644 index 0000000..aba8a2a --- /dev/null +++ b/Tests/AgentsUpdatesTests/SkillPathReadLocationsTests.swift @@ -0,0 +1,25 @@ +import AgentsCore +import Foundation +import Testing + +@testable import AgentsUpdates + +struct SkillPathReadLocationsTests { + @Test func ownSkillPathsKeepNarrowRootAndUnusedGroupDiscovery() throws { + let f = try UpdateFixture() + let declaration = Declaration( + components: [.skills(source: ".", .init(select: .all, path: "selected/one"))], + groups: [ + .init( + name: "unused", + components: [ + .skills(source: ".", .init(select: .names([]), path: "selected/two")) + ]) + ]) + let paths = try UpdateOperations.readLocations( + declarations: [declaration], ledgers: [], store: f.store) + #expect(paths.contains(f.root.appendingPathComponent("selected/one"))) + #expect(paths.contains(f.root.appendingPathComponent("selected/two"))) + #expect(!paths.contains(f.root)) + } +} diff --git a/Tests/AgentsUpdatesTests/SourceAccessTests.swift b/Tests/AgentsUpdatesTests/SourceAccessTests.swift new file mode 100644 index 0000000..3bc585e --- /dev/null +++ b/Tests/AgentsUpdatesTests/SourceAccessTests.swift @@ -0,0 +1,852 @@ +import AgentsManifest +import AgentsUpdates +import Foundation +import StateTestSupport +import Synchronization +import Testing + +@testable import AgentsCore + +#if canImport(FoundationNetworking) + import FoundationNetworking +#endif +#if canImport(Darwin) + import Darwin +#else + import Glibc +#endif + +@Suite("Trusted package source access", .serialized) +struct SourceAccessTests { + @Test func credentialParityAndExportBoundary() throws { + let fixture = try ArchiveSourceFixture() + defer { fixture.remove() } + let endpoint = URL(string: "https://enterprise.invalid:8443/api/v3/user")! + let direct = try SourceAuthority(host: "enterprise.invalid", port: 8443) + let upstream = try SourceAuthority(host: "other.invalid", port: 8443) + let mirror = try SourceAuthority(host: "mirror.invalid", port: 9443) + let selected = Mutex([String]()) + let first = try SourceCredentialBinding( + route: .direct, authority: direct, path: "/org/first.git", exportable: true, + validationEndpoint: endpoint + ) { + selected.withLock { $0.append("first") } + return "fixture-first-secret" + } + let second = try SourceCredentialBinding( + route: .direct, authority: direct, path: "/org/second", validationEndpoint: endpoint + ) { + selected.withLock { $0.append("second") } + return "fixture-second-secret" + } + let proxied = try SourceCredentialBinding( + route: .mirror, authority: mirror, path: "/proxy/org/third" + ) { + selected.withLock { $0.append("third") } + return "fixture-mirror-secret" + } + var environment = fixture.environment + environment.sourceAccess = .init( + providers: [direct: .github, upstream: .github], + mirrors: [ + try .init( + source: upstream, base: URL(string: "https://mirror.invalid:9443/proxy")!, + flavor: .github) + ], + credentials: [first, second, proxied]) + let declaration = Declaration( + sources: ["first": .init(kind: .git, location: "https://enterprise.invalid:8443/org/first")]) + let policy = EffectiveSourcePolicy() + let firstStatus = try SourceCredentialOperations.inspect( + source: "first", declaration: declaration, environment: environment, policy: policy) + #expect(firstStatus.provider == .github) + #expect(firstStatus.effectiveHost == "enterprise.invalid:8443") + #expect(firstStatus.availability == .available) + #expect( + try SourceCredentialOperations.inspect(host: direct, environment: environment) + .availability == .unconfigured) + #expect(selected.withLock { $0 }.isEmpty) + + let requests = Mutex([String]()) + try PackageSourceHTTP.$fixture.withValue( + { request, maximum in + #expect(request.url == endpoint) + #expect(maximum == nil) + let header = request.value(forHTTPHeaderField: "Authorization") ?? "" + requests.withLock { $0.append(header) } + return .init( + status: header == "Bearer fixture-first-secret" ? 200 : 401, + body: Data("fixture-private-provider-response".utf8)) + }, + operation: { + let accepted = try SourceCredentialOperations.validate( + source: "first", declaration: declaration, environment: environment, policy: policy) + let refused = try SourceCredentialOperations.validate( + source: "https://enterprise.invalid:8443/org/second@tag:release/v1", + declaration: declaration, environment: environment, policy: policy) + let indeterminate = try SourceCredentialOperations.validate( + source: "https://other.invalid:8443/org/third", declaration: declaration, + environment: environment, policy: policy) + #expect(accepted.validation == .accepted) + #expect(refused.validation == .refused) + #expect(indeterminate.validation == .indeterminate) + #expect(indeterminate.transport == .archive) + #expect(indeterminate.effectiveHost == "mirror.invalid:9443") + let reportBytes = try JSONEncoder().encode([accepted, refused, indeterminate]) + #expect(!String(decoding: reportBytes, as: UTF8.self).contains("fixture-")) + }) + #expect( + requests.withLock { $0 } == ["Bearer fixture-first-secret", "Bearer fixture-second-secret"]) + #expect(selected.withLock { $0 } == ["first", "second"]) + + let pipe = Pipe() + defer { + pipe.fileHandleForWriting.closeFile() + pipe.fileHandleForReading.closeFile() + } + let file = fixture.root.appendingPathComponent("export-denied") + try Data().write(to: file) + let handle = try FileHandle(forWritingTo: file) + defer { handle.closeFile() } + #expect(throws: SourceAccessError.exportRefused) { + try SourceCredentialOperations.export( + source: "first", declaration: declaration, environment: environment, policy: policy, + to: handle.fileDescriptor) + } + #expect(try Data(contentsOf: file).isEmpty) + #if canImport(Darwin) + var master: Int32 = -1 + var terminal: Int32 = -1 + try #require(openpty(&master, &terminal, nil, nil, nil) == 0) + defer { + close(master) + close(terminal) + } + #expect(throws: SourceAccessError.exportRefused) { + try SourceCredentialOperations.export( + source: "first", declaration: declaration, environment: environment, policy: policy, + to: terminal) + } + #endif + var ambiguous = environment + ambiguous.sourceAccess = .init(providers: [direct: .github], credentials: [first, first]) + #expect(throws: SourceAccessError.ambiguousCredential) { + try SourceCredentialOperations.export( + source: "first", declaration: declaration, environment: ambiguous, policy: policy, + to: pipe.fileHandleForWriting.fileDescriptor) + } + #expect(selected.withLock { $0 } == ["first", "second"]) + try SourceCredentialOperations.export( + source: "first", declaration: declaration, environment: environment, policy: policy, + to: pipe.fileHandleForWriting.fileDescriptor) + pipe.fileHandleForWriting.closeFile() + let exported = try pipe.fileHandleForReading.readToEnd() + #expect(exported == Data("fixture-first-secret".utf8)) + } + + @Test func routeMatrixAndPreNetworkAdmission() throws { + let fixture = try ArchiveSourceFixture() + defer { fixture.remove() } + let repository = try SourceRepository(fixture.source.location) + let github = try ArchiveSourceFixture.profile(.github) + let tag = try VCSArchiveRequest(repository: repository, ref: .tag("release/v1"), mirror: github) + let branch = try VCSArchiveRequest( + repository: repository, ref: .branch("release/v1"), mirror: github) + #expect( + tag.url.absoluteString + == "https://mirror.invalid:9443/base/org/repo/archive/refs/tags/release/v1.zip") + #expect( + branch.url.absoluteString + == "https://mirror.invalid:9443/base/org/repo/archive/refs/heads/release/v1.zip") + let gitlab = try ArchiveSourceFixture.profile(.gitlab, qualified: true) + let nested = try SourceRepository("https://origin.invalid:8443/group/sub/repo.git") + let qualified = try VCSArchiveRequest( + repository: nested, ref: .tag("release/v1"), mirror: gitlab) + #expect( + qualified.url.absoluteString + == "https://mirror.invalid:9443/base/api/v4/projects/group%2Fsub%2Frepo/repository/archive.zip?sha=refs%2Ftags%2Frelease%2Fv1" + ) + let sha = String(repeating: "a", count: 40) + let bare = try ArchiveSourceFixture.profile(.gitlab) + let exact = try VCSArchiveRequest(repository: nested, ref: .commit(sha), mirror: bare) + #expect(exact.url.absoluteString.hasSuffix("archive.zip?sha=" + sha)) + #expect(throws: SourceAccessError.discoveryUnavailable) { + _ = try VCSArchiveRequest(repository: nested, ref: .branch("release/v1"), mirror: bare) + } + #expect(throws: SourceAccessError.invalidRepository) { + _ = try VCSArchiveRequest(repository: repository, ref: .tag("../escape"), mirror: github) + } + + try PackageSourceHTTP.$fixture.withValue( + { _, _ in + Issue.record("denied route ran a request") + throw SourceAccessError.requestFailed + }, + operation: { + let store = StateStore(scope: .project, environment: fixture.environment) + try SourceResolutionSession.withTemporaryRead(store: store) { session in + #expect(throws: SourceAccessError.discoveryUnavailable) { + _ = try session.candidates(for: fixture.source, requirements: [.exact("1.2.3")]) + } + var ambiguous = fixture.source + ambiguous.requirement = .exact("1.2.3") + #expect(throws: SourceAccessError.discoveryUnavailable) { + _ = try SourceCache(store: store).inspectRevision(ambiguous) + } + #expect(throws: SourceAccessError.egressDenied) { + _ = try session.requireSource( + .init(kind: .wellKnown, location: "https://mirror.invalid:9443/index")) + } + } + var unsupported = fixture.environment + unsupported.sourceAccess = .init( + egress: .proxyOnly, mirrors: [try ArchiveSourceFixture.profile(.artifactory)]) + _ = try SourceResolutionSession.withTemporaryRead( + store: StateStore(scope: .project, environment: unsupported) + ) { session in + #expect(throws: SourceAccessError.unsupportedMirror) { + _ = try session.candidates( + for: fixture.source, requirements: [fixture.source.requirement]) + } + } + }) + } + + @Test func redirectAndDeniedEffectiveOriginDoNotRetry() throws { + let fixture = try ArchiveSourceFixture() + defer { fixture.remove() } + let requests = Mutex(0) + let mirror = try SourceAuthority(host: "mirror.invalid", port: 9443) + var environment = fixture.environment + environment.sourceAccess = .init( + egress: .proxyOnly, mirrors: [try ArchiveSourceFixture.profile(.github)], + credentials: [ + try .init(route: .mirror, authority: mirror) { + "fixture-mirror-route-secret" + } + ]) + try PackageSourceHTTP.$fixture.withValue( + { request, _ in + #expect( + request.value(forHTTPHeaderField: "Authorization") == "Bearer fixture-mirror-route-secret" + ) + requests.withLock { $0 += 1 } + return .init(status: 302, body: Data()) + }, + operation: { + let store = StateStore(scope: .project, environment: environment) + let layer = SourcePolicyLayer( + scope: .project, url: fixture.root.appendingPathComponent("source-policy.json"), + rules: .init(allow: [try .git(fixture.source.location)])) + _ = try SourceResolutionSession.withTemporaryRead( + store: store, sourcePolicy: .init(layers: [layer]) + ) { session in + #expect(throws: SourcePolicyFailure.self) { + _ = try session.candidates( + for: fixture.source, requirements: [fixture.source.requirement]) + } + } + #expect(requests.withLock { $0 } == 0) + _ = try SourceResolutionSession.withTemporaryRead(store: store) { session in + #expect(throws: SourceAccessError.requestFailed) { + _ = try session.candidates( + for: fixture.source, requirements: [fixture.source.requirement]) + } + } + #expect(requests.withLock { $0 } == 1) + }) + } + + @Test func lockedRangeUsesItsExactTagEvidence() throws { + let fixture = try ArchiveSourceFixture() + defer { fixture.remove() } + let bytes = fixture.zip() + let calls = Mutex(0) + try PackageSourceHTTP.$fixture.withValue( + { request, _ in + #expect(request.url?.path.hasSuffix("refs/tags/v1.2.3.zip") == true) + calls.withLock { $0 += 1 } + return .init(status: 200, body: bytes) + }, + operation: { + try SourceResolutionSession.withTemporaryRead(store: fixture.store) { session in + let pin = try #require( + session.candidates( + for: fixture.source, requirements: [.revision("refs/tags/v1.2.3")] + ).first) + #expect(pin.version == "1.2.3") + let archive = try #require(pin.archive) + #expect(archive.admits(.upToNextMajor(from: "1.1.0"), version: pin.version)) + #expect(!archive.admits(.upToNextMajor(from: "2.0.0"), version: pin.version)) + let view = try session.snapshot(fixture.source, at: pin, offline: true) + #expect(try Data(contentsOf: view.resource("skills/demo/SKILL.md")) == fixture.skillBytes) + } + }) + #expect(calls.withLock { $0 } == 1) + } + + @Test(arguments: [InstallMode.link, .copy]) + func privateDeploymentAndOfflineRecovery(_ mode: InstallMode) throws { + let fixture = try ArchiveSourceFixture() + defer { fixture.remove() } + let requests = Mutex(0) + let bytes = fixture.zip() + try PackageSourceHTTP.$fixture.withValue( + { request, _ in + #expect(request.url?.path == "/base/org/repo/archive/refs/tags/release/v1.zip") + requests.withLock { $0 += 1 } + return .init(status: 200, body: bytes) + }, + operation: { + try fixture.install(mode) + }) + #expect(requests.withLock { $0 } == 1) + let ledger = try fixture.store.loadLedger() + let archive = try #require(ledger.sources.values.first(where: { $0.archive != nil })?.archive) + #expect(archive.observedArchiveDigest == "sha256:" + FileHash.sha256Hex(data: bytes)) + #expect(archive.requiredArchiveDigest == nil) + #expect(ledger.resources.values.contains { $0.kind == .archive }) + #expect(ledger.contentObjects.isEmpty) + let lockBytes = try Data(contentsOf: fixture.store.resolvedURL) + #expect(!String(decoding: lockBytes, as: UTF8.self).contains("fixture-private")) + #expect(try Data(contentsOf: fixture.skill) == fixture.skillBytes) + let deployed = fixture.skill.deletingLastPathComponent().resolvingSymlinksInPath() + let script = deployed.appendingPathComponent("run.sh") + #expect(try fixture.mode(deployed) == 0o700) + #expect(try fixture.mode(deployed.appendingPathComponent("SKILL.md")) == 0o600) + #expect(try fixture.mode(script) == 0o700) + let retained = try fixture.recoveryEntry(archive) + #expect(try fixture.mode(retained.deletingLastPathComponent()) == 0o700) + #expect(try fixture.mode(retained.appendingPathComponent("archive")) == 0o600) + #expect(try AcquisitionCache(environment: fixture.environment).inspect().entries.isEmpty) + + let damage = mode == .link ? retained.appendingPathComponent("tree") : deployed + try FileManager.default.removeItem(at: damage) + try PackageSourceHTTP.$fixture.withValue( + { _, _ in + Issue.record("offline replay ran an HTTP request") + throw SourceAccessError.requestFailed + }, + operation: { + _ = try UpdateOperations.restore(environment: fixture.environment, offline: true) + #expect(try Data(contentsOf: fixture.skill) == fixture.skillBytes) + #expect(try Data(contentsOf: fixture.store.resolvedURL) == lockBytes) + let outsider = try fixture.copyLock() + #expect(throws: SourceAccessError.recoveryUnavailable) { + _ = try UpdateOperations.restore(environment: outsider, offline: true) + } + }) + } + + @Test func recompressionAndStrictArchivePin() throws { + for strict in [false, true] { + let fixture = try ArchiveSourceFixture(strict: strict) + defer { fixture.remove() } + let original = fixture.zip() + let recompressed = fixture.zip(deflate: true, enclosing: "mirror-renamed") + #expect(original != recompressed) + #expect( + try VerifiedVCSArchive(original).treeDigest == VerifiedVCSArchive(recompressed).treeDigest) + #expect( + try VerifiedVCSArchive(original).treeDigest + != VerifiedVCSArchive(fixture.zip(executable: false)).treeDigest) + try PackageSourceHTTP.$fixture.withValue( + { _, _ in .init(status: 200, body: original) }, + operation: { + try fixture.install(.link) + }) + let archive = try #require( + fixture.store.loadLedger().sources.values.compactMap(\.archive).first) + let representation = try fixture.recoveryEntry(archive).appendingPathComponent("archive") + let sealed = try Data(contentsOf: representation) + try FileManager.default.removeItem(at: representation) + try PackageSourceHTTP.$fixture.withValue( + { _, _ in .init(status: 200, body: recompressed) }, + operation: { + if strict { + #expect(throws: SourceAccessError.archiveChanged) { + _ = try UpdateOperations.restore(environment: fixture.environment) + } + #expect(try Data(contentsOf: fixture.skill) == fixture.skillBytes) + try sealed.write(to: representation) + try FileManager.default.setAttributes( + [.posixPermissions: 0o600], ofItemAtPath: representation.path) + } else { + let deploy = fixture.skill.deletingLastPathComponent() + try FileManager.default.removeItem(at: deploy) + _ = try UpdateOperations.restore(environment: fixture.environment) + #expect(try Data(contentsOf: representation) != sealed) + let report = try UpdateOperations.preview( + .init(operation: .update), environment: fixture.environment) + #expect(report.archiveRepresentationChanges?.count == 1) + } + }) + _ = try UpdateOperations.restore(environment: fixture.environment, offline: true) + let stored = try Data(contentsOf: representation) + try (stored + Data([0])).write(to: representation) + #expect(throws: SourceAccessError.invalidArchive) { + _ = try UpdateOperations.restore(environment: fixture.environment, offline: true) + } + } + } + + @Test func renderedAggregateUsesAnOwnerOnlyDestination() throws { + let fixture = try ArchiveSourceFixture() + defer { fixture.remove() } + let text = """ + --- + description: private instruction fixture + --- + # Guidance + fixture-private-guidance + """ + let archive = ArchiveSourceFixture.zip( + [("producer/instructions/guidance.md", Data(text.utf8), 0o100644)], deflate: false) + let declaration = Declaration( + agents: [.codex], sources: ["fixture": fixture.source], + instructions: .init(agents: [.codex], sections: ["fixture:guidance"])) + try PackageSourceHTTP.$fixture.withValue( + { _, _ in .init(status: 200, body: archive) }, + operation: { + try UpdateOperations.withPreparedUpdate( + .init(operation: .declaration(declaration)), environment: fixture.environment + ) { _ = try $0.apply() } + }) + let destination = fixture.environment.projectDirectory.appendingPathComponent("AGENTS.md") + #expect(try fixture.mode(destination) == 0o600) + let contents = try String(contentsOf: destination, encoding: .utf8) + #expect(contents.contains("fixture-private-guidance")) + let lock = try String(contentsOf: fixture.store.resolvedURL, encoding: .utf8) + #expect(!lock.contains("fixture-private-guidance")) + } + + @Test func privateArchiveSurvivesUntilItsLastCommittedScopeReleasesIt() throws { + let fixture = try ArchiveSourceFixture() + defer { fixture.remove() } + let bytes = fixture.zip() + try PackageSourceHTTP.$fixture.withValue( + { _, _ in .init(status: 200, body: bytes) }, + operation: { + try fixture.install(.link) + }) + let ledger = try fixture.store.loadLedger() + let archive = try #require(ledger.sources.values.compactMap(\.archive).first) + let entry = try fixture.recoveryEntry(archive) + let other = try fixture.copyLock(sameHome: true) + _ = try UpdateOperations.restore(environment: other, offline: true) + let remove = UpdateRequest(operation: .declaration(Declaration())) + try UpdateOperations.withPreparedUpdate(remove, environment: fixture.environment) { + _ = try $0.apply() + } + #expect(FileManager.default.fileExists(atPath: entry.path)) + let otherSkill = other.projectDirectory.appendingPathComponent(".agents/skills/demo/SKILL.md") + #expect(try Data(contentsOf: otherSkill) == fixture.skillBytes) + try UpdateOperations.withPreparedUpdate(remove, environment: other) { _ = try $0.apply() } + #expect(!FileManager.default.fileExists(atPath: entry.path)) + } + + @Test(arguments: ["archive.recovery.reserved", TransactionCheckpoint.phase(.committed).name]) + func interruptedRetentionKeepsOnlyVisibleGenerations(_ checkpoint: String) throws { + let fixture = try ArchiveSourceFixture() + defer { fixture.remove() } + let bytes = fixture.zip() + let child = try fixture.launch(checkpoint: checkpoint, archive: bytes) + defer { try? ProcessWait.terminate(child) } + try ProcessWait.marker( + fixture.root.appendingPathComponent("ready"), child: child, root: fixture.root) + try ProcessWait.stopped(child, root: fixture.root) + try ProcessWait.terminate(child) + + if checkpoint == "archive.recovery.reserved" { + #expect(!FileManager.default.fileExists(atPath: fixture.store.resolvedURL.path)) + #expect(!FileManager.default.fileExists(atPath: fixture.skill.path)) + try PackageSourceHTTP.$fixture.withValue( + { _, _ in .init(status: 200, body: bytes) }, + operation: { + try fixture.install(.link) + }) + } else { + #expect(FileManager.default.fileExists(atPath: fixture.store.resolvedURL.path)) + #expect(try Data(contentsOf: fixture.skill) == fixture.skillBytes) + do { + _ = try UpdateOperations.restore(environment: fixture.environment, offline: true) + Issue.record("the committed journal was not recovered") + } catch let error as CoreError { + guard case .transactionRecovered = error else { throw error } + } + } + let cache = AcquisitionCache(environment: fixture.environment) + #expect(try cache.apply(cache.preview(.clean)).isComplete) + try FileManager.default.removeItem(at: fixture.skill.deletingLastPathComponent()) + try PackageSourceHTTP.$fixture.withValue( + { _, _ in + Issue.record("offline crash recovery made a request") + throw SourceAccessError.requestFailed + }, + operation: { + _ = try UpdateOperations.restore(environment: fixture.environment, offline: true) + }) + #expect(try Data(contentsOf: fixture.skill) == fixture.skillBytes) + } + + @Test func changedParentPermissionsInvalidatePreparedPublication() throws { + let fixture = try ArchiveSourceFixture() + defer { fixture.remove() } + let destinationParent = fixture.skill.deletingLastPathComponent().deletingLastPathComponent() + try FileManager.default.createDirectory( + at: destinationParent, withIntermediateDirectories: true) + let bytes = fixture.zip() + PackageSourceHTTP.$fixture.withValue( + { _, _ in .init(status: 200, body: bytes) }, + operation: { + #expect(throws: UpdateApplyError.self) { + try UpdateOperations.withPreparedUpdate( + fixture.request(.copy), environment: fixture.environment + ) { prepared in + #expect(prepared.report.hasChanges) + try FileManager.default.setAttributes( + [.posixPermissions: 0o777], ofItemAtPath: destinationParent.path) + _ = try prepared.apply() + } + } + }) + #expect(!FileManager.default.fileExists(atPath: fixture.skill.path)) + #expect(!FileManager.default.fileExists(atPath: fixture.store.resolvedURL.path)) + } +} + +private struct ArchiveSourceFixture: Sendable { + let root: URL + let environment: RuntimeEnvironment + let source = SourceDeclaration( + kind: .git, location: "https://origin.invalid:8443/org/repo.git", + requirement: .revision("refs/tags/release/v1")) + let skillBytes = Data( + "---\nname: demo\ndescription: fixture-private-description\n---\n# Demo\nfixture-private-source\n" + .utf8) + + init(strict: Bool = false) throws { + root = try SourceCache.privateWorkspace(prefix: "agents-source-access-test-") + let project = root.appendingPathComponent("project") + let home = root.appendingPathComponent("home") + do { + for directory in [project, home] { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false) + } + environment = RuntimeEnvironment( + projectDirectory: project, homeDirectory: home, environment: [:], + acquisitionCacheRoot: root.appendingPathComponent("disposable"), + sourceAccess: .init( + egress: .proxyOnly, mirrors: [try Self.profile(.github, strict: strict)])) + } catch { + try? FileManager.default.removeItem(at: root) + throw error + } + } + + static func profile( + _ flavor: SourceArchiveMirror.Flavor, qualified: Bool = false, strict: Bool = false + ) throws -> SourceArchiveMirror { + try .init( + source: SourceAuthority(host: "origin.invalid", port: 8443), + base: URL(string: "https://mirror.invalid:9443/base/")!, flavor: flavor, + supportsQualifiedGitLabRefs: qualified, requiresExactArchiveBytes: strict) + } + + var store: StateStore { .init(scope: .project, environment: environment) } + var skill: URL { + environment.projectDirectory.appendingPathComponent(".agents/skills/demo/SKILL.md") + } + + func request(_ mode: InstallMode) -> UpdateRequest { + .init( + operation: .declaration( + Declaration( + agents: [.codex], sources: ["fixture": source], + skills: ["fixture": .init(select: .names(["demo"]), mode: mode)]))) + } + + func install(_ mode: InstallMode) throws { + try UpdateOperations.withPreparedUpdate(request(mode), environment: environment) { + _ = try $0.apply() + } + } + + func recoveryEntry(_ evidence: SourceArchiveEvidence) throws -> URL { + let tree = SourceCache(store: store).archiveTree(transport: source.location, evidence: evidence) + return tree.deletingLastPathComponent() + } + + func mode(_ url: URL) throws -> Int { + let attributes = try FileManager.default.attributesOfItem(atPath: url.path) + return try #require((attributes[.posixPermissions] as? NSNumber)?.intValue) + } + + func copyLock(sameHome: Bool = false) throws -> RuntimeEnvironment { + var other = environment + if !sameHome { other.homeDirectory = root.appendingPathComponent("other-home") } + other.projectDirectory = root.appendingPathComponent("other-project") + if !sameHome { + try FileManager.default.createDirectory( + at: other.homeDirectory, withIntermediateDirectories: false) + } + let target = StateStore(scope: .project, environment: other) + try FileManager.default.createDirectory(at: target.directory, withIntermediateDirectories: true) + try FileManager.default.copyItem(at: store.declarationURL, to: target.declarationURL) + try FileManager.default.copyItem(at: store.resolvedURL, to: target.resolvedURL) + return other + } + + func launch(checkpoint: String, archive: Data) throws -> Process { + var directory = Bundle(for: SourceArchiveTestBundle.self).bundleURL + while !FileManager.default.isExecutableFile( + atPath: directory.appendingPathComponent("StateTestProcess").path), directory.path != "/" + { + directory.deleteLastPathComponent() + } + let scratch = root.appendingPathComponent("child-temporary") + try FileManager.default.createDirectory(at: scratch, withIntermediateDirectories: false) + let input = root.appendingPathComponent("response.zip") + try archive.write(to: input) + let process = Process() + process.executableURL = directory.appendingPathComponent("StateTestProcess") + process.arguments = [root.path, "source-archive", checkpoint, input.path] + process.environment = [ + "HOME": environment.homeDirectory.path, "TMPDIR": scratch.path, + "PATH": "/usr/bin:/bin", "GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": "/dev/null", + "GIT_ALLOW_PROTOCOL": "file", + ] + try process.run() + return process + } + + func remove() { try? FileManager.default.removeItem(at: root) } + + func zip(deflate: Bool = false, enclosing: String = "producer", executable: Bool = true) -> Data { + Self.zip( + [ + (enclosing + "/skills/demo/SKILL.md", skillBytes, 0o100644), + ( + enclosing + "/skills/demo/run.sh", Data("#!/bin/sh\n".utf8), + executable ? 0o100755 : 0o100644 + ), + ], + deflate: deflate) + } + + fileprivate static func zip( + _ members: [(String, Data, UInt32)], deflate: Bool + ) -> Data { + func pair(_ value: Int) -> Data { + Data([UInt8(truncatingIfNeeded: value), UInt8(truncatingIfNeeded: value >> 8)]) + } + func word(_ value: Int) -> Data { pair(value) + pair(value >> 16) } + func crc(_ content: Data) -> Int { + let register = content.reduce(UInt32.max) { crc, byte in + (0..<8).reduce(crc ^ UInt32(byte)) { state, _ in + (state >> 1) ^ ((state & 1) == 1 ? 0xEDB8_8320 : 0) + } + } + return Int(~register) + } + var result = Data() + var directory = Data() + for (path, contents, mode) in members { + let compressed = + deflate + ? Data([1]) + pair(contents.count) + pair(~contents.count) + contents : contents + let method = deflate ? 8 : 0 + let name = Data(path.utf8) + let fields = + pair(0x800) + pair(method) + word(0) + word(crc(contents)) + + word(compressed.count) + word(contents.count) + pair(name.count) + pair(0) + directory += word(0x0201_4b50) + pair(0x0314) + pair(20) + fields + directory += word(0) + pair(0) + word(Int(mode) << 16) + word(result.count) + name + result += word(0x0403_4b50) + pair(20) + fields + name + compressed + } + let end = + word(0x0605_4b50) + word(0) + pair(members.count) + pair(members.count) + + word(directory.count) + word(result.count) + pair(0) + return result + directory + end + } +} + +private final class SourceArchiveTestBundle: NSObject {} + +extension SourceAccessTests { + @Test func userSettingsDriveDefaultDiagnosisAndInstallation() throws { + let fixture = try ArchiveSourceFixture() + defer { fixture.remove() } + let project = fixture.environment.projectDirectory + let home = fixture.environment.homeDirectory + let variables = [ + "HOME": home.path, "PACKAGE_ARCHIVE_FIXTURE": "synthetic-profile-value", + "UNSCOPED_FIXTURE": "never-selected-value", + ] + let absent = RuntimeEnvironment(projectDirectory: project, environment: variables) + let editor = try SourceAccessSettingsEditor(environment: absent) + let profile = Data( + """ + version: 1 + egress: proxyOnly + providers: + - host: origin.invalid + port: 8443 + provider: github + mirrors: + - source: {host: origin.invalid, port: 8443} + base: https://mirror.invalid:9443/base + flavor: github + credentials: + - route: mirror + host: mirror.invalid + port: 9443 + path: /base/org/repo + environmentVariable: PACKAGE_ARCHIVE_FIXTURE + """.utf8) + let projectSettings = project.appendingPathComponent(".agent/source-access.yaml") + try FileManager.default.createDirectory( + at: projectSettings.deletingLastPathComponent(), withIntermediateDirectories: true) + try profile.write(to: projectSettings) + #expect(try absent.resolvedSourceAccess().egress == .directAllowed) + #expect(!FileManager.default.fileExists(atPath: editor.url.path)) + + try editor.save(editor.preview(profile)) + #expect(throws: SourceAccessSettingsError.changed(editor.url)) { + try absent.resolvedSourceAccess() + } + let runtime = RuntimeEnvironment(projectDirectory: project, environment: variables) + let policy = EffectiveSourcePolicy() + func inspect(_ selector: String, environment: RuntimeEnvironment = runtime) throws + -> SourceCredentialReport + { + try SourceCredentialOperations.inspect( + source: selector, declaration: Declaration(), environment: environment, policy: policy) + } + + let bytes = fixture.zip() + let requests = Mutex(0) + try PackageSourceHTTP.$fixture.withValue( + { request, _ in + requests.withLock { $0 += 1 } + #expect( + request.url?.absoluteString + == "https://mirror.invalid:9443/base/org/repo/archive/refs/tags/release/v1.zip") + #expect( + request.value(forHTTPHeaderField: "Authorization") == "Bearer synthetic-profile-value") + return .init(status: 200, body: bytes) + }, + operation: { + let status = try inspect("https://origin.invalid:8443/org/repo@tag:release/v1") + #expect(status.provider == .github) + #expect(status.transport == .archive) + #expect(status.effectiveHost == "mirror.invalid:9443") + #expect(status.credentialSource == .environment) + #expect(status.availability == .available) + #expect( + try inspect("https://origin.invalid:8443/org/another").availability == .unconfigured) + #expect(throws: SourceAccessError.egressDenied) { + try inspect("https://origin.invalid:443/org/repo.git") + } + let missing = RuntimeEnvironment( + projectDirectory: project, environment: ["HOME": home.path, "UNSCOPED_FIXTURE": "value"]) + #expect( + try inspect("https://origin.invalid:8443/org/repo", environment: missing) + .availability == .unavailable) + let serialized = try JSONEncoder().encode(status) + for secret in ["synthetic-profile-value", "never-selected-value"] { + #expect(!String(decoding: serialized, as: UTF8.self).contains(secret)) + #expect( + !String(decoding: try Data(contentsOf: editor.url), as: UTF8.self).contains(secret)) + } + #expect(requests.withLock { $0 } == 0) + try UpdateOperations.withPreparedUpdate(fixture.request(.copy), environment: runtime) { + _ = try $0.apply() + } + }) + #expect(requests.withLock { $0 } > 0) + #expect(try Data(contentsOf: fixture.skill) == fixture.skillBytes) + } + + @Test func malformedSettingsBlockDiagnosisAndCanBeRepairedAndReloaded() throws { + let fixture = try ArchiveSourceFixture() + defer { fixture.remove() } + let home = fixture.environment.homeDirectory + let root = fixture.environment.projectDirectory + var runtime = RuntimeEnvironment(projectDirectory: root, environment: ["HOME": home.path]) + let url = SourceAccessSettingsEditor.settingsURL(environment: runtime) + try FileManager.default.createDirectory( + at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data("version: 1\negress: SENSITIVE_INVALID_FIELD_VALUE\n".utf8).write(to: url) + runtime.reloadSourceAccessSettings() + let syntax = SourceAccessSettingsError.invalidFile(url, reason: "Missing or invalid egress.") + let authority = try SourceAuthority(host: "github.com") + #expect(throws: syntax) { + try SourceCredentialOperations.inspect(host: authority, environment: runtime) + } + #expect(throws: syntax) { + try UpdateOperations.preview(fixture.request(.copy), environment: runtime) + } + #expect(!syntax.localizedDescription.contains("SENSITIVE_INVALID_FIELD_VALUE")) + #expect(!FileManager.default.fileExists(atPath: fixture.store.resolvedURL.path)) + + let repair = try SourceAccessSettingsEditor(environment: runtime) + try repair.save(repair.preview(Data("version: 1\negress: proxyOnly\n".utf8))) + runtime.reloadSourceAccessSettings() + #expect(try runtime.resolvedSourceAccess().egress == .proxyOnly) + #expect(throws: SourceAccessError.egressDenied) { + try SourceCredentialOperations.inspect( + source: "org/repo", declaration: Declaration(), environment: runtime, policy: .init()) + } + let reset = try SourceAccessSettingsEditor(environment: runtime) + try reset.save(reset.preview(nil)) + #expect(throws: SourceAccessSettingsError.changed(url)) { try runtime.resolvedSourceAccess() } + runtime.reloadSourceAccessSettings() + #expect(try runtime.resolvedSourceAccess().egress == .directAllowed) + let report = try SourceCredentialOperations.inspect( + source: "org/repo", declaration: Declaration(), environment: runtime, policy: .init()) + #expect(report.transport == .https && report.availability == .unconfigured) + } + + @Test func profileReplacementInvalidatesPreparedInstall() throws { + let fixture = try ArchiveSourceFixture() + defer { fixture.remove() } + let runtime = RuntimeEnvironment( + projectDirectory: fixture.environment.projectDirectory, + environment: ["HOME": fixture.environment.homeDirectory.path]) + let editor = try SourceAccessSettingsEditor(environment: runtime) + try editor.save( + editor.preview( + Data( + """ + version: 1 + egress: proxyOnly + mirrors: + - source: {host: origin.invalid, port: 8443} + base: https://mirror.invalid:9443/base + flavor: github + """.utf8))) + var reloaded = runtime + reloaded.reloadSourceAccessSettings() + let bytes = fixture.zip() + let requests = Mutex(0) + try PackageSourceHTTP.$fixture.withValue( + { _, _ in + requests.withLock { $0 += 1 } + return .init(status: 200, body: bytes) + }, + operation: { + try UpdateOperations.withPreparedUpdate(fixture.request(.copy), environment: reloaded) { + prepared in + #expect(prepared.report.hasChanges) + let reset = try SourceAccessSettingsEditor(environment: reloaded) + try reset.save(reset.preview(nil)) + let count = requests.withLock { $0 } + #expect(throws: UpdateApplyError.self) { try prepared.apply() } + #expect(requests.withLock { $0 } == count) + } + }) + #expect(!FileManager.default.fileExists(atPath: fixture.store.resolvedURL.path)) + #expect(!FileManager.default.fileExists(atPath: fixture.skill.path)) + } +} diff --git a/Tests/AgentsUpdatesTests/SourceCatalogInspectionTests.swift b/Tests/AgentsUpdatesTests/SourceCatalogInspectionTests.swift new file mode 100644 index 0000000..4a08890 --- /dev/null +++ b/Tests/AgentsUpdatesTests/SourceCatalogInspectionTests.swift @@ -0,0 +1,588 @@ +import AgentsCore +import AgentsManifest +import Foundation +import Testing + +@testable import AgentsUpdates +@testable import Components + +@Suite("Captured source catalog additions", .serialized) +struct SourceCatalogInspectionTests { + @Test func instructionSelectionPreparesAppliesAndRejectsForeignDestination() throws { + let f = try UpdateFixture() + let other = try UpdateFixture() + var environment = f.environment + environment.environment["PRIVATE_CATALOG_ENV"] = "CATALOG_ENV_CANARY" + let before = try FileHash.folderHash(f.root) + let catalog = try UpdateOperations.inspectSource( + alias: "catalog", source: .init(kind: .local, location: f.repo.path), environment: environment + ) + #expect(!String(reflecting: catalog).contains("CATALOG_ENV_CANARY")) + #expect(!String(reflecting: catalog).contains("agents-resolution-")) + let choice = try #require( + catalog.availableChoices.first { + if case .instruction = $0.unit { return true } + return false + }) + let otherCatalog = try UpdateOperations.inspectSource( + alias: "catalog", source: .init(kind: .local, location: f.repo.path), environment: environment + ) + #expect(throws: (any Error).self) { try otherCatalog.select([choice.id]) } + #expect(throws: (any Error).self) { try catalog.select([choice.id, choice.id]) } + let discovery = try #require(try catalog.select([choice.id], options: .init(agents: [.codex]))) + #expect(try FileHash.folderHash(f.root) == before) + let request = discovery.updateRequest() + #expect(throws: (any Error).self) { + try UpdateOperations.preview(request, environment: other.environment) + } + let preview = try UpdateOperations.preview(request, environment: environment) + _ = try UpdateOperations.withPreparedUpdate(request, environment: environment) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + #expect( + try UpdateOperations.inspect(environment: environment).components.contains { + $0.kind == .instructions + }) + } + + @Test(arguments: [false, true]) + func antigravitySelectionCapturesDerivedIncludesAndRejectsStaleRequests(git: Bool) throws { + let f = try UpdateFixture(scope: .user) + let producer = git ? f.repo : f.root.appendingPathComponent("live-instructions") + let include = producer.appendingPathComponent("support/details.txt") + try f.write( + "---\ndescription: Team style\n---\n# Team\n@[Details](../../support/details.txt)\n", + to: producer.appendingPathComponent("package/instructions/rules.md")) + try f.write("Use the shared format.", to: include) + if git { try f.commit() } + func inspect() throws -> (SourceCatalogInspection, SourceCatalogChoiceInspection) { + let catalog = try UpdateOperations.inspectSource( + alias: "team", source: .init(kind: .local, location: producer.path, path: "package"), + scope: .user, environment: f.environment) + let choice = try #require( + catalog.availableChoices.first { + if case .instruction = $0.unit { return true } + return false + }) + return (catalog, choice) + } + let (catalog, choice) = try inspect() + let options = SourceCatalogSelectionOptions(agents: [.antigravity]) + let discovery = try #require(try catalog.select([choice.id], options: options)) + #expect( + discovery.readLocations.contains { + $0.resolvingSymlinksInPath() == include.resolvingSymlinksInPath() + }) + let request = discovery.updateRequest() + let preview = try UpdateOperations.preview(request, scope: .user, environment: f.environment) + let rule = try #require(preview.instructions.targets.first) + #expect(rule.afterAgents == [.antigravity]) + #expect( + String(decoding: try #require(rule.after), as: UTF8.self).contains("Use the shared format.")) + #expect(!FileManager.default.fileExists(atPath: rule.url.path)) + + try f.write("Changed include.", to: include) + if git { try f.commit() } + #expect(throws: (any Error).self) { try catalog.select([choice.id], options: options) } + #expect(throws: (any Error).self) { + try UpdateOperations.withPreparedUpdate(request, scope: .user, environment: f.environment) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + } + #expect(!FileManager.default.fileExists(atPath: rule.url.path)) + + let (fresh, freshChoice) = try inspect() + let replacement = try #require(try fresh.select([freshChoice.id], options: options)) + let replacementRequest = replacement.updateRequest() + let ready = try UpdateOperations.preview( + replacementRequest, scope: .user, environment: f.environment) + _ = try UpdateOperations.withPreparedUpdate( + replacementRequest, scope: .user, environment: f.environment + ) { try $0.apply(ifUnchangedFrom: ready.displayedFingerprint) } + #expect(String(decoding: try f.bytes(rule.url), as: UTF8.self).contains("Changed include.")) + } + + @Test func emptySelectionDoesNotReadDeletedSourceAndStaleRequestsReject() throws { + let f = try UpdateFixture() + let catalog = try UpdateOperations.inspectSource( + alias: "catalog", source: .init(kind: .local, location: f.repo.path), + environment: f.environment) + let choice = try #require( + catalog.availableChoices.first { + if case .skill = $0.unit { return true } + return false + }) + let discovery = try #require( + try catalog.select([choice.id], options: .init(agents: [.codex], skillMode: .copy))) + try f.advance() + #expect(throws: (any Error).self) { try catalog.select([choice.id]) } + #expect(throws: (any Error).self) { + try UpdateOperations.preview(discovery.updateRequest(), environment: f.environment) + } + try FileManager.default.removeItem(at: f.repo) + #expect(try catalog.select([]) == nil) + #expect(!FileManager.default.fileExists(atPath: f.store.declarationURL.path)) + #expect(!FileManager.default.fileExists(atPath: f.store.resolvedURL.path)) + } + + @Test func importerRealKeyRetainsAllFamiliesAndFixedEffectsAndOriginalFreshness() throws { + let f = try UpdateFixture() + let producer = f.root.appendingPathComponent("import-source") + try f.write( + #"{"mcp":{"servers":{"same":{"type":"local","command":["never-run"]}}},"commands":{"same":{"template":"Review"},"other":{"template":"Other"}},"agents":{"same":{"system":"Review","mode":"subagent"}},"lsp":{"fixed":{"command":["never-run"]}}}"#, + to: producer.appendingPathComponent("opencode.json")) + let before = try FileHash.folderHash(f.root) + let catalog = try UpdateOperations.inspectSource( + alias: "catalog", source: .init(kind: .local, location: producer.path), + importing: .init(format: "openCodeConfigV2", document: "opencode.json", selection: []), + environment: f.environment) + let key = try #require( + catalog.availableChoices.first { $0.importedEffects?.components.count == 3 }) + #expect( + Set(key.importedEffects!.components.map(\.declaration.kind)) == [ + .mcpServer, .command, .subagent, + ]) + #expect(catalog.fixedEffects?.components.map(\.declaration.kind) == [.lspServer]) + let discovery = try #require(try catalog.select([key.id])) + #expect(discovery.components.count == 4) + #expect(try FileHash.folderHash(f.root) == before) + _ = try UpdateOperations.preview(discovery.updateRequest(), environment: f.environment) + // Inline canonical declarations alone cannot attest this original adapter document. + try f.write("{}", to: producer.appendingPathComponent("opencode.json")) + #expect(throws: (any Error).self) { + try UpdateOperations.preview(discovery.updateRequest(), environment: f.environment) + } + try f.write( + #"{"commands":{"review":{"template":"Review captured sources"}}}"#, + to: producer.appendingPathComponent("opencode.json")) + let refreshed = try UpdateOperations.inspectSource( + alias: "catalog", source: .init(kind: .local, location: producer.path), + importing: .init(format: "openCodeConfigV2", document: "opencode.json"), + environment: f.environment) + let refreshedChoice = try #require(refreshed.availableChoices.first) + let selected = try #require(try refreshed.select([refreshedChoice.id])) + let preview = try UpdateOperations.preview(selected.updateRequest(), environment: f.environment) + _ = try UpdateOperations.withPreparedUpdate( + selected.updateRequest(), environment: f.environment + ) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + #expect( + try UpdateOperations.inspect(environment: f.environment).components.contains { + $0.kind == .command + }) + } + + @Test func membersComposeOneContainerAndNativeStrategyConflicts() throws { + let f = try UpdateFixture() + let producer = f.root.appendingPathComponent("plugin-source") + try f.write( + #"{"name":"exact-package","version":"1.2.3"}"#, + to: producer.appendingPathComponent("gemini-extension.json")) + try f.write( + "description = \"First\"\nprompt = \"One\"\n", + to: producer.appendingPathComponent("commands/one.toml")) + try f.write( + "description = \"Second\"\nprompt = \"Two\"\n", + to: producer.appendingPathComponent("commands/two.toml")) + let catalog = try UpdateOperations.inspectSource( + alias: "catalog", source: .init(kind: .local, location: producer.path), + environment: f.environment) + let members = catalog.availableChoices.filter { + if case .pluginMember = $0.unit { return true } + return false + } + #expect(members.count == 2) + let discovery = try #require(try catalog.select(members.map(\.id))) + let request = discovery.updateRequest() + guard case .declaration(let declaration) = request.operation else { + Issue.record("missing addition") + return + } + #expect(declaration.components.count == 1) + guard + case .plugin(_, _, _, let strategy, let kinds, let exclusions, _, _, _) = + declaration.components[0] + else { + Issue.record("missing container") + return + } + #expect(strategy == .components && kinds == [.command] && exclusions.isEmpty) + let native = try #require( + catalog.availableChoices.first { + if case .nativePlugin = $0.unit { return true } + return false + }) + let metadata = try #require( + try SourceImport.preview( + .init(profile: .geminiExtensionV1, root: producer, document: "gemini-extension.json") + ).packageMetadata) + #expect(native.origin.pointer == metadata.nameLocation.pointer) + #expect(native.origin.span == metadata.nameLocation.span) + #expect(throws: (any Error).self) { try catalog.select([native.id, members[0].id]) } + } +} + +extension SourceCatalogInspectionTests { + @Test func symbolicGroupAdditionPreservesUnrelatedCommittedPins() throws { + let f = try UpdateFixture() + try f.install(agents: [.codex]) + let previous = try f.store.loadLedger() + try f.advance() + let producer = f.root.appendingPathComponent("export-source") + try f.write( + """ + version: 1 + exports: [review] + groups: + review: + components: + - {kind: command, name: review, description: Review, prompt: Exact, agents: [claude-code]} + """, to: producer.appendingPathComponent(".agent/agents.yaml")) + let catalog = try UpdateOperations.inspectSource( + alias: "exports", source: .init(kind: .local, location: producer.path), + environment: f.environment) + let choice = try #require( + catalog.availableChoices.first { + if case .group = $0.unit { return true } + return false + }) + let discovery = try #require(try catalog.select([choice.id])) + let request = discovery.updateRequest() + guard case .declaration(let declaration) = request.operation else { + Issue.record("missing declaration") + return + } + #expect(declaration.uses == [.init(name: "review", source: "exports")]) + let preview = try UpdateOperations.preview(request, environment: f.environment) + _ = try UpdateOperations.withPreparedUpdate(request, environment: f.environment) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + let next = try f.store.loadLedger() + for (id, component) in previous.components { + #expect(next.components[id] == component) + #expect(next.sources[component.source] == previous.sources[component.source]) + } + } + + @Test func rawResourceRewriteCannotBeClearedThroughCatalogBindingInput() throws { + let f = try UpdateFixture() + let producer = f.root.appendingPathComponent("credential-source") + try f.write( + #"{"mcpServers":{"review":{"command":"never-run","env":{"TOKEN":"CATALOG_PRIVATE_CANARY"}}}}"#, + to: producer.appendingPathComponent("settings.json")) + let catalog = try UpdateOperations.inspectSource( + alias: "catalog", source: .init(kind: .local, location: producer.path), + importing: .init(format: "claudeSettingsV1", document: "settings.json"), + environment: f.environment) + let choice = try #require(catalog.availableChoices.first) + let binding = try #require(catalog.requiredInputs.first { $0.kind == .bindingReference }) + #expect(!String(reflecting: catalog).contains("CATALOG_PRIVATE_CANARY")) + #expect(throws: (any Error).self) { + try catalog.select( + [choice.id], inputs: [.init(id: binding.id, value: .binding(.environment("REVIEW_TOKEN")))]) + } + #expect(!FileManager.default.fileExists(atPath: f.store.declarationURL.path)) + } +} + +extension SourceCatalogInspectionTests { + @Test(arguments: [AgentID.claudeCode, .cursor], [PluginModeDeclaration.native, .components]) + func nativeCatalogSelectionPublishesExactRegistrationAndSelectedGeneratedMembers( + _ agent: AgentID, _ strategy: PluginModeDeclaration + ) throws { + let f = try UpdateFixture(scope: .user) + let producer = f.root.appendingPathComponent("catalog-package") + let container = producer.appendingPathComponent("bundle") + let manifest = + agent == .claudeCode ? ".claude-plugin/plugin.json" : ".cursor-plugin/plugin.json" + let profile: SourceImportProfile = agent == .claudeCode ? .claudePluginV1 : .cursorPluginV1 + try f.write(#"{"name":"producer-package"}"#, to: container.appendingPathComponent(manifest)) + for (name, body) in [("review", "Selected captured command"), ("other", "Unselected command")] { + try f.write( + agent == .claudeCode ? "---\ndescription: Review\n---\n\(body)\n" : body + "\n", + to: container.appendingPathComponent("commands/\(name).md")) + } + try f.write( + "---\nname: helper\ndescription: Helper\n---\nSelected captured skill\n", + to: container.appendingPathComponent("skills/helper/SKILL.md")) + let script = container.appendingPathComponent("scripts/never-run") + try f.write("#!/bin/sh\n# Never executed.\n", to: script) + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: script.path) + let before = try FileHash.folderHash(f.root) + let catalog = try UpdateOperations.inspectSource( + alias: "consumer-alias", + source: .init(kind: .local, location: producer.path, path: "bundle"), scope: .user, + environment: f.environment) + let native = try #require( + catalog.availableChoices.first { + if case .nativePlugin = $0.unit { return true } + return false + }) + let metadata = try #require( + try SourceImport.preview( + .init( + profile: profile, root: producer, + document: "bundle/" + manifest) + ).packageMetadata) + #expect(native.unavailableReason == nil) + #expect(native.origin.document == metadata.nameLocation.document) + #expect(native.origin.pointer == metadata.nameLocation.pointer) + #expect(native.origin.span == metadata.nameLocation.span) + #expect(native.effects.first?.name.utf8.elementsEqual(metadata.name.utf8) == true) + #expect(native.effects.first?.recipients == [agent]) + let choices: [SourceCatalogChoiceID] + if strategy == .native { + choices = [native.id] + } else { + choices = catalog.availableChoices.compactMap { + guard case .pluginMember(let selector) = $0.unit else { return nil } + switch selector { + case .command(name: "review"), .skill(name: "helper"): return $0.id + default: return nil + } + } + #expect(choices.count == 2) + } + let discovery = try #require(try catalog.select(choices, options: .init(agents: [agent]))) + let request = discovery.updateRequest() + guard case .declaration(let declaration) = request.operation else { + Issue.record("missing captured declaration") + return + } + #expect(declaration.components.count == 1) + guard + case .plugin(_, _, _, let mode, let select, let exclude, let recipients, _, _) = + declaration.components[0] + else { + Issue.record("missing plugin declaration") + return + } + #expect(mode == strategy && recipients == [agent]) + if strategy == .native { #expect(select == nil && exclude.isEmpty) } + #expect(try FileHash.folderHash(f.root) == before) + let preview = try UpdateOperations.preview(request, scope: .user, environment: f.environment) + _ = try UpdateOperations.withPreparedUpdate(request, scope: .user, environment: f.environment) { + try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + let installed = try UpdateOperations.inspect(scope: .user, environment: f.environment) + #expect(installed.deployments.allSatisfy { $0.status == .current }) + let tree = try #require( + installed.deployments.first { + FileManager.default.fileExists(atPath: $0.location.appendingPathComponent(manifest).path) + }?.location) + #expect( + try String(contentsOf: tree.appendingPathComponent("commands/review.md"), encoding: .utf8) + .contains("Selected captured command")) + #expect( + try String(contentsOf: tree.appendingPathComponent("skills/helper/SKILL.md"), encoding: .utf8) + .contains("Selected captured skill")) + #expect( + FileManager.default.fileExists(atPath: tree.appendingPathComponent("commands/other.md").path) + == (strategy == .native)) + let frozen = try FileHash.folderHash(tree) + let flags = try FileHash.executableFlags(tree) + if strategy == .native { #expect(flags["scripts/never-run"] == true) } + try FileManager.default.removeItem(at: producer) + if FileManager.default.fileExists(atPath: f.store.cacheDirectory.path) { + try FileManager.default.removeItem(at: f.store.cacheDirectory) + } + try FileManager.default.removeItem(at: tree) + _ = try UpdateOperations.restore(scope: .user, environment: f.environment) + #expect(try FileHash.folderHash(tree) == frozen) + #expect(try FileHash.executableFlags(tree) == flags) + } +} + +extension SourceCatalogInspectionTests { + @Test func selectionRejectsChangedExternalDependencyWithUnchangedCatalogRoot() throws { + let f = try UpdateFixture() + let a = f.root.appendingPathComponent("producer-a") + let b = f.root.appendingPathComponent("producer-b") + try f.write( + """ + version: 1 + sources: {b: {path: '\(b.path)'}} + exports: [outer] + groups: + outer: + uses: [{source: b, group: inner}] + """, to: a.appendingPathComponent(".agent/agents.yaml")) + func dependency(_ prompt: String) throws { + try f.write( + """ + version: 1 + exports: [inner] + groups: + inner: + components: + - {kind: command, name: review, description: Review, prompt: '\(prompt)', agents: [claude-code]} + """, to: b.appendingPathComponent(".agent/agents.yaml")) + } + try dependency("before") + let rootHash = try FileHash.folderHash(a) + let catalog = try UpdateOperations.inspectSource( + alias: "catalog", source: .init(kind: .local, location: a.path), environment: f.environment) + let choice = try #require( + catalog.availableChoices.first { + if case .group = $0.unit { return true } + return false + }) + let discovery = try #require(try catalog.select([choice.id])) + try dependency("after") + #expect(try FileHash.folderHash(a) == rootHash) + #expect(throws: (any Error).self) { try catalog.select([choice.id]) } + #expect(throws: (any Error).self) { + try UpdateOperations.preview(discovery.updateRequest(), environment: f.environment) + } + } +} + +extension SourceCatalogInspectionTests { + @Test func protectedUnrelatedRevisionCannotAttestSelectedSkill() throws { + let f = try UpdateFixture() + try f.store.save( + declaration: Declaration( + sources: ["fixture": .init(kind: .local, location: f.repo.path)], + skills: ["fixture": .init(select: .names(["demo"]), agents: [.codex], mode: .copy)], + instructions: .init(agents: [.claudeCode], sections: ["fixture:rules"])), + ledger: ResolvedLedger()) + _ = try f.apply() + try f.writeSource("new") + try f.commit() + _ = try UpdateOperations.withPreparedUpdate( + .init(kinds: [.instructions]), environment: f.environment + ) { try $0.apply() } + let catalog = try UpdateOperations.inspectSource( + alias: "fixture", source: .init(kind: .local, location: f.repo.path), + environment: f.environment) + let choice = try #require(catalog.availableChoices.first { $0.label == "Skill demo" }) + let retained = try f.store.loadLedger() + #expect(retained.sources.values.contains { $0.revision == catalog.revision }) + #expect(throws: (any Error).self) { + _ = try catalog.select([choice.id], options: .init(agents: [.codex], skillMode: .copy)) + } + } +} + +extension SourceCatalogInspectionTests { + @Test(arguments: [InstallMode.copy, .edit]) + func unchangedSkillCompositionRetainsConsumerModeAndRestrictions(_ mode: InstallMode) throws { + let f = try UpdateFixture() + let catalog = try UpdateOperations.inspectSource( + alias: "catalog", source: .init(kind: .local, location: f.repo.path), + environment: f.environment) + let choice = try #require(catalog.availableChoices.first { $0.label == "Skill demo" }) + let discovery = try #require( + try catalog.select( + [choice.id], options: .init(agents: [.codex], skillMode: mode))) + #expect(discovery.components.count == 1) + #expect(discovery.components[0].recipients == [.codex]) + _ = try UpdateOperations.preview(discovery.updateRequest(), environment: f.environment) + } +} + +extension SourceCatalogInspectionTests { + @Test func directEditDoesNotEraseExportedSkillRevisionEvidence() throws { + let f = try UpdateFixture() + try f.git(["tag", "1.0.0"]) + let oldRevision = try f.git(["rev-parse", "HEAD"]) + try f.write("Unrelated producer change\n", to: f.repo.appendingPathComponent("README.md")) + try f.commit() + try f.git(["tag", "1.1.0"]) + let newRevision = try f.git(["rev-parse", "HEAD"]) + try #require(newRevision != oldRevision) + + let producer = f.root.appendingPathComponent("mixed-producer") + try f.write( + "---\nname: helper\ndescription: Helper\n---\nUnchanged live skill\n", + to: producer.appendingPathComponent("skills/helper/SKILL.md")) + try f.write( + """ + version: 1 + sources: {b: {path: '\(f.repo.path)'}} + exports: [empty, review] + groups: + empty: + components: [] + review: + components: + - kind: skills + source: b + select: [demo] + agents: [claude-code] + mode: copy + """, to: producer.appendingPathComponent(".agent/agents.yaml")) + #if os(macOS) + let platform = DeclarationPlatform.macOS + #else + let platform = DeclarationPlatform.linux + #endif + let catalog = try SourceCatalog.inspect( + alias: "mixed", source: .init(kind: .local, location: producer.path), + store: f.store, platform: platform) + let direct = try #require(catalog.choices.first { $0.label == "Skill helper" }) + let review = try #require( + catalog.choices.first { + if case .group(let use) = $0.unit { return use.name == "review" } + return false + }) + let source = try SourceDeclaration(kind: .local, location: f.repo.path) + .identity(environment: f.environment) + let expected = try #require(review.graph?.components.first) + let expectedResource = try #require(expected.resources.first) + try requireCopiedReview(expected, source: source, revision: newRevision) + + let declaration = try catalog.additions( + [direct.id, review.id], agents: nil, condition: nil, mode: .edit) + let identity = DocumentIdentity(f.store.declarationURL.path) + let bytes = try #require( + try DeclarationEditPlan.bytes( + replacing: Declaration(), with: declaration, in: nil, identity: identity, + environment: f.environment)) + let document = try DeclarationDocument(bytes: bytes, identity: identity) + let expectation = CatalogCompositionExpectation(choices: [direct, review], skillMode: .edit) + + for revision in [oldRevision, newRevision] { + try ComponentLinker.withLinkedComponents( + document: document, store: f.store, platform: platform, + directPins: [expected.key: SourceRevision(revision: revision)] + ) { linked, _ in + let copied = try #require(linked.components.first { $0.key == expected.key }) + try requireCopiedReview(copied, source: source, revision: revision) + let resource = try #require(copied.resources.first) + try #require(resource.path == expectedResource.path) + try #require(resource.hash == expectedResource.hash) + try #require(resource.snapshot == copied.snapshot) + let helper = try #require(linked.components.first { $0.key.name == "helper" }) + guard case .skill(_, .edit, _) = helper.payload else { + Issue.record("Expected the direct helper to be linked in edit mode") + return + } + if revision == oldRevision { + #expect( + throws: CoreError.invalidState( + "catalog addition changed dependency; refresh inspection") + ) { + try expectation.validate(linked) + } + } else { + try expectation.validate(linked) + } + } + } + } + + private func requireCopiedReview(_ component: LinkedComponent, source: String, revision: String) + throws + { + guard case .skill(_, .copy, _) = component.payload else { + throw CoreError.invalidState("Expected the review skill to be linked in copy mode") + } + try #require(component.key.name == "demo") + try #require(component.key.group == "review") + try #require(component.snapshot.source == source) + try #require(component.snapshot.revision == revision) + try #require(component.origins.contains { $0.dependencies.contains(component.snapshot) }) + } +} diff --git a/Tests/AgentsUpdatesTests/SourceImportSelectionTests.swift b/Tests/AgentsUpdatesTests/SourceImportSelectionTests.swift new file mode 100644 index 0000000..9f9a627 --- /dev/null +++ b/Tests/AgentsUpdatesTests/SourceImportSelectionTests.swift @@ -0,0 +1,346 @@ +import AgentsCore +import Foundation +import Testing + +@testable import AgentsUpdates +@testable import Components + +struct SourceImportSelectionTests { + @Test func oneProducerKeyShowsEveryFamilyAndFixedContributions() throws { + let f = try ImportSelectionFixture() + let text = + #"{"mcp":{"servers":{"same":{"type":"local","command":["never-run"]}}},"commands":{"same":{"template":"Review"},"other":{"template":"Other"}},"agents":{"same":{"system":"Review","mode":"subagent"}},"lsp":{"fixed":{"command":["never-run"]}}}"# + try f.write("opencode.json", text) + let before = try FileHash.folderHash(f.root) + let report = try SourceImportOperations.inspect( + format: "openCodeConfigV2", root: f.root, document: "opencode.json") + let shared = try #require(report.availableChoices.first { $0.effects.components.count == 3 }) + #expect( + Set(shared.effects.components.map(\.declaration.kind)) == [.mcpServer, .command, .subagent]) + #expect(report.fixedEffects.components.map(\.declaration.kind) == [.lspServer]) + let selected = try report.resolving(choices: [shared.id]) + #expect(selected.components.count == 4) + let empty = try report.resolving(choices: []) + #expect(empty.components.map(\.declaration.kind) == [.lspServer]) + #expect(throws: (any Error).self) { try selected.resolving(choices: [shared.id]) } + #expect(try FileHash.folderHash(f.root) == before) + try f.write("opencode.json", "{}") + #expect(throws: (any Error).self) { try report.resolving(choices: [shared.id]) } + } + + @Test func linkedSkillSupportingBytesInvalidateResolution() throws { + let f = try ImportSelectionFixture() + try f.write("bundle/.claude-plugin/plugin.json", #"{"name":"producer"}"#) + try f.write( + "bundle/skills/helper/SKILL.md", "---\nname: helper\ndescription: Helper\n---\nBody\n") + try f.write("bundle/shared/tool.txt", "Original support\n") + try FileManager.default.createSymbolicLink( + atPath: f.root.appendingPathComponent("bundle/skills/helper/reference.txt").path, + withDestinationPath: "../../shared/tool.txt") + let report = try SourceImportOperations.inspect( + format: "claudePluginV1", root: f.root, document: "bundle/.claude-plugin/plugin.json") + #expect(report.diagnostics.isEmpty) + let support = try #require(report.resources.first { $0.path == "shared/tool.txt" }) + #expect(support.hash == nil && !support.requiresBindingRewrite) + try f.write("bundle/shared/tool.txt", "Modified support\n") + #expect(throws: (any Error).self) { try report.resolving() } + let refreshed = try SourceImportOperations.inspect( + format: "claudePluginV1", root: f.root, document: "bundle/.claude-plugin/plugin.json") + #expect(try refreshed.resolving().diagnostics.isEmpty) + } + + @Test func supportingBytesInvalidateCapturedRequestPreparation() throws { + let f = try ImportSelectionFixture() + try f.write("bundle/.claude-plugin/plugin.json", #"{"name":"producer"}"#) + try f.write( + "bundle/commands/review.md", + "---\ndescription: Review\n---\nUse [support](../shared/tool.txt).\n") + try f.write("bundle/shared/tool.txt", "Original support\n") + let environment = RuntimeEnvironment( + projectDirectory: f.root, homeDirectory: f.root, environment: [:]) + let scope = try UpdateOperations.inspect(environment: environment) + let report = try SourceImportOperations.inspect( + format: "claudePluginV1", root: f.root, document: "bundle/.claude-plugin/plugin.json") + #expect(report.diagnostics.isEmpty) + let request = try report.updateRequest(in: scope) + try f.write("bundle/shared/tool.txt", "Modified support\n") + #expect(throws: (any Error).self) { try report.resolving() } + #expect(throws: (any Error).self) { + try UpdateOperations.withPreparedUpdate(request, environment: environment) { _ in + Issue.record("Stale supporting content must not reach the prepared handle") + } + } + let refreshed = try SourceImportOperations.inspect( + format: "claudePluginV1", root: f.root, document: "bundle/.claude-plugin/plugin.json") + let freshRequest = try refreshed.updateRequest(in: scope) + _ = try UpdateOperations.preview(freshRequest, environment: environment) + } + + @Test func literalSupportingBytesRemainPrivateAndFreshAfterSymbolicResolution() throws { + let f = try ImportSelectionFixture() + try f.write( + "bundle/.claude-plugin/plugin.json", + #"{"name":"producer","lspServers":"./shared/language.json"}"#) + try f.write( + "bundle/skills/helper/SKILL.md", "---\nname: helper\ndescription: Helper\n---\nBody\n") + let original = + #"{"review":{"command":"never-run","extensionToLanguage":{".txt":"text"},"env":{"TOKEN":"PRIVATE_SUPPORT_A"}}}"# + try f.write("bundle/shared/language.json", original) + try FileManager.default.createSymbolicLink( + atPath: f.root.appendingPathComponent("bundle/skills/helper/reference.txt").path, + withDestinationPath: "../../shared/language.json") + let report = try SourceImportOperations.inspect( + format: "claudePluginV1", root: f.root, document: "bundle/.claude-plugin/plugin.json") + let slot = try #require(report.requiredInputs.first { $0.kind == .bindingReference }) + let resolved = try report.resolving(inputs: [ + .init(id: slot.id, value: .binding(.environment("SUPPORT_TOKEN"))) + ]) + #expect(resolved.bindings.isEmpty) + let preserved = resolved.resources.filter { + $0.path == "skills/helper" || $0.path == "shared/language.json" + } + #expect(!preserved.isEmpty) + #expect(preserved.allSatisfy { $0.hash == nil && $0.requiresBindingRewrite }) + #expect(!String(reflecting: resolved).contains("PRIVATE_SUPPORT_A")) + let environment = RuntimeEnvironment( + projectDirectory: f.root, homeDirectory: f.root, environment: [:]) + let scope = try UpdateOperations.inspect(environment: environment) + #expect(throws: (any Error).self) { try resolved.updateRequest(in: scope) } + try f.write( + "bundle/shared/language.json", + original.replacingOccurrences(of: "PRIVATE_SUPPORT_A", with: "PRIVATE_SUPPORT_B")) + #expect(throws: (any Error).self) { try report.resolving() } + #expect(throws: (any Error).self) { try resolved.resolving() } + let refreshed = try SourceImportOperations.inspect( + format: "claudePluginV1", root: f.root, document: "bundle/.claude-plugin/plugin.json") + #expect(!refreshed.bindings.isEmpty) + #expect(!String(reflecting: refreshed).contains("PRIVATE_SUPPORT_B")) + #expect( + refreshed.resources.filter { $0.path == "skills/helper" }.allSatisfy { + $0.hash == nil && $0.requiresBindingRewrite + }) + } + + @Test func resolvedCanonicalBindingCannotAdmitRawPreservedBytes() throws { + let f = try ImportSelectionFixture() + try f.write( + "settings.json", + #"{"mcpServers":{"review":{"command":"never-run","env":{"TOKEN":"PRIVATE_INPUT_CANARY"}}}}"#) + let initial = try SourceImportOperations.inspect( + format: "claudeSettingsV1", root: f.root, document: "settings.json") + let slot = try #require(initial.requiredInputs.first { $0.kind == .bindingReference }) + let resolved = try initial.resolving(inputs: [ + .init(id: slot.id, value: .binding(.environment("REVIEW_TOKEN"))) + ]) + #expect(resolved.bindings.isEmpty) + #expect(resolved.diagnostics.isEmpty) + #expect(resolved.resources.allSatisfy { $0.requiresBindingRewrite && $0.hash == nil }) + guard case .mcpServer(_, .stdio(let run), _, _, _, _) = resolved.components.first?.declaration + else { + Issue.record("Expected canonical MCP transport") + return + } + #expect(run.environment["TOKEN"] == .environment("REVIEW_TOKEN")) + #expect(!String(reflecting: resolved).contains("PRIVATE_INPUT_CANARY")) + let environment = RuntimeEnvironment( + projectDirectory: f.root, homeDirectory: f.root, environment: [:]) + let store = StateStore(scope: .project, environment: environment) + try store.save(declaration: Declaration(), ledger: ResolvedLedger()) + let scope = try UpdateOperations.inspect(environment: environment) + #expect(throws: (any Error).self) { try resolved.updateRequest(in: scope) } + + var input = SourceImportInput( + profile: .claudeSettingsV1, root: f.root, document: "settings.json") + let raw = try SourceImport.preview(input) + let key = try #require(raw.bindings.first(where: \.canonicalSlot)?.key) + input.bindingReferences[key] = .secret("local-review-token") + let proposal = try SourceImport.preview(input) + var enumeration = input + enumeration.enumerateChoices = true + let document = f.root.appendingPathComponent("settings.json") + let preparation = try ImportPreparation( + input: input, proposal: proposal, + catalog: try SourceImport.preview(enumeration), + locations: [document]) + #expect(throws: (any Error).self) { try preparation.capture() } + #expect(try preparation.capture(admitConversion: false).count == 1) + let reinspected = try SourceImportOperations.inspect( + format: "claudeSettingsV1", root: f.root, document: "settings.json") + #expect(!reinspected.bindings.isEmpty) + #expect(reinspected.resources.allSatisfy { $0.requiresBindingRewrite }) + } + + @Test func excludedCredentialsRemainBlockedAndCannotReceiveFakeSlotHandles() throws { + let f = try ImportSelectionFixture() + try f.write( + "settings.json", + #"{"mcpServers":{"clean":{"command":"never-run"},"private":{"command":"never-run","env":{"TOKEN":"EXCLUDED_INPUT_CANARY"}}}}"# + ) + let report = try SourceImportOperations.inspect( + format: "claudeSettingsV1", root: f.root, + document: "settings.json", selection: ["clean"]) + #expect(report.components.count == 1) + #expect(!report.bindings.isEmpty) + #expect(report.bindings.allSatisfy { !$0.canResolveCanonicalSlot }) + #expect(!report.requiredInputs.contains { $0.kind == .bindingReference }) + #expect(report.resources.allSatisfy { $0.requiresBindingRewrite && $0.hash == nil }) + #expect(!String(reflecting: report).contains("EXCLUDED_INPUT_CANARY")) + } + + @Test func originalSymbolicBindingsDoNotInventRawCredentialRewrite() throws { + let f = try ImportSelectionFixture() + try f.write( + "settings.json", + #"{"mcpServers":{"review":{"command":"never-run","env":{"TOKEN":"${REVIEW_TOKEN}"}}}}"#) + let original = try SourceImportOperations.inspect( + format: "claudeSettingsV1", root: f.root, document: "settings.json") + let slot = try #require(original.requiredInputs.first { $0.kind == .bindingReference }) + #expect(original.resources.allSatisfy { !$0.requiresBindingRewrite && $0.hash != nil }) + let resolved = try original.resolving(inputs: [ + .init(id: slot.id, value: .binding(.environment("REVIEW_TOKEN"))) + ]) + #expect(resolved.bindings.isEmpty) + #expect(resolved.resources.allSatisfy { !$0.requiresBindingRewrite && $0.hash != nil }) + } + + @Test func failedNativeConversionDoesNotOfferAnUnusedCanonicalBindingSlot() throws { + let f = try ImportSelectionFixture() + try f.write( + "settings.json", + #"{"mcpServers":{"bad":{"command":"./missing-server","env":{"TOKEN":"FAILED_MEMBER_CANARY"}}}}"# + ) + let report = try SourceImportOperations.inspect( + format: "claudeSettingsV1", root: f.root, document: "settings.json") + #expect(report.components.isEmpty) + #expect(!report.bindings.isEmpty) + #expect(report.bindings.allSatisfy { !$0.canResolveCanonicalSlot }) + #expect(!report.requiredInputs.contains { $0.kind == .bindingReference }) + #expect(!String(reflecting: report).contains("FAILED_MEMBER_CANARY")) + } + + @Test func overlappingResourceAdmissionSurvivesCanonicalResolution() throws { + let f = try ImportSelectionFixture() + try f.write( + "opencode.json", + #"{"mcp":{"servers":{"clean":{"type":"local","command":["never-run"],"cwd":"."}}},"lsp":{"fixed":{"command":["never-run"],"env":{"TOKEN":"OVERLAP_CANARY"}}}}"# + ) + let initial = try SourceImportOperations.inspect( + format: "openCodeConfigV2", root: f.root, document: "opencode.json") + let slot = try #require(initial.requiredInputs.first { $0.kind == .bindingReference }) + let resolved = try initial.resolving(inputs: [ + .init(id: slot.id, value: .binding(.secret("local-token"))) + ]) + #expect(resolved.bindings.isEmpty) + #expect(resolved.diagnostics.isEmpty) + let root = try #require(resolved.resources.first { $0.path == "." }) + #expect(root.requiresBindingRewrite && root.hash == nil) + #expect(!String(reflecting: resolved).contains("OVERLAP_CANARY")) + } + + @Test func sourceHandlesRerunTheOwningLockAdapter() throws { + let f = try ImportSelectionFixture() + try f.write( + "lock.json", + "{\"lockfileVersion\":1,\"sources\":{\"acme/repo\":{\"resolvedRef\":\"" + + String(repeating: "a", count: 40) + "\",\"skillsPath\":\"skills\",\"skills\":{}}}}") + let initial = try SourceImportOperations.inspect( + format: "rulesyncSourcesV1", root: f.root, document: "lock.json") + let source = try #require(initial.requiredInputs.first { $0.kind == .sourceCoordinates }) + let resolved = try initial.resolving(inputs: [ + .init( + id: source.id, + value: .source(.init(kind: .git, location: "https://example.invalid/acme/repo"))) + ]) + #expect(resolved.requiredInputs.isEmpty) + #expect(resolved.diagnostics.isEmpty) + #expect(resolved.sources.first?.commit == String(repeating: "a", count: 40)) + #expect(throws: (any Error).self) { + try resolved.resolving(inputs: [.init(id: source.id, value: .content(path: "."))]) + } + } + + @Test func explicitContentAndMarketplaceChoicesRerunTheirOwnAdmission() throws { + let f = try ImportSelectionFixture() + try f.write( + "skills/review/SKILL.md", "---\nname: review\ndescription: Review\n---\nReview\n") + let capture = try ImportSkillContent.read( + "skills/review", input: .init(profile: .vercelProjectV2, root: f.root, document: "lock.json"), + limits: .init()) + let hash = ImportSkillContent.vercelHash(capture) + try f.write( + "lock.json", + "{\"version\":2,\"skills\":{\"review\":{\"source\":\"acme/repo\",\"sourceType\":\"github\",\"computedHash\":\"" + + hash + "\"}}}") + let initial = try SourceImportOperations.inspect( + format: "vercelProjectV2", root: f.root, document: "lock.json") + let content = try #require(initial.requiredInputs.first { $0.kind == .explicitContent }) + #expect(throws: (any Error).self) { + try initial.resolving(inputs: [.init(id: content.id, value: .content(path: "../escape"))]) + } + let missing = try initial.resolving(inputs: [ + .init(id: content.id, value: .content(path: "absent")) + ]) + #expect(missing.requiredInputs.contains { $0.kind == .explicitContent }) + let captured = try initial.resolving(inputs: [ + .init(id: content.id, value: .content(path: "skills/review")) + ]) + #expect(!captured.requiredInputs.contains { $0.kind == .explicitContent }) + #expect(captured.resources.contains { $0.hash != nil && $0.requiresStandaloneSource }) + #expect(captured.sources.allSatisfy { $0.commit == nil }) + #expect(captured.diagnostics.contains { $0.code == "incompletePin" }) + + try f.write( + ".claude-plugin/marketplace.json", + #"{"name":"market","owner":{"name":"Owner"},"plugins":[{"name":"review","source":{"source":"github","repo":"acme/repo","sha":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}}]}"# + ) + let catalog = try SourceImportOperations.inspect( + format: "claudeMarketplaceV1", root: f.root, document: ".claude-plugin/marketplace.json") + #expect(catalog.sources.isEmpty) + #expect(!catalog.diagnostics.isEmpty) + let choice = try #require(catalog.availableChoices.first) + #expect(choice.effects.sources.count == 1) + let selected = try catalog.resolving(choices: [choice.id]) + #expect(selected.sources.count == 1) + #expect(selected.sources.first?.commit == String(repeating: "a", count: 40)) + let empty = try catalog.resolving(choices: []) + #expect(empty.sources.isEmpty) + } + + @Test func ordinalChoicesAndUnfilteredContainersKeepTheirOwnSemantics() throws { + let f = try ImportSelectionFixture() + try f.write( + "apm.yml", + "name: example\nversion: '1.0.0'\ndependencies:\n apm: [acme/one]\ndevDependencies:\n apm: [acme/two]\n" + ) + let yaml = try SourceImportOperations.inspect( + format: "apmManifest", root: f.root, document: "apm.yml") + #expect(yaml.availableChoices.count == 1) + #expect(yaml.availableChoices.first?.locations.count == 2) + #expect(yaml.availableChoices.first?.effects.sources.count == 2) + let empty = try yaml.resolving(choices: []) + #expect(empty.sources.isEmpty) + try f.write("bundle/.cursor-plugin/plugin.json", #"{"name":"bundle"}"#) + try f.write("bundle/commands/review.md", "Review") + let container = try SourceImportOperations.inspect( + format: "cursorPluginV1", root: f.root, document: "bundle/.cursor-plugin/plugin.json") + #expect(container.availableChoices.isEmpty) + #expect(container.fixedEffects.components.count == 1) + #expect(try container.resolving(choices: []).components.count == 1) + } +} + +private final class ImportSelectionFixture { + let root: URL + init() throws { + root = FileManager.default.temporaryDirectory.appendingPathComponent( + "import-selection-" + UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + } + deinit { try? FileManager.default.removeItem(at: root) } + func write(_ path: String, _ text: String) throws { + let url = root.appendingPathComponent(path) + try FileManager.default.createDirectory( + at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data(text.utf8).write(to: url) + } +} diff --git a/Tests/AgentsUpdatesTests/SourcePolicyTests.swift b/Tests/AgentsUpdatesTests/SourcePolicyTests.swift new file mode 100644 index 0000000..439c83f --- /dev/null +++ b/Tests/AgentsUpdatesTests/SourcePolicyTests.swift @@ -0,0 +1,313 @@ +import AgentsCore +import AgentsManifest +import AgentsUpdates +import Foundation +import Testing + +struct SourcePolicyTests { + @Test(arguments: [InstallScope.project, .user]) + func editorCreatesPolicyAndPreservesConcurrentEdits(_ scope: InstallScope) throws { + let fixture = try UpdateFixture() + let first = try SourcePolicyEditor(scope: scope, environment: fixture.environment) + let stale = try SourcePolicyEditor(scope: scope, environment: fixture.environment) + #expect(first.original == nil) + #expect(throws: ManifestFailure.self) { try first.save(Data("allow: true".utf8)) } + #expect(!FileManager.default.fileExists(atPath: first.url.path)) + let rules = Data("version: 1\nallow: [local]\n".utf8) + try first.save(rules) + #expect(throws: CoreError.self) { try stale.save(Data("version: 1\n".utf8)) } + var managed = fixture.environment + managed.organizationSourcePolicyURL = first.url + let editor = try SourcePolicyEditor(scope: scope, environment: managed) + #expect(throws: CoreError.self) { try editor.save(Data("version: 1\n".utf8)) } + #expect(try Data(contentsOf: first.url) == rules) + } + + @Test func policyDocumentsRoundTripCanonicalOriginsAndReportLocations() throws { + let identity = DocumentIdentity("synthetic-source-policy.yaml") + let document = Data( + """ + version: 1 + allow: + - git: ssh://git@CODE.EXAMPLE:22/Team/Repository.git/ + - git: ssh://git@code.example:443/Team/another.git.git + - git: http://code.example:80/Team/legacy.git + - http: https://INDEX.EXAMPLE:443/some/path + - local + - inline + deny: [missing] + """.utf8) + let rules = try SourcePolicyDocument.parse(document, identity: identity) + let encoded = try SourcePolicyDocument.bytes(for: rules) + #expect(try SourcePolicyDocument.parse(encoded, identity: identity) == rules) + #expect(rules.allow?[0] == (try SourceOrigin.git("https://code.example/Team/Repository"))) + #expect(rules.allow?[0] == (try SourceOrigin.git("git@code.example:Team/Repository.git"))) + #expect(rules.allow?[0] == (try SourceOrigin.git("git@code.example:/Team/Repository.git"))) + #expect(rules.allow?[0] != (try SourceOrigin.git("https://code.example/Team/repository"))) + #expect(rules.allow?[0] != (try SourceOrigin.git("http://code.example/Team/Repository"))) + #expect(rules.allow?[3] == (try SourceOrigin.http("https://index.example/?query=redacted"))) + #expect(rules.allow?[3] != (try SourceOrigin.http("http://index.example"))) + #expect( + try SourceOrigin.git("ssh://git@GitHub.COM./Team/Repository.git") + == SourceOrigin.git("https://github.com/team/repository")) + #expect( + try SourceOrigin.http("http://127.1:8080") == SourceOrigin.http("http://127.0.0.1:8080")) + #expect( + try SourceOrigin.http("https://[0:0:0:0:0:0:0:1]") == SourceOrigin.http("https://[::1]")) + #expect(throws: CoreError.self) { + try SourceOrigin.git("https://code.example/Team%2fRepository") + } + #expect(throws: CoreError.self) { + try SourceOrigin.git("file:///Team/Repository") + } + let invalid = Data("version: 1\nallow: true\n".utf8) + do { + _ = try SourcePolicyDocument.parse(invalid, identity: identity) + Issue.record("Malformed policy was admitted") + } catch let failure as ManifestFailure { + let diagnostic = try #require(failure.diagnostics.first) + #expect(diagnostic.code == "source-policy.field") + #expect(diagnostic.span.document == identity) + #expect(diagnostic.span.line == 2) + } + #expect(throws: ManifestFailure.self) { + try SourcePolicyDocument.parse( + Data("version: 1\ndeny: []\ndeny: []\n".utf8), identity: identity) + } + } + + @Test func layersIntersectAndMissingLocalAndInlineAreDistinct() throws { + let f = try UpdateFixture() + let user = SourcePolicyOperations.policyURL(scope: .user, environment: f.environment) + let project = SourcePolicyOperations.policyURL(scope: .project, environment: f.environment) + let organization = f.root.appendingPathComponent("shared-policy.yaml") + let unconfigured = try SourcePolicyOperations.inspect(environment: f.environment) + #expect(!unconfigured.effective.isConfigured) + #expect(unconfigured.effective.violations(for: .missing).isEmpty) + let sourceSettings = SourceAccessSettingsEditor.settingsURL(environment: f.environment) + #expect(Set(unconfigured.readDependencies.map(\.url)) == Set([user, project, sourceSettings])) + try f.write("version: 1\nallow: [inline, local]\n", to: user) + try f.write("version: 1\nallow: [inline, missing]\n", to: project) + try f.write("version: 1\nallow: [inline]\ndeny: [inline]\n", to: organization) + var environment = f.environment + environment.organizationSourcePolicyURL = organization + let effective = try SourcePolicyOperations.inspect(environment: environment).effective + #expect(effective.layers.map(\.scope) == [.user, .project, .organization]) + #expect(effective.violations(for: .inline).map(\.reason) == [.denied]) + #expect( + effective.violations(for: .local(at: f.repo)).map(\.scope) == [.project, .organization]) + #expect(effective.violations(for: .missing).map(\.reason) == [.missingOrigin, .missingOrigin]) + let userOnly = try SourcePolicyOperations.inspect(scope: .user, environment: f.environment) + #expect(userOnly.effective.violations(for: .local(at: f.repo)).isEmpty) + environment.organizationSourcePolicyURL = f.root.appendingPathComponent("missing-policy.yaml") + #expect(throws: CoreError.self) { try SourcePolicyOperations.inspect(environment: environment) } + } + + @Test func directSourceDenialPrecedesAcquisitionAndInstallation() throws { + let f = try UpdateFixture() + let user = SourcePolicyOperations.policyURL(scope: .user, environment: f.environment) + let project = SourcePolicyOperations.policyURL(scope: .project, environment: f.environment) + try f.write("version: 1\ndeny: [{git: code.invalid/Team/repository}]\n", to: user) + try f.write("version: 1\nallow: [{git: code.invalid/Team/repository}]\n", to: project) + let source = SourceDeclaration( + kind: .git, location: "ssh://git@CODE.invalid/Team/repository.git") + let declaration = Declaration( + sources: ["demo": source], skills: ["demo": .init(select: .names(["item"]))]) + let operation = UpdateRequest(operation: .declaration(declaration)) + let before = try f.snapshot() + do { + _ = try UpdateOperations.preview(operation, environment: f.environment) + Issue.record("Disallowed repository was selected") + } catch let failure as SourcePolicyFailure { + #expect(failure.violations.map(\.scope) == [.user]) + #expect(failure.violations.map(\.reason) == [.denied]) + } + #expect(throws: SourcePolicyFailure.self) { + try UpdateOperations.inspectSource(alias: "demo", source: source, environment: f.environment) + } + #expect(throws: SourcePolicyFailure.self) { + try UpdateOperations.withPreparedUpdate(operation, environment: f.environment) { + try $0.apply() + } + } + #expect(try f.snapshot() == before) + #expect(!FileManager.default.fileExists(atPath: f.store.cacheDirectory.path)) + } + + @Test func inlineDeclarationCanInstallWithoutGrantingLocalSourceAccess() throws { + let f = try UpdateFixture() + try f.write( + """ + version: 1 + components: + - kind: command + name: policy-inline + description: Synthetic command + prompt: Review the sample. + agents: [claude-code] + """, to: f.store.declarationURL) + let project = SourcePolicyOperations.policyURL(scope: .project, environment: f.environment) + try f.write("version: 1\nallow: [inline]\n", to: project) + _ = try f.apply() + #expect(try SourcePolicyOperations.audit(environment: f.environment).violations.isEmpty) + try f.write("version: 1\nallow: [local]\n", to: project) + let audit = try SourcePolicyOperations.audit(environment: f.environment) + #expect(audit.violations.map(\.origin) == [.inline]) + #expect(throws: SourcePolicyFailure.self) { + try UpdateOperations.restore(environment: f.environment) + } + } + + @Test func indirectLocalSourceIsCheckedDuringLookupAndLockedRestore() throws { + let f = try UpdateFixture() + let producer = f.root.appendingPathComponent("producer") + try f.write( + """ + version: 1 + sources: {downstream: {path: '\(f.repo.path)'}} + exports: [shared] + groups: + shared: + components: + - kind: skills + source: downstream + select: [demo] + agents: [codex] + mode: copy + """, to: producer.appendingPathComponent(".agent/agents.yaml")) + try f.write( + """ + version: 1 + sources: {producer: {path: './producer'}} + uses: [{source: producer, group: shared}] + """, to: f.store.declarationURL) + let project = SourcePolicyOperations.policyURL(scope: .project, environment: f.environment) + let policy = "version: 1\nallow: [{local: '\(producer.path)'}, {local: '\(f.repo.path)'}]\n" + // Policy paths name physical roots. The fixture may live under macOS's /var alias. + let allowed = policy.replacingOccurrences( + of: f.root.path, with: f.root.resolvingSymlinksInPath().path) + try f.write(allowed, to: project) + #expect(try f.preview().hasChanges) + _ = try f.apply() + #expect(FileManager.default.fileExists(atPath: f.target().path)) + let permitted = try SourcePolicyOperations.audit(environment: f.environment) + #expect(permitted.hasLock) + #expect(permitted.violations.isEmpty) + try FileManager.default.removeItem(at: f.target()) + let denied = allowed + "deny: [{local: '\(f.repo.resolvingSymlinksInPath().path)'}]\n" + try f.write(denied, to: project) + let before = try FileHash.folderHash(f.root) + let audit = try SourcePolicyOperations.audit(environment: f.environment) + #expect(audit.hasLock) + #expect(audit.violations.map(\.origin) == [.local(at: f.repo)]) + #expect(!((try JSONEncoder().encode(audit)).isEmpty)) + #expect(throws: SourcePolicyFailure.self) { try f.preview() } + #expect(throws: SourcePolicyFailure.self) { + try UpdateOperations.restore(environment: f.environment) + } + #expect(try FileHash.folderHash(f.root) == before) + try f.write(allowed, to: project) + _ = try UpdateOperations.restore(environment: f.environment) + #expect(FileManager.default.fileExists(atPath: f.target().path)) + } + + @Test(arguments: [false, true], [InstallScope.user, .project]) + func portableResourceWithoutOriginalCoordinatesRequiresMissingOriginOptIn( + authored: Bool, policyScope: InstallScope + ) throws { + let publisher = try UpdateFixture() + let executable = publisher.repo.appendingPathComponent("server") + try publisher.write("#!/bin/sh\nexit 1\n", to: executable) + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: executable.path) + try publisher.commit() + let declaration = Declaration( + sources: ["program": .init(kind: .local, location: publisher.repo.path)], + components: [ + .mcpServer( + name: "resource-server", + transport: .stdio(.init(executable: "./server", executableSource: "program")), + agents: [.codex], + ) + ]) + _ = try UpdateOperations.withPreparedUpdate( + UpdateRequest(operation: .declaration(declaration)), environment: publisher.environment + ) { try $0.apply() } + let published = try UpdateOperations.inspect(environment: publisher.environment) + let package = BundlePackage(name: "resource-server", version: "1.0.0") + let bundle: BundleInspection + if authored { + let capture = try AuthorPackageOperations.preview( + .init(package: package, lockedMembers: [.init(kind: .mcpServer, name: "resource-server")]), + environment: publisher.environment) + bundle = capture.inspection + } else { + bundle = try BundleOperations.inspect( + BundleOperations.export( + package, selections: published.components.map(\.selection), scope: .project, + environment: publisher.environment)) + } + let server = try #require(bundle.components.first) + let resourceRevision = try publisher.git(["rev-parse", "HEAD"]) + #expect( + server.sources.contains { $0.revision == resourceRevision && $0.policyOrigin == .missing }) + #expect(server.entries.contains { $0.path.hasSuffix("/server") && $0.executable }) + try FileManager.default.removeItem(at: publisher.repo) + + let consumer = try UpdateFixture() + let selected = [BundleImportSelection(componentID: server.id, targets: [.codex])] + let policy = SourcePolicyOperations.policyURL( + scope: policyScope, environment: consumer.environment) + try consumer.write("version: 1\nallow: [local, inline]\n", to: policy) + let untouched = try FileHash.folderHash(consumer.root) + do { + _ = try BundleOperations.previewImport( + bundle, selections: selected, scope: .project, environment: consumer.environment) + Issue.record("The original resource origin could not be established") + } catch let failure as SourcePolicyFailure { + #expect(failure.violations.map(\.reason) == [.missingOrigin]) + #expect(failure.violations.map(\.origin) == [.missing]) + } + #expect(try FileHash.folderHash(consumer.root) == untouched) + try consumer.write("version: 1\nallow: [missing, inline]\n", to: policy) + let preview = try BundleOperations.previewImport( + bundle, selections: selected, scope: .project, environment: consumer.environment) + _ = try BundleOperations.withPreparedImport(preview) { try $0.apply() } + #expect(try SourcePolicyOperations.audit(environment: consumer.environment).violations.isEmpty) + try consumer.write("version: 1\nallow: [local, inline]\n", to: policy) + let installed = try FileHash.folderHash(consumer.root) + #expect( + try SourcePolicyOperations.audit(environment: consumer.environment).violations.map(\.origin) + == [.missing]) + #expect(throws: SourcePolicyFailure.self) { + try UpdateOperations.restore(environment: consumer.environment) + } + #expect(try FileHash.folderHash(consumer.root) == installed) + } + + @Test(arguments: [false, true]) + func policyGenerationIsBoundToDisplayedAndPreparedUpdates(_ policyInitiallyExists: Bool) throws { + let f = try UpdateFixture() + try f.declare(agents: [.codex]) + let user = SourcePolicyOperations.policyURL(scope: .user, environment: f.environment) + if policyInitiallyExists { try f.write("version: 1\nallow: [local]\n", to: user) } + let before = try f.snapshot() + let report = try f.preview() + #expect(report.readLocations.contains(user)) + try f.write("version: 1\nallow: [local, inline]\n", to: user) + #expect(throws: UpdateApplyError.self) { + try UpdateOperations.withPreparedUpdate(environment: f.environment) { + try $0.apply(ifUnchangedFrom: report.displayedFingerprint) + } + } + #expect(try f.snapshot() == before) + if !policyInitiallyExists { try FileManager.default.removeItem(at: user) } + #expect(throws: UpdateApplyError.self) { + try UpdateOperations.withPreparedUpdate(environment: f.environment) { prepared in + try f.write("version: 1\nallow: []\n", to: user) + _ = try prepared.apply() + } + } + #expect(try f.snapshot() == before) + #expect(!FileManager.default.fileExists(atPath: f.store.cacheDirectory.path)) + } +} diff --git a/Tests/AgentsUpdatesTests/SourceReplacementUpdateTests.swift b/Tests/AgentsUpdatesTests/SourceReplacementUpdateTests.swift new file mode 100644 index 0000000..c270fbb --- /dev/null +++ b/Tests/AgentsUpdatesTests/SourceReplacementUpdateTests.swift @@ -0,0 +1,64 @@ +import AgentsCore +import AgentsManifest +import AgentsUpdates +import Foundation +import Testing + +struct SourceReplacementUpdateTests { + @Test func sourceReplacementPreviewApplyAndStaleReadUseCapturedDocument() throws { + let f = try UpdateFixture() + try f.store.save( + declaration: Declaration( + sources: ["original": .init(kind: .local, location: f.repo.path)], watch: ["original"], + components: [ + .skills( + source: "original", .init(select: .names(["demo"]), agents: [.claudeCode], mode: .copy)) + ]), ledger: .init()) + let identity = "local:" + f.repo.path + let watch = try JSONEncoder().encode( + WatchState(sources: [identity: .init(seen: .revision(try f.git(["rev-parse", "HEAD"])))])) + try watch.write(to: f.store.watchURL) + _ = try f.apply() + let snapshot = try UpdateOperations.inspect(environment: f.environment) + let doc = try #require(snapshot.document) + let source = try #require(doc.node(at: "/sources/0")) + let request = UpdateRequest( + operation: .edit([ + .replaceSource( + source, with: .init(name: "renamed", source: .init(kind: .local, location: f.repo.path))) + ]), expectedDeclarationDigest: doc.digest) + let before = try Data(contentsOf: f.store.declarationURL) + let preview = try UpdateOperations.preview(request, environment: f.environment) + #expect(try Data(contentsOf: f.store.declarationURL) == before) + _ = try UpdateOperations.withPreparedUpdate(request, environment: f.environment) { + #expect($0.report.displayedFingerprint == preview.displayedFingerprint) + return try $0.apply(ifUnchangedFrom: preview.displayedFingerprint) + } + let cold = try UpdateOperations.inspect(environment: f.environment) + #expect(cold.deployments.allSatisfy { $0.status == .current }) + let declaration = try f.store.loadDeclaration() + #expect(declaration.sources["original"] == nil && declaration.sources["renamed"] != nil) + #expect(declaration.watch == ["renamed"]) + #expect(try Data(contentsOf: f.store.watchURL) == watch) + #expect(throws: (any Error).self) { + try UpdateOperations.preview(request, environment: f.environment) + } + let refreshed = try #require(cold.document) + let replacement = try #require(refreshed.node(at: "/sources/0")) + let nextRequest = UpdateRequest( + operation: .edit([ + .replaceSource( + replacement, + with: .init(name: "final", source: .init(kind: .local, location: f.repo.path))) + ]), expectedDeclarationDigest: refreshed.digest) + _ = try UpdateOperations.preview(nextRequest, environment: f.environment) + let external = Data("# external edit\n".utf8) + Data(refreshed.bytes) + try external.write(to: f.store.declarationURL) + #expect(throws: (any Error).self) { + try UpdateOperations.withPreparedUpdate(nextRequest, environment: f.environment) { _ in + Issue.record("Changed source document must reject replacement before publication") + } + } + #expect(try Data(contentsOf: f.store.declarationURL) == external) + } +} diff --git a/Tests/AgentsUpdatesTests/UpdateFixture.swift b/Tests/AgentsUpdatesTests/UpdateFixture.swift index 7d0b8fe..1185e5f 100644 --- a/Tests/AgentsUpdatesTests/UpdateFixture.swift +++ b/Tests/AgentsUpdatesTests/UpdateFixture.swift @@ -1,8 +1,10 @@ import AgentsCore import AgentsInstructions +import AgentsManifest import AgentsSkills import AgentsUpdates import Foundation +import StateTestSupport import Testing final class UpdateFixture { @@ -76,7 +78,7 @@ final class UpdateFixture { instructions: InstructionsDeclaration( agents: agents, sections: ["fixture:rules"], chatgpt: ["weekly": PromptDeclaration(sections: ["fixture:rules"])])), - resolved: ResolvedState()) + ledger: ResolvedLedger()) } func install(mode: InstallMode = .copy, agents: [AgentID] = [.codex, .claudeCode]) throws { @@ -113,7 +115,7 @@ final class UpdateFixture { func snapshot() throws -> [String: Data] { let files = [store.declarationURL, store.resolvedURL, store.watchURL] - + AgentID.allCases.map { target($0).appendingPathComponent("SKILL.md") } + + AgentRegistry.skillAgents.map { target($0).appendingPathComponent("SKILL.md") } + AgentID.allCases.compactMap { InstructionLocations.file(for: $0, scope: store.scope, environment: environment) } diff --git a/Tests/AgentsUpdatesTests/UpdateTransactionTests.swift b/Tests/AgentsUpdatesTests/UpdateTransactionTests.swift index 01dd744..eb9792f 100644 --- a/Tests/AgentsUpdatesTests/UpdateTransactionTests.swift +++ b/Tests/AgentsUpdatesTests/UpdateTransactionTests.swift @@ -1,9 +1,10 @@ -import AgentsCore import AgentsSkills -import Darwin +import CPlatform import Foundation +import StateTestSupport import Testing +@testable import AgentsCore @testable import AgentsUpdates @Suite("Combined update transactions") @@ -19,7 +20,7 @@ struct UpdateTransactionTests { _ = try UpdateOperations.withPreparedUpdate( environment: fixture.environment, checkpoint: { step in - if step == "replace.0" { + if step == TransactionCheckpoint.progress(0, .applied).name { // Exchange a journal-bound root so every automatic recovery attempt must stop. try FileManager.default.moveItem(at: root, to: moved) try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) @@ -34,8 +35,10 @@ struct UpdateTransactionTests { let journal = fixture.store.directory.appendingPathComponent("transaction.json") #expect(FileManager.default.fileExists(atPath: journal.path)) let retained = try FileManager.default.contentsOfDirectory(atPath: moved.path) - #expect(retained.contains { $0.hasSuffix(".old") }) - #expect(throws: CoreError.self) { try fixture.store.loadResolved() } + #expect(retained.contains { $0.hasPrefix(".agents-") }) + #expect(throws: CoreError.invalidState("transaction root identity changed")) { + try fixture.store.withLock {} + } #expect(try FileManager.default.contentsOfDirectory(atPath: moved.path) == retained) try FileManager.default.removeItem(at: root) try FileManager.default.moveItem(at: moved, to: root) @@ -48,8 +51,41 @@ struct UpdateTransactionTests { } @Test(arguments: [ - "between-kinds", "journal.preparing", "journal.applying.renamed", - "journal.committed.renamed", "journal.committed", "cleanup.0", "journal.removed", + (TransactionCheckpoint.phase(.preparing).name, UpdateTerminalDisposition.unchanged), + ( + TransactionCheckpoint.persisted(.applying, .entry(0, .publishing), .renamed).name, .rolledBack + ), + (TransactionCheckpoint.phase(.committed).name, .committed), + ]) + func outerTerminalReportsTheDurablePublication( + point: String, expected: UpdateTerminalDisposition + ) throws { + let fixture = try UpdateFixture() + try fixture.install() + let before = try fixture.snapshot() + try fixture.advance() + var interrupted = false + let result = UpdateOperations.perform( + environment: fixture.environment, + checkpoint: { step in + if step == point { + interrupted = true + throw CoreError.invalidState("terminal fixture failure") + } + }, { try $0.apply() }) + #expect(interrupted) + #expect(result.disposition == expected) + #expect(!result.recovery.pending) + #expect(throws: UpdateApplyError.self) { try result.result.get() } + if expected != .committed { #expect(try fixture.snapshot() == before) } + } + + @Test(arguments: [ + "between-kinds", TransactionCheckpoint.phase(.preparing).name, + TransactionCheckpoint.persisted(.applying, .entry(0, .publishing), .renamed).name, + TransactionCheckpoint.persisted(.committed, .terminal, .renamed).name, + TransactionCheckpoint.phase(.committed).name, TransactionCheckpoint.containerRemoved(0).name, + TransactionCheckpoint.journalRemoved.name, ]) func failuresReportTheRecoveredGeneration(_ failure: String) throws { let fixture = try UpdateFixture() @@ -66,11 +102,12 @@ struct UpdateTransactionTests { _ = try UpdateOperations.withPreparedUpdate( environment: fixture.environment, checkpoint: { step in - if step == "journal.preparing" { + if step == TransactionCheckpoint.phase(.preparing).name { lastSkill = try lastSkillIndex(fixture.store) } if step == failure - || (failure == "between-kinds" && step == lastSkill.map { "replace.\($0)" }) + || (failure == "between-kinds" + && step == lastSkill.map { TransactionCheckpoint.progress($0, .applied).name }) { failed = true throw CoreError.invalidState("injected update failure") @@ -79,9 +116,7 @@ struct UpdateTransactionTests { { try $0.apply() }) Issue.record("failure checkpoint was not reached") } catch let error as UpdateApplyError { - let committed = - failure.hasPrefix("journal.committed") || failure == "cleanup.0" - || failure == "journal.removed" + let committed = committedPoints.contains(failure) #expect(error.disposition == (committed ? .committed : .unchanged)) #expect(error.underlyingError as? CoreError == .invalidState("injected update failure")) if committed { @@ -98,8 +133,10 @@ struct UpdateTransactionTests { } @Test(arguments: [ - "between-kinds", "journal.preparing", "journal.applying.renamed", - "journal.committed.renamed", "cleanup.0", + "between-kinds", TransactionCheckpoint.phase(.preparing).name, + TransactionCheckpoint.persisted(.applying, .entry(0, .publishing), .renamed).name, + TransactionCheckpoint.persisted(.committed, .terminal, .renamed).name, + TransactionCheckpoint.containerRemoved(0).name, ]) func killedCombinedWriterRecoversThenPreparesTheWholeUpdate(_ checkpoint: String) throws { let fixture = try UpdateFixture() @@ -110,11 +147,26 @@ struct UpdateTransactionTests { defer { terminate(child) } try waitFor("ready", fixture: fixture, child: child) terminate(child) - #expect(throws: CoreError.self) { try fixture.preview() } + #expect(throws: CoreError.recoveryPending(TransactionRecoveryDiagnostic.pendingMessage)) { + try fixture.preview() + } + let inspection = try UpdateOperations.inspect(environment: fixture.environment) + #expect(inspection.recovery.pending) + #expect(inspection.components.isEmpty) + var delivered = false + let recovered: UpdateCompletion = UpdateOperations.perform( + environment: fixture.environment + ) { _ in + delivered = true + } + #expect(!delivered) + #expect(recovered.recoveredBeforePreparation) + #expect(recovered.disposition == .unchanged) + #expect(!recovered.recovery.pending) #expect(throws: CoreError.transactionRecovered(fixture.store.directory.path)) { - try fixture.apply() + try recovered.result.get() } - let committed = checkpoint.hasPrefix("journal.committed") || checkpoint == "cleanup.0" + let committed = committedPoints.contains(checkpoint) if !committed { #expect(try fixture.snapshot() == before) } var displayed = 0 _ = try UpdateOperations.withPreparedUpdate(environment: fixture.environment) { update in @@ -144,11 +196,12 @@ struct UpdateTransactionTests { #expect( !FileManager.default.fileExists( atPath: fixture.root.appendingPathComponent("contender-finished").path)) + try ProcessWait.stopped(prepared, root: fixture.root) kill(prepared.processIdentifier, SIGCONT) - prepared.waitUntilExit() + try ProcessWait.exit(prepared, root: fixture.root) #expect(prepared.terminationStatus == 0) try waitFor("contender-finished", fixture: fixture, child: contender) - contender.waitUntilExit() + try ProcessWait.exit(contender, root: fixture.root) #expect(contender.terminationStatus == 0) } @@ -192,31 +245,77 @@ private func lastSkillIndex(_ store: StateStore) throws -> Int { private final class UpdateTestBundle: NSObject {} -private func launch(_ fixture: UpdateFixture, command: String, argument: String) throws -> Process { - var directory = Bundle(for: UpdateTestBundle.self).bundleURL.deletingLastPathComponent() +/// Interruptions at or after the terminal commit marker. +private let committedPoints = [ + TransactionCheckpoint.persisted(.committed, .terminal, .renamed), .phase(.committed), + .containerRemoved(0), .journalRemoved, +].map(\.name) + +func launch(_ fixture: UpdateFixture, command: String, argument: String) throws -> Process { + var directory = Bundle(for: UpdateTestBundle.self).bundleURL while !FileManager.default.isExecutableFile( atPath: directory.appendingPathComponent("StateTestProcess").path), directory.path != "/" { directory.deleteLastPathComponent() } let process = Process() process.executableURL = directory.appendingPathComponent("StateTestProcess") - process.arguments = [fixture.root.path, command, argument, fixture.store.scope.rawValue] + process.arguments = [ + fixture.root.path, command, argument, "--scope", fixture.store.scope.rawValue, + ] + let scratch = fixture.root.appendingPathComponent("process-temporary") + try FileManager.default.createDirectory(at: scratch, withIntermediateDirectories: true) + var environment = ProcessInfo.processInfo.environment + environment["TMPDIR"] = scratch.path + "/" + process.environment = environment try process.run() return process } -private func waitFor(_ name: String, fixture: UpdateFixture, child: Process) throws { +func waitFor(_ name: String, fixture: UpdateFixture, child: Process) throws { let file = fixture.root.appendingPathComponent(name) - let deadline = Date().addingTimeInterval(20) - while !FileManager.default.fileExists(atPath: file.path), Date() < deadline, child.isRunning { - Thread.sleep(forTimeInterval: 0.01) - } - try #require(FileManager.default.fileExists(atPath: file.path)) + try ProcessWait.marker(file, child: child, root: fixture.root) } -private func terminate(_ process: Process) { - if process.isRunning { - kill(process.processIdentifier, SIGKILL) - process.waitUntilExit() +/// A child that survives the termination deadline fails the test instead of blocking the run. +func terminate(_ process: Process) { + do { try ProcessWait.terminate(process) } catch { Issue.record(error) } +} + +extension UpdateTransactionTests { + @Test func combinedNativeFileAndSharedDocumentFaultRollBackTogether() throws { + let fixture = try UpdateFixture() + let config = fixture.root.appendingPathComponent(".codex/config.toml") + let role = fixture.root.appendingPathComponent(".codex/agents/researcher.toml") + try fixture.write("# User setting\ntheme = 'fixture'\n", to: config) + let initial = Declaration(components: [ + .subagent( + name: "researcher", description: "Research sources", prompt: .literal("Before."), + agents: [.codex]), + .mcpServer(name: "db", transport: .stdio(.init(executable: "before")), agents: [.codex]), + ]) + try fixture.store.save(declaration: initial, ledger: ResolvedLedger()) + _ = try fixture.apply() + let files = [fixture.store.declarationURL, fixture.store.resolvedURL, config, role] + let before = try files.map { try Data(contentsOf: $0) } + let next = Declaration(components: [ + .subagent( + name: "researcher", description: "Research sources", prompt: .literal("After."), + agents: [.codex]), + .mcpServer(name: "db", transport: .stdio(.init(executable: "after")), agents: [.codex]), + ]) + var reached = false + let completion = UpdateOperations.perform( + .init(operation: .declaration(next)), environment: fixture.environment, + checkpoint: { step in + if step == TransactionCheckpoint.progress(0, .applied).name { + reached = true + throw CoreError.invalidState("combined native fault fixture") + } + }, { try $0.apply() }) + #expect(reached) + #expect(completion.disposition == .rolledBack) + #expect(!completion.recovery.pending) + #expect(throws: UpdateApplyError.self) { try completion.result.get() } + #expect(try files.map { try Data(contentsOf: $0) } == before) } } diff --git a/Tests/AgentsUpdatesTests/WatchConfirmationTests.swift b/Tests/AgentsUpdatesTests/WatchConfirmationTests.swift new file mode 100644 index 0000000..dd3f89e --- /dev/null +++ b/Tests/AgentsUpdatesTests/WatchConfirmationTests.swift @@ -0,0 +1,300 @@ +import AgentsManifest +import AgentsSkills +import AgentsUpdates +import Foundation +import Testing + +@testable import AgentsCore + +struct WatchConfirmationTests { + @Test func newSubscriptionPreviewIsPureAndConfirmationUsesTheExactContent() throws { + let f = try UpdateFixture() + let operations = SkillOperations.watchOperations() + let before = try FileHash.folderHash(f.root) + let preview = try operations.previewAdd( + f.repo.path, alias: "watched", environment: f.environment) + let repeated = try operations.previewAdd( + f.repo.path, alias: "watched", environment: f.environment) + #expect(preview.displayedFingerprint == repeated.displayedFingerprint) + #expect(preview.readLocations.map(\.path).contains(f.repo.path)) + #expect(try FileHash.folderHash(f.root) == before) + #expect(!FileManager.default.fileExists(atPath: f.store.directory.path)) + let completion = UpdateOperations.performWatch(preview) + #expect(completion.disposition == .committed && !completion.recovery.pending) + #expect(try completion.result.get().seen == preview.seen) + #expect(try f.store.loadWatch().sources[preview.sourceID]?.seen == preview.seen) + #expect(try f.store.loadDeclaration().watch == ["watched"]) + #expect(!FileManager.default.fileExists(atPath: f.target().path)) + let removal = try operations.previewRemove("watched", environment: f.environment) + let subscribed = try FileHash.folderHash(f.root) + _ = try operations.previewRemove("watched", environment: f.environment) + #expect(try FileHash.folderHash(f.root) == subscribed) + let removed = UpdateOperations.performWatch(removal) + #expect(removed.disposition == .committed && !removed.recovery.pending) + #expect(try removed.result.get().seen == nil) + #expect(try f.store.loadWatch().sources.isEmpty) + #expect(try f.store.loadDeclaration().sources["watched"] != nil) + } + + @Test func upstreamChangesAfterPreviewCannotBeAcknowledged() throws { + let f = try UpdateFixture() + try f.declare() + let operations = SkillOperations.watchOperations() + let preview = try operations.previewAdd("fixture", environment: f.environment) + let before = try f.snapshot() + try f.advance() + let completion = UpdateOperations.performWatch(preview) + #expect(completion.disposition == .unchanged && !completion.recovery.pending) + #expect(throws: (any Error).self) { try completion.result.get() } + #expect(try f.snapshot() == before) + #expect(try f.store.loadWatch().sources.isEmpty) + } + + @Test func declarationEditsAfterPreviewPreventSubscriptionPublication() throws { + let f = try UpdateFixture() + try f.declare() + let operations = SkillOperations.watchOperations() + let preview = try operations.previewAdd("fixture", environment: f.environment) + let edited = + try String(contentsOf: f.store.declarationURL, encoding: .utf8) + "# External edit.\n" + try f.write(edited, to: f.store.declarationURL) + let before = try f.snapshot() + let completion = UpdateOperations.performWatch(preview) + #expect(completion.disposition == .unchanged && !completion.recovery.pending) + #expect(throws: (any Error).self) { try completion.result.get() } + #expect(try f.snapshot() == before) + #expect(try f.store.loadDeclaration().watch == nil) + } + + @Test func removalRejectsAnAcknowledgmentChangedAfterConfirmation() throws { + let f = try UpdateFixture() + let operations = SkillOperations.watchOperations() + _ = try operations.add(f.repo.path, alias: "watched", environment: f.environment) + let preview = try operations.previewRemove("watched", environment: f.environment) + try f.advance() + _ = try operations.seen("watched", environment: f.environment) + let before = try f.snapshot() + let completion = UpdateOperations.performWatch(preview) + #expect(completion.disposition == .unchanged && !completion.recovery.pending) + #expect(throws: (any Error).self) { try completion.result.get() } + #expect(try f.snapshot() == before) + #expect(try f.store.loadDeclaration().watch == ["watched"]) + } + + @Test(arguments: [false, true]) + func committedWatchDisposalFailureHasAnOuterTerminalAndRetainedRecovery(_ acknowledging: Bool) + throws + { + let f = try UpdateFixture() + let operations = SkillOperations.watchOperations() + let preview: WatchMutationPreview + if acknowledging { + _ = try operations.add(f.repo.path, alias: "watched", environment: f.environment) + try f.advance() + preview = operations.previewSeen( + try #require(operations.status(environment: f.environment).first)) + } else { + preview = try operations.previewAdd( + f.repo.path, alias: "watched", environment: f.environment) + } + let displaced = f.root.appendingPathComponent("displaced-watch") + let interrupted = WatchOperations( + discoverSkills: { _ in throw CoreError.invalidState("unexpected discovery") }, + fetchArtifacts: { _ in throw CoreError.invalidState("unexpected artifact fetch") }, + declarations: .manifest, + checkpoint: { [watchURL = f.store.watchURL] point in + if point == TransactionCheckpoint.phase(.committed).name { + try FileManager.default.moveItem(at: watchURL, to: displaced) + throw CoreError.invalidState("fixture disposal interruption") + } + }) + let completion = UpdateOperations.performWatch(preview, operations: interrupted) + #expect(completion.disposition == .committed && completion.recovery.pending) + #expect(throws: (any Error).self) { try completion.result.get() } + #expect(throws: (any Error).self) { + try operations.previewRemove("watched", environment: f.environment) + } + let blocked = UpdateOperations.performWatch(preview) + #expect(blocked.disposition == .unchanged && blocked.recovery.pending) + try FileManager.default.moveItem(at: displaced, to: f.store.watchURL) + let recovered = UpdateOperations.performWatch(preview) + #expect(recovered.disposition == .unchanged && recovered.recoveredBeforePreparation) + #expect(!recovered.recovery.pending) + #expect(try f.store.loadWatch().sources[preview.sourceID]?.seen == preview.seen) + } +} + +extension WatchConfirmationTests { + @Test(arguments: [InstallScope.project, .user]) + func displayedStatusRetainsDurableInputsAndAcknowledgesInItsCapturedScope(_ scope: InstallScope) + throws + { + let f = try UpdateFixture(scope: scope) + let operations = SkillOperations.watchOperations() + _ = try operations.add(f.repo.path, alias: "watched", scope: scope, environment: f.environment) + try f.advance() + let before = try f.snapshot() + let inspection = try operations.inspectStatus(scope: scope, environment: f.environment) + let displayed = try #require(inspection.statuses.first) + let diff = try operations.diff( + "watched", name: "demo", kind: .skill, scope: scope, environment: f.environment) + let expected = Set( + [f.store.declarationURL, f.store.resolvedURL, f.store.watchURL, f.repo].map(\.path)) + #expect(Set(inspection.readLocations.map(\.path)) == expected) + #expect(Set(displayed.readLocations.map(\.path)) == expected) + #expect(diff.readLocations == displayed.readLocations) + #expect(diff.changes.count == 1) + #expect(try f.snapshot() == before) + let preview = operations.previewSeen(diff) + #expect(preview == operations.previewSeen(displayed)) + let completion = UpdateOperations.performWatch(diff) + #expect(completion.disposition == .committed && !completion.recovery.pending) + #expect(!completion.recoveredBeforePreparation) + #expect(try completion.result.get().seen == displayed.current) + #expect(try f.store.loadWatch().sources[displayed.sourceID]?.seen == displayed.current) + #expect(!FileManager.default.fileExists(atPath: f.target().path)) + } + + @Test(arguments: ["content", "source", "declaration", "baseline"]) + func displayedAcknowledgmentRejectsChangedEvidence(_ changed: String) throws { + let f = try UpdateFixture() + let operations = SkillOperations.watchOperations() + _ = try operations.add(f.repo.path, alias: "watched", environment: f.environment) + try f.advance() + let displayed = try operations.diff("watched", environment: f.environment) + switch changed { + case "content": + try f.writeSource("later") + try f.commit() + case "source": + let other = f.root.appendingPathComponent("other-source") + try FileManager.default.copyItem(at: f.repo, to: other) + var declaration = try f.store.loadDeclaration() + declaration.sources["watched"]?.location = other.path + try f.store.save(declaration: declaration, ledger: f.store.loadLedger()) + case "declaration": + let bytes = try Data(contentsOf: f.store.declarationURL) + Data("# External edit.\n".utf8) + try bytes.write(to: f.store.declarationURL) + default: + _ = try operations.seen("watched", environment: f.environment) + } + let before = try f.snapshot() + let completion = UpdateOperations.performWatch(displayed) + #expect(completion.disposition == .unchanged && !completion.recovery.pending) + #expect(throws: (any Error).self) { try completion.result.get() } + #expect(try f.snapshot() == before) + } + + @Test(arguments: ["scope", "project", "home", "environment"]) + func displayedAcknowledgmentRejectsAnotherContext(_ changed: String) throws { + let f = try UpdateFixture() + let operations = SkillOperations.watchOperations() + _ = try operations.add(f.repo.path, alias: "watched", environment: f.environment) + let displayed = try operations.diff("watched", environment: f.environment) + var environment = f.environment + var scope = InstallScope.project + switch changed { + case "scope": scope = .user + case "project": environment.projectDirectory = f.root.appendingPathComponent("other-project") + case "home": environment.homeDirectory = f.root.appendingPathComponent("other-home") + default: environment.environment["WATCH_TEST_CONTEXT"] = "changed" + } + let before = try FileHash.folderHash(f.root) + #expect(throws: (any Error).self) { + try operations.seen(displayed, scope: scope, environment: environment) + } + #expect(try FileHash.folderHash(f.root) == before) + } + + @Test func unrelatedSecretVariationPreservesPublicFingerprintAndPrivateContextGuard() throws { + let f = try UpdateFixture() + let operations = SkillOperations.watchOperations() + _ = try operations.add(f.repo.path, alias: "watched", environment: f.environment) + var originalEnvironment = f.environment + originalEnvironment.environment["UNRELATED_CREDENTIAL"] = "first-private-value" + var changedEnvironment = originalEnvironment + changedEnvironment.environment["UNRELATED_CREDENTIAL"] = "second-private-value" + let original = try operations.diff("watched", environment: originalEnvironment) + let changed = try operations.diff("watched", environment: changedEnvironment) + let originalPreview = operations.previewSeen(original) + let changedPreview = operations.previewSeen(changed) + #expect(originalPreview.displayedFingerprint == changedPreview.displayedFingerprint) + #expect(originalPreview != changedPreview) + let before = try f.snapshot() + #expect(throws: (any Error).self) { + try operations.seen(original, environment: changedEnvironment) + } + #expect(try f.snapshot() == before) + let completion = UpdateOperations.performWatch(original) + #expect(completion.disposition == .committed && !completion.recovery.pending) + #expect(try completion.result.get().seen == original.current) + } + + @Test func displayedAcknowledgmentReportsRollbackAfterPublicationFailure() throws { + let f = try UpdateFixture() + let operations = SkillOperations.watchOperations() + _ = try operations.add(f.repo.path, alias: "watched", environment: f.environment) + try f.advance() + let displayed = try operations.diff("watched", environment: f.environment) + let before = try f.snapshot() + let interrupted = WatchOperations( + discoverSkills: { _ in [] }, fetchArtifacts: { _ in [] }, declarations: .manifest, + checkpoint: { point in + if point == TransactionCheckpoint.publication(0, .exchanged).name { + throw CoreError.invalidState("fixture publication interruption") + } + }) + let completion = UpdateOperations.performWatch(displayed, operations: interrupted) + #expect(completion.disposition == .rolledBack && !completion.recovery.pending) + #expect(throws: (any Error).self) { try completion.result.get() } + #expect(try f.snapshot() == before) + } +} + +extension WatchConfirmationTests { + @Test func artifactAcknowledgmentUsesTheOuterOutcomeAndRevalidatesDigests() throws { + let f = try UpdateFixture() + func operations(_ body: String, failPreparation: Bool = false) -> WatchOperations { + let bytes = Data(body.utf8) + let digest = "sha256:" + FileHash.sha256Hex(data: bytes) + return WatchOperations( + discoverSkills: { _ in [] }, + fetchArtifacts: { _ in + [ + WatchArtifact( + name: "demo", + artifact: LockedArtifact( + type: .skillMD, url: "https://example.invalid/demo.md", digest: digest), + files: ["SKILL.md": bytes], payloads: [digest: bytes]) + ] + }, declarations: .manifest, + checkpoint: { point in + if failPreparation && point == "watch.artifact.0.content.journal.committed" { + throw CoreError.invalidState("fixture artifact preparation interruption") + } + }) + } + let original = operations("original") + _ = try original.add( + "https://example.invalid/index", alias: "watched", environment: f.environment) + let originalStatus = try original.diff("watched", environment: f.environment) + let advanced = operations("advanced") + let before = try f.snapshot() + let stale = UpdateOperations.performWatch(originalStatus, operations: advanced) + #expect(stale.disposition == .unchanged && !stale.recovery.pending) + #expect(throws: (any Error).self) { try stale.result.get() } + #expect(try f.snapshot() == before) + let displayed = try advanced.diff("watched", environment: f.environment) + #expect( + Set(displayed.readLocations.map(\.path)) + == Set([f.store.declarationURL, f.store.resolvedURL, f.store.watchURL].map(\.path))) + let interrupted = UpdateOperations.performWatch( + displayed, operations: operations("advanced", failPreparation: true)) + #expect(interrupted.disposition == .unchanged && !interrupted.recovery.pending) + #expect(throws: (any Error).self) { try interrupted.result.get() } + #expect(try f.snapshot() == before) + let completed = UpdateOperations.performWatch(displayed, operations: advanced) + #expect(completed.disposition == .committed && !completed.recovery.pending) + #expect(try completed.result.get().seen == displayed.current) + } +} diff --git a/Tests/ComponentsTests/ArtifactLinkingTests.swift b/Tests/ComponentsTests/ArtifactLinkingTests.swift new file mode 100644 index 0000000..067e957 --- /dev/null +++ b/Tests/ComponentsTests/ArtifactLinkingTests.swift @@ -0,0 +1,365 @@ +import AgentsCore +import AgentsManifest +import Foundation +import Testing + +@testable import Components + +@Suite("Indexed component resources", .serialized) +struct ArtifactLinkingTests { + @Test func nestedArtifactFilesAreScopedAndContained() throws { + let fixture = try LinkFixture() + var borrowed: URL? + try SourceResolutionSession.withTemporaryRead(store: fixture.store) { session in + let view = try session.fileSnapshot( + source: "https://example.invalid", revision: "fixture", + files: [ + "SKILL.md": Data("skill".utf8), "references/context.md": Data("context".utf8), + "scripts/run": Data("script".utf8), + ], executableFlags: ["scripts/run": true]) + borrowed = view.root + #expect(try Data(contentsOf: view.resource("references/context.md")) == Data("context".utf8)) + #expect(try FileHash.executableFlags(view.root)["scripts/run"] == true) + #expect(throws: CoreError.self) { + try session.fileSnapshot( + source: "https://example.invalid", revision: "unsafe", + files: ["../escape": Data()]) + } + } + #expect(!FileManager.default.fileExists(atPath: try #require(borrowed).path)) + } + + @Test(arguments: [InstallMode.copy, .link]) + func selectedIndexDownloadsAndRetainedClosuresAreIndependent(_ mode: InstallMode) throws { + let fixture = try LinkFixture() + let web = fixture.root.appendingPathComponent("web") + try FileManager.default.createDirectory(at: web, withIntermediateDirectories: true) + let server = try IndexHTTPServer(root: web) + defer { server.stop() } + let oldAlpha = try archive("alpha", body: "old alpha", fixture: fixture, web: web) + let oldBeta = try archive("beta", body: "old beta", fixture: fixture, web: web) + try index([("alpha", oldAlpha), ("beta", oldBeta)], fixture: fixture, web: web) + let document = try fixture.document( + """ + version: 1 + sources: {web: {index: '\(server.url)'}} + components: [{kind: skills, source: web, select: [alpha, beta], mode: \(mode.rawValue)}] + """) + func freeze(pins: [ComponentKey: SourceRevision] = [:], previous: ResolvedLedger? = nil) throws + -> ResolvedLedger + { + try ComponentLinker.withLinkedComponents( + document: document, store: fixture.store, platform: .macOS, + directPins: pins, retaining: previous + ) { graph, session in + try LedgerFreeze.freeze( + graph, session: session, + locations: .init(sources: [ + "local:" + fixture.project.path: .init(kind: .registered, root: "project", path: ".") + ]), limits: .standard) + } + } + let original = try freeze() + let previous = try ResolvedLedgerCodec.decode( + ResolvedLedgerCodec.encode(original, limits: .standard), limits: .standard) + let beta = try #require(previous.components.values.first { $0.name == "beta" }) + #expect(previous.sources[beta.source]?.revision == oldBeta) + let betaResourceID = try #require(beta.resources.first) + let betaResource = try #require(previous.resources[betaResourceID]) + #expect(betaResource.entries.contains { $0.path == "references/context.md" }) + #expect(betaResource.entries.contains { $0.path == "scripts/run" && $0.executable }) + let key = ComponentKey( + source: "local:" + fixture.project.path, root: ".", group: nil, + kind: .skills, name: "beta") + let newAlpha = try archive("alpha", body: "new alpha", fixture: fixture, web: web) + // The protected member disappears from the index and its exact download is unavailable. + try FileManager.default.removeItem(at: web.appendingPathComponent("beta.tar.gz")) + try index([("alpha", newAlpha)], fixture: fixture, web: web) + let next = try freeze(pins: [key: .init(revision: oldBeta)], previous: previous) + let retained = try #require(next.components.values.first { $0.name == "beta" }) + #expect(retained == beta) + let retainedResourceID = try #require(retained.resources.first) + #expect(next.resources[retainedResourceID] == betaResource) + let alpha = try #require(next.components.values.first { $0.name == "alpha" }) + #expect(next.sources[alpha.source]?.revision == newAlpha) + let nested = try #require( + betaResource.entries.first { $0.path == "references/context.md" }?.object) + #expect(next.contentObjects[nested] == Data("old beta context".utf8)) + #expect(throws: LinkError.self) { try freeze(pins: [key: .init(revision: oldBeta)]) } + // A different advertised artifact must not be fetched for the protected member. + try index( + [("alpha", newAlpha), ("beta", "sha256:" + String(repeating: "a", count: 64))], + fixture: fixture, web: web) + let advertised = try freeze(pins: [key: .init(revision: oldBeta)], previous: previous) + #expect(advertised.components.values.first { $0.name == "beta" } == beta) + var replay = next + #if os(macOS) + let platform = "macos" + #else + let platform = "linux" + #endif + replay.lowerings = replay.components.sorted { $0.key < $1.key }.map { id, component in + .init( + id: component.name, format: "agents/skill@1", inputs: [id], + resources: component.resources, deployments: [], + layout: .init(object: ["name": .init(component.name)]), platform: platform, artifacts: []) + } + replay = try LedgerReplay.prepareLowerings( + replay, store: fixture.store, + roots: ["project": fixture.project], limits: .standard) + replay = try ResolvedLedgerCodec.decode( + ResolvedLedgerCodec.encode(replay, limits: .standard), limits: .standard) + server.stop() + try FileManager.default.removeItem(at: web) + try LedgerReplay.withReplay( + replay, store: fixture.store, roots: ["project": fixture.project], limits: .standard + ) { artifacts in + let betaTree = try #require(artifacts.first { $0.name == "beta" }?.tree) + #expect( + try Data(contentsOf: betaTree.appendingPathComponent("references/context.md")) + == Data("old beta context".utf8)) + #expect(try FileHash.executableFlags(betaTree)["scripts/run"] == true) + } + // A wholly retained named selection works without an index or server. + let offline = try fixture.document( + """ + version: 1 + sources: {web: {index: '\(server.url)'}} + components: [{kind: skills, source: web, select: [beta], mode: copy}] + """) + try ComponentLinker.withLinkedComponents( + document: offline, store: fixture.store, platform: .macOS, + directPins: [key: .init(revision: oldBeta)], retaining: previous + ) { graph, session in + #expect(graph.components.count == 1) + let resource = try #require(graph.components.first?.resources.first) + #expect( + try FileHash.folderHash(session.resource(snapshot: resource.snapshot, path: resource.path)) + == String(betaResource.hash.dropFirst(7))) + } + let rebound = try fixture.document( + """ + version: 1 + sources: {web: {index: '\(server.url)/other'}} + components: [{kind: skills, source: web, select: [beta], mode: copy}] + """) + #expect(throws: LinkError.self) { + try ComponentLinker.withLinkedComponents( + document: rebound, store: fixture.store, platform: .macOS, + directPins: [key: .init(revision: oldBeta)], retaining: previous + ) { _, _ in } + } + var corrupt = previous + corrupt.resources[betaResourceID]?.hash = "sha256:" + String(repeating: "0", count: 64) + #expect(throws: LinkError.self) { + try ComponentLinker.withLinkedComponents( + document: offline, store: fixture.store, platform: .macOS, + directPins: [key: .init(revision: oldBeta)], retaining: corrupt + ) { _, _ in } + } + } + + @Test(arguments: [InstallScope.project, .user]) + func retainedAllMembersBelongToTheirRecordedIndexes(_ scope: InstallScope) throws { + let fixture = try LinkFixture() + let store = StateStore(scope: scope, environment: fixture.environment) + let packageRoot = scope == .project ? fixture.project : store.directory + let webA = fixture.root.appendingPathComponent("web-a") + let webB = fixture.root.appendingPathComponent("web-b") + for web in [webA, webB] { + try FileManager.default.createDirectory(at: web, withIntermediateDirectories: true) + } + let serverA = try IndexHTTPServer(root: webA) + defer { serverA.stop() } + let serverB = try IndexHTTPServer(root: webB) + defer { serverB.stop() } + let alphaDigest = try archive("alpha", body: "alpha original", fixture: fixture, web: webA) + let betaDigest = try archive("beta", body: "beta original", fixture: fixture, web: webB) + try index([("alpha", alphaDigest)], fixture: fixture, web: webA) + try index([("beta", betaDigest)], fixture: fixture, web: webB) + let document = try fixture.document( + """ + version: 1 + sources: {a: {index: '\(serverA.url)'}, b: {index: '\(serverB.url)'}} + components: [{kind: skills, source: a}, {kind: skills, source: b}] + """) + func freeze(pins: [ComponentKey: SourceRevision] = [:], previous: ResolvedLedger? = nil) throws + -> ResolvedLedger + { + try ComponentLinker.withLinkedComponents( + document: document, store: store, platform: .macOS, + directPins: pins, retaining: previous + ) { graph, session in + try LedgerFreeze.freeze( + graph, session: session, + locations: .init(sources: [ + "local:" + packageRoot.path: .init( + kind: .registered, root: scope == .project ? "project" : "state", path: ".") + ]), limits: .standard) + } + } + let previous = try ResolvedLedgerCodec.decode( + ResolvedLedgerCodec.encode(freeze(), limits: .standard), limits: .standard) + func key(_ name: String) -> ComponentKey { + .init( + source: "local:" + packageRoot.path, root: ".", group: nil, kind: .skills, name: name) + } + let pins: [ComponentKey: SourceRevision] = [ + key("alpha"): .init(revision: alphaDigest), key("beta"): .init(revision: betaDigest), + ] + // Membership comes from each pin's recorded index, even after its download disappears. + try FileManager.default.removeItem(at: webA.appendingPathComponent("alpha.tar.gz")) + try FileManager.default.removeItem(at: webB.appendingPathComponent("beta.tar.gz")) + try index([], fixture: fixture, web: webA) + try index([], fixture: fixture, web: webB) + let retained = try freeze(pins: pins, previous: previous) + #expect(retained.components == previous.components) + #expect(retained.resources == previous.resources) + #expect(retained.contentObjects == previous.contentObjects) + let freshAlpha = try archive("alpha", body: "alpha fresh", fixture: fixture, web: webA) + try index([("alpha", freshAlpha)], fixture: fixture, web: webA) + let mixed = try freeze(pins: [key("beta"): .init(revision: betaDigest)], previous: previous) + let beta = try #require(previous.components.values.first { $0.name == "beta" }) + #expect(mixed.components.values.first { $0.name == "beta" } == beta) + for id in beta.resources { #expect(mixed.resources[id] == previous.resources[id]) } + let alpha = try #require(mixed.components.values.first { $0.name == "alpha" }) + #expect(mixed.sources[alpha.source]?.revision == freshAlpha) + var missingPin = pins + missingPin[key("alpha")] = .init(revision: "sha256:" + String(repeating: "0", count: 64)) + #expect(throws: LinkError.self) { try freeze(pins: missingPin, previous: previous) } + var corrupt = previous + let betaResource = try #require(beta.resources.first) + corrupt.resources[betaResource]?.hash = "sha256:" + String(repeating: "0", count: 64) + #expect(throws: LinkError.self) { try freeze(pins: pins, previous: corrupt) } + } + + @Test func catalogIndexSkillCarriesCapturedRestrictionsAndResourceEffects() throws { + let fixture = try LinkFixture() + let web = fixture.root.appendingPathComponent("web") + try FileManager.default.createDirectory(at: web, withIntermediateDirectories: true) + let server = try IndexHTTPServer(root: web) + defer { server.stop() } + let digest = try archive( + "alpha", body: "restricted", fixture: fixture, web: web, + restrictions: "agents: [codex]\n") + try index([("alpha", digest)], fixture: fixture, web: web) + let source = SourceDeclaration(kind: .wellKnown, location: server.url) + let catalog = try Components.SourceCatalog.inspect( + alias: "web", source: source, + store: fixture.store, platform: .macOS) + let choice = try #require(catalog.choices.first) + let graph = try #require(choice.graph) + let effect = try #require(graph.components.first) + #expect(effect.recipients == [.codex]) + #expect(effect.conditions.first?.agents == [.codex]) + #expect(effect.resources.first?.artifact?.digest == digest) + let document = try fixture.document( + """ + version: 1 + sources: {web: {index: '\(server.url)'}} + components: [{kind: skills, source: web, select: [alpha]}] + """) + try ComponentLinker.withLinkedComponents( + document: document, store: fixture.store, platform: .macOS + ) { elected, _ in + let actual = try #require(elected.components.first) + #expect(actual.snapshot == effect.snapshot) + #expect(actual.payload == effect.payload) + #expect(actual.conditions == effect.conditions) + #expect(actual.recipients == effect.recipients) + #expect(actual.resources == effect.resources) + } + } + + private func archive( + _ name: String, body: String, fixture: LinkFixture, web: URL, restrictions: String = "" + ) throws + -> String + { + let root = fixture.root.appendingPathComponent(name) + try fixture.write( + "---\nname: \(name)\ndescription: Fixture\n\(restrictions)---\n\(body)\n", to: "SKILL.md", + base: root) + try fixture.write(body + " context", to: "references/context.md", base: root) + try fixture.write("fixture script", to: "scripts/run", base: root) + try FileManager.default.setAttributes( + [.posixPermissions: 0o755], ofItemAtPath: root.appendingPathComponent("scripts/run").path) + let archive = web.appendingPathComponent(name + ".tar.gz") + if FileManager.default.fileExists(atPath: archive.path) { + try FileManager.default.removeItem(at: archive) + } + try ProcessRunner.run( + "/usr/bin/env", arguments: ["tar", "-czf", archive.path, "."], workingDirectory: root) + return "sha256:" + (try FileHash.sha256Hex(file: archive)) + } + + private func index(_ members: [(String, String)], fixture: LinkFixture, web: URL) throws { + let entries = members.map { name, digest in + [ + "name": name, "description": "Fixture", "type": "archive", "url": "/\(name).tar.gz", + "digest": digest, + ] + } + let bytes = try JSONSerialization.data(withJSONObject: [ + "$schema": "https://schemas.agentskills.io/discovery/0.2.0/schema.json", "skills": entries, + ]) + try fixture.write( + String(decoding: bytes, as: UTF8.self), to: ".well-known/agent-skills/index.json", base: web) + } +} + +private final class IndexHTTPServer { + private let process = Process() + private let output = Pipe() + let url: String + + init(root: URL) throws { + process.executableURL = URL(fileURLWithPath: "/usr/bin/perl") + process.arguments = [ + "-e", + #""" + use IO::Socket::INET; + use POSIX qw(SIG_SETMASK sigprocmask); + # The fixture's deadline and termination signals must be deliverable. + sigprocmask(SIG_SETMASK, POSIX::SigSet->new()) or die "sigprocmask: $!"; + alarm 120; + my $root = shift; + my $server = IO::Socket::INET->new(LocalAddr => '127.0.0.1', LocalPort => 0, Listen => 8, Proto => 'tcp') or die $!; + $| = 1; print $server->sockport, "\n"; + while (my $client = $server->accept()) { + my $request = <$client>; + my ($path) = $request =~ m{^GET (/[^ ]*) HTTP/}; + while (my $line = <$client>) { last if $line eq "\r\n"; } + my $bytes = ''; my $status = '404 Not Found'; + if (defined($path) && $path !~ /\.\./ && open(my $file, '<', "$root$path")) { + binmode $file; local $/; $bytes = <$file>; close $file; $status = '200 OK'; + } + print $client "HTTP/1.1 $status\r\nContent-Length: ", length($bytes), "\r\nConnection: close\r\n\r\n", $bytes; + close $client; + } + """#, root.path, + ] + process.standardOutput = output + try process.run() + output.fileHandleForWriting.closeFile() + var bytes = Data() + while let byte = try output.fileHandleForReading.read(upToCount: 1), !byte.isEmpty { + if byte == Data([10]) { break } + bytes.append(byte) + } + guard let port = Int(String(decoding: bytes, as: UTF8.self)) else { + process.waitUntilExit() + try? output.fileHandleForReading.close() + throw CoreError.invalidState("fixture listener unavailable") + } + url = "http://127.0.0.1:\(port)" + } + + func stop() { + if process.isRunning { + process.terminate() + process.waitUntilExit() + } + try? output.fileHandleForReading.close() + } +} diff --git a/Tests/ComponentsTests/Fixtures/MCPHTTPServer.py b/Tests/ComponentsTests/Fixtures/MCPHTTPServer.py new file mode 100644 index 0000000..d3ac125 --- /dev/null +++ b/Tests/ComponentsTests/Fixtures/MCPHTTPServer.py @@ -0,0 +1,93 @@ +"""Owned loopback fixture. Synthetic MCP frames; no external service/client.""" +import http.server,json,os,queue,socket,sys,threading,time +from pathlib import Path +mode,root=sys.argv[1],Path(sys.argv[2]) +messages=queue.Queue(maxsize=32) +record_lock=threading.Lock() +last_initialize=None +resume_reply=None + +def record(value): + with record_lock: + with (root/'wire.jsonl').open('a') as f:f.write(json.dumps(value)+'\n') + +def result(message): + method=message.get('method') + if method=='initialize': + return {'protocolVersion':'2025-11-25','capabilities':{'tools':{}},'serverInfo':{'name':'http-fixture','version':'1'}} + cursor=message.get('params',{}).get('cursor') + value={'tools':[{'name':'first' if not cursor else 'second','inputSchema':{'type':'object'}}]} + if not cursor:value['nextCursor']='next' + return value + +class Handler(http.server.BaseHTTPRequestHandler): + protocol_version='HTTP/1.1' + def log_message(self,*args):pass + def log_request_data(self,method): + record({'http':self.command,'path':self.path,'method':method, + 'authorization':self.headers.get('Authorization') is not None, + 'session':self.headers.get('Mcp-Session-Id'),'version':self.headers.get('MCP-Protocol-Version'), + 'lastEventID':self.headers.get('Last-Event-ID')}) + def empty(self,status,headers={}): + self.send_response(status) + for key,value in headers.items():self.send_header(key,value) + self.send_header('Content-Length','0');self.end_headers() + def do_POST(self): + global resume_reply,last_initialize + body=self.rfile.read(int(self.headers.get('Content-Length','0'))) + message=json.loads(body) + self.log_request_data(message.get('method','response')) + if mode=='auth':self.empty(401,{'WWW-Authenticate':'Basic realm="fixture"'});return + if mode=='forbidden':self.empty(403);return + if mode=='redirect':self.empty(307,{'Location':'http://localhost:%d/leak'%self.server.server_port});return + if 'id' not in message:self.empty(202);return + reply=json.dumps({'jsonrpc':'2.0','id':message['id'],'result':result(message)}).encode() + if mode.startswith('legacy'): + messages.put(reply);self.empty(202);return + self.send_response(200) + self.send_header('Mcp-Session-Id','fixture-session') + if mode=='json': + self.send_header('Content-Type','application/json');self.send_header('Content-Length',str(len(reply)));self.end_headers();self.wfile.write(reply);return + self.send_header('Content-Type','text/event-stream');self.send_header('Connection','close');self.end_headers() + try: + if mode=='pending-body': + while True:self.wfile.write(b'data: {"jsonrpc":"2.0","method":"notifications/progress","params":{"progressToken":"fixture","progress":1}}\n\n');self.wfile.flush();time.sleep(.01) + elif mode=='event-flood': + self.wfile.write(b'data: '+b'x'*65536);self.wfile.flush() + elif mode=='comment-flood': + while True:self.wfile.write(b':'+b'x'*255+b'\n');self.wfile.flush() + elif mode=='resume' and message['method']=='initialize': + resume_reply=reply + self.wfile.write(b'id: 1\nretry: 1\ndata: {"jsonrpc":"2.0","method":"notifications/progress","params":{"progressToken":"probe","progress":1}}\n\n') + self.wfile.write(b'id: 2\ndata: {\"jsonrpc\":') + self.wfile.flush() + else: + # Split a multiline data event inside its field name and use CRLF. + self.wfile.write(b'event: message\r\nid: response\r\nda');self.wfile.flush() + time.sleep(.005) + payload=b'\r\ndata: '.join(json.dumps(json.loads(reply),indent=1).encode().splitlines()) + self.wfile.write(b'ta: '+payload+b'\r\n\r\n');self.wfile.flush() + except (BrokenPipeError,ConnectionResetError):record({'peerClosed':True}) + self.close_connection=True + def do_GET(self): + self.log_request_data(None) + if mode=='resume' and self.headers.get('Last-Event-ID')!='1':self.empty(409);return + self.send_response(200);self.send_header('Content-Type','text/event-stream');self.send_header('Connection','close');self.end_headers() + try: + if mode=='resume': + self.wfile.write(b'event: message\nid: 2\ndata: '+resume_reply+b'\n\n');self.wfile.flush();self.close_connection=True;return + endpoint=('/messages' if mode!='legacy-cross' else 'http://localhost:%d/messages'%self.server.server_port).encode() + self.wfile.write(b'event: endpoint\ndata: '+endpoint+b'\n\n');self.wfile.flush() + while True: + try:reply=messages.get(timeout=.05);self.wfile.write(b'event: message\ndata: '+reply+b'\n\n') + except queue.Empty:self.wfile.write(b': heartbeat\n\n') + self.wfile.flush() + except (BrokenPipeError,ConnectionResetError):record({'peerClosed':True}) + self.close_connection=True + +server=http.server.ThreadingHTTPServer(('127.0.0.1',0),Handler) +server.daemon_threads=True +endpoint='http://127.0.0.1:%d/mcp'%server.server_port +(root/'endpoint.pending').write_text(endpoint) +os.replace(root/'endpoint.pending',root/'endpoint') +server.serve_forever() diff --git a/Tests/ComponentsTests/GeneratedPluginTests.swift b/Tests/ComponentsTests/GeneratedPluginTests.swift new file mode 100644 index 0000000..cfe2ae3 --- /dev/null +++ b/Tests/ComponentsTests/GeneratedPluginTests.swift @@ -0,0 +1,429 @@ +import AgentsManifest +import Foundation +import NativeDocuments +import Testing + +@testable import AgentsCore +@testable import Components + +@Suite("Frozen generated native plugins") +struct GeneratedPluginTests { + private var platform: DeclarationPlatform { + #if os(macOS) + .macOS + #else + .linux + #endif + } + + private func freeze( + _ fixture: LinkFixture, _ expression: String, scope: InstallScope = .project + ) throws -> ([LinkedComponent], LedgerFreeze.Result) { + let store = StateStore(scope: scope, environment: fixture.environment) + return try ComponentLinker.withLinkedComponents( + document: fixture.document(expression), store: store, platform: platform + ) { graph, session in + let locations = Dictionary( + (graph.sourceSnapshots + graph.declaringSnapshots).filter { + $0.source?.kind == .local && $0.container == nil + }.map { + ( + $0.snapshot.source, + LedgerLocation(kind: .absolute, path: String($0.snapshot.source.dropFirst(6))) + ) + }, uniquingKeysWith: { first, _ in first }) + return ( + graph.components, + try LedgerFreeze.freezeWithSources( + graph, session: session, locations: .init(sources: locations), limits: .standard) + ) + } + } + + private func budget() -> NativeDocumentBudget { + .init( + limits: .init( + storage: 32_000_000, work: 100_000_000, nodes: 100_000, depth: 128, + uninterruptedBytes: 1_000_000)) + } + + private func lower( + _ components: [LinkedComponent], _ frozen: LedgerFreeze.Result, + surface: NativeClientSurface = .claudeCode, scope: InstallScope = .project + ) throws -> LockedLowering { + try NativeGeneratedPluginLayoutV1.lower( + components.first { $0.key.kind == .plugin }!, members: components, frozen: frozen, + request: .init(surface: surface, scope: scope), id: "generated", platform: platform) + } + + @Test func frozenClosureColdReplayPreservesOrderBindingsResourcesAndRegistration() throws { + let fixture = try LinkFixture() + try fixture.write( + #"{"name":"source-name","mcpServers":{"server":{"command":"${CLAUDE_PLUGIN_ROOT}/bin/server","env":{"TOKEN":"private-source-canary"}}},"hooks":{"PreToolUse":[{"matcher":"Read","hooks":[{"type":"command","command":"first"}]},{"matcher":"Write","hooks":[{"type":"command","command":"second"}]}]}}"#, + to: "bundle/.claude-plugin/plugin.json", base: fixture.project) + try fixture.write( + "---\ndescription: Review exactly\n---\nLiteral source body\n", + to: "bundle/commands/review.md", base: fixture.project) + try fixture.write( + "---\nname: inspect\ndescription: Inspect\n---\nInspect exact sources\n", + to: "bundle/agents/inspect.md", base: fixture.project) + try fixture.write( + "---\nname: helper\ndescription: Help\n---\nSkill body\n", + to: "bundle/skills/helper/SKILL.md", base: fixture.project) + try fixture.write( + "#!/bin/sh\n# source-owned, never executed\n", to: "bundle/bin/server", base: fixture.project) + try FileManager.default.setAttributes( + [.posixPermissions: 0o755], + ofItemAtPath: fixture.project.appendingPathComponent("bundle/bin/server").path) + let (components, frozen) = try freeze( + fixture, + """ + version: 1 + components: + - {kind: plugin, name: selected, source: ".", path: bundle, agents: ["claude-code"]} + - {kind: command, name: review, description: Independent, prompt: Direct body, agents: ["claude-code"]} + """) + var ledger = frozen.ledger + ledger.lowerings = [try lower(components, frozen)] + #expect(ledger.lowerings[0].inputs.count == components.count - 1) + #expect( + !ledger.occurrences.filter { ledger.lowerings[0].inputs.contains($0.component) }.contains { + $0.id == components.last!.origins[0].occurrence + }) + ledger = try LedgerReplay.prepareLowerings( + ledger, store: fixture.store, roots: [:], limits: .standard) + let encoded = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + #expect(!String(decoding: encoded, as: UTF8.self).contains("private-source-canary")) + let expected = ledger.lowerings[0].artifacts + try FileManager.default.removeItem(at: fixture.project) + ledger = try ResolvedLedgerCodec.decode(encoded, limits: .standard) + try LedgerReplay.withReplay(ledger, store: fixture.store, roots: [:], limits: .standard) { + artifacts in + #expect(try artifacts.map { try $0.digest(limits: .standard) } == expected) + let contribution = try NativeGeneratedPluginContribution.decode( + ledger.lowerings[0], ledger: ledger, artifacts: artifacts, limits: .standard) + #expect(contribution.route == .claudeSkillPlugin) + #expect(contribution.directory == "selected") + #expect(contribution.recipients == [.claudeCode]) + #expect(Set(contribution.knownReaders) == [.claudeCode, .cursor]) + #expect( + contribution.members.flatMap(\.occurrences) + == ledger.occurrences[0].pluginExpansion!.children) + var values: [String: Data] = [:] + for member in contribution.members { + if case .mcp(let server) = member.content { + for binding in server.bindings { + if case .secret(let name) = binding.binding { + values[name] = Data("resolved-private-value".utf8) + } + } + } + } + let paths = Dictionary( + uniqueKeysWithValues: contribution.resourcePlacements.map { + ($0.resource, "/registered/selected/" + $0.path) + }) + let bundle = try contribution.stagedBundle( + bindings: RuntimeBindingValues(values), environment: fixture.environment, + resourcePaths: paths, budget: budget()) + #expect( + String(decoding: bundle.files["commands/review.md"]!, as: UTF8.self).hasSuffix( + "Literal source body\n")) + guard case .object(let manifest) = bundle.documents[contribution.manifestPath], + case .object(let events) = manifest["hooks"], + case .array(let groups) = events["PreToolUse"] + else { + Issue.record("missing native hook groups") + return + } + #expect(groups.count == 2) + guard case .object(let first) = groups[0], case .object(let second) = groups[1] else { + Issue.record("missing hook metadata") + return + } + #expect(first["matcher"] == .string("Read")) + #expect(second["matcher"] == .string("Write")) + #expect(contribution.resourcePlacements.contains { $0.path == "skills/helper" }) + #expect( + contribution.resources.values.contains { + $0.entries.contains { $0.kind == .file && $0.executable } + }) + var changed = artifacts + changed[0].values!.object!["members"]!.array!.removeLast() + #expect(throws: (any Error).self) { + try NativeGeneratedPluginContribution.decode( + ledger.lowerings[0], ledger: ledger, artifacts: changed, limits: .standard) + } + } + var missing = frozen + missing.ledger.occurrences[0].pluginExpansion = nil + #expect(throws: (any Error).self) { try lower(components, missing) } + } + + @Test func explicitEmptySelectionHasSealedManifestAndNoAdoptedChildren() throws { + let fixture = try LinkFixture() + try fixture.write( + #"{"name":"upstream"}"#, to: "bundle/.claude-plugin/plugin.json", base: fixture.project) + try fixture.write( + "---\ndescription: Unselected\n---\nNever included\n", to: "bundle/commands/unselected.md", + base: fixture.project) + let (components, frozen) = try freeze( + fixture, + """ + version: 1 + components: + - {kind: plugin, name: empty, source: ".", path: bundle, select: [], agents: ["claude-code"]} + """) + var ledger = frozen.ledger + ledger.lowerings = [try lower(components, frozen)] + ledger = try LedgerReplay.prepareLowerings( + ledger, store: fixture.store, roots: [:], limits: .standard) + try LedgerReplay.withReplay(ledger, store: fixture.store, roots: [:], limits: .standard) { + artifacts in + let result = try NativeGeneratedPluginContribution.decode( + ledger.lowerings[0], ledger: ledger, artifacts: artifacts, limits: .standard) + #expect(result.members.isEmpty) + #expect(result.resources.isEmpty) + let bundle = try result.stagedBundle( + bindings: RuntimeBindingValues([:]), environment: fixture.environment, resourcePaths: [:], + budget: budget()) + #expect(bundle.files.isEmpty) + #expect( + bundle.documents == [".claude-plugin/plugin.json": .object(["name": .string("empty")])]) + } + } + + @Test func cursorPluginCommandUsesPluginScopeAndNativePlainBody() throws { + let fixture = try LinkFixture() + let store = StateStore(scope: .user, environment: fixture.environment) + try fixture.write( + #"{"name":"upstream"}"#, to: "bundle/.cursor-plugin/plugin.json", base: store.directory) + try fixture.write("Exact plain body\n", to: "bundle/commands/review.md", base: store.directory) + try fixture.write( + #"{"mcpServers":{"native":{"command":"fixture-server"}}}"#, + to: "bundle/mcp.json", base: store.directory) + try fixture.write( + #"{"version":1,"hooks":{"preToolUse":[{"type":"command","command":"fixture-hook"}]}}"#, + to: "bundle/hooks/hooks.json", base: store.directory) + let (components, frozen) = try freeze( + fixture, + """ + version: 1 + components: + - {kind: plugin, name: selected, source: ".", path: bundle, agents: [cursor]} + """, scope: .user) + var ledger = frozen.ledger + ledger.lowerings = [try lower(components, frozen, surface: .cursorEditor, scope: .user)] + ledger = try LedgerReplay.prepareLowerings(ledger, store: store, roots: [:], limits: .standard) + try LedgerReplay.withReplay(ledger, store: store, roots: [:], limits: .standard) { artifacts in + let result = try NativeGeneratedPluginContribution.decode( + ledger.lowerings[0], ledger: ledger, artifacts: artifacts, limits: .standard) + #expect(result.route == .cursorLocalPlugin) + let bundle = try result.stagedBundle( + bindings: RuntimeBindingValues([:]), environment: fixture.environment, resourcePaths: [:], + budget: budget(), cursorCommandShell: .posix) + #expect(bundle.files["commands/review.md"] == Data("Exact plain body\n".utf8)) + guard case .object(let manifest) = bundle.documents[result.manifestPath] else { + Issue.record("missing manifest") + return + } + #expect(manifest["mcpServers"] == .string("./mcp.json")) + #expect(manifest["hooks"] == .string("./hooks/hooks.json")) + #expect(bundle.documents["mcp.json"] != nil) + #expect(bundle.documents["hooks/hooks.json"] != nil) + } + } + @Test func independentParentsKeepSeparateMemberOwnersAndNativeLSPFields() throws { + let fixture = try LinkFixture() + try fixture.write( + #"{"name":"producer","lspServers":{"native-lsp":{"command":"fixture-lsp","extensionToLanguage":{".fixture":"fixture"},"restartOnCrash":true,"requestTimeout":1200}}}"#, + to: "bundle/.claude-plugin/plugin.json", base: fixture.project) + let (components, frozen) = try freeze( + fixture, + """ + version: 1 + components: + - {kind: plugin, name: first, source: ".", path: bundle, agents: ["claude-code"]} + - {kind: plugin, name: second, source: ".", path: bundle, agents: ["claude-code"]} + """) + let parents = components.filter { $0.key.kind == .plugin } + var ledger = frozen.ledger + ledger.lowerings = try parents.enumerated().map { index, parent in + try NativeGeneratedPluginLayoutV1.lower( + parent, members: components, frozen: frozen, + request: .init(surface: .claudeCode, scope: .project), id: "parent/" + String(index), + platform: platform) + } + ledger = try LedgerReplay.prepareLowerings( + ledger, store: fixture.store, roots: [:], limits: .standard) + try LedgerReplay.withReplay(ledger, store: fixture.store, roots: [:], limits: .standard) { + artifacts in + var ownerSets: [Set] = [] + for lowering in ledger.lowerings { + let result = try NativeGeneratedPluginContribution.decode( + lowering, ledger: ledger, + artifacts: artifacts.filter { $0.name == lowering.id }, limits: .standard) + ownerSets.append(Set(result.members.flatMap(\.occurrences))) + let bundle = try result.stagedBundle( + bindings: RuntimeBindingValues([:]), environment: fixture.environment, resourcePaths: [:], + budget: budget()) + guard case .object(let manifest) = bundle.documents[result.manifestPath], + case .object(let servers) = manifest["lspServers"], + case .object(let server) = servers["native-lsp"] + else { + Issue.record("missing native LSP fields") + return + } + #expect(server["requestTimeout"] == .integer(1200)) + #expect(server["restartOnCrash"] == .boolean(true)) + } + #expect(ownerSets.count == 2) + #expect(ownerSets[0].isDisjoint(with: ownerSets[1])) + var corrupted = ledger + corrupted.lowerings[0].layout.object!["members"]!.array![0].object!["occurrences"] = + .init(array: ownerSets[1].map { .init(integer: $0) }) + #expect(throws: (any Error).self) { + try NativeGeneratedPluginContribution.decode( + corrupted.lowerings[0], ledger: corrupted, + artifacts: artifacts.filter { $0.name == ledger.lowerings[0].id }, limits: .standard) + } + } + } + + @Test(arguments: [String?.none, "1.2.3"], [false, true]) + func geminiUsesFrozenVersionAndNativeExtensionFiles( + authoredVersion: String?, emptySelection: Bool + ) throws { + let fixture = try LinkFixture() + let store = StateStore(scope: .user, environment: fixture.environment) + let producerVersion = "9.0.0-e\u{301}" + try fixture.write( + """ + {"name":"upstream","version":"\(producerVersion)","mcpServers":{"native":{"command":"fixture-server"}}} + """, + to: "extension/gemini-extension.json", base: store.directory) + try fixture.write( + "description = \"Native review\"\nprompt = \"Literal review body\"\n".replacingOccurrences( + of: "\\", with: ""), + to: "extension/commands/review.toml", base: store.directory) + let (components, frozen) = try freeze( + fixture, + """ + version: 1 + components: + - kind: plugin + name: selected + source: "." + path: extension + agents: [gemini-cli] + \(emptySelection ? "select: []" : "") + native: + gemini-cli: + description: Consumer description + \(authoredVersion.map { "version: \"\($0)\"" } ?? "") + """, scope: .user) + let expectedVersion = authoredVersion ?? producerVersion + let parent = try #require(frozen.ledger.components.values.first { $0.kind == "plugin" }) + let effective = try #require( + parent.payload.object?["native"]?.object?["gemini-cli"]? + .object?["version"]?.text) + #expect(effective.utf8.elementsEqual(expectedVersion.utf8)) + var ledger = frozen.ledger + ledger.lowerings = [try lower(components, frozen, surface: .geminiCLI, scope: .user)] + ledger = try LedgerReplay.prepareLowerings(ledger, store: store, roots: [:], limits: .standard) + let encoded = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + try FileManager.default.removeItem(at: store.directory.appendingPathComponent("extension")) + ledger = try ResolvedLedgerCodec.decode(encoded, limits: .standard) + try LedgerReplay.withReplay(ledger, store: store, roots: [:], limits: .standard) { artifacts in + let result = try NativeGeneratedPluginContribution.decode( + ledger.lowerings[0], ledger: ledger, + artifacts: artifacts, limits: .standard) + #expect(result.route == .geminiExtension) + let bundle = try result.stagedBundle( + bindings: RuntimeBindingValues([:]), environment: fixture.environment, + resourcePaths: [:], budget: budget()) + guard case .object(let manifest) = bundle.documents["gemini-extension.json"] else { + Issue.record("missing extension") + return + } + guard case .string(let version) = manifest["version"] else { + Issue.record("missing extension version") + return + } + #expect(version.utf8.elementsEqual(expectedVersion.utf8)) + #expect(manifest["description"] == .string("Consumer description")) + #expect((bundle.files["commands/review.toml"] == nil) == emptySelection) + #expect((manifest["mcpServers"] == nil) == emptySelection) + } + } + + @Test func geminiUnavailableVersionKeepsImportRefusalAndBindingBoundary() throws { + let fixture = try LinkFixture() + let declaration = """ + version: 1 + components: + - {kind: plugin, name: selected, source: ".", path: extension, select: [], agents: [gemini-cli]} + """ + for field in ["", ", \"version\": \"\"", ", \"version\": 7"] { + try fixture.write( + "{\"name\":\"upstream\"\(field)}", to: "extension/gemini-extension.json", + base: fixture.project) + do { + _ = try freeze(fixture, declaration) + Issue.record("Invalid producer version was admitted") + } catch { + #expect(String(describing: error).contains("native plugin invalidInput")) + } + } + try fixture.write( + #"{"name":"upstream","version":"https://user:PRIVATE_VERSION_CANARY@example.test"}"#, + to: "extension/gemini-extension.json", base: fixture.project) + let (components, frozen) = try freeze(fixture, declaration) + let parent = try #require(frozen.ledger.components.values.first { $0.kind == "plugin" }) + #expect(parent.payload.object?["native"]?.object?["gemini-cli"]?.object?["version"] == nil) + let encoded = try ResolvedLedgerCodec.encode(frozen.ledger, limits: .standard) + #expect(!String(decoding: encoded, as: UTF8.self).contains("PRIVATE_VERSION_CANARY")) + var ledger = frozen.ledger + ledger.lowerings = [try lower(components, frozen, surface: .geminiCLI, scope: .user)] + ledger = try LedgerReplay.prepareLowerings( + ledger, store: fixture.store, roots: [:], limits: .standard) + _ = try LedgerReplay.withReplay(ledger, store: fixture.store, roots: [:], limits: .standard) { + artifacts in + #expect(throws: (any Error).self) { + try NativeGeneratedPluginContribution.decode( + ledger.lowerings[0], ledger: ledger, artifacts: artifacts, limits: .standard) + } + } + } + + @Test func geminiVersionComesFromSelectedProducerCommitAndContainer() throws { + let fixture = try LinkFixture() + let repository = fixture.root.appendingPathComponent("producer") + try fixture.initialize(repository) + try fixture.write( + #"{"name":"selected","version":"2.0.0"}"#, + to: "chosen/gemini-extension.json", base: repository) + try fixture.write( + #"{"name":"other","version":"3.0.0"}"#, + to: "other/gemini-extension.json", base: repository) + let commit = try fixture.commit(repository, tag: "1.0.0") + try fixture.write( + #"{"name":"selected","version":"99.0.0"}"#, + to: "chosen/gemini-extension.json", base: repository) + let (_, frozen) = try freeze( + fixture, + """ + version: 1 + sources: {p: {url: "file://localhost\(repository.path)", requirement: {exact: "1.0.0"}}} + components: + - {kind: plugin, name: consumer, source: p, path: chosen, select: [], agents: [gemini-cli]} + """) + let parent = try #require(frozen.ledger.components.values.first { $0.kind == "plugin" }) + #expect( + parent.payload.object?["native"]?.object?["gemini-cli"]?.object?["version"] == .init("2.0.0")) + let expansion = try #require(frozen.ledger.occurrences.first?.pluginExpansion) + #expect(expansion.document == "chosen/gemini-extension.json") + #expect(frozen.ledger.sources[expansion.source]?.revision == commit) + } + +} diff --git a/Tests/ComponentsTests/ImpactTests.swift b/Tests/ComponentsTests/ImpactTests.swift new file mode 100644 index 0000000..a9c1c1b --- /dev/null +++ b/Tests/ComponentsTests/ImpactTests.swift @@ -0,0 +1,240 @@ +import AgentsCore +import Components +import Foundation +import Testing + +@Suite("Component targeting and impact", .serialized) +struct ImpactTests { + @Test func conditionsNarrowAndNamedHooksCoalesce() throws { + let fixture = try LinkFixture() + let graph = try fixture.link( + """ + version: 1 + defaultAgents: ["claude-code", "codex"] + components: [{"kind": "hook", "name": "format", "event": "afterTool", "run": {"executable": "never-run"}}, {"kind": "hook", "name": "format", "event": "afterTool", "run": {"executable": "never-run"}}, {"kind": "hook", "name": "format", "event": "afterTool", "run": {"executable": "different"}, "condition": {"agents": []}}, {"kind": "mcpServer", "name": "empty", "transport": {"kind": "stdio", "executable": "never-run"}, "agents": []}, {"kind": "mcpServer", "name": "linux", "transport": {"kind": "stdio", "executable": "never-run"}, "condition": {"platforms": ["linux"]}}] + """) + #expect(graph.components.count == 4) + #expect(graph.components[0].origins.count == 2) + #expect(graph.components.dropFirst().allSatisfy { $0.recipients.isEmpty }) + #expect(throws: LinkError.self) { + try fixture.link( + """ + version: 1 + components: [{"kind": "hook", "name": "format", "event": "afterTool", "run": {"executable": "one"}}, {"kind": "hook", "name": "format", "event": "afterTool", "run": {"executable": "two"}}] + """) + } + } + + @Test func directSkillAndInstructionPinsRemainIndependent() throws { + let fixture = try LinkFixture() + let repository = fixture.root.appendingPathComponent("repository") + try fixture.initialize(repository) + try fixture.skill("review", at: repository) + try fixture.instruction("rules", at: repository, own: false) + let firstPin = try fixture.commit(repository, tag: "1.0.0") + let expression = """ + version: 1 + sources: {"s": {"path": "\(repository.path)"}} + components: [{"kind": "skills", "source": "s", "select": ["review"]}, {"kind": "instructions", "sections": [{"name": "rules", "source": "s"}]}] + """ + let before = try fixture.link(expression) + let sectionKey = try #require(before.components.last?.key) + try fixture.write( + "---\ndescription: Changed\n---\n# rules\nChanged\n", to: "instructions/rules.md", + base: repository) + try fixture.write( + "---\nname: review\ndescription: Changed\n---\nChanged\n", to: "skills/review/SKILL.md", + base: repository) + let secondPin = try fixture.commit(repository, tag: "1.1.0") + let after = try fixture.link( + expression, directPins: [sectionKey: try #require(before.components.last?.pin)]) + #expect(after.components[0].snapshot.revision == secondPin) + #expect(after.components[1].snapshot.revision == firstPin) + #expect(after.protectedChanges(from: before, allowing: [.skills]).isEmpty) + let combined = try fixture.link(expression) + #expect(combined.protectedChanges(from: before, allowing: [.skills]) == [sectionKey]) + } + + @Test func sharedTransitivePinChangesAreProtected() throws { + let fixture = try LinkFixture() + let repository = fixture.root.appendingPathComponent("repository") + try fixture.initialize(repository) + try fixture.skill("review", at: repository) + try fixture.manifest( + """ + version: 1 + exports: ["skills", "mcp"] + groups: {"skills": {"components": [{"kind": "skills", "source": ".", "select": ["review"]}]}, "mcp": {"components": [{"kind": "mcpServer", "name": "server", "transport": {"kind": "stdio", "executable": "never-run"}}]}} + """, at: repository) + let firstPin = try fixture.commit(repository, tag: "1.0.0") + let expression = """ + version: 1 + sources: {"s": {"path": "\(repository.path)"}} + uses: [{"source": "s", "group": "skills"}, {"source": "s", "group": "mcp"}] + """ + let before = try fixture.link(expression) + try fixture.write("change", to: "unrelated.txt", base: repository) + try fixture.commit(repository, tag: "1.1.0") + let after = try fixture.link(expression) + #expect(after.protectedChanges(from: before, allowing: [.skills]).map(\.name) == ["server"]) + #expect( + before.protectedPins(allowing: [.skills])["local:" + repository.path]?.revision == firstPin) + let preserved = try fixture.link( + expression, preserving: before.protectedPins(allowing: [.skills])) + #expect(preserved.protectedChanges(from: before, allowing: [.skills]).isEmpty) + #expect(throws: LinkError.self) { try after.requireEditable(after.components[0].key) } + } + + @Test func chatGPTUsesScopeAndPlatformProjection() throws { + let fixture = try LinkFixture() + try fixture.instruction( + "rules", at: fixture.project, + restrictions: "agents: []\nscopes: [\"project\"]\nplatforms: [\"macos\"]\n") + let graph = try fixture.link( + """ + version: 1 + components: [{"kind": "instructions", "sections": [{"name": "rules"}], "chatgpt": {"p": {"sections": [{"name": "rules"}]}}}] + """) + #expect(graph.components[0].recipients.isEmpty) + #expect(!graph.components[0].chatGPT) + #expect(graph.components[1].chatGPT) + } +} + +extension ImpactTests { + @Test(arguments: [false, true]) + func coalescedRestrictionClausesIgnoreDeclarationOrder(permissions: Bool) throws { + let fixture = try LinkFixture() + let body = + permissions + ? "{kind: permissions, name: shared, rules: [{effect: allow, operation: read, pattern: \"Sources/**\"}]" + : "{kind: hook, name: shared, event: afterTool, run: {executable: never-run}" + func graph(_ conditions: [String]) throws -> LinkedComponents { + let components = conditions.map { body + ", condition: \($0)}" }.joined(separator: ",") + return try fixture.link("version: 1\ncomponents: [\(components)]\n") + } + let clauses = [ + "{\"agents\": [\"codex\"], \"scopes\": [\"project\"], \"platforms\": [\"macos\"]}", + "{\"agents\": [\"claude-code\"], \"scopes\": [\"project\"], \"platforms\": [\"macos\", \"linux\"]}", + ] + let before = try graph(clauses) + let after = try graph(clauses.reversed()) + let component = try #require(after.components.first) + #expect(after.components.count == 1) + #expect(component.origins.count == 2) + #expect(component.conditions.count == 2) + #expect(component.conditions == before.components[0].conditions.reversed()) + #expect(after.protectedChanges(from: before, allowing: [.skills]).isEmpty) + #expect(before.protectedChanges(from: after, allowing: [.skills]).isEmpty) + + let changed = try graph([ + clauses[0], + "{\"agents\": [\"claude-code\"], \"scopes\": [\"project\"], \"platforms\": [\"macos\"]}", + ]) + #expect(changed.components[0].recipients == component.recipients) + #expect(changed.protectedChanges(from: before, allowing: [.skills]) == [component.key]) + + let paired = try graph([ + "{\"agents\": [\"codex\"], \"scopes\": [\"project\"], \"platforms\": [\"macos\"]}", + "{\"agents\": [\"claude-code\"], \"scopes\": [\"project\"], \"platforms\": [\"linux\"]}", + "{\"agents\": [\"codex\", \"claude-code\"], \"scopes\": [\"project\"], \"platforms\": [\"macos\"]}", + ]) + let swapped = try graph([ + "{\"agents\": [\"codex\"], \"scopes\": [\"project\"], \"platforms\": [\"linux\"]}", + "{\"agents\": [\"claude-code\"], \"scopes\": [\"project\"], \"platforms\": [\"macos\"]}", + "{\"agents\": [\"codex\", \"claude-code\"], \"scopes\": [\"project\"], \"platforms\": [\"macos\"]}", + ]) + #expect(swapped.components[0].recipients == paired.components[0].recipients) + #expect(swapped.protectedChanges(from: paired, allowing: [.skills]) == [component.key]) + } + + @Test(arguments: [false, true]) + func coalescingChecksEveryDifferentPayload(permissions: Bool) throws { + let fixture = try LinkFixture() + func declaration(_ payload: String, _ agent: String) -> String { + let body = + permissions + ? "{kind: permissions, name: shared, rules: [{effect: allow, operation: read, pattern: \"\(payload)/**\"}]" + : "{kind: hook, name: shared, event: afterTool, run: {executable: \"\(payload)\"}" + return body + ", condition: {agents: [\(agent == "claudeCode" ? "claude-code" : agent)]}}" + } + let a = declaration("a", "codex") + let b = declaration("b", "claudeCode") + let c = declaration("a", "claudeCode") + for declarations in [[a, b, c], [b, a, c], [a, c, b]] { + do { + _ = try fixture.link( + "version: 1\ncomponents: [\(declarations.joined(separator: ","))]\n") + Issue.record("expected overlapping different payloads to conflict") + } catch LinkError.conflict(let key, let origins) { + #expect(key.kind == (permissions ? .permissions : .hook)) + #expect(origins.count >= 2) + } + } + } + + @Test(arguments: [false, true]) + func instructionOrderIsProtectedPerDestination(chatGPT: Bool) throws { + let fixture = try LinkFixture() + for name in ["a", "b"] { try fixture.instruction(name, at: fixture.project) } + func expression(_ sections: String) -> String { + let component = + chatGPT + ? "{\"kind\": \"instructions\", \"chatgpt\": {\"review\": {\"sections\": [\(sections)]}}}" + : "{\"kind\": \"instructions\", \"sections\": [\(sections)], \"agents\": [\"codex\"]}" + return "version: 1\ncomponents: [\(component)]\n" + } + let before = try fixture.link(expression("{name: a}, {name: b}")) + let after = try fixture.link(expression("{name: b}, {name: a}")) + #expect(after.protectedChanges(from: before, allowing: [.skills]).map(\.name) == ["a", "b"]) + #expect(after.protectedChanges(from: before, allowing: [.instructions]).isEmpty) + } + + @Test func unrelatedOrderAndOccurrenceChangesAreNotProtected() throws { + let fixture = try LinkFixture() + try fixture.skill("review", at: fixture.project) + for name in ["a", "b"] { try fixture.instruction(name, at: fixture.project) } + let declarations = [ + "{\"kind\": \"instructions\", \"sections\": [{\"name\": \"a\"}], \"agents\": [\"codex\"]}", + "{\"kind\": \"instructions\", \"sections\": [{\"name\": \"b\"}], \"agents\": [\"claude-code\"]}", + "{\"kind\": \"instructions\", \"chatgpt\": {\"first\": {\"sections\": [{\"name\": \"a\"}]}}}", + "{\"kind\": \"instructions\", \"chatgpt\": {\"second\": {\"sections\": [{\"name\": \"b\"}]}}}", + "{\"kind\": \"mcpServer\", \"name\": \"one\", \"transport\": {\"kind\": \"stdio\", \"executable\": \"never-run\"}}", + "{\"kind\": \"mcpServer\", \"name\": \"two\", \"transport\": {\"kind\": \"stdio\", \"executable\": \"never-run\"}}", + ] + let before = try fixture.link( + "version: 1\ncomponents: [\(declarations.joined(separator: ","))]\n") + let after = try fixture.link( + "version: 1\ncomponents: [{\"kind\": \"skills\", \"source\": \".\", \"select\": [\"review\"], \"mode\": \"edit\"}, \(declarations.reversed().joined(separator: ","))]\n" + ) + #expect(after.protectedChanges(from: before, allowing: [.skills]).isEmpty) + } + + @Test func identicalNamedHooksUnionRecipientsAndKeepRestrictionOrigins() throws { + let fixture = try LinkFixture() + let graph = try fixture.link( + """ + version: 1 + components: [{"kind": "hook", "name": "format", "event": "afterTool", "run": {"executable": "never-run"}, "condition": {"agents": ["codex"]}}, {"kind": "hook", "name": "format", "event": "afterTool", "run": {"executable": "never-run"}, "condition": {"agents": ["claude-code"]}}] + """) + #expect(graph.components.count == 1) + #expect(graph.components[0].recipients == [.codex, .claudeCode]) + try #require(graph.components[0].origins.count == 2) + #expect(graph.components[0].origins[0].recipients == [.codex]) + #expect(graph.components[0].origins[1].recipients == [.claudeCode]) + } +} + +extension ImpactTests { + @Test func resourceAliasSpellingDoesNotChangeProtectedContent() throws { + let fixture = try LinkFixture() + let source = fixture.root.appendingPathComponent("source") + try fixture.write("Review", to: "review.md", base: source) + func expression(_ alias: String) -> String { + "version: 1\nsources: {\"\(alias)\": {\"path\": \"\(source.path)\"}}\ncomponents: [{\"kind\": \"command\", \"name\": \"review\", \"description\": \"Review\", \"prompt\": {\"file\": {\"path\": \"review.md\", \"source\": \"\(alias)\"}}}]\n" + } + let before = try fixture.link(expression("old")) + let after = try fixture.link(expression("renamed")) + #expect(after.protectedChanges(from: before, allowing: [.skills]).isEmpty) + } +} diff --git a/Tests/ComponentsTests/ImportNativeTests.swift b/Tests/ComponentsTests/ImportNativeTests.swift new file mode 100644 index 0000000..ccfc6ce --- /dev/null +++ b/Tests/ComponentsTests/ImportNativeTests.swift @@ -0,0 +1,920 @@ +import AgentsCore +import Components +import Foundation +import Testing + +struct ImportNativeTests { + @Test(arguments: [ + SourceImportProfile.claudeSettingsV1, .codexConfigV1, .cursorMCPV1, .geminiSettingsV1, + .openCodeConfigV2, + ]) + func fiveNativeMCPProfilesKeepArgvBindingsAndOriginalLocations(_ profile: SourceImportProfile) + throws + { + let fixture = try NativeImportFixture() + let file: String + let text: String + switch profile { + case .codexConfigV1: + file = "config.toml" + text = + "[mcp_servers.review]\ncommand='review-server'\nargs=['--read-only']\nenv_vars=['PUBLIC_TOKEN']\n[mcp_servers.review.env]\nTOKEN='NATIVE_SECRET_CANARY'\n" + case .openCodeConfigV2: + file = "opencode.jsonc" + text = + #"{"mcp":{"servers":{"review":{"type":"local","command":["review-server","--read-only"],"environment":{"TOKEN":"NATIVE_SECRET_CANARY"}}}}}"# + default: + file = "settings.json" + text = + #"{"mcpServers":{"review":{"command":"review-server","args":["--read-only"],"env":{"TOKEN":"NATIVE_SECRET_CANARY"}}}}"# + } + try fixture.write(file, text) + let before = try fixture.hash() + let result = try SourceImport.preview(fixture.input(profile, file)) + let item = try #require(result.components.first) + guard case .mcpServer(let name, .stdio(let run), let agents, _, _, _) = item.declaration else { + Issue.record("Expected typed stdio member") + return + } + #expect(name == "review") + #expect(run.executable == "review-server") + #expect(run.arguments == ["--read-only"]) + #expect(agents?.count == 1) + if case .secret(let key) = run.environment["TOKEN"] { + #expect(result.bindings.contains { $0.key == key }) + } else { + Issue.record("Literal credential must be symbolic") + } + if profile == .codexConfigV1 { + #expect(run.environment["PUBLIC_TOKEN"] == .environment("PUBLIC_TOKEN")) + } + #expect(item.member?.selector == .mcpServer(name: "review")) + #expect(item.member?.containerRoot == ".") + #expect(item.origin.document == file) + #expect(item.origin.span?.start != nil) + #expect(result.resources.last?.requiresBindingRewrite == true) + #expect(result.resources.last?.observedHash == nil) + #expect(!String(reflecting: result).contains("NATIVE_SECRET_CANARY")) + #expect(try fixture.hash() == before) + } + + @Test func nativeProfileProvenanceUsesUpstreamSourcesAndHonestDocumentationStatus() { + #expect( + SourceImportProfile.codexConfigV1.producerRevision + == "092d3acd6bec3e3a14bdc7e7a2810ab628ab759d") + #expect( + SourceImportProfile.geminiExtensionV1.producerRevision + == "5a5c7180ff3f0a02511f54b54db7f228d4982a30") + #expect( + SourceImportProfile.openCodeConfigV2.producerRevision + == "fedc6f208aa2bd54c1019227214568083f6380ad") + for profile in [ + SourceImportProfile.claudeSettingsV1, .claudePluginV1, .claudeMarketplaceV1, + .claudeCommandV1, .claudeAgentV1, .cursorMCPV1, .cursorPluginV1, .cursorCommandV1, + .cursorAgentV1, .cursorIgnoreV1, + ] { + #expect(profile.producerRevision == nil) + #expect(profile.specificationStatus.contains("Documented")) + #expect(profile.specificationStatus.contains("upstream source revision unavailable")) + } + } + + @Test func claudeContainerPreservesTypedChildrenRootsExecutableClosureAndSecrets() throws { + let fixture = try NativeImportFixture() + try fixture.write( + "bundle/.claude-plugin/plugin.json", + #"{"name":"review-bundle","version":"1","mcpServers":{"review":{"command":"${CLAUDE_PLUGIN_ROOT}/bin/server","env":{"TOKEN":"NATIVE_SECRET_CANARY"}}}}"# + ) + try fixture.write("bundle/bin/server", "#!/bin/sh\nexit 0\n", executable: true) + try fixture.write( + "bundle/commands/check.md", "---\ndescription: Check changes\n---\nReview the change.\n") + try fixture.write( + "bundle/agents/reviewer.md", + "---\nname: reviewer\ndescription: Review changes\n---\nReview carefully.\n") + try fixture.write( + "bundle/skills/audit/SKILL.md", "---\nname: audit\ndescription: Audit changes\n---\nAudit.\n") + try fixture.write( + "bundle/.lsp.json", + #"{"swift":{"command":"swift-lsp","extensionToLanguage":{".swift":"swift"}}}"#) + try fixture.write( + "bundle/hooks/hooks.json", + #"{"hooks":{"PreToolUse":[{"matcher":"Read","hooks":[{"type":"command","command":"./bin/server"}]}]}}"# + ) + var input = fixture.input(.claudePluginV1, "bundle/.claude-plugin/plugin.json") + input.selection = [] // Member all/none is B's operation, not container parsing. + let before = try fixture.hash() + let result = try SourceImport.preview(input) + #expect( + Set(result.components.map(\.declaration.kind)) == [ + .command, .subagent, .skills, .mcpServer, .lspServer, .hook, + ]) + #expect(result.components.allSatisfy { $0.member?.containerRoot == "bundle" }) + #expect( + result.components.first { $0.declaration.kind == .command }?.origin.document + == "bundle/commands/check.md") + #expect( + result.components.first { $0.declaration.kind == .lspServer }?.origin.document + == "bundle/.lsp.json") + #expect( + result.resources.contains { + $0.path == "bin/server" && $0.executableFlags["."] == true && $0.requiresStandaloneSource + }) + #expect(!result.resources.contains { $0.sourceAlias == "native-input" && $0.path == "." }) + #expect( + result.resources.first { $0.path == ".claude-plugin/plugin.json" }?.requiresBindingRewrite + == true) + #expect(!String(reflecting: result).contains("NATIVE_SECRET_CANARY")) + #expect(try fixture.hash() == before) + } + + @Test func cursorReplacementAndGeminiCommandNamespaceKeepProducerMeaning() throws { + let fixture = try NativeImportFixture() + try fixture.write( + "cursor/.cursor-plugin/plugin.json", #"{"name":"review","commands":"custom"}"#) + try fixture.write("cursor/commands/ignored.md", "Default must not be selected\n") + try fixture.write("cursor/custom/selected.txt", "Selected prompt\n") + let cursor = try SourceImport.preview( + fixture.input(.cursorPluginV1, "cursor/.cursor-plugin/plugin.json")) + #expect(cursor.components.map(\.member?.selector) == [.command(name: "selected")]) + try fixture.write("extension/gemini-extension.json", #"{"name":"review","version":"1"}"#) + try fixture.write( + "extension/commands/gcs/sync.toml", "description='Sync'\nprompt='Sync {{args}}'\n") + let gemini = try SourceImport.preview( + fixture.input(.geminiExtensionV1, "extension/gemini-extension.json")) + #expect(gemini.components.first?.member?.selector == .command(name: "gcs/sync")) + #expect(gemini.components.first?.origin.document == "extension/commands/gcs/sync.toml") + } + + @Test func geminiPackageMetadataKeepsExactFieldsAndOriginalCoordinates() throws { + let fixture = try NativeImportFixture() + let file = "extension/gemini-extension.json" + let name = "cafe\u{301}" + let version = "1.2.3-e\u{301}" + let manifest = + "{\n \"version\": \"\(version)\",\n \"name\": \"\(name)\",\n \"contextFileName\": \"extra.md\"\n}" + try fixture.write(file, manifest) + try fixture.write("extension/commands/review.toml", "description='Review'\nprompt='Review'\n") + var input = fixture.input(.geminiExtensionV1, file) + input.selection = [] + let before = try fixture.hash() + let proposal = try SourceImport.preview(input) + let metadata = try #require(proposal.packageMetadata) + #expect(metadata.name.utf8.elementsEqual(name.utf8)) + #expect((try #require(metadata.version)).utf8.elementsEqual(version.utf8)) + #expect(metadata.nameLocation.document == file) + #expect(metadata.nameLocation.pointer == "/member[1]") + #expect(metadata.nameLocation.span?.line == 3) + #expect(metadata.versionLocation?.document == file) + #expect(metadata.versionLocation?.pointer == "/member[2]") + #expect(metadata.versionLocation?.span?.line == 2) + #expect(proposal.components.map(\.member?.selector) == [.command(name: "review")]) + #expect(proposal.diagnostics.contains { $0.code == .unconverted }) + #expect(try fixture.hash() == before) + + for field in ["", ", \"version\": \"\"", ", \"version\": 7", ", \"version\": null"] { + try fixture.write(file, "{\"name\":\"review\"\(field)}") + let invalidBefore = try fixture.hash() + let invalid = try SourceImport.preview(input) + #expect(invalid.packageMetadata == nil) + #expect(invalid.components.isEmpty) + #expect( + invalid.diagnostics.contains { + $0.code == .invalidInput && $0.location.document == file + && $0.message == "Native extension requires a version string." + }) + #expect(try fixture.hash() == invalidBefore) + } + try fixture.write( + file, #"{"name":"review","version":"https://user:PRIVATE_VERSION_CANARY@example.test"}"#) + let sensitive = try SourceImport.preview(input) + #expect(sensitive.packageMetadata == nil) + #expect(!sensitive.bindings.isEmpty) + #expect(sensitive.components.count == 1) + #expect(!String(reflecting: sensitive).contains("PRIVATE_VERSION_CANARY")) + } + + @Test(arguments: [SourceImportProfile.claudePluginV1, .cursorPluginV1]) + func nativePackageNameKeepsExactProducerCoordinatesWithoutVersion( + _ profile: SourceImportProfile + ) throws { + let fixture = try NativeImportFixture() + let suffix = + profile == .claudePluginV1 ? ".claude-plugin/plugin.json" : ".cursor-plugin/plugin.json" + let file = "different-folder/" + suffix + let name = profile == .claudePluginV1 ? "cafe\u{301}" : "exact.producer-name" + try fixture.write(file, "{\n \"name\": \"\(name)\"\n}") + try fixture.write( + "different-folder/skills/helper/SKILL.md", + "---\nname: helper\ndescription: Helper\n---\nBody\n") + let before = try fixture.hash() + let proposal = try SourceImport.preview(fixture.input(profile, file)) + let metadata = try #require(proposal.packageMetadata) + #expect(metadata.name.utf8.elementsEqual(name.utf8)) + #expect(metadata.nameLocation.document == file) + #expect(metadata.nameLocation.pointer == "/member[0]") + #expect(metadata.nameLocation.span?.line == 2) + #expect(metadata.version == nil && metadata.versionLocation == nil) + #expect(proposal.components.count == 1 && proposal.diagnostics.isEmpty) + #expect(try fixture.hash() == before) + for invalidName in [#"7"#, #""""#, #""https://user:PRIVATE_NAME_CANARY@example.test""#] { + try fixture.write(file, "{\"name\":\(invalidName)}") + let invalid = try SourceImport.preview(fixture.input(profile, file)) + #expect(invalid.packageMetadata == nil) + #expect(!invalid.diagnostics.isEmpty) + #expect(!String(reflecting: invalid).contains("PRIVATE_NAME_CANARY")) + } + if profile == .cursorPluginV1 { + try fixture.write(file, #"{"name":"Invalid_Producer"}"#) + let invalid = try SourceImport.preview(fixture.input(profile, file)) + #expect(invalid.packageMetadata == nil) + #expect( + invalid.diagnostics.contains { + $0.code == .invalidInput && $0.location.document == file + && $0.location.pointer == "/member[0]" + }) + } + } + + @Test func codexRoleRelativeFileAndOpenCodeOrderedPolicyBecomeTypedIntent() throws { + let fixture = try NativeImportFixture() + try fixture.write( + "codex/config.toml", + "[agents.review]\ndescription='Review'\nconfig_file='./roles/review.toml'\n") + try fixture.write( + "codex/roles/review.toml", "developer_instructions='Review carefully'\nmodel='model-id'\n") + let codex = try SourceImport.preview(fixture.input(.codexConfigV1, "codex/config.toml")) + #expect(codex.components.first?.origin.document == "codex/roles/review.toml") + #expect(codex.resources.contains { $0.path == "codex/roles/review.toml" }) + try fixture.write( + "opencode.jsonc", + #"{"commands":{"review":{"description":"Review","template":"Review $ARGUMENTS"}},"agents":{"reviewer":{"description":"Reviewer","mode":"subagent","system":"Review","model":"provider/model"}},"permissions":[{"action":"read","resource":"*","effect":"deny"},{"action":"read","resource":"safe/*","effect":"allow"}]}"# + ) + let opencode = try SourceImport.preview(fixture.input(.openCodeConfigV2, "opencode.jsonc")) + #expect( + Set(opencode.components.map(\.declaration.kind)) == [.command, .subagent, .permissions]) + guard case .permissions(_, let rules, _, _, _) = opencode.components.last?.declaration else { + Issue.record("Expected native ordered policy") + return + } + #expect(rules == [.deny(.tool("read"), "*"), .allow(.tool("read"), "safe/*")]) + } + + @Test func selectedCatalogCoordinatesKeepExactPinsAndNeverExecuteCommandSources() throws { + let fixture = try NativeImportFixture() + let commit = String(repeating: "a", count: 40) + try fixture.write( + "catalog/.claude-plugin/marketplace.json", + """ + {"name":"catalog","owner":{"name":"owner"},"plugins":[ + {"name":"pinned","source":{"source":"github","repo":"acme/review","ref":"main","sha":"\(commit)"}}, + {"name":"mutable","source":{"source":"url","url":"https://example.test/repo.git","ref":"main"}}, + {"name":"command","source":{"source":"command","command":"touch SHOULD_NOT_EXIST"}}]} + """) + var input = fixture.input(.claudeMarketplaceV1, "catalog/.claude-plugin/marketplace.json") + let unselected = try SourceImport.preview(input) + #expect(unselected.sources.isEmpty) + input.selection = ["pinned", "mutable", "command"] + let before = try fixture.hash() + let result = try SourceImport.preview(input) + #expect(result.sources.map(\.pin.commit) == [commit, nil]) + #expect(result.sources.first?.declaration?.requirement == .revision(commit)) + #expect(result.sources.first?.requestedRef == "main") + #expect(result.diagnostics.contains { $0.code == .incompletePin }) + #expect(result.diagnostics.contains { $0.code == .unconverted }) + #expect( + !FileManager.default.fileExists( + atPath: fixture.root.appendingPathComponent("SHOULD_NOT_EXIST").path)) + #expect(try fixture.hash() == before) + } + + @Test func nativeRefusalsAreLocatedValueFreeAndPreserveAllInputBytes() throws { + let fixture = try NativeImportFixture() + try fixture.write( + "settings.json", + #"{"mcpServers":{"bad":{"command":"tool","args":["--token=NATIVE_SECRET_CANARY"]}},"hooks":{"PreToolUse":[{"hooks":[{"type":"command","command":"echo a | sed b"}]}]},"future":{"token":"NATIVE_SECRET_CANARY"}}"# + ) + let before = try fixture.hash() + let result = try SourceImport.preview(fixture.input(.claudeSettingsV1, "settings.json")) + #expect(result.components.isEmpty) + #expect(!result.bindings.isEmpty) + #expect( + result.diagnostics.contains { + $0.code == .unconverted && $0.location.document == "settings.json" + }) + #expect(!String(reflecting: result).contains("NATIVE_SECRET_CANARY")) + #expect(try fixture.hash() == before) + try fixture.write("duplicate.json", #"{"mcpServers":{},"mcpServers":{}}"#) + let duplicate = try SourceImport.preview(fixture.input(.claudeSettingsV1, "duplicate.json")) + #expect(duplicate.components.isEmpty) + #expect(duplicate.diagnostics.last?.code == .invalidInput) + try fixture.write( + "bundle/.claude-plugin/plugin.json", #"{"name":"bundle","commands":"./../outside"}"#) + let traversal = try SourceImport.preview( + fixture.input(.claudePluginV1, "bundle/.claude-plugin/plugin.json")) + #expect(traversal.diagnostics.last?.code == .unsafePath) + var limits = SourceImportLimits() + limits.documentBytes = 8 + #expect( + try SourceImport.preview(fixture.input(.claudeSettingsV1, "settings.json"), limits: limits) + .components.isEmpty) + } + + @Test func nativeIgnoreAndCatalogSubdirectoryPreserveFormatCoordinates() throws { + let fixture = try NativeImportFixture() + try fixture.write(".geminiignore", "build/\n!important.txt\n") + let ignored = try SourceImport.preview(fixture.input(.geminiIgnoreV1, ".geminiignore")) + guard case .ignore(_, let patterns, _, _, _, _) = ignored.components.first?.declaration else { + Issue.record("Expected context exclusion patterns") + return + } + #expect(patterns == ["build/", "!important.txt"]) + let commit = String(repeating: "b", count: 40) + try fixture.write( + ".claude-plugin/marketplace.json", + """ + {"name":"catalog","owner":{"name":"owner"},"plugins":[ + {"name":"nested","source":{"source":"git-subdir","url":"https://example.test/repo.git","path":"plugins/review","sha":"\(commit)"}}]} + """) + var input = fixture.input(.claudeMarketplaceV1, ".claude-plugin/marketplace.json") + input.selection = ["nested"] + let result = try SourceImport.preview(input) + #expect(result.sources.first?.declaration?.path == "plugins/review") + #expect(result.sources.first?.pin.commit == commit) + guard case .plugin(_, let path, _, _, _, _, _, _, _) = result.components.first?.declaration + else { + Issue.record("Expected selected catalog plugin") + return + } + #expect(path == ".") + } + + @Test func optionalNativeDescriptionsAndReferencedUnknownFieldsStayVisible() throws { + let fixture = try NativeImportFixture() + try fixture.write("command.toml", "prompt='Review {{args}}'\n") + let command = try SourceImport.preview(fixture.input(.geminiCommandV1, "command.toml")) + #expect(command.components.count == 1) + try fixture.write("opencode.jsonc", #"{"commands":{"review":{"template":"Review"}}}"#) + let opencode = try SourceImport.preview(fixture.input(.openCodeConfigV2, "opencode.jsonc")) + #expect(opencode.components.count == 1) + try fixture.write("bundle/.claude-plugin/plugin.json", #"{"name":"bundle"}"#) + try fixture.write( + "bundle/.mcp.json", #"{"mcpServers":{},"future":{"token":"NATIVE_SECRET_CANARY"}}"#) + let bundle = try SourceImport.preview( + fixture.input(.claudePluginV1, "bundle/.claude-plugin/plugin.json")) + #expect( + bundle.diagnostics.contains { + $0.code == .unconverted && $0.location.document == "bundle/.mcp.json" + }) + #expect(!bundle.bindings.isEmpty) + #expect(bundle.resources.contains { $0.path == ".mcp.json" && $0.requiresBindingRewrite }) + #expect(!String(reflecting: bundle).contains("NATIVE_SECRET_CANARY")) + } + + @Test func missingExplicitContainerMembersAreLocatedWhileOptionalDefaultsStayOptional() throws { + let fixture = try NativeImportFixture() + try fixture.write( + "bundle/.cursor-plugin/plugin.json", #"{"name":"bundle","commands":"missing"}"#) + let missing = try SourceImport.preview( + fixture.input(.cursorPluginV1, "bundle/.cursor-plugin/plugin.json")) + #expect(missing.components.isEmpty) + #expect( + missing.diagnostics.contains { + $0.code == .missingResource && $0.location.document == "bundle/.cursor-plugin/plugin.json" + && $0.location.pointer == "/commands" && $0.location.span != nil + }) + try fixture.write("bundle/.cursor-plugin/plugin.json", #"{"name":"bundle"}"#) + let defaults = try SourceImport.preview( + fixture.input(.cursorPluginV1, "bundle/.cursor-plugin/plugin.json")) + #expect(!defaults.diagnostics.contains { $0.code == .missingResource }) + } + + @Test func preservedMCPDocumentsClassifyExcludedAndReplacedBindings() throws { + let fixture = try NativeImportFixture() + try fixture.write( + "settings.json", + #"{"mcpServers":{"clean":{"command":"tool"},"private":{"command":"tool","env":{"CUSTOM":"EXCLUDED_SECRET"}}}}"# + ) + var input = fixture.input(.claudeSettingsV1, "settings.json") + input.selection = ["clean"] + let before = try fixture.hash() + let selected = try SourceImport.preview(input) + #expect(selected.components.count == 1) + #expect(selected.bindings.contains { $0.location.pointer.contains("member[1]/env") }) + #expect(selected.resources.allSatisfy { $0.requiresBindingRewrite && $0.observedHash == nil }) + #expect(!String(reflecting: selected).contains("EXCLUDED_SECRET")) + #expect(try fixture.hash() == before) + #expect(selected.components.first?.member?.selector == .mcpServer(name: "clean")) + try fixture.write( + "settings.json", + #"{"mcpServers":{"clean":{"command":"tool","env":{}},"private":{"command":"tool","env":{"CUSTOM":"${OPTIONAL_TOKEN}"}}}}"# + ) + let symbolic = try SourceImport.preview(input) + #expect(symbolic.components.count == 1) + #expect(symbolic.bindings.isEmpty) + #expect(symbolic.resources.allSatisfy { !$0.requiresBindingRewrite && $0.observedHash != nil }) + try fixture.write( + "settings.json", + #"{"mcpServers":{"clean":{"command":"tool"},"private":{"command":"tool","env_http_headers":{"CUSTOM":"EXCLUDED_HEADER_SECRET"}}}}"# + ) + let foreignField = try SourceImport.preview(input) + #expect(!foreignField.bindings.isEmpty) + #expect( + foreignField.resources.allSatisfy { $0.requiresBindingRewrite && $0.observedHash == nil }) + #expect(!String(reflecting: foreignField).contains("EXCLUDED_HEADER_SECRET")) + + try fixture.write( + "bundle/.claude-plugin/plugin.json", + #"{"name":"bundle","mcpServers":{"same":{"command":"winning-tool"}}}"#) + try fixture.write( + "bundle/.mcp.json", + #"{"mcpServers":{"same":{"command":"old-tool","env":{"CUSTOM":"REPLACED_SECRET"}}}}"#) + let bundleBefore = try fixture.hash() + let replaced = try SourceImport.preview( + fixture.input(.claudePluginV1, "bundle/.claude-plugin/plugin.json")) + #expect(replaced.components.count == 1) + #expect(replaced.bindings.contains { $0.location.document == "bundle/.mcp.json" }) + #expect( + replaced.resources.contains { + $0.path == ".mcp.json" && $0.requiresBindingRewrite && $0.observedHash == nil + }) + #expect(!String(reflecting: replaced).contains("REPLACED_SECRET")) + #expect(try fixture.hash() == bundleBefore) + } + + @Test func rootRelativeExecutablesRemainResourcesAcrossNativeKinds() throws { + let fixture = try NativeImportFixture() + try fixture.write( + ".claude-plugin/plugin.json", + #"{"name":"bundle","mcpServers":{"mcp":{"command":"./server"}},"hooks":{"PreToolUse":[{"hooks":[{"type":"command","command":"./server"}]}]}}"# + ) + try fixture.write( + ".lsp.json", + #"{"lsp":{"command":"${CLAUDE_PLUGIN_ROOT}/server","extensionToLanguage":{".x":"x"}}}"#) + try fixture.write("server", "#!/bin/sh\nexit 0\n", executable: true) + let before = try fixture.hash() + let result = try SourceImport.preview( + fixture.input(.claudePluginV1, ".claude-plugin/plugin.json")) + var executables: [String] = [] + for item in result.components { + switch item.declaration { + case .mcpServer(_, .stdio(let run), _, _, _, _), .hook(_, _, let run, _, _, _, _, _), + .lspServer(_, let run, _, _, _, _, _): + executables.append(run.executable) + default: Issue.record("Unexpected member") + } + } + #expect(executables == ["./server", "./server", "./server"]) + #expect(result.resources.contains { $0.path == "server" && $0.executableFlags["."] == true }) + #expect(try fixture.hash() == before) + } + + @Test func lspBindingsKeepOriginalMapCoordinatesThroughPrecedence() throws { + let fixture = try NativeImportFixture() + try fixture.write("bundle/.claude-plugin/plugin.json", #"{"name":"bundle"}"#) + try fixture.write( + "bundle/.lsp.json", + """ + {"a":{"command":"a-lsp","extensionToLanguage":{".a":"a"},"env":{"CUSTOM":"LSP_A_SECRET"}}, + "b":{"command":"b-lsp","extensionToLanguage":{".b":"b"},"env":{"CUSTOM":"LSP_B_SECRET"}}} + """) + func keys(_ result: SourceImportProposal) -> [String] { + result.components.compactMap { + if case .lspServer(_, let run, _, _, _, _, _) = $0.declaration, + case .secret(let key) = run.environment["CUSTOM"] + { + return key + } + return nil + } + } + let original = try SourceImport.preview( + fixture.input(.claudePluginV1, "bundle/.claude-plugin/plugin.json")) + #expect(Set(keys(original)).count == 2) + #expect(Set(original.components.map(\.origin.pointer)) == ["/member[0]", "/member[1]"]) + #expect(Set(original.components.compactMap { $0.origin.span?.line }) == [1, 2]) + try fixture.write( + "bundle/.claude-plugin/plugin.json", #"{"name":"bundle","lspServers":"./override.json"}"#) + try fixture.write( + "bundle/override.json", + #"{"a":{"command":"new-lsp","extensionToLanguage":{".a":"a"},"env":{"CUSTOM":"NEW_LSP_SECRET"}}}"# + ) + let replaced = try SourceImport.preview( + fixture.input(.claudePluginV1, "bundle/.claude-plugin/plugin.json")) + #expect(Set(keys(replaced)).count == 2) + #expect(Set(replaced.bindings.compactMap(\.key)).count == 3) + #expect( + replaced.components.contains { + $0.origin.document == "bundle/.lsp.json" && $0.origin.pointer == "/member[1]" + }) + #expect( + replaced.components.contains { + $0.origin.document == "bundle/override.json" && $0.origin.pointer == "/member[0]" + && $0.origin.span != nil + }) + #expect( + replaced.resources.filter { $0.path == ".lsp.json" || $0.path == "override.json" }.allSatisfy + { $0.requiresBindingRewrite && $0.observedHash == nil }) + #expect(!String(reflecting: replaced).contains("LSP_B_SECRET")) + } + + @Test func openCodeExplicitOAuthDisableSurvivesTypedImport() throws { + let fixture = try NativeImportFixture() + try fixture.write( + "opencode.jsonc", + #"{"mcp":{"servers":{"review":{"type":"remote","url":"https://example.test/mcp","oauth":false}}}}"# + ) + let result = try SourceImport.preview(fixture.input(.openCodeConfigV2, "opencode.jsonc")) + guard + case .mcpServer(_, .streamableHTTP, _, _, let native, _) = result.components.first? + .declaration + else { + Issue.record("Expected remote MCP") + return + } + #expect(native[AgentID.opencode.rawValue]?["oauth"] == .boolean(false)) + #expect(result.diagnostics.isEmpty) + } + + @Test func nativeConfigurationMemberSelectionHonorsEmptyAndNarrowNames() throws { + let fixture = try NativeImportFixture() + try fixture.write( + "opencode.jsonc", + #"{"commands":{"other":{"template":"Other"},"selected":{"template":"Selected"}},"agents":{"other":{"system":"Other","mode":"subagent"},"selected":{"system":"Selected","mode":"subagent"}}}"# + ) + try fixture.write( + "config.toml", + "[agents.other]\ndescription='Other'\nconfig_file='other.toml'\n[agents.selected]\ndescription='Selected'\nconfig_file='selected.toml'\n" + ) + try fixture.write("other.toml", "developer_instructions='Other'\n") + try fixture.write("selected.toml", "developer_instructions='Selected'\n") + let selections: [Set?] = [nil, [], ["selected"]] + for selection in selections { + var openCode = fixture.input(.openCodeConfigV2, "opencode.jsonc") + var codex = fixture.input(.codexConfigV1, "config.toml") + openCode.selection = selection + codex.selection = selection + let a = try SourceImport.preview(openCode) + let b = try SourceImport.preview(codex) + #expect(a.components.count == (selection == nil ? 4 : selection!.isEmpty ? 0 : 2)) + #expect(b.components.count == (selection == nil ? 2 : selection!.isEmpty ? 0 : 1)) + if selection == ["selected"] { + #expect( + a.components.compactMap { $0.member?.selector } == [ + .command(name: "selected"), .subagent(name: "selected"), + ]) + #expect(b.components.first?.member?.selector == .subagent(name: "selected")) + } + } + try FileManager.default.removeItem(at: fixture.root.appendingPathComponent("other.toml")) + var narrow = fixture.input(.codexConfigV1, "config.toml") + narrow.selection = ["selected"] + #expect(try SourceImport.preview(narrow).components.count == 1) + } + + @Test func sharedMarkdownFieldsKeepNativeIntentAndActualRegistrationContext() throws { + let fixture = try NativeImportFixture() + try fixture.write( + "auditor.md", + "---\nname: auditor\ndescription: Inspect source\npermissionMode: plan\nmaxTurns: 3\n---\nInspect carefully.\n" + ) + let standalone = try SourceImport.preview(fixture.input(.claudeAgentV1, "auditor.md")) + guard case .subagent(_, _, _, _, _, _, _, let native) = standalone.components.first?.declaration + else { + Issue.record("Expected standalone agent") + return + } + #expect(native[AgentID.claudeCode.rawValue]?["permissionMode"] == .string("plan")) + #expect(native[AgentID.claudeCode.rawValue]?["maxTurns"] == .integer(3)) + try fixture.write("bundle/.claude-plugin/plugin.json", #"{"name":"bundle"}"#) + try fixture.write( + "bundle/agents/auditor.md", + "---\nname: auditor\ndescription: Inspect source\npermissionMode: plan\n---\nInspect.\n") + let plugin = try SourceImport.preview( + fixture.input(.claudePluginV1, "bundle/.claude-plugin/plugin.json")) + #expect(!plugin.components.contains { $0.declaration.kind == .subagent }) + #expect( + plugin.diagnostics.contains { + $0.code == .unconverted && $0.location.document == "bundle/agents/auditor.md" + && $0.location.span?.line == 4 + }) + try fixture.write( + "review.md", + "---\ncontext: fork\nagent: auditor\nbackground: true\nmodel: sonnet\n---\nReview.\n") + let command = try SourceImport.preview(fixture.input(.claudeCommandV1, "review.md")) + guard case .command(_, _, _, _, _, _, let fields) = command.components.first?.declaration else { + Issue.record("Expected native command") + return + } + #expect(fields[AgentID.claudeCode.rawValue]?["context"] == .string("fork")) + #expect(fields[AgentID.claudeCode.rawValue]?["model"] == .string("sonnet")) + try fixture.write("review.md", "---\nbackground: true\n---\nReview.\n") + let refused = try SourceImport.preview(fixture.input(.claudeCommandV1, "review.md")) + #expect(refused.components.isEmpty) + #expect( + refused.diagnostics.contains { $0.code == .unconverted && $0.location.span?.line == 2 }) + try fixture.write( + "review.md", "---\nzzzUnknown: value\ndescription: Review\naaaUnknown: value\n---\nReview.\n") + let unknown = try SourceImport.preview(fixture.input(.claudeCommandV1, "review.md")) + #expect(unknown.components.isEmpty) + #expect(unknown.diagnostics.contains { $0.code == .unconverted && $0.location.span?.line == 4 }) + try fixture.write("review.md", "---\nzzz: 3.5\ndescription: Review\n---\nReview.\n") + let decimalUnknown = try SourceImport.preview(fixture.input(.claudeCommandV1, "review.md")) + #expect(decimalUnknown.components.isEmpty) + #expect( + decimalUnknown.diagnostics.contains { $0.code == .unconverted && $0.location.span?.line == 2 } + ) + let cursorBody = "---\nnot-frontmatter: [this is prompt text\n---\nKeep all bytes.\n" + try fixture.write("review.md", cursorBody) + let cursor = try SourceImport.preview(fixture.input(.cursorCommandV1, "review.md")) + guard case .command(_, _, .literal(let body), _, _, _, _) = cursor.components.first?.declaration + else { + Issue.record("Expected plain Cursor prompt") + return + } + #expect(body == cursorBody) + } + + @Test func sharedLSPFieldsPreserveExtrasBindingsAndRefuseAbsentPrograms() throws { + let fixture = try NativeImportFixture() + try fixture.write("bundle/.claude-plugin/plugin.json", #"{"name":"bundle"}"#) + try fixture.write( + "bundle/.lsp.json", + #"{"source":{"command":"${CLAUDE_PLUGIN_ROOT}/server","extensionToLanguage":{".s":"source"},"transport":"socket","workspaceFolder":"workspace","requestTimeout":4,"settings":{"nested":[true,7]},"initializationOptions":{"feature":true},"env":{"TOKEN":"SHARED_SECRET_CANARY"}}}"# + ) + try fixture.write("bundle/server", "#!/bin/sh\nexit 0\n", executable: true) + let before = try fixture.hash() + let result = try SourceImport.preview( + fixture.input(.claudePluginV1, "bundle/.claude-plugin/plugin.json")) + guard + case .lspServer(_, let run, _, let options, _, _, let native) = result.components.first? + .declaration + else { + Issue.record("Expected native LSP") + return + } + #expect(run.executable == "./server") + #expect(run.workingDirectory == nil) + #expect(options == ["feature": .boolean(true)]) + #expect(native[AgentID.claudeCode.rawValue]?["workspaceFolder"] == .string("workspace")) + #expect( + native[AgentID.claudeCode.rawValue]?["settings"] + == .object(["nested": .array([.boolean(true), .integer(7)])])) + #expect(!String(reflecting: result).contains("SHARED_SECRET_CANARY")) + #expect( + result.resources.contains { + $0.path == ".lsp.json" && $0.requiresBindingRewrite && $0.observedHash == nil + }) + #expect(try fixture.hash() == before) + try fixture.write( + "opencode.json", + #"{"lsp":{"builtin":{"disabled":true},"empty":{"command":[]},"valid":{"command":["source-lsp"],"initialization":{"feature":true}}}}"# + ) + let open = try SourceImport.preview(fixture.input(.openCodeConfigV2, "opencode.json")) + #expect(open.components.map(\.member?.selector) == [.lspServer(name: "valid")]) + #expect(open.diagnostics.filter { $0.code == .unconverted }.count == 2) + try fixture.write( + "bundle/.lsp.json", + #"{"source":{"command":"server","extensionToLanguage":{".s":"source"},"requestTimeout":0}}"#) + let invalid = try SourceImport.preview( + fixture.input(.claudePluginV1, "bundle/.claude-plugin/plugin.json")) + #expect(invalid.components.isEmpty) + #expect( + invalid.diagnostics.contains { + $0.code == .invalidInput && $0.location.document == "bundle/.lsp.json" + && $0.location.pointer == "/member[0]/member[2]" && $0.location.span != nil + }) + try fixture.write("opencode.json", #"{"lsp":{"source":{"command":17}}}"#) + let wrapped = try SourceImport.preview(fixture.input(.openCodeConfigV2, "opencode.json")) + #expect(wrapped.components.isEmpty) + #expect( + wrapped.diagnostics.contains { + $0.code == .invalidInput && $0.location.document == "opencode.json" + && $0.location.pointer == "/member[0]/member[0]/member[0]" + }) + } + + @Test func sharedPluginDefaultsReplaceClaudeCommandsAgentsAndValidateRealDocuments() throws { + let fixture = try NativeImportFixture() + try fixture.write( + "bundle/.claude-plugin/plugin.json", + #"{"name":"bundle","commands":"./chosen/review.md","agents":"./chosen/auditor.md"}"#) + try fixture.write("bundle/commands/ignored.md", "Ignored default\n") + try fixture.write( + "bundle/agents/ignored.md", "---\nname: ignored\ndescription: Ignored\n---\nIgnored default\n" + ) + try fixture.write("bundle/chosen/review.md", "Chosen command\n") + try fixture.write( + "bundle/chosen/auditor.md", "---\nname: auditor\ndescription: Inspect\n---\nChosen agent\n") + try fixture.write("bundle/hooks/hooks.json", #"{"hooks":{"invented":[]}}"#) + let input = fixture.input(.claudePluginV1, "bundle/.claude-plugin/plugin.json") + let invalidDefault = try SourceImport.preview(input) + #expect( + invalidDefault.components.map(\.member?.selector) == [ + .command(name: "review"), .subagent(name: "auditor"), + ]) + #expect( + invalidDefault.diagnostics.contains { + $0.code == .unconverted && $0.location.document == "bundle/hooks/hooks.json" + }) + try fixture.write("bundle/hooks/hooks.json", #"{"hooks":{}}"#) + let valid = try SourceImport.preview(input) + #expect(valid.diagnostics.isEmpty) + try fixture.write( + "bundle/.claude-plugin/plugin.json", #"{"name":"bundle","agents":"./chosen"}"#) + let wrongKind = try SourceImport.preview(input) + #expect( + wrongKind.diagnostics.contains { + $0.code == .invalidInput && $0.location.document == input.document + }) + } + + @Test func nativeSensitiveDefaultsRequireBindingsBeforeManifestPreservation() throws { + let fixture = try NativeImportFixture() + try fixture.write( + "bundle/.claude-plugin/plugin.json", + #"{"name":"bundle","userConfig":{"access":{"type":"string","title":"Access","description":"Local binding","sensitive":true,"default":"USER_CONFIG_SECRET_CANARY"}}}"# + ) + let result = try SourceImport.preview( + fixture.input(.claudePluginV1, "bundle/.claude-plugin/plugin.json")) + #expect(!result.bindings.isEmpty) + #expect(!String(reflecting: result).contains("USER_CONFIG_SECRET_CANARY")) + #expect( + result.resources.contains { + $0.path == ".claude-plugin/plugin.json" && $0.requiresBindingRewrite + && $0.observedHash == nil + }) + } + + @Test(arguments: [false, true]) + func multiplePluginConfigurationInputsKeepExactFailureDocument(_ firstInvalid: Bool) throws { + let fixture = try NativeImportFixture() + try fixture.write( + "bundle/.claude-plugin/plugin.json", + #"{"name":"bundle","mcpServers":["./first.json","./second.json"]}"#) + let invalid = "{\n \"mcpServers\": {\n \"same\": {\n \"command\": 17\n }\n }\n}" + let valid = #"{"mcpServers":{"same":{"command":"tool"}}}"# + try fixture.write("bundle/first.json", firstInvalid ? invalid : valid) + try fixture.write("bundle/second.json", firstInvalid ? valid : invalid) + let before = try fixture.hash() + let result = try SourceImport.preview( + fixture.input(.claudePluginV1, "bundle/.claude-plugin/plugin.json")) + #expect(result.components.count == (firstInvalid ? 1 : 0)) + let invalidDocument = firstInvalid ? "bundle/first.json" : "bundle/second.json" + #expect( + result.diagnostics.contains { + $0.code == .invalidInput && $0.location.document == invalidDocument + && $0.location.pointer == "/member[0]/member[0]/member[0]" + && $0.location.span?.line == 4 + }) + #expect( + !result.diagnostics.contains { + $0.code == .invalidInput && $0.location.document != invalidDocument + }) + #expect(try fixture.hash() == before) + } + + @Test func overlappingPreservationResourcesUseCompleteBindingClassification() throws { + let fixture = try NativeImportFixture() + try fixture.write( + "opencode.jsonc", + #"{"mcp":{"servers":{"clean":{"type":"local","command":["tool"],"cwd":"."}}},"lsp":{"language":{"command":["language-server"],"env":{"TOKEN":"LATE_LITERAL_CANARY"}}}}"# + ) + let before = try fixture.hash() + let result = try SourceImport.preview(fixture.input(.openCodeConfigV2, "opencode.jsonc")) + #expect(result.components.count == 2) + let directory = try #require(result.resources.first { $0.path == "." }) + #expect(directory.requiresBindingRewrite) + #expect(directory.observedHash == nil) + #expect(!String(reflecting: result).contains("LATE_LITERAL_CANARY")) + #expect(try fixture.hash() == before) + + try fixture.write( + "bundle/.claude-plugin/plugin.json", + #"{"name":"bundle","lspServers":"./skills/audit/language.json"}"#) + try fixture.write( + "bundle/skills/audit/SKILL.md", "---\nname: audit\ndescription: Audit\n---\nBody\n") + try fixture.write( + "bundle/skills/audit/language.json", + #"{"language":{"command":"language-server","extensionToLanguage":{".x":"x"},"env":{"TOKEN":"LATE_SKILL_CANARY"}}}"# + ) + let bundleBefore = try fixture.hash() + let bundle = try SourceImport.preview( + fixture.input(.claudePluginV1, "bundle/.claude-plugin/plugin.json")) + #expect(bundle.components.contains { $0.declaration.kind == .skills }) + let skill = try #require(bundle.resources.first { $0.kind == .skills }) + #expect(skill.requiresBindingRewrite) + #expect(skill.observedHash == nil) + #expect(!String(reflecting: bundle).contains("LATE_SKILL_CANARY")) + #expect(try fixture.hash() == bundleBefore) + } + + @Test(arguments: [SourceImportProfile.openCodeCommandV2, .openCodeAgentV2]) + func openCodeMarkdownRejectsInvalidDescriptionAtOriginalField(_ profile: SourceImportProfile) + throws + { + let fixture = try NativeImportFixture() + try fixture.write("review.md", "---\ndescription: [invalid]\n---\nBody\n") + let before = try fixture.hash() + let result = try SourceImport.preview(fixture.input(profile, "review.md")) + #expect(result.components.isEmpty) + #expect( + result.diagnostics.contains { + $0.code == .invalidInput && $0.location.document == "review.md" + && $0.location.span?.line == 2 + }) + #expect(try fixture.hash() == before) + try fixture.write("review.md", "---\ndescription: Review\n---\nBody\n") + let valid = try SourceImport.preview(fixture.input(profile, "review.md")) + #expect(valid.components.count == 1) + #expect(valid.diagnostics.isEmpty) + } + + @Test func geminiExtensionHooksRemainVisibleAndPrivatelyPreserved() throws { + let fixture = try NativeImportFixture() + try fixture.write("bundle/gemini-extension.json", #"{"name":"bundle","version":"1"}"#) + try fixture.write( + "bundle/commands/review.toml", "description='Review'\nprompt='Review changes'\n") + try fixture.write( + "bundle/hooks/hooks.json", + #"{"hooks":{"BeforeTool":[{"hooks":[{"type":"command","command":"./check","token":"HOOK_LITERAL_CANARY"}]}]}}"# + ) + let before = try fixture.hash() + let result = try SourceImport.preview( + fixture.input(.geminiExtensionV1, "bundle/gemini-extension.json")) + #expect(result.components.count == 1) + #expect(result.components.first?.declaration.kind == .command) + #expect( + result.diagnostics.contains { + $0.code == .unconverted && $0.location.document == "bundle/hooks/hooks.json" + }) + #expect(result.bindings.contains { $0.location.document == "bundle/hooks/hooks.json" }) + let hooks = try #require(result.resources.first { $0.path == "hooks/hooks.json" }) + #expect(hooks.requiresBindingRewrite && hooks.observedHash == nil) + #expect(!String(reflecting: result).contains("HOOK_LITERAL_CANARY")) + #expect(try fixture.hash() == before) + } + + @Test func nativeMemberCoordinatesPreserveExactUTF8Selectors() throws { + let fixture = try NativeImportFixture() + try fixture.write("unicode/.claude-plugin/plugin.json", #"{"name":"unicode"}"#) + for (path, name) in [("first", "\u{e9}"), ("second", "e\u{301}")] { + try fixture.write( + "unicode/agents/" + path + ".md", + "---\nname: \(name)\ndescription: Agent\n---\nBody\n") + } + let result = try SourceImport.preview( + fixture.input(.claudePluginV1, "unicode/.claude-plugin/plugin.json")) + #expect(result.components.count == 2) + let members = result.components.compactMap(\.member) + #expect(members.count == 2) + #expect(members.first != members.last) + #expect(!result.diagnostics.contains { $0.code == .ambiguousSource }) + let first = try #require(members.first) + #expect(first == first) + try fixture.write( + "unicode/agents/second.md", "---\nname: \u{e9}\ndescription: Agent\n---\nBody\n") + let duplicate = try SourceImport.preview( + fixture.input(.claudePluginV1, "unicode/.claude-plugin/plugin.json")) + #expect(duplicate.components.isEmpty) + #expect(duplicate.diagnostics.contains { $0.code == .ambiguousSource }) + } + + @Test func typedMembersStayStableWhenCallerMovesTheInputRoot() throws { + let one = try NativeImportFixture() + let two = try NativeImportFixture() + for fixture in [one, two] { + try fixture.write("bundle/.cursor-plugin/plugin.json", #"{"name":"bundle"}"#) + try fixture.write("bundle/commands/review.md", "Review\n") + } + let a = try SourceImport.preview( + one.input(.cursorPluginV1, "bundle/.cursor-plugin/plugin.json")) + let b = try SourceImport.preview( + two.input(.cursorPluginV1, "bundle/.cursor-plugin/plugin.json")) + #expect(a.components.map(\.member) == b.components.map(\.member)) + #expect(a.components.map(\.origin) == b.components.map(\.origin)) + #expect(a.resources.map(\.observedHash) == b.resources.map(\.observedHash)) + } +} + +private final class NativeImportFixture { + let root: URL + init() throws { + root = FileManager.default.temporaryDirectory.appendingPathComponent( + "native-import-" + UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + } + deinit { do { try FileManager.default.removeItem(at: root) } catch { Issue.record(error) } } + func write(_ path: String, _ text: String, executable: Bool = false) throws { + let file = root.appendingPathComponent(path) + try FileManager.default.createDirectory( + at: file.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data(text.utf8).write(to: file) + if executable { + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: file.path) + } + } + func input(_ profile: SourceImportProfile, _ path: String) -> SourceImportInput { + .init(profile: profile, root: root, document: path) + } + func hash() throws -> String { try FileHash.folderHash(root) } +} diff --git a/Tests/ComponentsTests/ImportPinnedFixtures.swift b/Tests/ComponentsTests/ImportPinnedFixtures.swift new file mode 100644 index 0000000..969550e --- /dev/null +++ b/Tests/ComponentsTests/ImportPinnedFixtures.swift @@ -0,0 +1,114 @@ +// Exact sample data from the pinned producer releases. No fixture command is executed. +enum ImportPinnedFixtures { + // https://github.com/microsoft/apm/blob/787a97cc52fbbcc344374e1567b2a1e5b8adf441/apm.yml + static let apmManifest = #""" + name: apm + version: 0.10.0 + description: APM (Agent Package Manager) -- ship and govern AI agent context + includes: auto + author: Microsoft + license: Apache-2.0 + + # Pinned so every contributor's `apm install` deploys the same tree this + # repo commits (.github/ plus .agents/skills/ via skills convergence), + # instead of auto-detecting whichever harness their machine signals. + # Contributors on another harness opt in with `apm install --target `. + targets: + - copilot + + # Local-path manifest deps on the extracted skill packages. + # Each was INLINE in .apm/skills/ until the v2 extraction. + # Extraction unlocks consumer reuse of each primitive standalone + # (consumers can install just a panel for single-PR review / single- + # issue triage, or an orchestrator entrypoint which transitively + # pulls its engine + panels). + # + # User-facing schedulers are declared here. Workers arrive + # transitively: + # - autopilot-issue-triage-scheduler -> autopilot-issue-triage-worker + # - autopilot-issue-delivery-scheduler -> autopilot-issue-delivery-worker + # - autopilot-pr-triage-scheduler -> autopilot-pr-triage-worker + # - autopilot-pr-review-scheduler -> autopilot-pr-review-worker + # - autopilot-pr-merge-worker is summoned by name (never by + # the PR review scheduler) + dependencies: + apm: + - ./packages/autopilot/autopilot-issue-triage-scheduler + - ./packages/autopilot/autopilot-issue-delivery-scheduler + - ./packages/autopilot/autopilot-pr-triage-scheduler + - ./packages/autopilot/autopilot-pr-review-scheduler + - ./packages/autopilot/autopilot-pr-merge-worker + mcp: [] + + scripts: {} + """# + "\n" + // https://github.com/dyoshikawa/rulesync/blob/fbe4fe58334cab4e84b87f20d730d6450a35e0f7/rulesync.jsonc + static let rulesyncConfig = #""" + { + "$schema": "https://github.com/dyoshikawa/rulesync/releases/latest/download/config-schema.json", + + // Per-target features using the new object form on `targets`. + // See docs/guide/configuration.md for details. + "targets": { + "copilot": { + "rules": { + "ruleDiscoveryMode": "explicit", + "includeLocalRoot": false + }, + "commands": true, + "mcp": false, + "subagents": true, + "skills": true, + "hooks": true + }, + "claudecode": { + "rules": true, + "commands": true, + "mcp": true, + "subagents": true, + "skills": true, + "hooks": true + }, + "opencode": { + "rules": true, + "commands": true, + "mcp": true, + "subagents": true, + "skills": true, + "hooks": true + }, + "codexcli": { + "rules": true, + "commands": false, + "mcp": false, + "subagents": true, + "skills": true, + "hooks": false, + "permissions": true + }, + "takt": { + "rules": true, + "commands": true, + "subagents": true, + "skills": true + } + }, + + // Output root directory or directories for generation. + "outputRoots": ["."], + + // Delete existing files before generating + "delete": true, + "verbose": true, + "silent": false, + + "simulateCommands": true, + "simulateSubagents": true, + "simulateSkills": true, + + // When true (default), `rulesync gitignore` only emits entries for the + // tools listed in `targets`. + "gitignoreTargetsOnly": false + } + """# + "\n" +} diff --git a/Tests/ComponentsTests/ImportProfileTests.swift b/Tests/ComponentsTests/ImportProfileTests.swift new file mode 100644 index 0000000..99f4da7 --- /dev/null +++ b/Tests/ComponentsTests/ImportProfileTests.swift @@ -0,0 +1,725 @@ +import AgentsCore +import Components +import Foundation +import Testing + +struct ImportProfileTests { + @Test func pinnedProducerSamplesRemainReadOnlyAndReportUnconvertedSemantics() throws { + let fixture = try ImportProfileFixture() + #expect( + FileHash.sha256Hex(data: Data(ImportPinnedFixtures.apmManifest.utf8)) + == "66261774fac336a23e4521fde39fb822e606527e32a0de8144993710bf4ce726") + #expect( + FileHash.sha256Hex(data: Data(ImportPinnedFixtures.rulesyncConfig.utf8)) + == "68c1da2097de1f81408cf08eac0f033cdf8c793d75d2e340cb10113b2f652fb7") + try fixture.write("apm.yml", ImportPinnedFixtures.apmManifest) + try fixture.write("rulesync.jsonc", ImportPinnedFixtures.rulesyncConfig) + try fixture.directory(".rulesync") + let before = try fixture.hash() + let apm = try SourceImport.preview(fixture.input(.apmManifest, "apm.yml")) + let rulesync = try SourceImport.preview(fixture.input(.rulesyncConfig, "rulesync.jsonc")) + #expect(try fixture.hash() == before) + #expect(apm.sources.count == 5) + #expect(apm.selections.first?.values == ["copilot"]) + #expect(apm.selections.last?.automatic == true) + #expect(apm.diagnostics.contains { $0.code == .incompletePin }) + #expect(!rulesync.diagnostics.contains { $0.code == .invalidInput }) + #expect(rulesync.diagnostics.contains { $0.code == .unconverted }) + #expect(rulesync.components.isEmpty) + } + + @Test func apmPackageIdentityIsLocatedMetadataAndDoesNotBlockAuthoringContent() throws { + let fixture = try ImportProfileFixture() + // APM permits a manifest with only its required package identity fields. + try fixture.write("apm.yml", "name: example\nversion: '1.0.0'\n") + try fixture.write( + ".apm/skills/review/SKILL.md", + "---\nname: review\ndescription: Review\n---\n# Review\n") + let before = try fixture.hash() + let proposal = try SourceImport.preview(fixture.input(.apmManifest, "apm.yml")) + #expect(proposal.diagnostics.isEmpty) + #expect(proposal.bindings.isEmpty) + #expect(proposal.components.count == 1) + #expect(proposal.resources.first?.requiresStandaloneSource == true) + let metadata = try #require(proposal.packageMetadata) + #expect(metadata.name == "example") + #expect(metadata.version == "1.0.0") + #expect(metadata.nameLocation.document == "apm.yml") + #expect(metadata.nameLocation.span?.line == 1) + #expect(metadata.versionLocation?.span?.line == 2) + #expect(proposal.profile.producerRevision == "787a97cc52fbbcc344374e1567b2a1e5b8adf441") + #expect(try fixture.hash() == before) + + try fixture.write("apm.yml", "name: example\nversion: '1.0.0'\nscripts: {start: never-run}\n") + let unresolved = try SourceImport.preview(fixture.input(.apmManifest, "apm.yml")) + #expect(unresolved.packageMetadata == metadata) + #expect( + unresolved.diagnostics.contains { $0.code == .unconverted && $0.location.span?.line == 3 }) + #expect(!String(reflecting: unresolved).contains("never-run")) + + try fixture.write("apm.yml", "name: https://user:METADATA_SECRET@host.test\nversion: '1.0.0'\n") + let privateMetadata = try SourceImport.preview(fixture.input(.apmManifest, "apm.yml")) + #expect(privateMetadata.packageMetadata == nil) + #expect(!privateMetadata.bindings.isEmpty) + #expect(!String(reflecting: privateMetadata).contains("METADATA_SECRET")) + } + + @Test func apmCompositionNeedsMatchingCoordinatesAndCapturesExplicitContentHonestly() throws { + let fixture = try ImportProfileFixture() + try fixture.write( + "apm.yml", + "name: fixture\nversion: '1.0.0'\ndependencies:\n apm:\n - git: https://github.com/acme/repo\n path: exports\n ref: main\n" + ) + try fixture.write( + "apm.lock.yaml", + "lockfile_version: '1'\ndependencies:\n - repo_url: https://github.com/acme/repo\n virtual_path: exports\n resolved_ref: main\n resolved_commit: \(String(repeating: "a", count: 40))\n" + ) + let result = try SourceImport.previewAPM( + manifest: fixture.input(.apmManifest, "apm.yml"), + lock: fixture.input(.apmLock, "apm.lock.yaml")) + #expect(result.sources[0].pin.commit == String(repeating: "a", count: 40)) + #expect(result.sources[0].requestedRef == "main") + #expect( + result.sources[0].declaration?.requirement == .revision(String(repeating: "a", count: 40))) + #expect( + !result.diagnostics.contains { + $0.code == .incompletePin && $0.location.document == "apm.yml" + }) + try fixture.write( + "apm.yml", + "name: fixture\nversion: '1.0.0'\ndependencies:\n apm:\n - git: https://github.com/acme/repo\n path: exports\n ref: changed\n" + ) + let mismatch = try SourceImport.previewAPM( + manifest: fixture.input(.apmManifest, "apm.yml"), + lock: fixture.input(.apmLock, "apm.lock.yaml")) + #expect(mismatch.sources[0].pin.commit == nil) + #expect(mismatch.diagnostics.contains { $0.code == .ambiguousSource }) + try fixture.write( + "installed/review/SKILL.md", + "---\nname: review\ndescription: fixture\nx-unknown: value\nenv: {TOKEN: secret-sentinel}\n---\nactual installed bytes\n" + ) + var input = fixture.input(.apmLock, "apm.lock.yaml") + input.installedSkills = ["review": "installed/review"] + let before = try fixture.hash() + let captured = try SourceImport.preview(input) + #expect(try fixture.hash() == before) + #expect(captured.resources.last?.observedHash?.hasPrefix("sha256:") == true) + #expect(captured.resources.last?.requiresStandaloneSource == true) + #expect(captured.components.count == 1) + #expect(captured.sources.last?.pin.commit == nil) + #expect(!captured.bindings.isEmpty) + #expect(!String(reflecting: captured).contains("secret-sentinel")) + } + + @Test func apmNativeSkillLayoutDoesNotGuessPluginFallbackOrTreatIncludesAsScope() throws { + let fixture = try ImportProfileFixture() + try fixture.write( + "apm.yml", + "name: fixture\nversion: '1.0.0'\nincludes: [.apm/instructions]\ntargets: [codex]\n") + try fixture.write( + ".apm/skills/review/SKILL.md", + "---\nname: review\ndescription: fixture\n---\nactual source bytes\n") + try fixture.write( + ".apm/instructions/review.instructions.md", "---\ndescription: review\n---\nbody\n") + try fixture.write( + "skills/fallback/SKILL.md", + "---\nname: fallback\ndescription: fixture\n---\nunselected plugin-native bytes\n") + let before = try fixture.hash() + let result = try SourceImport.preview(fixture.input(.apmManifest, "apm.yml")) + #expect(try fixture.hash() == before) + #expect(result.components.count == 1) + #expect(result.resources.first?.producerName == "review") + #expect(result.resources.first?.observedHash?.hasPrefix("sha256:") == true) + #expect(result.resources.first?.requiresStandaloneSource == true) + #expect(result.sources.first?.declaration?.location == ".apm/skills/review") + #expect( + result.diagnostics.contains { + $0.code == .unconverted && $0.location.pointer.contains("layout") + }) + #expect(result.selections.first?.values == ["codex"]) + #expect(result.selections.last?.values == [".apm/instructions"]) + } + + @Test func apmManifestPreservesIntentAndRefPrecedenceWithoutPinsOrScopeGuessing() throws { + let fixture = try ImportProfileFixture() + try fixture.write( + "apm.yml", + """ + name: on + version: '1.2.3' + targets: [claude, codex] + includes: [docs, .apm/skills] + dependencies: + apm: + - git: https://github.com/acme/repo + ref: main + version: old-version + path: packages/review + skills: [review] + targets: [claude] + x-extra: not-retained + mcp: + - name: private + env: + TOKEN: secret-sentinel + scripts: + start: never-execute-sentinel + devDependencies: + apm: [acme/dev#v2] + x-extension: secret-sentinel + """) + let before = try fixture.hash() + let proposal = try SourceImport.preview(fixture.input(.apmManifest, "apm.yml")) + #expect(try fixture.hash() == before) + #expect(proposal.sources.count == 2) + #expect(proposal.sources[0].requestedRef == "main") + #expect(proposal.sources[0].declaration?.location == "https://github.com/acme/repo") + #expect(proposal.sources[0].declaration?.path == "packages/review") + #expect(proposal.sources.allSatisfy { $0.pin.commit == nil }) + #expect(proposal.components.isEmpty) + #expect(proposal.resources.allSatisfy { $0.requiresStandaloneSource }) + #expect(proposal.selections.map(\.kind) == [.targets, .includes, .skills, .targets]) + #expect(!proposal.bindings.isEmpty) + #expect(proposal.diagnostics.contains { $0.location.span?.line == 22 }) + #expect(!String(reflecting: proposal).contains("secret-sentinel")) + #expect(!String(reflecting: proposal).contains("never-execute-sentinel")) + #expect(proposal.profile.specificationStatus.contains("unratified")) + } + + @Test func apmLocksKeepGitCommitRegistryIntegrityAndResolvedRefDistinct() throws { + let fixture = try ImportProfileFixture() + try fixture.write( + "apm.lock.yaml", + """ + lockfile_version: '2' + apm_version: '0.35.1' + dependencies: + - repo_url: https://github.com/acme/repo + resolved_commit: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + resolved_ref: moving-branch + version: '1.2.3' + virtual_path: packages/review + deployed_files: [.agents/skills/review/SKILL.md] + tree_sha256: sha256:\(String(repeating: "b", count: 64)) + - repo_url: acme/archive + source: registry + version: '2.0.0' + resolved_url: https://registry.example/archive.tgz + resolved_hash: sha512:\(String(repeating: "c", count: 128)) + - repo_url: https://github.com/acme/unlocked + resolved_ref: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + local_deployed_files: [.agents/skills/local/SKILL.md] + mcp_configs: + hidden: + headers: {Authorization: secret-sentinel} + """) + let before = try fixture.hash() + let proposal = try SourceImport.preview(fixture.input(.apmLock, "apm.lock.yaml")) + #expect(try fixture.hash() == before) + #expect(proposal.sources.count == 3) + #expect(proposal.sources[0].pin.commit == String(repeating: "a", count: 40)) + #expect(proposal.sources[0].resolvedRef == "moving-branch") + #expect(proposal.sources[0].pin.integrity?.kind == .apmDigest) + #expect(proposal.sources[1].pin.commit == nil) + #expect( + proposal.sources[1].pin.integrity?.value == "sha512:" + String(repeating: "c", count: 128)) + #expect(proposal.sources[1].resolvedURL == "https://registry.example/archive.tgz") + #expect(proposal.sources[2].pin.commit == nil) + #expect(proposal.deployments.first?.files == [".agents/skills/review/SKILL.md"]) + #expect(proposal.components.isEmpty) + #expect(!proposal.bindings.isEmpty) + #expect(!String(reflecting: proposal).contains("secret-sentinel")) + } + + @Test func rulesyncYAMLLocksAreDistinctAndDeploymentsDoNotInventSkillSourcePaths() throws { + let fixture = try ImportProfileFixture() + try fixture.write( + "gh.yml", + """ + lockfile_version: '1' + generated_at: '2026-01-01' + installations: + - source: acme/repo + owner: acme + repo: repo + agent: codex + scope: user + skill: review + requested_ref: main + resolved_ref: main + resolved_commit: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + install_dir: .agents/skills/review + deployed_files: [.agents/skills/review/SKILL.md] + content_hash: sha256:\(String(repeating: "b", count: 64)) + new_field: hidden + """) + let gh = try SourceImport.preview(fixture.input(.rulesyncGitHubV1, "gh.yml")) + #expect(gh.sources.first?.pin.commit == String(repeating: "a", count: 40)) + #expect(gh.sources.first?.requestedRef == "main") + #expect(gh.sources.first?.pin.integrity?.kind == .rulesyncSHA256) + #expect(gh.resources.first?.path == nil) + #expect(gh.deployments.first?.scope == "user") + #expect(gh.deployments.first?.agent == "codex") + #expect(gh.components.isEmpty) + #expect(gh.diagnostics.contains { $0.code == .unconverted }) + try fixture.write( + "mirror.yml", + """ + lockfile_version: '1' + generated_at: '2026-01-01' + apm_version: rulesync-compat + dependencies: + - repo_url: https://github.com/acme/repo + resolved_ref: main + depth: 1 + package_type: apm_package + content_hash: arbitrary-producer-string + deployed_files: [] + """) + let mirror = try SourceImport.preview(fixture.input(.rulesyncAPMV1, "mirror.yml")) + #expect(mirror.sources.first?.pin.commit == nil) + #expect(mirror.sources.first?.pin.integrity == nil) + #expect(mirror.sources.first?.resolvedRef == "main") + #expect(mirror.diagnostics.contains { $0.code == .incompletePin }) + #expect(mirror.profile.producerRevision != SourceImportProfile.apmLock.producerRevision) + #expect(!String(reflecting: mirror).contains("arbitrary-producer-string")) + } + + @Test(arguments: ["3", "true", "1"]) + func yamlLockVersionUsesStringIdentityAndRefusesCandidates(_ version: String) throws { + let fixture = try ImportProfileFixture() + try fixture.write("lock.yml", "lockfile_version: \(version)\ndependencies: []\n") + let result = try SourceImport.preview(fixture.input(.apmLock, "lock.yml")) + #expect(result.sources.isEmpty) + #expect(result.diagnostics.first?.code == .unsupportedVersion) + #expect(result.diagnostics.first?.location.span?.line == 1) + } + + @Test func yamlAdmissionLocationsAndLimitsAreValueFree() throws { + let fixture = try ImportProfileFixture() + try fixture.write("bad.yml", "name: secret-sentinel\nname: secret-sentinel\n") + let result = try SourceImport.preview(fixture.input(.apmManifest, "bad.yml")) + #expect(result.diagnostics.first?.code == .invalidInput) + #expect(result.diagnostics.first?.location.span != nil) + #expect(!String(reflecting: result).contains("secret-sentinel")) + try fixture.write("deep.yml", "name: a\nversion: '1.0.0'\nx-extra: [[[[[deep]]]]]\n") + var limits = SourceImportLimits() + limits.depth = 3 + let bounded = try SourceImport.preview(fixture.input(.apmManifest, "deep.yml"), limits: limits) + #expect(bounded.sources.isEmpty) + #expect(bounded.diagnostics.last?.code == .invalidInput) + } + + @Test func configJSONCPreservesBytesAndLocalOverrideDoesNotMergeSourceArrays() throws { + let fixture = try ImportProfileFixture() + try fixture.write( + "rulesync.jsonc", + """ + // Explicit project config; no init-template discovery. + {"sources":[{"source":"acme/base"}], "inputRoots":["primary"], + "targets":["codex"], "features":["skills"],} + """) + try fixture.write( + "local.jsonc", + """ + {"sources":[{"source":"gitlab:acme/local@release:export", "skills":["*"]}], + "inputRoot":"legacy", "targets":["claudecode"]} + """) + try fixture.directory("primary") + let before = try fixture.hash() + let result = try SourceImport.previewRulesync(configs: [ + fixture.input(.rulesyncConfig, "rulesync.jsonc"), + fixture.input(.rulesyncConfig, "local.jsonc"), + ]) + #expect(try fixture.hash() == before) + #expect(result.orderedSources.count == 1) + #expect(result.orderedSources[0].identity == "gitlab:acme/local@release:export") + #expect(result.orderedSources[0].requestedRef == "release") + #expect(result.orderedSources[0].skillsPath == "export") + #expect(result.sources[0].declaration?.location == "https://gitlab.com/acme/local") + #expect(result.selections.first?.values == ["claudecode"]) + #expect(!result.diagnostics.contains { $0.code == .missingResource }) + } + + @Test func remoteSourceOrderWinsIndependentlyOfSortedLockOrder() throws { + let fixture = try ImportProfileFixture() + try fixture.directory(".rulesync") + try fixture.write( + "rulesync.jsonc", + """ + {"sources":[{"source":"z/first"},{"source":"a/last"}]} + """) + try fixture.write( + "rulesync.lock", + """ + {"lockfileVersion":1,"sources":{ + "a/last":{"resolvedRef":"\(String(repeating: "a", count: 40))","skillsPath":"skills","skillSelection":["*"],"skills":{"review":{"integrity":"sha256-\(String(repeating: "b", count: 64))"}}}, + "z/first":{"resolvedRef":"\(String(repeating: "c", count: 40))","skillsPath":"skills","skillSelection":["*"],"skills":{"review":{"integrity":"sha256-\(String(repeating: "d", count: 64))"}}}}} + """) + let before = try fixture.hash() + let result = try SourceImport.previewRulesync( + configs: [fixture.input(.rulesyncConfig, "rulesync.jsonc")], + locks: [fixture.input(.rulesyncSourcesV1, "rulesync.lock")]) + #expect(try fixture.hash() == before) + #expect( + result.sources.filter { !$0.alias.contains("-skill-") }.map(\.pin.commit) == [ + String(repeating: "c", count: 40), String(repeating: "a", count: 40), + ]) + #expect(result.resources.map(\.selected) == [true, false]) + #expect(result.components.count == 1) + #expect( + result.components.first?.declaration + == .skills(source: "rulesync-source-0-skill-0", .init(select: .names(["review"])))) + #expect(result.resources.map(\.sourceAlias) == ["rulesync-source-0", "rulesync-source-1"]) + #expect(result.resources.allSatisfy { $0.requiresStandaloneSource }) + } + + @Test func npmConfigRetainsRegistryAndSymbolicBindingWithoutConsultingEnvironment() throws { + let fixture = try ImportProfileFixture() + try fixture.directory(".rulesync") + try fixture.write( + "config.jsonc", + "{\"sources\":[{\"source\":\"@acme/pkg\",\"transport\":\"npm\",\"ref\":\"latest\",\"registry\":\"https://registry.example\",\"tokenEnv\":\"IMPORT_PRIVATE_TOKEN\"}]}" + ) + let result = try SourceImport.preview(fixture.input(.rulesyncConfig, "config.jsonc")) + #expect(result.orderedSources.first?.registry == "https://registry.example") + #expect(result.sources.first?.registry == "https://registry.example") + #expect(result.sources.first?.requestedRef == "latest") + #expect(result.bindings.first?.environmentVariable == "IMPORT_PRIVATE_TOKEN") + #expect(result.sources.first?.pin.commit == nil) + #expect(result.sources.first?.pin.version == nil) + #expect(result.diagnostics.contains { $0.code == .incompletePin }) + #expect(result.components.isEmpty) + } + + @Test func repeatedRepositoryQualifiersUseExplicitConfigFieldsAndOccurrenceOrder() throws { + let fixture = try ImportProfileFixture() + try fixture.directory(".rulesync") + try fixture.write( + "config.jsonc", + """ + {"sources":[{"source":"acme/repo", "path":"skills/a", "ref":"team/release"}, + {"source":"acme/repo", "path":"skills/a", "ref":"team/release"}]} + """) + let hash = String(repeating: "a", count: 40) + try fixture.write( + "lock.json", + """ + {"lockfileVersion":1,"sources":{ + "acme/repo#path=skills/a&ref=team/release":{"requestedRef":"team/release","resolvedRef":"\(hash)","skillsPath":"skills/a","skills":{}}, + "acme/repo#path=skills/a&ref=team/release&entry=2":{"requestedRef":"team/release","resolvedRef":"\(hash)","skillsPath":"skills/a","skills":{}}}} + """) + let result = try SourceImport.previewRulesync( + configs: [fixture.input(.rulesyncConfig, "config.jsonc")], + locks: [fixture.input(.rulesyncSourcesV1, "lock.json")]) + #expect(result.sources.count == 2) + #expect(result.sources.allSatisfy { $0.pin.commit == hash }) + #expect( + !result.diagnostics.contains { $0.code == .ambiguousSource || $0.code == .incompletePin }) + } + + @Test(arguments: ["empty", "valid", "selection"]) + func sourceOccurrencesStayAlignedWithCompleteProducerList(_ first: String) throws { + let fixture = try ImportProfileFixture() + try fixture.directory(".rulesync") + let firstSource = first == "selection" ? "github:acme/repo" : "acme/repo" + let firstSkills = first == "empty" ? "[]" : #"["*"]"# + try fixture.write( + "config.jsonc", + """ + {"sources":[{"source":"\(firstSource)","skills":\(firstSkills)}, + {"source":"acme/repo","skills":["*"]}]} + """) + let commitA = String(repeating: "a", count: 40) + let commitB = String(repeating: "b", count: 40) + let integrityA = "sha256-" + String(repeating: "c", count: 64) + let integrityB = "sha256-" + String(repeating: "d", count: 64) + try fixture.write( + "lock.json", + """ + {"lockfileVersion":1,"sources":{ + "acme/repo":{"resolvedRef":"\(commitA)","skillsPath":"skills","skillSelection":["*"], + "skills":{"from-a":{"integrity":"\(integrityA)"}}}, + "acme/repo#entry=2":{"resolvedRef":"\(commitB)","skillsPath":"skills","skillSelection":["*"], + "skills":{"from-b":{"integrity":"\(integrityB)"}}}}} + """) + var config = fixture.input(.rulesyncConfig, "config.jsonc") + if first == "selection" { config.selection = ["acme/repo"] } + let before = try fixture.hash() + let result = try SourceImport.previewRulesync( + configs: [config], locks: [fixture.input(.rulesyncSourcesV1, "lock.json")]) + let acceptedBoth = first == "valid" + let sources = result.sources.filter { !$0.alias.contains("-skill-") } + #expect(sources.map(\.pin.commit) == (acceptedBoth ? [commitA, commitB] : [commitB])) + #expect(sources.last?.alias == "rulesync-source-1") + #expect(sources.last?.declaration?.requirement == .revision(commitB)) + #expect( + result.orderedSources.map(\.origin.pointer) + == (acceptedBoth ? ["/sources/0", "/sources/1"] : ["/sources/1"])) + #expect( + result.resources.map(\.producerName) == (acceptedBoth ? ["from-a", "from-b"] : ["from-b"])) + #expect( + result.resources.map(\.path) + == (acceptedBoth ? ["skills/from-a", "skills/from-b"] : ["skills/from-b"])) + #expect(result.resources.last?.sourceAlias == "rulesync-source-1") + #expect(result.resources.last?.producerIntegrity?.value == integrityB) + #expect(result.resources.allSatisfy { $0.requiresStandaloneSource }) + #expect( + result.components.last?.declaration + == .skills(source: "rulesync-source-1-skill-0", .init(select: .names(["from-b"])))) + #expect(result.components.count == (acceptedBoth ? 2 : 1)) + #expect( + result.diagnostics.contains { + $0.code == .invalidInput && $0.location.document == "config.jsonc" + && $0.location.pointer == "/sources/0/skills" + } == (first == "empty")) + #expect( + !result.diagnostics.contains { + $0.code == .incompletePin && $0.location.document == "config.jsonc" + && $0.location.pointer == "/sources/1" + }) + #expect(try fixture.hash() == before) + } + + @Test func embeddedRulesyncSelectorPreservesExplicitSourceAndLockedResources() throws { + let fixture = try ImportProfileFixture() + try fixture.directory(".rulesync") + try fixture.write( + "config.jsonc", #"{"sources":[{"source":"acme/repo@main:skills"}]}"#) + let commit = String(repeating: "a", count: 40) + try fixture.write( + "lock.json", + """ + {"lockfileVersion":1,"sources":{"acme/repo@main:skills":{ + "requestedRef":"main","resolvedRef":"\(commit)","skillsPath":"skills", + "skillSelection":["*"],"skills":{"review":{"integrity":"sha256-\(String(repeating: "b", count: 64))"}}}}} + """) + let before = try fixture.hash() + var lock = fixture.input(.rulesyncSourcesV1, "lock.json") + lock.sourceDeclarations = [ + "acme/repo@main:skills": .init(kind: .git, location: "https://github.com/acme/repo") + ] + let standalone = try SourceImport.preview(lock) + let ordered = try SourceImport.previewRulesync( + configs: [fixture.input(.rulesyncConfig, "config.jsonc")], locks: [lock]) + for result in [standalone, ordered] { + #expect(result.bindings.isEmpty) + #expect(result.sources.first?.producerIdentity == "acme/repo@main:skills") + #expect(result.sources.first?.pin.commit == commit) + #expect(result.sources.first?.requestedRef == "main") + #expect(result.sources.last?.declaration?.location == "https://github.com/acme/repo") + #expect(result.sources.last?.declaration?.requirement == .revision(commit)) + #expect(result.resources.map(\.path) == ["skills/review"]) + #expect( + result.resources.first?.producerIntegrity?.value == "sha256-" + + String(repeating: "b", count: 64)) + #expect(result.components.count == 1) + #expect( + !result.diagnostics.contains { $0.code == .ambiguousSource || $0.code == .incompletePin }) + } + #expect(try fixture.hash() == before) + } + + @Test func staleLockCannotBroadenCurrentSourceIntent() throws { + let fixture = try ImportProfileFixture() + try fixture.directory(".rulesync") + try fixture.write( + "config.jsonc", #"{"sources":[{"source":"acme/repo","ref":"new","skills":["*"]}]}"#) + try fixture.write( + "lock.json", + "{\"lockfileVersion\":1,\"sources\":{\"acme/repo\":{\"requestedRef\":\"old\",\"resolvedRef\":\"\(String(repeating: "a", count: 40))\",\"skillsPath\":\"skills\",\"skillSelection\":[\"*\"],\"skills\":{\"review\":{\"integrity\":\"sha256-\(String(repeating: "b", count: 64))\"}}}}}" + ) + let stale = try SourceImport.previewRulesync( + configs: [fixture.input(.rulesyncConfig, "config.jsonc")], + locks: [fixture.input(.rulesyncSourcesV1, "lock.json")]) + #expect(stale.sources.first?.pin.commit == nil) + #expect(stale.resources.isEmpty) + #expect(stale.components.isEmpty) + #expect(stale.diagnostics.contains { $0.code == .ambiguousSource }) + } + + @Test(arguments: [ + #""skills":[]"#, #""rules":[]"#, #""skills":[],"rules":[]"#, + #""skills":["*"],"rules":[]"#, #""skills":[],"rules":["*"]"#, + ]) + func emptySelectionInvalidatesWholeRemoteSource(_ fields: String) throws { + let fixture = try ImportProfileFixture() + try fixture.directory(".rulesync") + try fixture.write("config.jsonc", "{\"sources\":[{\"source\":\"acme/repo\",\(fields)}]}") + try fixture.write( + "lock.json", + """ + {"lockfileVersion":1,"sources":{"acme/repo":{"resolvedRef":"\(String(repeating: "a", count: 40))", + "skillsPath":"skills","skillSelection":["*"],"skills":{"review":{"integrity":"sha256-\(String(repeating: "b", count: 64))"}}, + "rulesPath":"rules","rules":{"overview":{"integrity":"sha256-\(String(repeating: "c", count: 64))"}}}}} + """) + let before = try fixture.hash() + let result = try SourceImport.previewRulesync( + configs: [fixture.input(.rulesyncConfig, "config.jsonc")], + locks: [fixture.input(.rulesyncSourcesV1, "lock.json")]) + #expect(result.sources.isEmpty) + #expect(result.orderedSources.isEmpty) + #expect(result.resources.isEmpty) + #expect(result.components.isEmpty) + #expect( + result.diagnostics.contains { + $0.code == .invalidInput && $0.location.document == "config.jsonc" + && ["/sources/0/skills", "/sources/0/rules"].contains($0.location.pointer) + }) + #expect(try fixture.hash() == before) + } + + @Test func defaultGitHubCredentialsAndUnknownTokenRequireBindingsWithoutLiterals() throws { + let fixture = try ImportProfileFixture() + try fixture.directory(".rulesync") + try fixture.write( + "config.jsonc", + #"{"sources":[{"source":"https://user:SECRET_LOCATOR@github.com/acme/repo"},{"source":"acme/repo","token":"SECRET_FIELD"}]}"# + ) + let before = try fixture.hash() + let result = try SourceImport.preview(fixture.input(.rulesyncConfig, "config.jsonc")) + #expect( + result.bindings.map(\.location.pointer) == ["/sources/0/source", "/sources/1/member[1]"]) + #expect(result.bindings.allSatisfy { $0.environmentVariable == nil }) + #expect( + result.diagnostics.contains { $0.code == .unconverted && $0.location.pointer == "/sources/0" } + ) + #expect( + result.diagnostics.contains { + $0.code == .unconverted && $0.location.pointer == "/sources/1/member[1]" + }) + #expect(result.sources.map(\.producerIdentity) == ["acme/repo"]) + #expect(!String(reflecting: result).contains("SECRET_LOCATOR")) + #expect(!String(reflecting: result).contains("SECRET_FIELD")) + #expect(try fixture.hash() == before) + } + + @Test func nativeInputConflictsAndYAMLCredentialLocatorsStayExplicit() throws { + let fixture = try ImportProfileFixture() + try fixture.write("bad.jsonc", "{\"targets\":{},\"features\":[]}") + let conflict = try SourceImport.preview(fixture.input(.rulesyncConfig, "bad.jsonc")) + #expect(conflict.diagnostics.last?.code == .invalidInput) + #expect(conflict.diagnostics.last?.location.span?.line == 1) + try fixture.write( + "bad.yml", + "lockfile_version: '2'\ndependencies:\n - repo_url: acme/archive\n source: registry\n version: '1.0.0'\n resolved_hash: sha256:\(String(repeating: "a", count: 64))\n resolved_url: https://user:secret-sentinel@registry.example/archive\n" + ) + let secret = try SourceImport.preview(fixture.input(.apmLock, "bad.yml")) + #expect(secret.sources.first?.resolvedURL == nil) + #expect(!secret.bindings.isEmpty) + #expect(secret.diagnostics.contains { $0.code == .incompletePin }) + #expect(!String(reflecting: secret).contains("secret-sentinel")) + try fixture.write("bad.yml", "lockfile_version: '3'\ndependencies: []\n") + try fixture.write( + "installed/review/SKILL.md", "---\nname: review\ndescription: fixture\n---\nprivate\n") + var request = fixture.input(.apmLock, "bad.yml") + request.installedSkills = ["review": "installed/review"] + let unsupported = try SourceImport.preview(request) + #expect(unsupported.resources.isEmpty) + #expect(unsupported.components.isEmpty) + } + + @Test func localCuratedAndInputRootCollisionsSelectActualContent() throws { + let fixture = try ImportProfileFixture() + try fixture.write("config.jsonc", "{\"inputRoots\":[\"one\",\"two\"]}") + for (path, body) in [ + ("one/skills/.curated/review/SKILL.md", "curated-one"), + ("one/skills/review/SKILL.md", "local-one"), + ("two/skills/.curated/review/SKILL.md", "curated-two"), + ("two/skills/review/SKILL.md", "local-two"), + ("one/rules/.curated/overview.md", "curated-rule"), + ("one/rules/overview.md", "local-rule"), + ] { try fixture.write(path, "---\nname: review\ndescription: fixture\n---\n\(body)\n") } + let before = try fixture.hash() + let result = try SourceImport.preview(fixture.input(.rulesyncConfig, "config.jsonc")) + #expect(try fixture.hash() == before) + #expect(result.resources.count == 2) + let skill = try #require(result.resources.first { $0.kind == .skills }) + #expect(skill.path == ".") + #expect(skill.observedHash != nil) + #expect(result.sources.last?.declaration?.location == "two/skills/review") + #expect(result.components.count == 1) + #expect(result.diagnostics.filter { $0.message.contains("precedence") }.count == 4) + } + + @Test func unknownSecretFieldsAndJSONCDuplicatesCannotEscape() throws { + let fixture = try ImportProfileFixture() + try fixture.write("config.jsonc", "{\"future\":{\"env\":{\"TOKEN\":\"secret-sentinel\"}}}") + let result = try SourceImport.preview(fixture.input(.rulesyncConfig, "config.jsonc")) + #expect(!result.bindings.isEmpty) + #expect(!String(reflecting: result).contains("secret-sentinel")) + try fixture.write("duplicate.jsonc", "{\"sources\":[], /* keep */ \"\\u0073ources\":[]}") + let duplicate = try SourceImport.preview(fixture.input(.rulesyncConfig, "duplicate.jsonc")) + #expect(duplicate.sources.isEmpty) + #expect(duplicate.diagnostics.last?.code == .invalidInput) + var limits = SourceImportLimits() + limits.documentBytes = 5 + #expect( + try SourceImport.preview(fixture.input(.rulesyncConfig, "config.jsonc"), limits: limits) + .diagnostics.last?.code == .invalidInput) + } + + @Test(arguments: ["alias", "entries", "bytes", "depth"]) + func capturedContentAdmissionRejectsMaliciousYAMLAndExceededBudgets(_ kind: String) throws { + let fixture = try ImportProfileFixture() + try fixture.write("lock.yml", "lockfile_version: '1'\ndependencies: []\n") + let header = + kind == "alias" + ? "name: &hidden review\ndescription: *hidden\n" + : "name: review\ndescription: fixture\nx-depth: [[[deep]]]\n" + try fixture.write("installed/review/SKILL.md", "---\n" + header + "---\nbody\n") + var limits = SourceImportLimits() + if kind == "entries" { limits.resourceEntries = 1 } + if kind == "bytes" { limits.resourceBytes = 10 } + if kind == "depth" { limits.depth = 2 } + var input = fixture.input(.apmLock, "lock.yml") + input.installedSkills = ["review": "installed/review"] + let before = try fixture.hash() + let result = try SourceImport.preview(input, limits: limits) + #expect(try fixture.hash() == before) + #expect(result.resources.isEmpty) + #expect(result.components.isEmpty) + #expect(result.diagnostics.contains { $0.code == .missingResource }) + #expect(!String(reflecting: result).contains("hidden")) + } + + @Test func inputRootsCannotEscapeOrReadLinkedContentOutsideBoundary() throws { + let fixture = try ImportProfileFixture() + let outside = try ImportProfileFixture() + try outside.write( + "skills/review/SKILL.md", "---\nname: review\ndescription: fixture\n---\nprivate\n") + try fixture.write("config.jsonc", "{\"inputRoots\":[\"../outside\"]}") + let traversal = try SourceImport.preview(fixture.input(.rulesyncConfig, "config.jsonc")) + #expect(traversal.diagnostics.contains { $0.code == .unsafePath }) + try FileManager.default.createSymbolicLink( + at: fixture.root.appendingPathComponent("linked"), withDestinationURL: outside.root) + try fixture.write("config.jsonc", "{\"inputRoots\":[\"linked\"]}") + let before = try outside.hash() + let linked = try SourceImport.preview(fixture.input(.rulesyncConfig, "config.jsonc")) + #expect(linked.resources.isEmpty) + #expect(linked.diagnostics.contains { $0.code == .unsafePath }) + #expect(try outside.hash() == before) + } +} + +private final class ImportProfileFixture { + let root: URL + init() throws { + root = FileManager.default.temporaryDirectory.appendingPathComponent( + "import-profiles-" + UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + } + deinit { try? FileManager.default.removeItem(at: root) } + func directory(_ path: String) throws { + try FileManager.default.createDirectory( + at: root.appendingPathComponent(path), withIntermediateDirectories: true) + } + func write(_ path: String, _ text: String) throws { + try directory((path as NSString).deletingLastPathComponent) + try Data(text.utf8).write(to: root.appendingPathComponent(path)) + } + func input(_ profile: SourceImportProfile, _ document: String) -> SourceImportInput { + .init(profile: profile, root: root, document: document) + } + func hash() throws -> String { try FileHash.folderHash(root) } +} diff --git a/Tests/ComponentsTests/ImportSourceTests.swift b/Tests/ComponentsTests/ImportSourceTests.swift new file mode 100644 index 0000000..ea9d7bb --- /dev/null +++ b/Tests/ComponentsTests/ImportSourceTests.swift @@ -0,0 +1,372 @@ +import AgentsCore +import Components +import Foundation +import Testing + +struct ImportSourceTests { + @Test func rulesyncGitPinAndCanonicalSkillPreserveResourceCoordinates() throws { + let fixture = try ImportSourceFixture() + try fixture.write( + """ + {"lockfileVersion":1,"sources":{"acme/repo":{"requestedRef":"main", + "resolvedRef":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","skillsPath":"exports/skills", + "skills":{"review":{"integrity":"sha256-\(String(repeating: "b", count: 64))"}}, + "rulesPath":"rules","rules":{"overview":{"integrity":"sha256-\(String(repeating: "c", count: 64))"}}, + "skillSelection":["*"],"future":true}}} + """) + var input = fixture.input(.rulesyncSourcesV1) + input.sourceDeclarations = [ + "acme/repo": .init(kind: .git, location: "https://gitlab.com/acme/repo") + ] + let before = try FileHash.folderHash(fixture.root) + let proposal = try SourceImport.preview(input) + #expect(try FileHash.folderHash(fixture.root) == before) + #expect(proposal.profile.producerRevision == "fbe4fe58334cab4e84b87f20d730d6450a35e0f7") + #expect(proposal.sources.first?.pin.commit == String(repeating: "a", count: 40)) + #expect(proposal.sources.first?.requestedRef == "main") + #expect(proposal.sources.last?.declaration?.location == "https://gitlab.com/acme/repo") + #expect(proposal.sources.last?.declaration?.path == "exports/skills/review") + #expect( + proposal.components.map(\.declaration) == [ + .skills(source: "import-source-0-skill-0", .init(select: .names(["review"]))) + ]) + #expect(proposal.resources.map(\.path) == ["exports/skills/review", "rules/overview.md"]) + #expect(proposal.resources.allSatisfy { $0.requiresStandaloneSource }) + #expect(proposal.diagnostics.filter { $0.code == .unconverted }.count == 3) + #expect(proposal.diagnostics.allSatisfy { $0.location.document == "input.json" }) + } + + @Test func normalizedRulesyncKeyNeverGuessesProviderOrPinsRequestedRef() throws { + let fixture = try ImportSourceFixture() + try fixture.write( + """ + {"lockfileVersion":1,"sources":{"org/repo#path=skills&ref=main":{ + "requestedRef":"\(String(repeating: "a", count: 40))","resolvedRef":"main", + "skillsPath":"skills","skills":{"review":{"integrity":""}}}}} + """) + let proposal = try SourceImport.preview(fixture.input(.rulesyncSourcesV1)) + #expect(proposal.components.isEmpty) + #expect(proposal.sources.first?.declaration == nil) + #expect(proposal.sources.first?.pin.commit == nil) + #expect(proposal.diagnostics.contains { $0.code == .ambiguousSource }) + #expect(proposal.diagnostics.filter { $0.code == .incompletePin }.count == 2) + } + + @Test func rulesyncRootFallbackDoesNotInventMemberDirectory() throws { + let fixture = try ImportSourceFixture() + try fixture.write( + """ + {"lockfileVersion":1,"sources":{"org/repo":{"resolvedRef":"\(String(repeating: "a", count: 40))", + "skillsPath":"exports","skillSelection":["review"], + "skills":{"review":{"integrity":"sha256-\(String(repeating: "b", count: 64))"}}}}} + """) + var input = fixture.input(.rulesyncSourcesV1) + input.sourceDeclarations = [ + "org/repo": .init(kind: .git, location: "https://github.com/org/repo") + ] + let proposal = try SourceImport.preview(input) + #expect(proposal.components.isEmpty) + #expect(proposal.resources.first?.producerName == "review") + #expect(proposal.resources.first?.path == nil) + #expect( + proposal.resources.first?.producerIntegrity?.value == "sha256-" + + String(repeating: "b", count: 64)) + #expect(proposal.diagnostics.contains { $0.message.contains("root fallback") }) + } + + @Test func npmProfileKeepsTarballAndResourceIntegritySeparate() throws { + let fixture = try ImportSourceFixture() + let sri = "sha512-" + Data(repeating: 1, count: 64).base64EncodedString() + try fixture.write( + """ + {"lockfileVersion":1,"sources":{ + "@acme/with-integrity":{"resolvedVersion":"1.2.3","requestedVersion":"latest","integrity":"\(sri)", + "skillsPath":"skills","skills":{"review":{"integrity":"sha256-\(String(repeating: "b", count: 64))"}}}, + "@acme/without-integrity":{"resolvedVersion":"1.2.3","skillsPath":"skills","skills":{}}}} + """) + let proposal = try SourceImport.preview(fixture.input(.rulesyncNpmV1)) + #expect(proposal.sources.count == 2) + #expect(proposal.sources[0].pin.integrity == .init(kind: .npmSRI, value: sri)) + #expect(proposal.sources[0].pin.version == "1.2.3") + #expect(proposal.sources[0].pin.commit == nil) + #expect(proposal.resources.first?.producerIntegrity?.kind == .rulesyncSHA256) + #expect(proposal.diagnostics.filter { $0.code == .incompletePin }.count == 1) + #expect(proposal.components.isEmpty) + } + + @Test(arguments: ["latest", "^1.2.3", "1.2.3-01", "1.2.3+.."]) + func npmResolvedVersionMustBeExact(_ version: String) throws { + let fixture = try ImportSourceFixture() + let sri = "sha512-" + Data(repeating: 1, count: 64).base64EncodedString() + try fixture.write( + """ + {"lockfileVersion":1,"sources":{"@acme/package":{"resolvedVersion":"\(version)", + "integrity":"\(sri)","skillsPath":"skills","skills":{}}}} + """) + let proposal = try SourceImport.preview(fixture.input(.rulesyncNpmV1)) + #expect(proposal.sources.first?.pin.version == nil) + #expect(proposal.sources.first?.pin.integrity?.kind == .npmSRI) + #expect(proposal.diagnostics.contains { $0.code == .incompletePin }) + } + + @Test(arguments: ["github", "node_modules"]) + func vercelProjectCapturesActualContentWithoutInventingGitCommit(_ sourceType: String) throws { + let fixture = try ImportSourceFixture() + try fixture.skill() + try fixture.write("first\r\nsecond\r\n", at: "installed/review/guide.txt") + try Data([0, 13, 10]).write(to: fixture.root.appendingPathComponent("installed/review/binary")) + try fixture.write("{}", at: "installed/review/metadata.json/ignored.txt") + let source = sourceType == "node_modules" ? "@acme/pkg" : "acme/repo" + let metadata = sourceType == "node_modules" ? #""version":"1.2.3","# : #""ref":"main","# + try fixture.write( + """ + {"version":2,"skills":{"review":{"source":"\(source)","sourceType":"\(sourceType)",\(metadata) + "skillPath":"skills/review/SKILL.md","computedHash":"8ab07122fdd17957fa92a18c05f175744b26f661c87f3f479ad6279e200713e3"}}} + """) + var input = fixture.input(.vercelProjectV2) + input.installedSkills = ["review": "installed/review"] + let before = try FileHash.folderHash(fixture.root) + let proposal = try SourceImport.preview(input) + #expect(try FileHash.folderHash(fixture.root) == before) + #expect(proposal.sources.first?.pin.commit == nil) + #expect(proposal.sources.first?.pin.integrity?.kind == .vercelInstalledSHA256) + #expect( + proposal.sources.first?.declaration?.path == (sourceType == "github" ? "skills/review" : nil)) + #expect(proposal.sources.last?.declaration?.kind == .local) + #expect(proposal.sources.last?.declaration?.location == "installed/review") + #expect( + proposal.resources.first?.observedHash == "sha256:" + + (try FileHash.folderHash(fixture.root.appendingPathComponent("installed/review")))) + #expect(proposal.resources.first?.requiresStandaloneSource == true) + #expect(proposal.resources.first?.path == ".") + #expect(proposal.components.count == 1) + #expect(proposal.sources.first?.producerIdentity == source) + #expect(proposal.sources.first?.pin.version == (sourceType == "node_modules" ? "1.2.3" : nil)) + #expect(proposal.sources.allSatisfy { $0.pin.commit == nil }) + #expect(proposal.bindings.isEmpty) + #expect( + proposal.diagnostics.map(\.code) + == (sourceType == "node_modules" ? [.incompletePin, .unconverted] : [.incompletePin])) + } + + @Test func vercelChangedContentCannotBePresentedAsLockedContent() throws { + let fixture = try ImportSourceFixture() + try fixture.skill() + try fixture.write( + """ + {"version":2,"skills":{"review":{"source":"acme/repo","sourceType":"github", + "computedHash":"\(String(repeating: "a", count: 64))"}}} + """) + var input = fixture.input(.vercelProjectV2) + input.installedSkills = ["review": "installed/review"] + let proposal = try SourceImport.preview(input) + #expect(proposal.components.isEmpty) + #expect(proposal.resources.isEmpty) + #expect(proposal.diagnostics.contains { $0.code == .integrityMismatch }) + } + + @Test func vercelUserTreeHashAndLastSelectionAreNotCommitOrTargeting() throws { + let fixture = try ImportSourceFixture() + try fixture.write( + """ + {"version":3,"lastSelectedAgents":["codex"],"skills":{"review":{ + "source":"acme/repo","sourceType":"github","sourceUrl":"https://github.com/acme/repo", + "skillFolderHash":"\(String(repeating: "a", count: 40))","ref":"main", + "installedAt":"2026-11-10T00:00:00Z","updatedAt":"2026-11-10T00:00:00Z", + "future":{"token":"SECRET_LITERAL"}}}} + """) + let proposal = try SourceImport.preview(fixture.input(.vercelUserV3)) + #expect(proposal.sources.first?.pin.commit == nil) + #expect(proposal.sources.first?.pin.integrity?.kind == .githubTree) + guard case .skills(_, let skill) = proposal.components.first?.declaration else { + Issue.record("Expected skill proposal") + return + } + #expect(skill.agents == nil) + #expect( + proposal.diagnostics.contains { + $0.code == .unconverted && $0.location.pointer == "/lastSelectedAgents" + }) + #expect( + proposal.diagnostics.contains { + $0.code == .unconverted && $0.location.pointer.hasSuffix("/member[0]/member[0]") + }) + #expect(!proposal.bindings.isEmpty) + #expect(!String(describing: proposal).contains("SECRET_LITERAL")) + } + + @Test(arguments: ["github", "node_modules"]) + func credentialSourceDoesNotEscapeThroughProvenanceOrDiagnostics(_ sourceType: String) throws { + let fixture = try ImportSourceFixture() + let source = + sourceType == "node_modules" ? "@acme/pkg" : "https://SECRET_LITERAL@github.com/acme/repo" + try fixture.write( + """ + {"version":2,"skills":{"review":{"source":"\(source)", + "sourceType":"\(sourceType)","sourceUrl":"https://github.com/acme/repo?token=SECRET_LITERAL","computedHash":""}}} + """) + let before = try FileHash.folderHash(fixture.root) + let proposal = try SourceImport.preview(fixture.input(.vercelProjectV2)) + #expect(try FileHash.folderHash(fixture.root) == before) + #expect(proposal.sources.isEmpty) + #expect(proposal.bindings.count == 1) + #expect(proposal.diagnostics.map(\.code) == [.credentialBinding]) + #expect(!String(describing: proposal).contains("SECRET_LITERAL")) + } + + @Test func vercelUserCapturePinsActualContentAndKeepsProducerTreeUnverified() throws { + let fixture = try ImportSourceFixture() + try fixture.skill() + try fixture.write( + """ + {"version":3,"skills":{"review":{"source":"acme/repo","sourceType":"github", + "sourceUrl":"https://github.com/acme/repo","skillFolderHash":"\(String(repeating: "a", count: 40))", + "installedAt":"2026-11-10T00:00:00Z","updatedAt":"2026-11-10T00:00:00Z"}}} + """) + var input = fixture.input(.vercelUserV3) + input.installedSkills = ["review": "installed/review"] + let before = try FileHash.folderHash(fixture.root) + let proposal = try SourceImport.preview(input) + #expect(try FileHash.folderHash(fixture.root) == before) + #expect(proposal.sources.allSatisfy { $0.pin.commit == nil }) + #expect(proposal.sources.last?.declaration?.kind == .local) + #expect(proposal.components.count == 1) + #expect(proposal.resources.first?.observedHash?.hasPrefix("sha256:") == true) + #expect(proposal.resources.first?.producerIntegrity?.kind == .githubTree) + #expect(proposal.diagnostics.contains { $0.message.contains("not verified") }) + } + + @Test(arguments: [ + "{\"version\":2,\"version\":2,\"skills\":{}}", + "{\"version\":2,\"skills\":{},\"sk\\u0069lls\":{}}", + "{\"version\":2,\"skills\":{}} trailing", + "[]", + "{\"version\":2,\"skills\":{},}", + ]) func malformedOrAmbiguousJSONIsRejected(_ text: String) throws { + let fixture = try ImportSourceFixture() + try fixture.write(text) + let proposal = try SourceImport.preview(fixture.input(.vercelProjectV2)) + #expect(proposal.components.isEmpty) + #expect(proposal.diagnostics.map(\.code) == [.invalidInput]) + } + + @Test(arguments: ["true", "1", "3", "null", "\"2\""]) + func unsupportedVersionDoesNotPartiallyImport(_ version: String) throws { + let fixture = try ImportSourceFixture() + try fixture.write("{\"version\":\(version),\"skills\":{}}") + let proposal = try SourceImport.preview(fixture.input(.vercelProjectV2)) + #expect(proposal.sources.isEmpty) + #expect(proposal.diagnostics.map(\.code) == [.unsupportedVersion]) + } + + @Test func selectionIsExplicitAndMissingSelectionIsDiagnosed() throws { + let fixture = try ImportSourceFixture() + try fixture.write("{\"version\":2,\"skills\":{\"unselected\":{\"bad\":true}}}") + var input = fixture.input(.vercelProjectV2) + input.selection = [] + #expect(try SourceImport.preview(input).diagnostics.isEmpty) + input.selection = ["absent"] + #expect(try SourceImport.preview(input).diagnostics.map(\.code) == [.invalidInput]) + } + + @Test func unknownPayloadAndWrongOptionalTypeAreNeverSilentlyAccepted() throws { + let fixture = try ImportSourceFixture() + try fixture.write( + """ + {"version":2,"contentObjects":{"unknown":"SECRET_LITERAL"},"skills":{"review":{ + "source":"acme/repo","sourceType":"github","computedHash":"","skillPath":17}}} + """) + let proposal = try SourceImport.preview(fixture.input(.vercelProjectV2)) + #expect(proposal.sources.isEmpty) + #expect(proposal.diagnostics.contains { $0.code == .unconverted }) + #expect(proposal.diagnostics.contains { $0.code == .invalidInput }) + #expect(proposal.diagnostics.last?.location.pointer == "/skills/member[0]/skillPath") + #expect(!String(describing: proposal).contains("SECRET_LITERAL")) + } + + @Test func rulesyncCredentialKeyIsRedactedAndLockProfilesAreDistinct() throws { + let fixture = try ImportSourceFixture() + try fixture.write( + """ + {"lockfileVersion":1,"sources":{"https://SECRET_LITERAL@github.com/org/repo":{ + "resolvedRef":"\(String(repeating: "a", count: 40))","skillsPath":"skills","skills":{}}}} + """) + let git = try SourceImport.preview(fixture.input(.rulesyncSourcesV1)) + #expect(git.sources.isEmpty) + #expect(git.bindings.count == 1) + #expect(!String(describing: git).contains("SECRET_LITERAL")) + let npm = try SourceImport.preview(fixture.input(.rulesyncNpmV1)) + #expect(npm.sources.isEmpty) + #expect(npm.diagnostics.contains { $0.code == .invalidInput }) + #expect(!String(describing: npm).contains("SECRET_LITERAL")) + } + + @Test func resourceLinksAndDocumentLimitsLeaveInputsUntouched() throws { + let fixture = try ImportSourceFixture() + try fixture.skill() + try FileManager.default.createSymbolicLink( + atPath: fixture.root.appendingPathComponent("installed/review/secret").path, + withDestinationPath: "/etc/hosts") + try fixture.write( + """ + {"version":2,"skills":{"review":{"source":"acme/repo","sourceType":"github", + "computedHash":"\(String(repeating: "a", count: 64))"}}} + """) + var input = fixture.input(.vercelProjectV2) + input.installedSkills = ["review": "installed/review"] + let before = try FileHash.folderHash(fixture.root) + let proposal = try SourceImport.preview(input) + #expect(proposal.components.isEmpty) + #expect(proposal.diagnostics.contains { $0.code == .unsafePath }) + var limits = SourceImportLimits() + limits.documentBytes = 8 + #expect( + try SourceImport.preview(input, limits: limits).diagnostics.map(\.code) == [.invalidInput]) + #expect(try FileHash.folderHash(fixture.root) == before) + } + + @Test func pathTraversalAndExternalSymlinksNeverBecomeResources() throws { + let fixture = try ImportSourceFixture() + try fixture.write( + """ + {"version":2,"skills":{"review":{"source":"acme/repo","sourceType":"github", + "skillPath":"../outside/SKILL.md","computedHash":""}}} + """) + #expect( + try SourceImport.preview(fixture.input(.vercelProjectV2)).diagnostics.map(\.code) == [ + .unsafePath + ]) + try FileManager.default.createSymbolicLink( + atPath: fixture.root.appendingPathComponent("external.json").path, + withDestinationPath: "/etc/hosts") + var input = fixture.input(.vercelProjectV2) + input = .init(profile: input.profile, root: input.root, document: "external.json") + #expect(try SourceImport.preview(input).diagnostics.map(\.code) == [.unsafePath]) + } +} + +private final class ImportSourceFixture { + let root: URL + init() throws { + root = FileManager.default.temporaryDirectory.appendingPathComponent( + "import-tests-" + UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + } + deinit { + do { try FileManager.default.removeItem(at: root) } catch { Issue.record(error) } + } + func write(_ text: String, at path: String = "input.json") throws { + let file = root.appendingPathComponent(path) + try FileManager.default.createDirectory( + at: file.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data(text.utf8).write(to: file) + } + func input(_ profile: SourceImportProfile) -> SourceImportInput { + .init(profile: profile, root: root, document: "input.json") + } + func skill() throws { + try write( + "---\nname: review\ndescription: Review changes\n---\n# Review\n", + at: "installed/review/SKILL.md") + } +} diff --git a/Tests/ComponentsTests/ImportSupportingLinksTests.swift b/Tests/ComponentsTests/ImportSupportingLinksTests.swift new file mode 100644 index 0000000..fcb64f1 --- /dev/null +++ b/Tests/ComponentsTests/ImportSupportingLinksTests.swift @@ -0,0 +1,257 @@ +import AgentsCore +import Foundation +import Testing + +@testable import Components + +#if canImport(Darwin) + import Darwin +#else + import Glibc +#endif + +struct ImportSupportingLinksTests { + @Test(arguments: [ + SourceImportProfile.claudePluginV1, .cursorPluginV1, .geminiExtensionV1, + ]) + func nativeSkillPreservesContainedChainedExecutableSupport(_ profile: SourceImportProfile) throws + { + let f = try SupportingSkillFixture(profile) + try f.write("bundle/shared/tool.txt", "Supporting executable\n", executable: true) + try f.link("bundle/shared/current", "tool.txt") + try f.link("bundle/skills/helper/reference.txt", "../../shared/current") + try f.write( + "bundle/shared/directory/SKILL.md", "---\nname: hidden\ndescription: Hidden\n---\nBody\n") + try f.link("bundle/skills/helper/data", "../../shared/directory") + let before = try FileHash.folderHash(f.root) + let proposal = try SourceImport.preview(f.input) + #expect(proposal.diagnostics.isEmpty) + #expect(proposal.components.count == 1) + let member = try #require(proposal.components.first) + #expect(member.member?.selector == .skill(name: "helper")) + #expect(member.member?.containerRoot == "bundle") + #expect(member.origin.document == "bundle/skills/helper/SKILL.md") + guard case .skills(let alias, let selection) = member.declaration else { + Issue.record("Expected selected skill declaration") + return + } + let source = try #require(proposal.sources.first { $0.alias == alias }) + #expect(source.declaration?.location == "bundle") + #expect(source.declaration?.path == nil) + #expect(selection.path == "skills/helper") + #expect(source.producerPath == "bundle") + #expect(selection.select == .names(["helper"])) + let preservation = try #require(proposal.resources.first { $0.kind == .skills }) + #expect(preservation.path == "skills/helper") + #expect(preservation.requiresStandaloneSource && !preservation.requiresBindingRewrite) + #expect( + proposal.sources.first { $0.alias == preservation.sourceAlias }?.producerPath == "bundle") + #expect( + preservation.observedHash + == "sha256:" + + (try FileHash.folderHash(f.root.appendingPathComponent("bundle/skills/helper")))) + #expect( + proposal.resources.contains { + $0.path == "shared/tool.txt" && $0.executableFlags["shared/tool.txt"] == true + }) + let captured = try LedgerResources.capture( + f.root.appendingPathComponent("bundle/skills/helper"), embed: true, limits: .standard, + sourceRoot: f.root.appendingPathComponent("bundle")) + #expect( + captured.entries.contains { $0.path == "reference.txt" && $0.link == "../../shared/current" }) + #expect(captured.support.contains { $0.path == "shared/current" && $0.link == "tool.txt" }) + #expect(captured.support.contains { $0.path == "shared/tool.txt" && $0.executable }) + #expect(try FileHash.folderHash(f.root) == before) + } + + @Test func linkedSkillClosureSurvivesProductionFreezeAndLedgerRoundTrip() throws { + let f = try LinkFixture() + try f.write(#"{"name":"bundle"}"#, to: "bundle/.claude-plugin/plugin.json", base: f.project) + try f.write( + "---\nname: helper\ndescription: Helper\n---\nBody\n", + to: "bundle/skills/helper/SKILL.md", base: f.project) + try f.write("Executable support\n", to: "bundle/shared/tool.txt", base: f.project) + try FileManager.default.setAttributes( + [.posixPermissions: 0o755], + ofItemAtPath: f.project.appendingPathComponent("bundle/shared/tool.txt").path) + try FileManager.default.createSymbolicLink( + atPath: f.project.appendingPathComponent("bundle/skills/helper/reference.txt").path, + withDestinationPath: "../../shared/tool.txt") + let declaration = try f.document( + """ + version: 1 + components: [{kind: plugin, name: bundle, source: ".", path: bundle, agents: [claude-code]}] + """) + let ledger = try ComponentLinker.withLinkedComponents( + document: declaration, store: f.store, platform: .macOS + ) { graph, session in + let locations = Dictionary( + (graph.sourceSnapshots + graph.declaringSnapshots).filter { + $0.source?.kind == .local && $0.container == nil + }.map { + ( + $0.snapshot.source, + LedgerLocation( + kind: .absolute, path: String($0.snapshot.source.dropFirst("local:".count))) + ) + }, uniquingKeysWith: { first, _ in first }) + return try LedgerFreeze.freeze( + graph, session: session, locations: .init(sources: locations), limits: .standard) + } + let skill = try #require(ledger.resources.values.first { $0.path.hasSuffix("skills/helper") }) + #expect( + skill.entries.contains { $0.path == "reference.txt" && $0.link == "../../shared/tool.txt" }) + #expect(skill.support.contains { $0.path.hasSuffix("shared/tool.txt") && $0.executable }) + let encoded = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + #expect(try ResolvedLedgerCodec.decode(encoded, limits: .standard) == ledger) + } + + @Test func laterSupportingDocumentCredentialsBlockTheEntireSkillCapture() throws { + let f = try SupportingSkillFixture(.claudePluginV1) + try f.write( + "bundle/.claude-plugin/plugin.json", + #"{"name":"bundle","lspServers":"./shared/language.json"}"#) + try f.write( + "bundle/shared/language.json", + #"{"review":{"command":"never-run","extensionToLanguage":{".txt":"text"},"env":{"TOKEN":"SUPPORT_LITERAL_CANARY"}}}"# + ) + try f.link("bundle/skills/helper/reference.txt", "../../shared/language.json") + let proposal = try SourceImport.preview(f.input) + let skill = try #require(proposal.resources.first { $0.kind == .skills }) + #expect(skill.requiresBindingRewrite && skill.observedHash == nil) + #expect( + proposal.resources.filter { $0.origin == skill.origin }.allSatisfy { + $0.requiresBindingRewrite && $0.observedHash == nil + }) + #expect(!proposal.bindings.isEmpty) + #expect(!String(reflecting: proposal).contains("SUPPORT_LITERAL_CANARY")) + } + + @Test(arguments: ["absolute", "outside", "missing", "cycle", "linkThenParent", "fifo"]) + func invalidSupportingClosureCannotEmitASkill(_ kind: String) throws { + let f = try SupportingSkillFixture(.claudePluginV1) + try f.write("bundle/shared/tool.txt", "Support\n") + let reference = "bundle/skills/helper/reference.txt" + switch kind { + case "absolute": + try f.link(reference, f.root.appendingPathComponent("bundle/shared/tool.txt").path) + case "outside": + try f.write("outside.txt", "Outside container\n") + try f.link(reference, "../../../outside.txt") + case "missing": try f.link(reference, "../../shared/missing.txt") + case "cycle": + try f.link(reference, "../../shared/loop") + try f.link("bundle/shared/loop", "../skills/helper/reference.txt") + case "linkThenParent": + try f.write("outside/dir/child.txt", "Child\n") + try f.write("outside/tool.txt", "Outside container\n") + try f.link("bundle/shared/jump", "../../outside/dir") + try f.link(reference, "../../shared/jump/../tool.txt") + default: + let fifo = f.root.appendingPathComponent("bundle/shared/pipe").path + #expect(mkfifo(fifo, 0o600) == 0) + try f.link(reference, "../../shared/pipe") + } + let proposal = try SourceImport.preview(f.input) + #expect(!proposal.diagnostics.isEmpty) + #expect(!proposal.components.contains { $0.declaration.kind == .skills }) + #expect(!proposal.resources.contains { $0.kind == .skills }) + } + + @Test func supportingLinksCannotDiscoverMembersOrChangeOtherProducerHashAdmission() throws { + let f = try SupportingSkillFixture(.cursorPluginV1) + try FileManager.default.removeItem( + at: f.root.appendingPathComponent("bundle/skills/helper/SKILL.md")) + try f.write( + "bundle/shared/SKILL.md", "---\nname: linked\ndescription: Linked\n---\nBody\n") + try f.link("bundle/skills/helper/SKILL.md", "../../shared/SKILL.md") + let proposal = try SourceImport.preview(f.input) + #expect(proposal.components.isEmpty) + #expect( + proposal.diagnostics.contains { + $0.code == .unconverted && $0.location.document.hasSuffix("SKILL.md") + }) + + let regular = try SupportingSkillFixture(.claudePluginV1) + try regular.write("bundle/shared/tool.txt", "Support\n") + try regular.link("bundle/skills/helper/reference.txt", "../../shared/tool.txt") + #expect(throws: (any Error).self) { + try ImportSkillContent.read("bundle/skills/helper", input: regular.input, limits: .init()) + } + var producer = regular.input + producer = .init(profile: .vercelProjectV2, root: producer.root, document: producer.document) + #expect(throws: (any Error).self) { + try ImportSkillContent.read( + "bundle/skills/helper", input: producer, limits: .init(), nativeContainer: "bundle") + } + } + + @Test func explicitMemberPathCannotTraverseALinkedDirectory() throws { + let f = try SupportingSkillFixture(.claudePluginV1) + try f.write( + "bundle/.claude-plugin/plugin.json", + #"{"name":"bundle","skills":"./alias/nested"}"#) + try f.write( + "bundle/real/nested/SKILL.md", "---\nname: linked\ndescription: Linked\n---\nBody\n") + try f.link("bundle/alias", "real") + let proposal = try SourceImport.preview(f.input) + #expect(!proposal.components.contains { $0.member?.selector == .skill(name: "linked") }) + #expect(proposal.components.contains { $0.member?.selector == .skill(name: "helper") }) + #expect( + proposal.diagnostics.contains { + $0.code == .unconverted && $0.location.document == "bundle/alias" + }) + } + + @Test(arguments: ["entries", "bytes", "depth"]) + func supportingClosureRemainsBounded(_ budget: String) throws { + let f = try SupportingSkillFixture(.geminiExtensionV1) + try f.write("bundle/shared/tool.txt", String(repeating: "S", count: 256)) + try f.link("bundle/skills/helper/reference.txt", "../../shared/tool.txt") + var limits = SourceImportLimits() + switch budget { + case "entries": limits.resourceEntries = 3 + case "bytes": limits.resourceBytes = 128 + default: limits.depth = 1 + } + #expect(throws: (any Error).self) { + try ImportSkillContent.read( + "bundle/skills/helper", input: f.input, limits: limits, nativeContainer: "bundle") + } + } +} + +private final class SupportingSkillFixture { + let root: URL + let input: SourceImportInput + init(_ profile: SourceImportProfile) throws { + root = FileManager.default.temporaryDirectory.appendingPathComponent( + "import-support-" + UUID().uuidString) + let document: String + switch profile { + case .claudePluginV1: document = "bundle/.claude-plugin/plugin.json" + case .cursorPluginV1: document = "bundle/.cursor-plugin/plugin.json" + default: document = "bundle/gemini-extension.json" + } + input = .init(profile: profile, root: root, document: document) + try write(document, #"{"name":"bundle","version":"1.2.3"}"#) + try write( + "bundle/skills/helper/SKILL.md", "---\nname: helper\ndescription: Helper\n---\nBody\n") + } + deinit { try? FileManager.default.removeItem(at: root) } + func write(_ path: String, _ text: String, executable: Bool = false) throws { + let file = root.appendingPathComponent(path) + try FileManager.default.createDirectory( + at: file.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data(text.utf8).write(to: file) + if executable { + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: file.path) + } + } + func link(_ path: String, _ target: String) throws { + let file = root.appendingPathComponent(path) + try FileManager.default.createDirectory( + at: file.deletingLastPathComponent(), withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink(atPath: file.path, withDestinationPath: target) + } +} diff --git a/Tests/ComponentsTests/LedgerReplayBudgetTests.swift b/Tests/ComponentsTests/LedgerReplayBudgetTests.swift new file mode 100644 index 0000000..8a2d43b --- /dev/null +++ b/Tests/ComponentsTests/LedgerReplayBudgetTests.swift @@ -0,0 +1,102 @@ +import AgentsCore +import AgentsInstructions +import Components +import Foundation +import Testing + +@Suite("Ledger replay aggregate budget") +struct LedgerReplayBudgetTests { + private func fixture(bytes: Int, repeats: Int, format: String = "agents/instructions@1") throws + -> (LinkFixture, ResolvedLedger) + { + let fixture = try LinkFixture() + let content = Data(repeating: 97, count: bytes) + let hash = "sha256:" + FileHash.sha256Hex(data: content) + var ledger = ResolvedLedger() + ledger.sources["root"] = .init(kind: .local, revision: "live") + ledger.contentObjects[hash] = content + ledger.resources["file"] = .init( + kind: .embedded, source: "root", path: "file", hash: hash, + entries: [.init(path: ".", kind: .file, object: hash, executable: false, byteCount: bytes)]) + #if os(macOS) + let platform = "macos" + #else + let platform = "linux" + #endif + ledger.lowerings = [ + .init( + id: "test", format: format, inputs: [], resources: Array(repeating: "file", count: repeats), + deployments: [], + layout: .init(object: ["name": .init("output"), "sectionCount": .init(integer: repeats)]), + platform: platform, artifacts: []) + ] + return (fixture, ledger) + } + + @Test(arguments: ["agents/instructions@1", "agents/chatgpt@1"]) + func repeatedInputsRejectBeforeResourceAcquisition(_ format: String) throws { + let (fixture, ledger) = try fixture(bytes: 1024 * 1024, repeats: 50_000, format: format) + // Invalid content hashes would fail later; the aggregate bound must be the first failure. + do { + _ = try LedgerReplay.prepareLowerings( + ledger, store: fixture.store, roots: [:], limits: .standard) + Issue.record("oversized replay accepted") + } catch { + #expect(String(describing: error).contains("replay input byte budget")) + } + } + + @Test func validRepeatsAndRetainedOutputsShareBudget() throws { + let (fixture, original) = try fixture(bytes: 3, repeats: 2, format: "test/budget@1") + var limits = LedgerLimits.standard + limits.resourceBytes = 12 + var calls = 0 + let renderer: LedgerRenderer = { lowering, _, _ in + calls += 1 + return [.init(name: lowering.id, kind: .file, bytes: Data(repeating: 98, count: 6))] + } + let table = ["test/budget@1": renderer] + _ = try LedgerReplay.prepareLowerings( + original, store: fixture.store, roots: [:], limits: limits, renderers: table) + #expect(calls == 1) + var ledger = original + var second = ledger.lowerings[0] + second.id = "second" + ledger.lowerings.append(second) + limits.resourceBytes = 18 + #expect(throws: (any Error).self) { + _ = try LedgerReplay.prepareLowerings( + ledger, store: fixture.store, roots: [:], limits: limits, renderers: table) + } + #expect(calls == 3) + } + @Test(arguments: ["agents/instructions@1", "agents/chatgpt@1"]) + func compatibilityOutputsUseRemainingAggregateBudget(_ format: String) throws { + let content = Data("---\ndescription: Example\n---\n# Example\n\nBody\n".utf8) + let (fixture, original) = try fixture(bytes: content.count, repeats: 1, format: format) + var ledger = original + let hash = "sha256:" + FileHash.sha256Hex(data: content) + ledger.contentObjects = [hash: content] + ledger.resources["file"]?.hash = hash + ledger.resources["file"]?.entries[0].object = hash + let output = + try format == "agents/instructions@1" + ? InstructionCompatibility.renderSections([content], ids: ["file"]) + : InstructionCompatibility.renderPrompt([content], ids: ["file"], append: nil) + var limits = LedgerLimits.standard + limits.resourceBytes = content.count * 2 + output.count * 2 - 1 + _ = try LedgerReplay.prepareLowerings(ledger, store: fixture.store, roots: [:], limits: limits) + var second = ledger.lowerings[0] + second.id = "second" + second.layout.object?["name"] = .init("second-output") + ledger.lowerings.append(second) + do { + _ = try LedgerReplay.prepareLowerings( + ledger, store: fixture.store, roots: [:], limits: limits) + Issue.record("aggregate output budget accepted") + } catch { + #expect(String(describing: error).contains("rendered instruction byte budget")) + } + } + +} diff --git a/Tests/ComponentsTests/LedgerReplayTests.swift b/Tests/ComponentsTests/LedgerReplayTests.swift new file mode 100644 index 0000000..f735128 --- /dev/null +++ b/Tests/ComponentsTests/LedgerReplayTests.swift @@ -0,0 +1,337 @@ +import AgentsCore +import AgentsManifest +import Components +import Foundation +import StateTestSupport +import Testing + +@Suite("Ledger reconstruction") +struct LedgerReplayTests { + @Test func coldSubprocessReconstructsFrozenBResult() throws { + let fixture = try LinkFixture() + let project = fixture.project + try fixture.write("#!/bin/sh\nexit 0\n", to: "bin/server", base: project) + try FileManager.default.setAttributes( + [.posixPermissions: 0o755], ofItemAtPath: project.appendingPathComponent("bin/server").path) + try fixture.write("# Frozen prompt\n", to: "prompts/task.md", base: project) + try fixture.write("vendor bytes\n", to: "vendor/data", base: project) + try FileManager.default.createDirectory( + at: project.appendingPathComponent("vendor/empty"), withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink( + atPath: project.appendingPathComponent("vendor/alias").path, withDestinationPath: "data") + try fixture.manifest( + """ + version: 1 + components: [{"kind": "mcpServer", "name": "server", "transport": {"kind": "stdio", "executable": "./bin/server"}}, {"kind": "command", "name": "task", "description": "Task", "prompt": {"file": {"path": "prompts/task.md"}}}, {"kind": "plugin", "name": "vendor", "path": "vendor", "source": ".", "mode": "native", "agents": ["claude-code"]}] + """, at: project) + try run("ledger-freeze", root: project) + let ledger = try fixture.store.loadLedger(limits: .standard) + #expect(!ledger.contentObjects.isEmpty) + let locked = try Data(contentsOf: fixture.store.resolvedURL) + let expected = try #require(ledger.lowerings.first).artifacts + let cold = fixture.root.appendingPathComponent("cold") + try FileManager.default.createDirectory( + at: cold.appendingPathComponent(".agent"), withIntermediateDirectories: true) + try FileManager.default.copyItem( + at: fixture.store.declarationURL, to: cold.appendingPathComponent(".agent/agents.yaml")) + try locked.write(to: cold.appendingPathComponent(".agent/agents.resolved")) + try FileManager.default.removeItem(at: project) + try run("ledger-replay", root: cold) + let actual = try JSONDecoder().decode( + [LedgerArtifactDigest].self, + from: Data(contentsOf: cold.appendingPathComponent("replay-summary.json"))) + #expect(actual == expected) + #expect(try Data(contentsOf: cold.appendingPathComponent(".agent/agents.resolved")) == locked) + #expect( + !FileManager.default.fileExists(atPath: cold.appendingPathComponent(".agent/cache").path)) + let tree = cold.appendingPathComponent("probe-bundle") + #expect( + FileManager.default.fileExists(atPath: tree.appendingPathComponent("resource-2/empty").path)) + #expect( + try FileManager.default.destinationOfSymbolicLink( + atPath: tree.appendingPathComponent("resource-2/alias").path) == "data") + let flags = try FileManager.default.attributesOfItem( + atPath: tree.appendingPathComponent("resource-0").path) + #expect(((flags[.posixPermissions] as? NSNumber)?.intValue ?? 0) & 0o111 != 0) + } + + @Test func freezeRejectsMutationAndMissingLocations() throws { + let fixture = try LinkFixture() + try fixture.write("before", to: "prompt.md", base: fixture.project) + let document = try fixture.document( + "version: 1\ncomponents: [{\"kind\": \"command\", \"name\": \"task\", \"description\": \"Task\", \"prompt\": {\"file\": {\"path\": \"prompt.md\"}}}]\n" + ) + try ComponentLinker.withLinkedComponents( + document: document, store: fixture.store, platform: .macOS + ) { graph, session in + #expect(throws: (any Error).self) { + _ = try LedgerFreeze.freeze( + graph, session: session, locations: .init(sources: [:]), limits: .standard) + } + try fixture.write("changed", to: "prompt.md", base: fixture.project) + #expect(throws: (any Error).self) { + _ = try LedgerFreeze.freeze( + graph, session: session, + locations: .init(sources: [ + "local:" + fixture.project.path: .init(kind: .registered, root: "project", path: ".") + ]), limits: .standard) + } + } + } + + @Test(arguments: ["content", "executable", "escape"]) + func linkedDirectoryResourceMutationIsRejectedBeforeFreeze(_ mutation: String) throws { + let fixture = try LinkFixture() + try fixture.write("support", to: "working/check", base: fixture.project) + let check = fixture.project.appendingPathComponent("working/check") + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: check.path) + let alias = fixture.project.appendingPathComponent("working-alias") + try FileManager.default.createSymbolicLink(atPath: alias.path, withDestinationPath: "working") + let document = try fixture.document( + """ + version: 1 + components: [{"kind": "mcpServer", "name": "server", "transport": {"kind": "stdio", "executable": "server", "workingDirectory": {"path": "working-alias"}}}] + """ + ) + try ComponentLinker.withLinkedComponents( + document: document, store: fixture.store, platform: .macOS + ) { graph, session in + if mutation == "content" { + try Data("changed".utf8).write(to: check) + } else if mutation == "executable" { + try FileManager.default.setAttributes([.posixPermissions: 0o644], ofItemAtPath: check.path) + } else { + try FileManager.default.removeItem(at: alias) + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: fixture.home) + } + #expect(throws: CoreError.self) { + _ = try LedgerFreeze.freeze( + graph, session: session, + locations: .init(sources: [ + "local:" + fixture.project.path: .init(kind: .registered, root: "project", path: ".") + ]), limits: .standard) + } + } + } + + private func run(_ action: String, root: URL) throws { + var directory = Bundle(for: LedgerTestBundle.self).bundleURL + while directory.path != "/", + !FileManager.default.isExecutableFile( + atPath: directory.appendingPathComponent("StateTestProcess").path) + { + directory.deleteLastPathComponent() + } + let child = Process() + child.executableURL = directory.appendingPathComponent("StateTestProcess") + child.arguments = [root.path, action] + child.environment = ProcessInfo.processInfo.environment + try child.run() + defer { if child.isRunning { try? ProcessWait.terminate(child) } } + try ProcessWait.exit(child, root: root) + try #require(child.terminationStatus == 0) + } +} +private final class LedgerTestBundle: NSObject {} + +@Suite("Ledger replay failure boundaries") +struct LedgerReplayFailureTests { + @Test func formatAndHashRejectWithoutFallbackAndCleanup() throws { + let fixture = try LinkFixture() + var ledger = ResolvedLedger() + ledger.sources["root"] = LedgerSource( + kind: .local, location: .init(kind: .registered, root: "project", path: "."), revision: "live" + ) + try fixture.write("frozen", to: "file", base: fixture.project) + let input = try LedgerResources.capture( + fixture.project.appendingPathComponent("file"), embed: true, limits: .standard) + ledger.contentObjects = input.objects + ledger.resources["file"] = LedgerResource( + kind: .embedded, source: "root", path: "file", hash: input.hash, entries: input.entries) + #if os(macOS) + let platform = "macos" + #else + let platform = "linux" + #endif + ledger.lowerings = [ + LockedLowering( + id: "test", format: "test/frozen@1", inputs: [], resources: ["file"], deployments: [], + layout: .init(), platform: platform, artifacts: []) + ] + var borrowed: URL? + let renderer: LedgerRenderer = { _, _, resources in + borrowed = resources["file"] + return [ + ReplayedArtifact(name: "file", kind: .file, bytes: try Data(contentsOf: resources["file"]!)) + ] + } + ledger = try LedgerReplay.prepareLowerings( + ledger, store: fixture.store, + roots: ["project": fixture.project], limits: .standard, renderers: ["test/frozen@1": renderer] + ) + #expect(borrowed.map { !FileManager.default.fileExists(atPath: $0.path) } == true) + #expect(throws: (any Error).self) { + try LedgerReplay.withReplay(ledger, store: fixture.store, roots: [:], limits: .standard) { + _ in + } + } + let changed: LedgerRenderer = { _, _, _ in + [.init(name: "file", kind: .file, bytes: Data("new output".utf8))] + } + #expect(throws: (any Error).self) { + try LedgerReplay.withReplay( + ledger, store: fixture.store, roots: [:], limits: .standard, + renderers: ["test/frozen@1": changed] + ) { _ in } + } + let cancelled: LedgerRenderer = { _, _, resources in + borrowed = resources["file"] + throw CancellationError() + } + #expect(throws: CancellationError.self) { + try LedgerReplay.withReplay( + ledger, store: fixture.store, roots: [:], limits: .standard, + renderers: ["test/frozen@1": cancelled] + ) { _ in } + } + #expect(borrowed.map { !FileManager.default.fileExists(atPath: $0.path) } == true) + try LedgerReplay.withReplay( + ledger, store: fixture.store, roots: [:], limits: .standard, + renderers: ["test/frozen@1": renderer] + ) { #expect($0.count == 1) } + ledger.resources["file"]?.hash = "sha256:" + String(repeating: "0", count: 64) + #expect(throws: (any Error).self) { + try LedgerReplay.withReplay( + ledger, store: fixture.store, roots: [:], limits: .standard, + renderers: ["test/frozen@1": renderer] + ) { _ in } + } + } +} + +@Suite("Ledger resource closure") +struct LedgerResourceClosureTests { + @Test func freezesSourceContainedLinksOutsideSelectedSubtree() throws { + let fixture = try LinkFixture() + try fixture.write("outside selected subtree", to: "shared/text", base: fixture.project) + try FileManager.default.createDirectory( + at: fixture.project.appendingPathComponent("vendor"), withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink( + atPath: fixture.project.appendingPathComponent("vendor/reference").path, + withDestinationPath: "../shared/text") + let document = try fixture.document( + "version: 1\ncomponents: [{\"kind\": \"plugin\", \"name\": \"vendor\", \"path\": \"vendor\", \"source\": \".\", \"mode\": \"native\", \"agents\": [\"claude-code\"]}]\n" + ) + var ledger = try ComponentLinker.withLinkedComponents( + document: document, store: fixture.store, platform: .macOS + ) { linked, session in + try LedgerFreeze.freeze( + linked, session: session, + locations: .init(sources: [ + "local:" + fixture.project.path: .init(kind: .registered, root: "project", path: ".") + ]), limits: .standard) + } + let resource = try #require(ledger.resources.keys.first) + #expect(!ledger.resources[resource]!.support.isEmpty) + #if os(macOS) + let platform = "macos" + #else + let platform = "linux" + #endif + ledger.lowerings = [ + .init( + id: "closure", format: "test/closure@1", inputs: [], resources: [resource], deployments: [], + layout: .init(), platform: platform, artifacts: []) + ] + let renderer: LedgerRenderer = { _, _, resources in + [ + .init( + name: "linked", kind: .file, + bytes: try Data(contentsOf: resources[resource]!.appendingPathComponent("reference"))) + ] + } + ledger = try LedgerReplay.prepareLowerings( + ledger, store: fixture.store, roots: [:], limits: .standard, + renderers: ["test/closure@1": renderer]) + let bytes = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + try FileManager.default.removeItem(at: fixture.project) + let cold = fixture.root.appendingPathComponent("cold") + try FileManager.default.createDirectory(at: cold, withIntermediateDirectories: true) + let coldStore = StateStore( + scope: .project, + environment: RuntimeEnvironment( + projectDirectory: cold, homeDirectory: fixture.home, environment: [:])) + try LedgerReplay.withReplay( + ResolvedLedgerCodec.decode(bytes, limits: .standard), store: coldStore, + roots: [:], limits: .standard, renderers: ["test/closure@1": renderer] + ) { artifacts in + #expect(artifacts[0].bytes == Data("outside selected subtree".utf8)) + } + } +} + +@Suite("Ledger exact Git inputs") +struct LedgerExactGitTests { + @Test func changedProducerAndBranchDoNotReselectLockedInput() throws { + let fixture = try LinkFixture() + let producer = fixture.root.appendingPathComponent("producer") + try fixture.initialize(producer) + try fixture.write("original", to: "prompt.md", base: producer) + try fixture.manifest( + """ + version: 1 + exports: ["task"] + groups: {"task": {"components": [{"kind": "command", "name": "task", "description": "Task", "prompt": {"file": {"path": "prompt.md"}}}]}} + """, at: producer) + let original = try fixture.commit(producer) + let document = try fixture.document( + """ + version: 1 + sources: {"producer": {"path": "../producer", "requirement": {"branch": "main"}}} + uses: [{"source": "producer", "group": "task"}] + """) + var ledger = try ComponentLinker.withLinkedComponents( + document: document, store: fixture.store, platform: .macOS + ) { linked, session in + try LedgerFreeze.freeze( + linked, session: session, + locations: .init(sources: [ + "local:" + fixture.project.path: .init(kind: .registered, root: "project", path: "."), + "local:" + producer.path: .init( + kind: .authoringRelative, root: "project", path: "../producer"), + ]), limits: .standard) + } + #expect(ledger.groups.first?.manifestHash.hasPrefix("sha256:") == true) + #expect(ledger.sources.values.contains { $0.revision == original }) + try fixture.write("changed", to: "prompt.md", base: producer) + try fixture.write("invalid producer manifest", to: ".agent/agents.yaml", base: producer) + _ = try fixture.commit(producer) + let resource = try #require(ledger.resources.keys.first) + #if os(macOS) + let platform = "macos" + #else + let platform = "linux" + #endif + ledger.lowerings = [ + .init( + id: "exact", format: "test/exact@1", inputs: [], resources: [resource], deployments: [], + layout: .init(), platform: platform, artifacts: []) + ] + let renderer: LedgerRenderer = { _, _, resources in + let bytes = try Data(contentsOf: resources[resource]!) + guard bytes == Data("original".utf8) else { + throw CoreError.invalidState("mutable input selected") + } + return [.init(name: "original", kind: .file, bytes: bytes)] + } + let roots = ["project": fixture.project] + ledger = try LedgerReplay.prepareLowerings( + ledger, store: fixture.store, roots: roots, limits: .standard, + renderers: ["test/exact@1": renderer]) + try LedgerReplay.withReplay( + ledger, store: fixture.store, roots: roots, limits: .standard, + renderers: ["test/exact@1": renderer] + ) { #expect($0[0].bytes == Data("original".utf8)) } + #expect(!FileManager.default.fileExists(atPath: fixture.store.cacheDirectory.path)) + } +} diff --git a/Tests/ComponentsTests/LinkBudgetTests.swift b/Tests/ComponentsTests/LinkBudgetTests.swift new file mode 100644 index 0000000..87ecfd3 --- /dev/null +++ b/Tests/ComponentsTests/LinkBudgetTests.swift @@ -0,0 +1,207 @@ +import AgentsCore +import Components +import Foundation +import Testing + +@Suite("Observable component bounds", .serialized) +struct LinkBudgetTests { + @Test func repeatedExportsShareExpandedManifestValueLimits() throws { + let fixture = try LinkFixture() + let producer = fixture.root.appendingPathComponent("expanded-values") + try fixture.initialize(producer) + let prompt = String(repeating: "p", count: 100_000) + try fixture.manifest( + """ + version: 1 + exports: ["g"] + groups: {"g": {"components": [{"kind": "command", "name": "review", "description": "Review", "prompt": "\(prompt)"}]}} + """, at: producer) + try fixture.commit(producer) + func expression(_ count: Int) -> String { + let uses = Array(repeating: "{group: g, source: p}", count: count) + .joined(separator: ",") + return + "version: 1\nsources: {\"p\": {\"path\": \"\(producer.path)\"}}\nuses: [\(uses)]\n" + } + #expect(try fixture.link(expression(100)).components.count == 100) + do { + _ = try fixture.link(expression(200)) + Issue.record("expected aggregate expanded-value limit") + } catch LinkError.budget(let name) { + #expect(name == "expanded manifest values") + } + } + + @Test func repeatedContributionsReachLimitAndRejectOverflow() throws { + let fixture = try LinkFixture() + try fixture.instruction("rules", at: fixture.project) + func expression(overflow: Bool) -> String { + let sections = Array(repeating: "name: rules", count: 10_000).joined(separator: ",") + let extra = overflow ? ", {kind: instructions, sections: [{name: rules}]}" : "" + return "version: 1\ncomponents: [{kind: instructions, sections: [\(sections)]}\(extra)]\n" + + } + #expect(try fixture.link(expression(overflow: false)).components.count == 10_000) + do { + _ = try fixture.link(expression(overflow: true)) + Issue.record("expected occurrence limit") + } catch LinkError.budget(let name) { + #expect(name == "contribution occurrences") + } + } + + @Test func oversizedProducerManifestFailsBeforeParsing() throws { + let fixture = try LinkFixture() + let producer = fixture.root.appendingPathComponent("producer") + try fixture.write( + String(repeating: " ", count: 2_097_153), to: ".agent/agents.yaml", base: producer) + do { + _ = try fixture.link( + "version: 1\nsources: {\"p\": {\"path\": \"\(producer.path)\"}}\nuses: [{\"source\": \"p\", \"group\": \"g\"}]\n" + ) + Issue.record("expected input limit") + } catch LinkError.budget(let name) { #expect(name == "manifest input bytes") } + } +} + +extension LinkBudgetTests { + @Test func distinctLiveSnapshotLimitCountsReusedViewsOnce() throws { + let fixture = try LinkFixture() + var sources: [String] = [] + var selections: [String] = [] + for index in 0..<257 { + let source = fixture.root.appendingPathComponent("live\(index)") + try fixture.skill("s\(index)", at: source) + sources.append("\"s\(index)\": {\"path\": \"\(source.path)\"}") + selections.append( + "{\"kind\": \"skills\", \"source\": \"s\(index)\", \"select\": [\"s\(index)\"], \"mode\": \"edit\"}" + ) + } + func expression(_ count: Int, repeated: Bool = false) -> String { + let selected = Array(selections.prefix(count)) + let components = repeated ? selected + selected : selected + return + "version: 1\nsources: {\(sources.prefix(count).joined(separator: ","))}\ncomponents: [\(components.joined(separator: ","))]\n" + } + #expect(try fixture.link(expression(256)).sourceSnapshots.count == 256) + #expect(try fixture.link(expression(256, repeated: true)).components.count == 512) + do { + _ = try fixture.link(expression(257)) + Issue.record("expected live snapshot limit") + } catch LinkError.budget(let name) { #expect(name == "distinct snapshots") } + } + + @Test func distinctSnapshotLimitUsesSourceContent() throws { + let fixture = try LinkFixture() + var sources: [String] = [] + var uses: [String] = [] + for index in 0..<257 { + let producer = fixture.root.appendingPathComponent("p\(index)") + try fixture.manifest( + "version: 1\nexports: [\"g\"]\ngroups: {\"g\": {}}\n", at: producer) + sources.append("\"p\(index)\": {\"path\": \"\(producer.path)\"}") + uses.append("{group: g, source: p\(index)}") + } + func expression(_ count: Int) -> String { + "version: 1\nsources: {\(sources.prefix(count).joined(separator: ","))}\nuses: [\(uses.prefix(count).joined(separator: ","))]\n" + } + #expect(try fixture.link(expression(256)).references.count == 256) + do { + _ = try fixture.link(expression(257)) + Issue.record("expected snapshot limit") + } catch LinkError.budget(let name) { #expect(name == "distinct snapshots") } + } + + @Test func containedLiveSnapshotsShareTheDistinctViewBudget() throws { + let fixture = try LinkFixture() + var sources: [String] = [] + var uses: [String] = [] + for index in 0..<129 { + let producer = fixture.root.appendingPathComponent("producer\(index)") + try fixture.skill("s\(index)", at: producer) + try fixture.manifest( + "version: 1\nexports: [\"g\"]\ngroups: {\"g\": {\"components\": [{\"kind\": \"skills\", \"source\": \".\", \"select\": [\"s\(index)\"], \"mode\": \"edit\"}]}}\n", + at: producer) + sources.append("\"p\(index)\": {\"path\": \"\(producer.path)\"}") + uses.append("{group: g, source: p\(index)}") + } + func expression(_ count: Int, repeated: Bool = false) -> String { + let selected = Array(uses.prefix(count)) + let references = repeated ? selected + selected : selected + return + "version: 1\nsources: {\(sources.prefix(count).joined(separator: ","))}\nuses: [\(references.joined(separator: ","))]\n" + } + #expect(try fixture.link(expression(128)).sourceSnapshots.count == 256) + #expect(try fixture.link(expression(128, repeated: true)).components.count == 256) + do { + _ = try fixture.link(expression(129)) + Issue.record("expected immutable and live views to share the snapshot limit") + } catch LinkError.budget(let name) { #expect(name == "distinct snapshots") } + } + + @Test func qualifiedReferenceDepthIsBounded() throws { + let fixture = try LinkFixture() + for count in [64, 65] { + let producer = fixture.root.appendingPathComponent("depth\(count)") + var directory = producer + for index in 0.. String { + "version: 1\nsources: {\(sources.prefix(count).joined(separator: ","))}\nuses: [\(uses.prefix(count).joined(separator: ","))]\n" + } + #expect(try fixture.link(expression(8)).references.count == 8) + do { + _ = try fixture.link(expression(9)) + Issue.record("expected aggregate manifest limit") + } catch LinkError.budget(let name) { #expect(name == "aggregate manifest bytes") } + } +} + +extension LinkBudgetTests { + @Test func repeatedReferenceProvenanceConsumesTotalWorkBudget() throws { + let fixture = try LinkFixture() + let groups = (0..<40).map { index in + index == 39 + ? "\"g39\": {}" + : "\"g\(index)\": {\"uses\": [{\"group\": \"g\(index + 1)\"}]}" + }.joined(separator: ",") + let uses = Array(repeating: "{group: g0}", count: 1500).joined(separator: ",") + do { + _ = try fixture.link("version: 1\ngroups: {\(groups)}\nuses: [\(uses)]\n") + Issue.record("expected total-work bound for repeated provenance") + } catch LinkError.budget(let name) { #expect(name == "resolution/evaluation steps") } + } +} diff --git a/Tests/ComponentsTests/LinkFixture.swift b/Tests/ComponentsTests/LinkFixture.swift new file mode 100644 index 0000000..ce46e04 --- /dev/null +++ b/Tests/ComponentsTests/LinkFixture.swift @@ -0,0 +1,97 @@ +import AgentsCore +import AgentsManifest +import Components +import Foundation +import Testing + +final class LinkFixture { + let root: URL + let project: URL + let home: URL + var environment: RuntimeEnvironment { + RuntimeEnvironment(projectDirectory: project, homeDirectory: home, environment: [:]) + } + var store: StateStore { StateStore(scope: .project, environment: environment) } + + init() throws { + root = FileManager.default.temporaryDirectory.appendingPathComponent( + "component-tests-" + UUID().uuidString) + project = root.appendingPathComponent("project") + home = root.appendingPathComponent("home") + try FileManager.default.createDirectory(at: project, withIntermediateDirectories: true) + try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true) + } + + deinit { + do { try FileManager.default.removeItem(at: root) } catch { Issue.record(error) } + } + + func write(_ text: String, to path: String, base: URL? = nil) throws { + let file = (base ?? root).appendingPathComponent(path) + try FileManager.default.createDirectory( + at: file.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data(text.utf8).write(to: file) + } + + func manifest(_ expression: String, at directory: URL) throws { + try write(Self.text(expression), to: ".agent/agents.yaml", base: directory) + } + + static func text(_ expression: String) -> String { + expression + "\n" + } + + func document(_ expression: String) throws -> DeclarationDocument { + try DeclarationDocument( + bytes: Array(Self.text(expression).utf8), identity: DocumentIdentity("consumer/agents.yaml")) + } + + func link( + _ expression: String, preserving pins: [String: SourceRevision] = [:], + directPins: [ComponentKey: SourceRevision] = [:] + ) throws -> LinkedComponents { + try ComponentLinker.withLinkedComponents( + document: document(expression), store: store, + platform: .macOS, preserving: pins, directPins: directPins + ) { graph, _ in graph } + } + + @discardableResult + func git(_ directory: URL, _ arguments: [String]) throws -> String { + try ProcessRunner.run("/usr/bin/env", arguments: ["git", "-C", directory.path] + arguments) + .stdout.trimmingCharacters(in: .whitespacesAndNewlines) + } + + func initialize(_ directory: URL) throws { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + try git(directory, ["init", "--initial-branch=main"]) + for (key, value) in [ + ("maintenance.auto", "false"), ("gc.auto", "0"), + ("user.name", "Fixture"), ("user.email", "fixture@example.test"), ("commit.gpgsign", "false"), + ] { + try git(directory, ["config", key, value]) + } + } + + @discardableResult + func commit(_ directory: URL, tag: String? = nil) throws -> String { + try git(directory, ["add", "."]) + try git(directory, ["commit", "-m", "fixture"]) + if let tag { try git(directory, ["tag", tag]) } + return try git(directory, ["rev-parse", "HEAD"]) + } + + func skill(_ name: String, at directory: URL, restrictions: String = "") throws { + try write( + "---\nname: \(name)\ndescription: Fixture skill\n\(restrictions)---\nBody\n", + to: "skills/\(name)/SKILL.md", base: directory) + } + + func instruction(_ name: String, at directory: URL, own: Bool = true, restrictions: String = "") + throws + { + try write( + "---\ndescription: Fixture section\n\(restrictions)---\n# \(name)\nBody\n", + to: (own ? ".agent/instructions/" : "instructions/") + name + ".md", base: directory) + } +} diff --git a/Tests/ComponentsTests/LinkingAcceptanceTests.swift b/Tests/ComponentsTests/LinkingAcceptanceTests.swift new file mode 100644 index 0000000..5140aa7 --- /dev/null +++ b/Tests/ComponentsTests/LinkingAcceptanceTests.swift @@ -0,0 +1,310 @@ +import AgentsCore +import AgentsManifest +import AgentsSkills +import Components +import Foundation +import Testing + +@Suite("Component linking acceptance") +struct LinkingAcceptanceTests { + @Test("A later transitive constraint selects an older feasible Git version") + func laterTransitiveConstraintBacktracks() throws { + let fixture = try LinkingFixture() + defer { fixture.remove() } + + let repository = try fixture.gitRepository("a") + try fixture.write( + repository, ".agent/agents.yaml", + manifest( + """ + exports: ["server"] + groups: {"server": {"components": [{"kind": "mcpServer", "name": "server", "transport": {"kind": "stdio", "executable": "server-v1"}, "agents": ["codex"]}]}} + """)) + let older = try fixture.commit(repository, tag: "1.0.0") + try fixture.write( + repository, ".agent/agents.yaml", + manifest( + """ + exports: ["server"] + groups: {"server": {"components": [{"kind": "mcpServer", "name": "server", "transport": {"kind": "stdio", "executable": "server-v2"}, "agents": ["codex"]}]}} + """)) + _ = try fixture.commit(repository, tag: "2.0.0") + + let bridge = fixture.root.appendingPathComponent("bridge", isDirectory: true) + try fixture.write( + bridge, ".agent/agents.yaml", + manifest( + """ + exports: ["bridge"] + sources: {"a": {"path": "../a", "requirement": {"exact": "1.0.0"}}} + groups: {"bridge": {"uses": [{"source": "a", "group": "server"}]}} + """)) + let document = try fixture.document( + manifest( + """ + sources: {"a": {"path": "../a", "requirement": {"from": "1.0.0"}}, "bridge": {"path": "../bridge"}} + uses: [{"source": "a", "group": "server"}, {"source": "bridge", "group": "bridge"}] + """)) + + let graph = try fixture.link(document) + let selected = try #require(graph.selections.values.first { $0.revision == older }) + #expect(selected.version == "1.0.0") + #expect(graph.references.map(\.group) == ["server", "bridge", "server"]) + #expect(graph.references[2].parent == graph.references[1].occurrence) + #expect( + graph.constraints.filter { $0.source == graph.references[0].snapshot.source }.count == 2) + let server = try #require(graph.components.first { $0.key.name == "server" }) + let servers = graph.components.filter { $0.key == server.key } + let serverOrigins = servers.flatMap(\.origins) + #expect(servers.allSatisfy { $0.snapshot.revision == older }) + #expect(servers.allSatisfy { $0.recipients == [.codex] }) + #expect(serverOrigins.count == 2) + #expect(Set(serverOrigins.map(\.occurrence)).count == 2) + #expect(serverOrigins.map(\.provenance.referenceChain).allSatisfy { !$0.isEmpty }) + } + + @Test("Diamond references preserve occurrences, producer targeting and ownership") + func diamondOccurrencesAndTargeting() throws { + let fixture = try LinkingFixture() + defer { fixture.remove() } + + let producer = fixture.root.appendingPathComponent("producer", isDirectory: true) + try fixture.write( + producer, ".agent/agents.yaml", + manifest( + """ + defaultAgents: ["claude-code", "codex"] + exports: ["left", "right"] + components: [{"kind": "mcpServer", "name": "root-only", "transport": {"kind": "stdio", "executable": "root-only"}}] + groups: {"leaf": {"components": [{"kind": "mcpServer", "name": "leaf-server", "transport": {"kind": "stdio", "executable": "leaf"}}, {"kind": "mcpServer", "name": "empty-server", "transport": {"kind": "stdio", "executable": "empty"}, "condition": {"agents": []}}], "condition": {"agents": ["codex"], "scopes": ["project"]}}, "left": {"uses": [{"group": "leaf"}]}, "right": {"uses": [{"group": "leaf"}]}} + """)) + let document = try fixture.document( + manifest( + """ + defaultAgents: ["cursor"] + sources: {"producer": {"path": "../producer"}} + uses: [{"source": "producer", "group": "left"}, {"source": "producer", "group": "right"}, {"source": "producer", "group": "left"}] + """)) + + let graph = try fixture.link(document) + #expect(graph.references.map(\.group) == ["left", "leaf", "right", "leaf", "left", "leaf"]) + #expect(graph.references[1].parent == graph.references[0].occurrence) + #expect(graph.references[3].parent == graph.references[2].occurrence) + #expect(graph.references[5].parent == graph.references[4].occurrence) + #expect(!graph.components.contains { $0.key.name == "root-only" }) + let leaf = try #require(graph.components.first { $0.key.name == "leaf-server" }) + let leaves = graph.components.filter { $0.key == leaf.key } + let leafOrigins = leaves.flatMap(\.origins) + #expect(leaves.allSatisfy { $0.recipients == [.codex] }) + #expect(leaves.allSatisfy { $0.snapshot == leaf.snapshot }) + #expect(leafOrigins.count == 3) + #expect(Set(leafOrigins.map(\.occurrence)).count == 3) + #expect(leafOrigins.allSatisfy { $0.provenance.referenceChain.count == 2 }) + let empty = try #require(graph.components.first { $0.key.name == "empty-server" }) + #expect(graph.components.filter { $0.key == empty.key }.allSatisfy { $0.recipients.isEmpty }) + do { + try graph.requireEditable(leaf.key) + Issue.record("An imported child must not be editable in the consumer declaration") + } catch let error as LinkError { + guard case .notEditableHere(let key, let provenance) = error else { + Issue.record("Expected notEditableHere, got \(error)") + return + } + #expect(key == leaf.key) + #expect(provenance.relativePath.hasSuffix(".agent/agents.yaml")) + #expect(!provenance.referenceChain.isEmpty) + } + } + + @Test("Protected impact follows actual pins and ignores unrelated root skills") + func protectedImpactAndStablePreparation() throws { + let fixture = try LinkingFixture() + defer { fixture.remove() } + + let repository = try fixture.gitRepository("shared") + let producer = manifest( + """ + exports: ["server", "empty"] + groups: {"server": {"components": [{"kind": "mcpServer", "name": "shared-server", "transport": {"kind": "stdio", "executable": "shared"}, "agents": ["codex"]}]}, "empty": {}} + """) + try fixture.write(repository, ".agent/agents.yaml", producer) + let older = try fixture.commit(repository, tag: "1.0.0") + try fixture.write(repository, "revision-marker", "second snapshot\n") + let newer = try fixture.commit(repository, tag: "2.0.0") + let skills = fixture.root.appendingPathComponent("skills", isDirectory: true) + try fixture.write( + skills, "draft/SKILL.md", + "---\nname: draft\ndescription: A local draft.\n---\n\n# Draft\n") + + func root(version: String, includeSkill: Bool, includeEmpty: Bool) -> String { + let component = + includeSkill + ? "{\"kind\": \"skills\", \"source\": \"drafts\", \"select\": [\"draft\"], \"mode\": \"edit\", \"agents\": [\"codex\"]}" + : "" + let extra = includeEmpty ? #", {group: empty, source: shared}"# : "" + return manifest( + """ + sources: {shared: {path: ../shared, requirement: {exact: "\(version)"}}, drafts: {path: ../skills}} + components: [\(component)] + uses: [{group: server, source: shared}\(extra)] + """) + } + + let initial = try fixture.document( + root(version: "1.0.0", includeSkill: false, includeEmpty: false)) + let withSkill = try fixture.document( + root(version: "1.0.0", includeSkill: true, includeEmpty: false)) + let bookkeeping = try fixture.document( + root(version: "1.0.0", includeSkill: true, includeEmpty: true)) + let changedPin = try fixture.document( + root(version: "2.0.0", includeSkill: true, includeEmpty: false)) + + let beforeFiles = try fixture.inventory() + let first = try fixture.link(initial) + let skillGraph = try fixture.link(withSkill) + let repeated = try fixture.link(withSkill) + let bookkeepingGraph = try fixture.link(bookkeeping) + let changed = try fixture.link(changedPin) + #expect(skillGraph == repeated) + #expect(try fixture.inventory() == beforeFiles) + #expect(skillGraph.protectedChanges(from: first, allowing: [.skills]).isEmpty) + #expect(bookkeepingGraph.protectedChanges(from: skillGraph, allowing: [.skills]).isEmpty) + + let server = try #require(skillGraph.components.first { $0.key.name == "shared-server" }) + #expect(server.snapshot.revision == older) + #expect(changed.components.first { $0.key == server.key }?.snapshot.revision == newer) + #expect(changed.protectedChanges(from: skillGraph, allowing: [.skills]).contains(server.key)) + #expect(skillGraph.protectedPins(allowing: [.skills]).values.contains { $0.revision == older }) + + let draft = try #require(skillGraph.components.first { $0.key.name == "draft" }) + guard case .skill(let skill, let mode, _) = draft.payload else { + Issue.record("Expected the live skill payload") + return + } + #expect(mode == .edit) + #expect(skill.livePath == skills.appendingPathComponent("draft").path) + try fixture.write( + skills, "draft/SKILL.md", + "---\nname: draft\ndescription: A changed local draft.\n---\n\n# Draft\n") + let edited = try fixture.link(withSkill) + let editedDraft = try #require(edited.components.first { $0.key.name == "draft" }) + guard case .skill(let editedSkill, _, _) = editedDraft.payload else { + Issue.record("Expected the edited live skill payload") + return + } + #expect(editedSkill.livePath == skill.livePath) + #expect(editedSkill.hash != skill.hash) + } +} + +private func manifest(_ fields: String) -> String { + "version: 1\n" + fields + "\n" +} + +private struct LinkingFixture { + let root: URL + let project: URL + let home: URL + + init() throws { + root = FileManager.default.temporaryDirectory.appendingPathComponent( + "linking-acceptance-\(UUID().uuidString)", isDirectory: true) + project = root.appendingPathComponent("project", isDirectory: true) + home = root.appendingPathComponent("home", isDirectory: true) + try FileManager.default.createDirectory(at: project, withIntermediateDirectories: true) + try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true) + } + + func remove() { + try? FileManager.default.removeItem(at: root) + } + + func write(_ directory: URL, _ path: String, _ contents: String) throws { + let file = directory.appendingPathComponent(path) + try FileManager.default.createDirectory( + at: file.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data(contents.utf8).write(to: file) + } + + func document(_ text: String) throws -> DeclarationDocument { + try DeclarationDocument( + bytes: Array(text.utf8), identity: DocumentIdentity("consumer/.agent/agents.yaml")) + } + + func link(_ document: DeclarationDocument) throws -> LinkedComponents { + let environment = RuntimeEnvironment( + projectDirectory: project, homeDirectory: home, environment: ["HOME": home.path]) + let store = StateStore(scope: .project, environment: environment) + return try ComponentLinker.withLinkedComponents( + document: document, store: store, platform: .macOS + ) { graph, _ in graph } + } + + func gitRepository(_ name: String) throws -> URL { + let directory = root.appendingPathComponent(name, isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + _ = try git(directory, ["init", "--initial-branch=main"]) + _ = try git(directory, ["config", "--local", "user.name", "Fixture"]) + _ = try git(directory, ["config", "--local", "user.email", "fixture@example.invalid"]) + _ = try git(directory, ["config", "--local", "gc.auto", "0"]) + _ = try git(directory, ["config", "--local", "maintenance.auto", "false"]) + return directory + } + + func commit(_ repository: URL, tag: String) throws -> String { + _ = try git(repository, ["add", "."]) + _ = try git(repository, ["commit", "-m", "Fixture \(tag)"]) + _ = try git(repository, ["tag", tag]) + return try git(repository, ["rev-parse", "HEAD"]).trimmingCharacters( + in: .whitespacesAndNewlines) + } + + func git(_ directory: URL, _ arguments: [String]) throws -> String { + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/env") + process.arguments = ["git"] + arguments + process.currentDirectoryURL = directory + process.environment = [ + "PATH": "/usr/bin:/bin:/usr/local/bin:/opt/homebrew/bin", + "HOME": home.path, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": "/dev/null", + "GIT_TERMINAL_PROMPT": "0", + "GIT_AUTHOR_DATE": "2001-01-01T00:00:00Z", + "GIT_COMMITTER_DATE": "2001-01-01T00:00:00Z", + ] + let output = Pipe() + process.standardOutput = output + process.standardError = output + try process.run() + let data = output.fileHandleForReading.readDataToEndOfFile() + process.waitUntilExit() + guard process.terminationStatus == 0 else { + throw FixtureError.git(arguments, String(decoding: data, as: UTF8.self)) + } + return String(decoding: data, as: UTF8.self) + } + + func inventory() throws -> [String: Data] { + let manager = FileManager.default + guard + let enumerator = manager.enumerator( + at: project, includingPropertiesForKeys: [.isRegularFileKey], options: []) + else { throw FixtureError.inventory } + var files: [String: Data] = [:] + for case let url as URL in enumerator { + let values = try url.resourceValues(forKeys: [.isRegularFileKey]) + if values.isRegularFile == true { + files[String(url.path.dropFirst(project.path.count + 1))] = try Data(contentsOf: url) + } else { + files[String(url.path.dropFirst(project.path.count + 1)) + "/"] = Data() + } + } + return files + } +} + +private enum FixtureError: Error { + case git([String], String) + case inventory +} diff --git a/Tests/ComponentsTests/LinkingIntegrationTests.swift b/Tests/ComponentsTests/LinkingIntegrationTests.swift new file mode 100644 index 0000000..c99f172 --- /dev/null +++ b/Tests/ComponentsTests/LinkingIntegrationTests.swift @@ -0,0 +1,320 @@ +import AgentsCore +import AgentsInstructions +import AgentsManifest +import Foundation +import Testing + +@testable import Components + +@Suite("Component integration boundaries", .serialized) +struct LinkingIntegrationTests { + @Test(arguments: [SourceKind.local, .git]) + func annotatedObjectsConjoinAndFreezeAsCommits(_ kind: SourceKind) throws { + let fixture = try LinkFixture() + let repository = fixture.root.appendingPathComponent("repository") + try fixture.initialize(repository) + try fixture.skill("one", at: repository) + try fixture.manifest( + "version: 1\nexports: [g]\ngroups: {g: {components: [{kind: skills, source: .}]}}", + at: repository) + let commit = try fixture.commit(repository, tag: "1.0.0") + try fixture.git( + repository, ["-c", "tag.gpgsign=false", "tag", "-a", "release", "-m", "release"]) + let object = try fixture.git(repository, ["rev-parse", "release"]) + let source = SourceDeclaration( + kind: kind, location: kind == .local ? repository.path : "file://localhost" + repository.path, + requirement: .revision(object)) + try SourceResolutionSession.withTemporaryRead(store: fixture.store) { session throws -> Void in + #expect( + try session.candidates(for: source, requirements: [.revision(object), .revision(commit)]) + .map(\.revision) == [commit]) + #expect( + try session.candidates(for: source, requirements: [.revision(object), .exact("1.0.0")]) + .first?.revision == commit) + let selected = try session.snapshot(source, at: .init(revision: object)) + #expect(selected.snapshot.revision == commit) + #expect(selected.pin?.revision == commit) + } + let field = kind == .local ? "path" : "url" + let document = try fixture.document( + "version: 1\nsources: {p: {\(field): '\(source.location)', requirement: {revision: '\(object)'}}}\nuses: [{source: p, group: g}]" + ) + let (graph, ledger) = try ComponentLinker.withLinkedComponents( + document: document, store: fixture.store, platform: .macOS + ) { graph, session in + var locations = [ + "local:" + fixture.project.path: LedgerLocation( + kind: .registered, root: "project", path: ".") + ] + if kind == .local { + locations["local:" + repository.path] = .init( + kind: .authoringRelative, root: "project", path: "../repository") + } + return ( + graph, + try LedgerFreeze.freeze( + graph, session: session, locations: .init(sources: locations), limits: .standard) + ) + } + let decoded = try ResolvedLedgerCodec.decode( + ResolvedLedgerCodec.encode(ledger, limits: .standard), limits: .standard) + #expect(decoded.components.values.first?.revision == commit) + #expect(decoded.sources.values.contains { $0.kind == kind && $0.revision == commit }) + #expect(graph.components.first?.pin?.revision == commit) + #expect(graph.references.first?.snapshot.revision == commit) + let cache = SourceCache(store: fixture.store) + _ = try cache.resolve(source) + try fixture.git(repository, ["tag", "--delete", "release"]) + try FileManager.default.removeItem(at: repository) + let before = try FileHash.folderHash(fixture.store.cacheDirectory) + try SourceResolutionSession.withTemporaryRead(store: fixture.store) { session throws -> Void in + #expect( + try session.candidates(for: source, requirements: [.revision(object), .revision(commit)]) + .map(\.revision) == [commit]) + #expect(try session.snapshot(source, at: .init(revision: object)).snapshot.revision == commit) + #expect(throws: (any Error).self) { + try session.snapshot(source, at: .init(revision: "main")) + } + } + #expect(try FileHash.folderHash(fixture.store.cacheDirectory) == before) + } + + @Test func exactRelativeSourceKeepsItsDeclaringEnvironment() throws { + let fixture = try LinkFixture() + let repository = fixture.root.appendingPathComponent("repository") + try fixture.initialize(repository) + try fixture.skill("one", at: repository) + let commit = try fixture.commit(repository) + let source = SourceDeclaration( + kind: .local, location: "../repository", requirement: .revision(commit)) + try SourceResolutionSession.withTemporaryRead(store: fixture.store) { session in + let candidate = try #require( + try session.candidates(for: source, requirements: [.revision(commit)]).first) + let view = try session.snapshot(source, at: candidate) + #expect(view.snapshot.source == "local:" + repository.path) + #expect(view.localEnvironment?.projectDirectory.path == repository.path) + #expect(view.snapshot.revision == commit) + } + } + + @Test func selectedOwnSectionDoesNotReadUnrelatedDrafts() throws { + let fixture = try LinkFixture() + try fixture.instruction("guide", at: fixture.project, restrictions: "agents: [\"codex\"]\n") + try fixture.write( + "---\ndescription: [unterminated\n---\nDraft", to: ".agent/instructions/draft.md", + base: fixture.project) + let graph = try fixture.link( + "version: 1\ncomponents: [{kind: instructions, sections: [{name: guide}]}]") + #expect(graph.components.map(\.key.name) == ["guide"]) + #expect(graph.components[0].recipients == [.codex]) + let view = try SourceSnapshot( + snapshot: .init(source: "own", revision: "live"), pin: nil, root: fixture.project) + #expect(throws: (any Error).self) { try InstructionSnapshotReader.read(view, own: true) } + #expect(throws: (any Error).self) { + try fixture.link("version: 1\ncomponents: [{kind: instructions, sections: [{name: draft}]}]") + } + #expect(throws: (any Error).self) { + try fixture.link( + "version: 1\ncomponents: [{kind: instructions, sections: [{name: missing}]}]") + } + let guide = fixture.project.appendingPathComponent(".agent/instructions/guide.md") + try FileManager.default.removeItem(at: guide) + try fixture.write( + "---\ndescription: Selected\n---\nBody", to: "other.md", base: fixture.project) + try FileManager.default.createSymbolicLink( + at: guide, withDestinationURL: fixture.project.appendingPathComponent("other.md")) + #expect(throws: (any Error).self) { + try fixture.link("version: 1\ncomponents: [{kind: instructions, sections: [{name: guide}]}]") + } + } + + @Test func namedReaderPreservesDiscoveryAndRejectsSelectedContainerLinks() throws { + let fixture = try LinkFixture() + let published = fixture.project.appendingPathComponent("published") + try fixture.instruction("guide", at: published, restrictions: "scopes: [\"project\"]\n") + try fixture.write( + "---\ndescription: [broken\n---\nDraft", to: ".agent/instructions/draft.md", base: published) + let view = try SourceSnapshot( + snapshot: .init(source: "reader", revision: "live"), pin: nil, root: fixture.project, + discoveryPath: "published") + let selected = try InstructionSnapshotReader.read(view, own: "guide") + let section = try #require(selected) + #expect(section.path == "published/.agent/instructions/guide.md") + #expect(section.section.condition.scopes == [.project]) + #expect(try InstructionSnapshotReader.read(view, own: "missing") == nil) + #expect(throws: (any Error).self) { try InstructionSnapshotReader.read(view, own: "../guide") } + #expect(throws: (any Error).self) { try InstructionSnapshotReader.read(view, own: "draft") } + #expect(throws: (any Error).self) { try InstructionSnapshotReader.read(view, own: true) } + let agentRoot = try SourceSnapshot( + snapshot: view.snapshot, pin: nil, root: fixture.project, discoveryPath: "published/.agent") + #expect(try InstructionSnapshotReader.read(agentRoot, own: "guide") == section) + let container = published.appendingPathComponent(".agent/instructions") + let moved = published.appendingPathComponent("actual") + try FileManager.default.moveItem(at: container, to: moved) + try FileManager.default.createSymbolicLink(at: container, withDestinationURL: moved) + #expect(throws: (any Error).self) { try InstructionSnapshotReader.read(view, own: "guide") } + } + + @Test func exactAcquisitionDoesNotRefreshFrozenExpressions() throws { + let fixture = try LinkFixture() + let sourceRoot = fixture.root.appendingPathComponent("repository") + try fixture.initialize(sourceRoot) + try fixture.skill("one", at: sourceRoot) + let first = try fixture.commit(sourceRoot) + let source = SourceDeclaration(kind: .git, location: "file://localhost" + sourceRoot.path) + try SourceResolutionSession.withTemporaryRead(store: fixture.store) { session in + #expect(try session.candidates(for: source, requirements: [nil]).first?.revision == first) + try fixture.skill("two", at: sourceRoot) + let second = try fixture.commit(sourceRoot) + try fixture.git(sourceRoot, ["-c", "tag.gpgsign=false", "tag", "-a", "later", "-m", "later"]) + let object = try fixture.git(sourceRoot, ["rev-parse", "later"]) + #expect( + try session.candidates(for: source, requirements: [.revision(object)]).first?.revision + == second) + #expect( + try session.candidates(for: source, requirements: [.revision("main")]).first?.revision + == first) + #expect( + try session.candidates(for: source, requirements: [.branch("main")]).first?.revision + == first) + #expect(try session.snapshot(source, at: .init(revision: second)).snapshot.revision == second) + } + #expect(!FileManager.default.fileExists(atPath: fixture.store.cacheDirectory.path)) + } + + @Test func allMembershipUsesOverrideViewsAndCanonicalNames() throws { + let fixture = try LinkFixture() + let source = fixture.root.appendingPathComponent("skills") + try fixture.initialize(source) + try fixture.skill("Stable Skill", at: source) + try fixture.commit(source) + try fixture.skill("Live Draft", at: source) + try FileManager.default.moveItem( + at: source.appendingPathComponent("skills/Live Draft"), + to: source.appendingPathComponent("skills/folder")) + try fixture.skill("unrelated", at: source) + func expression(_ mode: String, _ override: String, named: Bool = false) -> String { + "version: 1\nsources: {s: {path: '\(source.path)'}}\ncomponents: [{kind: skills, source: s, mode: \(mode), \(named ? "select: [live-draft], " : "")overrides: {live-draft: {mode: \(override)}}}]" + } + let copy = try fixture.link(expression("copy", "edit")) + #expect(copy.components.map(\.key.name) == ["live-draft", "stable-skill"]) + let live = try #require(copy.components.first) + guard case .skill(let skill, .edit, _) = live.payload else { + Issue.record("expected live override") + return + } + #expect(skill.name == "Live Draft") + #expect(skill.path == "skills/folder") + #expect(skill.livePath == source.appendingPathComponent("skills/folder").path) + try FileManager.default.removeItem(at: source.appendingPathComponent("skills/folder")) + #expect( + try fixture.link(expression("copy", "edit")).components.map(\.key.name) == ["stable-skill"]) + #expect(throws: (any Error).self) { try fixture.link(expression("copy", "edit", named: true)) } + try fixture.skill("Live Draft", at: source) + #expect( + try fixture.link(expression("edit", "copy")).components.map(\.key.name) == [ + "stable-skill", "unrelated", + ]) + #expect(throws: (any Error).self) { try fixture.link(expression("edit", "copy", named: true)) } + try FileManager.default.removeItem(at: source.appendingPathComponent("skills/Stable Skill")) + let inverse = try fixture.link( + "version: 1\nsources: {s: {path: '\(source.path)'}}\ncomponents: [{kind: skills, source: s, mode: edit, overrides: {stable-skill: {mode: copy}}}]" + ) + #expect(inverse.components.map(\.key.name) == ["live-draft", "stable-skill", "unrelated"]) + #expect( + try fixture.link( + "version: 1\nsources: {s: {path: '\(source.path)'}}\ncomponents: [{kind: skills, source: s, exclude: [stable-skill]}]" + ).components.isEmpty) + try fixture.write( + "---\nname: broken\ndescription: [invalid]\n---\n", to: "skills/broken/SKILL.md", base: source + ) + #expect( + try fixture.link( + "version: 1\nsources: {s: {path: '\(source.path)'}}\ncomponents: [{kind: skills, source: s, mode: copy, exclude: [stable-skill], overrides: {stable-skill: {mode: edit}}}]" + ).components.isEmpty) + + } + + @Test func canonicalKeysKeepAnUnselectedMembersExactPin() throws { + let fixture = try LinkFixture() + let source = fixture.root.appendingPathComponent("skills") + try fixture.initialize(source) + for name in ["First Skill", "Second Skill"] { try fixture.skill(name, at: source) } + let first = try fixture.commit(source, tag: "1.0.0") + let expression = + "version: 1\nsources: {s: {path: '\(source.path)'}}\ncomponents: [{kind: skills, source: s, mode: copy}]" + let before = try fixture.link(expression) + let preserved = ComponentKey( + source: "local:" + fixture.project.path, root: ".", group: nil, kind: .skills, + name: "second-skill") + #expect(before.components.map(\.key.name) == ["first-skill", "second-skill"]) + try fixture.write("new", to: "skills/First Skill/new", base: source) + try fixture.write("new", to: "skills/Second Skill/new", base: source) + let second = try fixture.commit(source, tag: "1.1.0") + let after = try fixture.link(expression, directPins: [preserved: .init(revision: first)]) + #expect(after.components.map(\.snapshot.revision) == [second, first]) + #expect(after.components.last?.key == preserved) + try FileManager.default.removeItem(at: source.appendingPathComponent("skills/Second Skill")) + let third = try fixture.commit(source, tag: "1.2.0") + let explicit = expression.replacingOccurrences( + of: "mode: copy}", with: "mode: copy, select: [first-skill, second-skill]}") + let partial = try fixture.link(explicit, directPins: [preserved: .init(revision: first)]) + #expect(partial.components.map(\.snapshot.revision) == [third, first]) + } + + @Test(arguments: [InstallScope.project, .user]) + func missingConsumerAppendFreezesAsMetadata(_ scope: InstallScope) throws { + let fixture = try LinkFixture() + let store = StateStore(scope: scope, environment: fixture.environment) + let source = fixture.project.appendingPathComponent("rules") + try fixture.initialize(source) + try fixture.instruction("guide", at: source, own: false) + try fixture.commit(source) + let document = try fixture.document( + "version: 1\nsources: {s: {path: '\(source.path)'}}\ncomponents: [{kind: instructions, chatgpt: {daily: {sections: [{name: guide, source: s}], append: custom.md}}}]" + ) + let ledger = try ComponentLinker.withLinkedComponents( + document: document, store: store, platform: .macOS + ) { graph, session in + #expect(graph.components[0].resources.count == 1) + return try LedgerFreeze.freeze( + graph, session: session, + locations: .init(sources: [ + "local:" + source.path: .init(kind: .registered, root: "project", path: "rules"), + "local:" + (scope == .project ? fixture.project : store.directory).path: .init( + kind: .registered, root: scope == .project ? "project" : "state", path: "."), + ]), limits: .standard) + } + let restored = try ResolvedLedgerCodec.decode( + ResolvedLedgerCodec.encode(ledger, limits: .standard), limits: .standard) + let component = try #require(restored.components.values.first) + let append = try #require(component.payload.object?["localAppend"]?.object) + #expect(append["root"]?.text == (scope == .project ? "project" : "home")) + #expect(append["path"]?.text == "custom.md") + #expect(component.resources.count == 1) + let value = try #require(component.payload.object?["localAppend"]) + let location = try LedgerLocation(ledgerValue: value) + let roots = ["project": fixture.project, "home": fixture.home, "state": store.directory] + #expect(throws: (any Error).self) { try location.readContainedFile(roots: roots) } + let target = scope == .project ? fixture.project : fixture.home + for root in [fixture.project, fixture.home, store.directory] { + try fixture.write(root == target ? "first" : "shadow", to: "custom.md", base: root) + } + #expect(try location.readContainedFile(roots: roots) == Data("first".utf8)) + try fixture.write("current", to: "custom.md", base: target) + #expect(try location.readContainedFile(roots: roots) == Data("current".utf8)) + #expect( + try ResolvedLedgerCodec.encode(restored, limits: .standard) + == ResolvedLedgerCodec.encode(ledger, limits: .standard)) + try FileManager.default.removeItem(at: target.appendingPathComponent("custom.md")) + try FileManager.default.createDirectory( + at: target.appendingPathComponent("custom.md"), withIntermediateDirectories: true) + #expect(throws: (any Error).self) { try location.readContainedFile(roots: roots) } + try FileManager.default.removeItem(at: target.appendingPathComponent("custom.md")) + try fixture.write("outside", to: "outside.md") + try FileManager.default.createSymbolicLink( + at: target.appendingPathComponent("custom.md"), + withDestinationURL: fixture.root.appendingPathComponent("outside.md")) + #expect(throws: (any Error).self) { try location.readContainedFile(roots: roots) } + } +} diff --git a/Tests/ComponentsTests/LinkingReviewRegressionTests.swift b/Tests/ComponentsTests/LinkingReviewRegressionTests.swift new file mode 100644 index 0000000..1ade3db --- /dev/null +++ b/Tests/ComponentsTests/LinkingReviewRegressionTests.swift @@ -0,0 +1,147 @@ +import AgentsCore +import Components +import Foundation +import Testing + +@Suite("Component linking review regressions") +struct LinkingReviewRegressionTests { + @Test("Coalescing checks every overlapping hook and permission payload") + func coalescingRejectsOverlapInEitherOrder() throws { + let fixture = try LinkFixture() + + for kind in ["hook", "permissions"] { + func component(_ payload: String, _ agent: String) -> String { + let recipient = agent == "claudeCode" ? "claude-code" : agent + if kind == "hook" { + return + "{kind: hook, name: shared, event: afterTool, run: {executable: \"\(payload)\"}, agents: [\(recipient)]}" + } + let rule = payload == "a" ? "allow" : "deny" + return + "{kind: permissions, name: shared, rules: [{effect: \(rule), operation: read, pattern: files/**}], agents: [\(recipient)]}" + + } + + let aCodex = component("a", "codex") + let bClaude = component("b", "claudeCode") + let aClaude = component("a", "claudeCode") + let disjoint = try fixture.link( + "version: 1\ncomponents: [\(aCodex), \(bClaude)]\n") + #expect(disjoint.components.count == 2) + let identical = try fixture.link( + "version: 1\ncomponents: [\(aCodex), \(aClaude)]\n") + let merged = try #require(identical.components.first) + #expect(identical.components.count == 1) + #expect(merged.recipients == [.codex, .claudeCode]) + #expect(merged.origins.count == 2) + + for components in [ + [aCodex, bClaude, aClaude], + [aCodex, aClaude, bClaude], + ] { + do { + _ = try fixture.link( + "version: 1\ncomponents: [\(components.joined(separator: ", "))]\n") + Issue.record("Expected conflicting \(kind) payloads to be rejected") + } catch let error as LinkError { + guard case .conflict(let key, _) = error else { + Issue.record("Expected a \(kind) conflict, got \(error)") + continue + } + #expect(key.name == "shared") + } + } + } + } + + @Test("Protected instruction order includes ordinary and named prompt sections") + func protectedInstructionOrder() throws { + let fixture = try LinkFixture() + try fixture.instruction("a", at: fixture.project) + try fixture.instruction("b", at: fixture.project) + let drafts = fixture.root.appendingPathComponent("drafts") + try fixture.skill("draft", at: drafts) + + for prompt in [false, true] { + func declaration(_ sections: String, extra: Bool = false) -> String { + let instruction = + prompt + ? "{kind: instructions, chatgpt: {review: {sections: [\(sections)]}}}" + : "{kind: instructions, sections: [\(sections)], agents: [codex]}" + let skill = + extra + ? "{kind: skills, source: drafts, select: [draft], mode: edit, agents: [codex]}," : "" + let uses = extra ? "uses: [{group: empty}]" : "" + return """ + version: 1 + sources: {drafts: {path: ../drafts}} + components: [\(skill) \(instruction)] + groups: {empty: {}} + \(uses) + watch: [] + """ + + } + + let before = try fixture.link(declaration(#"{name: a}, {name: b}"#)) + let after = try fixture.link(declaration(#"{name: b}, {name: a}"#)) + let unrelated = try fixture.link(declaration(#"{name: a}, {name: b}"#, extra: true)) + let beforeSections = before.components.filter { + $0.key.kind == .instructions && $0.chatGPT == prompt + } + let afterSections = after.components.filter { + $0.key.kind == .instructions && $0.chatGPT == prompt + } + #expect(beforeSections.map(\.key.name) == ["a", "b"]) + #expect(afterSections.map(\.key.name) == ["b", "a"]) + #expect(!after.protectedChanges(from: before, allowing: [.skills]).isEmpty) + #expect(unrelated.protectedChanges(from: before, allowing: [.skills]).isEmpty) + } + } + + @Test("Live edit sources consume the distinct snapshot budget") + func liveEditSnapshotBudget() throws { + let fixture = try LinkFixture() + for index in 0..<257 { + let directory = fixture.root.appendingPathComponent("source-\(index)") + try fixture.skill("skill-\(index)", at: directory) + } + + func declaration(distinct count: Int, repetitions: Int = 1) -> String { + let sources = (0.. LinkedComponents { + try ComponentLinker.withLinkedComponents( + document: document, store: fixture.store, platform: .macOS + ) { graph, session in + let id = "local:" + dependency.path + #expect(graph.selections[id]?.revision == older) + #expect(graph.constraints.filter { $0.source == id }.count == 2) + #expect(graph.components.filter { $0.key.name == "dependency" }.count == 2) + #expect(graph.references[2].snapshot.source == id) + #expect(graph.references[3].snapshot.source == "local:" + absoluteDependency.path) + #expect(graph.references[4].snapshot.source == "local:" + homeDependency.path) + let command = try #require(graph.components.first { $0.key.name == "review" }) + #expect(command.snapshot.revision == producerPin) + #expect(command.origins[0].provenance.relativePath == "published/.agent/agents.yaml") + let resource = try #require(command.resources.first) + let file = try session.resource(snapshot: resource.snapshot, path: resource.path) + #expect(try String(contentsOf: file, encoding: .utf8) == "pinned prompt") + #expect(!graph.constraints.contains { $0.source.contains("agents-resolution-") }) + return graph + } + } + #expect(try link() == link()) + } + + @Test func orderDiamondsRepeatsAndProducerDefaults() throws { + let fixture = try LinkFixture() + let producer = fixture.root.appendingPathComponent("producer") + try fixture.instruction("section", at: producer) + try fixture.manifest( + """ + version: 1 + defaultAgents: ["claude-code"] + exports: ["bundle"] + components: [{"kind": "mcpServer", "name": "not-imported", "transport": {"kind": "stdio", "executable": "never-run"}}] + groups: {"leaf": {"components": [{"kind": "instructions", "sections": [{"name": "section"}]}]}, "left": {"uses": [{"group": "leaf"}]}, "right": {"uses": [{"group": "leaf"}]}, "bundle": {"components": [{"kind": "mcpServer", "name": "first", "transport": {"kind": "stdio", "executable": "never-run"}}], "uses": [{"group": "left"}, {"group": "right"}]}} + """, at: producer) + let expression = """ + version: 1 + defaultAgents: ["codex"] + sources: {"p": {"path": "\(producer.path)"}} + components: [{"kind": "mcpServer", "name": "root", "transport": {"kind": "stdio", "executable": "never-run"}}] + uses: [{"source": "p", "group": "bundle"}, {"source": "p", "group": "bundle"}] + """ + let graph = try fixture.link(expression) + #expect( + graph.components.map(\.key.name) == [ + "root", "first", "section", "section", "first", "section", "section", + ]) + #expect(graph.components.dropFirst().allSatisfy { $0.recipients == [.claudeCode] }) + #expect(Set(graph.components.flatMap(\.origins).map(\.occurrence)).count == 7) + #expect(graph.components[2].origins[0].provenance.referenceChain.count == 3) + #expect(graph.references.count == 10) + #expect(throws: LinkError.self) { try graph.requireEditable(graph.components[2].key) } + #expect(try fixture.link(expression) == graph) + #expect( + !FileManager.default.fileExists(atPath: fixture.project.appendingPathComponent(".agent").path) + ) + } + + @Test func crossSourceCycleAndExplicitExports() throws { + let fixture = try LinkFixture() + let producer = fixture.root.appendingPathComponent("producer") + try fixture.manifest( + """ + version: 1 + exports: ["loop"] + sources: {"self": {"path": "."}} + groups: {"loop": {"uses": [{"source": "self", "group": "loop"}]}} + """, at: producer) + #expect(throws: LinkError.self) { + try fixture.link( + "version: 1\nsources: {\"p\": {\"path\": \"\(producer.path)\"}}\nuses: [{\"source\": \"p\", \"group\": \"loop\"}]\n" + ) + } + try fixture.manifest("version: 1\ngroups: {\"private\": {}}\n", at: producer) + #expect(throws: LinkError.self) { + try fixture.link( + "version: 1\nsources: {\"p\": {\"path\": \"\(producer.path)\"}}\nuses: [{\"source\": \"p\", \"group\": \"private\"}]\n" + ) + } + } + + @Test func versionBacktrackingAndFixedBranchEvidence() throws { + let fixture = try LinkFixture() + let dependency = fixture.root.appendingPathComponent("dependency") + try fixture.initialize(dependency) + try fixture.manifest( + "version: 1\nexports: [\"d\"]\ngroups: {\"d\": {\"components\": [{\"kind\": \"mcpServer\", \"name\": \"dep-one\", \"transport\": {\"kind\": \"stdio\", \"executable\": \"never-run\"}}]}}\n", + at: dependency) + let depOne = try fixture.commit(dependency, tag: "1.0.0") + try fixture.manifest( + "version: 1\nexports: [\"d\"]\ngroups: {\"d\": {\"components\": [{\"kind\": \"mcpServer\", \"name\": \"dep-two\", \"transport\": {\"kind\": \"stdio\", \"executable\": \"never-run\"}}]}}\n", + at: dependency) + try fixture.commit(dependency, tag: "2.0.0") + let producer = fixture.root.appendingPathComponent("producer") + try fixture.initialize(producer) + let url = "file://localhost" + dependency.path + func writeProducer(_ version: String) throws { + try fixture.manifest( + """ + version: 1 + exports: ["p"] + sources: {"d": {"url": "\(url)", "requirement": {"exact": "\(version)"}}} + groups: {"p": {"uses": [{"source": "d", "group": "d"}]}} + """, at: producer) + } + try writeProducer("1.0.0") + let lower = try fixture.commit(producer, tag: "1.0.0") + try writeProducer("2.0.0") + try fixture.commit(producer, tag: "1.1.0") + let graph = try fixture.link( + """ + version: 1 + sources: {"p": {"path": "\(producer.path)", "requirement": {"from": "1.0.0"}}, "d": {"url": "\(url)", "requirement": {"exact": "1.0.0"}}} + uses: [{"source": "p", "group": "p"}, {"source": "d", "group": "d"}] + """) + #expect(graph.components.map(\.key.name) == ["dep-one", "dep-one"]) + #expect(graph.selections["local:" + producer.path]?.revision == lower) + #expect(graph.selections.values.contains { $0.revision == depOne }) + #expect(!FileManager.default.fileExists(atPath: fixture.store.cacheDirectory.path)) + } + + @Test func targetingAndLiveEdit() throws { + let fixture = try LinkFixture() + let source = fixture.root.appendingPathComponent("skills") + try fixture.skill( + "review", at: source, + restrictions: "agents: [claude-code]\nscopes: [project]\nplatforms: [macos]\n") + let graph = try fixture.link( + """ + version: 1 + defaultAgents: ["codex"] + sources: {"s": {"path": "\(source.path)"}} + components: [{"kind": "skills", "source": "s", "select": ["review"], "mode": "edit", "overrides": {"review": {"agents": ["claude-code", "codex"]}}}] + """) + let component = try #require(graph.components.first) + #expect(component.recipients == [.claudeCode]) + guard case .skill(let skill, .edit, _) = component.payload else { + Issue.record("expected live skill") + return + } + #expect(skill.livePath == source.appendingPathComponent("skills/review").path) + try fixture.skill("review", at: source, restrictions: "agents: wrong\n") + #expect(throws: (any Error).self) { + try fixture.link( + "version: 1\nsources: {\"s\": {\"path\": \"\(source.path)\"}}\ncomponents: [{\"kind\": \"skills\", \"source\": \"s\"}]\n" + ) + } + } +} + +extension LinkingTests { + @Test func packageResourcesShareTheExportSourceVariable() throws { + let fixture = try LinkFixture() + let dependency = fixture.root.appendingPathComponent("dependency") + try fixture.initialize(dependency) + try fixture.write("old", to: "prompt.md", base: dependency) + try fixture.manifest( + "version: 1\nexports: [\"d\"]\ngroups: {\"d\": {}}\n", at: dependency) + let first = try fixture.commit(dependency, tag: "1.0.0") + try fixture.write("new", to: "prompt.md", base: dependency) + try fixture.commit(dependency, tag: "1.1.0") + let producer = fixture.root.appendingPathComponent("producer") + try fixture.manifest( + """ + version: 1 + exports: ["tools"] + sources: {"r": {"url": "file://localhost\(dependency.path)", "requirement": {"from": "1.0.0"}}} + groups: {"tools": {"components": [{"kind": "command", "name": "review", "description": "Review", "prompt": {"file": {"path": "prompt.md", "source": "r"}}}]}} + """, at: producer) + let graph = try fixture.link( + """ + version: 1 + sources: {"p": {"path": "\(producer.path)"}, "d": {"url": "file://localhost\(dependency.path)", "requirement": {"exact": "1.0.0"}}} + uses: [{"source": "p", "group": "tools"}, {"source": "d", "group": "d"}] + """) + #expect(graph.components.first?.resources.first?.snapshot.revision == first) + #expect(graph.constraints.filter { $0.source.hasPrefix("localhost/") }.count == 2) + } +} diff --git a/Tests/ComponentsTests/MCPConnectionAcceptanceTests.swift b/Tests/ComponentsTests/MCPConnectionAcceptanceTests.swift new file mode 100644 index 0000000..11f5088 --- /dev/null +++ b/Tests/ComponentsTests/MCPConnectionAcceptanceTests.swift @@ -0,0 +1,53 @@ +import AgentsCore +import Foundation +import Testing + +@testable import Components + +private final class MCPAcceptanceBundle: NSObject {} + +@Suite(.serialized) struct MCPConnectionAcceptanceTests { + @Test func deadlineInterruptsBlockedInitializeWrite() async throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent( + "mcp-blocked-write-" + UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + + var directory = Bundle(for: MCPAcceptanceBundle.self).bundleURL + var executable: URL? + for _ in 0..<8 { + let candidate = directory.appendingPathComponent("MCPTestProcess") + if FileManager.default.isExecutableFile(atPath: candidate.path) { + executable = candidate + break + } + directory.deleteLastPathComponent() + } + let program = try #require(executable) + let configuration = DuplexProcessConfiguration( + executable: program.path, arguments: ["blocked-input", root.path], directory: root, + environment: ["PATH": "/usr/bin:/bin", "HOME": root.path]) + var limits = MCPConnectionLimits() + limits.totalTimeout = 1 + limits.requestTimeout = 2 + limits.textBytes = 2_000_000 + limits.sentBytes = 4_000_000 + limits.frameBytes = 4_000_000 + limits.queueBytes = 4_000_000 + let started = ContinuousClock.now + let result = await MCPConnectionRunner.run( + .stdio(configuration), + client: MCPConnectionClient(name: String(repeating: "x", count: 2_000_000), version: "1"), + limits: limits) + #expect(result.status == .failed(.timeout)) + #expect(result.cleanupComplete) + #expect(started.duration(to: .now) < .seconds(4)) + let ready = root.appendingPathComponent("holder-ready") + #expect(FileManager.default.fileExists(atPath: ready.path)) + #expect( + FileManager.default.fileExists(atPath: root.appendingPathComponent("stdin-pending").path)) + let pidText = try String(contentsOf: root.appendingPathComponent("pid"), encoding: .utf8) + let pid = try #require(Int32(pidText)) + #expect(kill(pid, 0) == -1 && errno == ESRCH) + } +} diff --git a/Tests/ComponentsTests/MCPConnectionTests.swift b/Tests/ComponentsTests/MCPConnectionTests.swift new file mode 100644 index 0000000..023714b --- /dev/null +++ b/Tests/ComponentsTests/MCPConnectionTests.swift @@ -0,0 +1,394 @@ +import AgentsCore +import CPlatform +import Foundation +import Testing + +@testable import Components + +private final class MCPTestBundle: NSObject {} + +private final class MCPFixture { + let root: URL + private var server: Process? + static var executable: URL { + var directory = Bundle(for: MCPTestBundle.self).bundleURL + for _ in 0..<8 { + let candidate = directory.appendingPathComponent("MCPTestProcess") + if FileManager.default.isExecutableFile(atPath: candidate.path) { return candidate } + directory.deleteLastPathComponent() + } + return directory.appendingPathComponent("MCPTestProcess") + } + init() throws { + root = FileManager.default.temporaryDirectory.appendingPathComponent( + "mcp-io-" + UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + } + var environment: [String: String] { + [ + "PATH": MCPFixture.executable.deletingLastPathComponent().path + ":/usr/bin:/bin", + "HOME": root.path, "FIXTURE_VALUE": "explicit-environment", + ] + } + func input(_ mode: String, extra: [String: String] = [:]) -> MCPConnectionInput { + .stdio(configuration(mode, extra: extra)) + } + func configuration(_ mode: String, extra: [String: String] = [:]) -> DuplexProcessConfiguration { + DuplexProcessConfiguration( + executable: "MCPTestProcess", arguments: [mode, root.path], directory: root, + environment: environment.merging(extra, uniquingKeysWith: { _, new in new })) + } + func text(_ name: String) -> String? { + try? String(contentsOf: root.appendingPathComponent(name), encoding: .utf8) + } + func records() -> [[String: Any]] { + (text("wire.jsonl") ?? "").split(separator: "\n").compactMap { + (try? JSONSerialization.jsonObject(with: Data($0.utf8))) as? [String: Any] + } + } + func methods() -> [String] { records().compactMap { $0["method"] as? String } } + func waitFor(_ predicate: () -> Bool) async -> Bool { + let deadline = ContinuousClock.now + .seconds(3) + while !predicate() { + if ContinuousClock.now >= deadline { return false } + try? await Task.sleep(for: .milliseconds(2)) + } + return true + } + func startHTTP(_ mode: String) async throws -> URL { + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/env") + let file = Bundle.module.url( + forResource: "MCPHTTPServer", withExtension: "py", subdirectory: "Fixtures")! + process.arguments = ["python3", file.path, mode, root.path] + var environment = self.environment + // Python is an existing test tool, not a downloaded service/client. + environment["PATH"] = "/usr/bin:/bin:/opt/homebrew/bin" + process.environment = environment + process.standardOutput = FileHandle.nullDevice + process.standardError = FileHandle.nullDevice + try process.run() + server = process + guard await waitFor({ self.text("endpoint") != nil }), + let endpoint = text("endpoint"), let url = URL(string: endpoint), + url.host == "127.0.0.1", let port = url.port, (1...65535).contains(port) + else { + throw MCPConnectionIssue.connectionFailed + } + return url + } + func stopHTTP() { + if let server, server.isRunning { + _ = kill(server.processIdentifier, SIGTERM) + let deadline = Date().addingTimeInterval(2) + while server.isRunning && Date() < deadline { usleep(1000) } + if server.isRunning { _ = kill(server.processIdentifier, SIGKILL) } + let killedDeadline = Date().addingTimeInterval(2) + while server.isRunning && Date() < killedDeadline { usleep(1000) } + if server.isRunning { Issue.record("Owned HTTP fixture did not terminate") } + } + server = nil + } + deinit { + stopHTTP() + try? FileManager.default.removeItem(at: root) + } +} + +private func runConnection(_ input: MCPConnectionInput, limits: MCPConnectionLimits = .init()) async + -> MCPConnectionOutcome +{ + await MCPConnectionRunner.run( + input, client: MCPConnectionClient(name: "fixture-client", version: "1"), limits: limits) +} + +@Suite(.serialized) struct MCPConnectionTests { + @Test func stdioDiscoversOnlyToolsAndInheritsExplicitValues() async throws { + let fixture = try MCPFixture() + let file = fixture.root.appendingPathComponent("lock") + let original = open(file.path, O_RDWR | O_CREAT, 0o600) + #expect(original >= 0) + let high = fcntl(original, F_DUPFD, 200) + defer { + close(original) + if high >= 0 { close(high) } + } + let result = await runConnection(fixture.input("normal", extra: ["FD_CHECK": String(high)])) + #expect(result.status == .discovered) + #expect(result.negotiatedVersion == "2025-11-25") + #expect(result.tools.map(\.name) == ["first", "second"]) + #expect(result.cleanupComplete) + #expect( + fixture.methods() == ["initialize", "notifications/initialized", "tools/list", "tools/list"]) + let startup = try #require(fixture.records().first) + let cwd = try #require(startup["cwd"] as? String) + let actual = try FileManager.default.attributesOfItem(atPath: cwd) + let expected = try FileManager.default.attributesOfItem(atPath: fixture.root.path) + #expect(actual[.systemNumber] as? NSNumber == expected[.systemNumber] as? NSNumber) + #expect(actual[.systemFileNumber] as? NSNumber == expected[.systemFileNumber] as? NSNumber) + #expect(startup["environment"] as? String == "explicit-environment") + #expect(startup["inheritedFD"] as? Bool == false) + let initialize = try #require( + fixture.records().first { $0["method"] as? String == "initialize" }) + #expect( + ((initialize["params"] as? [String: Any])?["capabilities"] as? [String: Any])?.isEmpty == true + ) + let pid = try #require(Int32(fixture.text("pid") ?? "")) + #expect(kill(pid, 0) == -1 && errno == ESRCH) + } + + @Test(arguments: ["wrong-version", "no-tools", "cursor-cycle", "stdout-flood", "stderr-flood"]) + func wireAndBudgetFailures(_ mode: String) async throws { + let fixture = try MCPFixture() + var limits = MCPConnectionLimits() + limits.frameBytes = 1024 + limits.stderrBytes = 1024 + let result = await runConnection(fixture.input(mode), limits: limits) + let expected: MCPConnectionOutcome.Status + switch mode { + case "wrong-version": expected = .failed(.unsupportedVersion) + case "no-tools": expected = .noTools + case "cursor-cycle": expected = .incomplete(.cursorCycle) + case "stdout-flood": expected = .failed(.messageLimit) + default: expected = .failed(.stderrLimit) + } + #expect(result.status == expected) + #expect(result.cleanupComplete) + if mode == "wrong-version" { #expect(fixture.methods() == ["initialize"]) } + if mode == "no-tools" { + #expect(fixture.methods() == ["initialize", "notifications/initialized"]) + } + } + + @Test(arguments: ["pending-initialize", "pending-tools"]) + func requestDeadlineActuallyReaps(_ mode: String) async throws { + let fixture = try MCPFixture() + var limits = MCPConnectionLimits() + limits.totalTimeout = 1 + limits.requestTimeout = 0.08 + let result = await runConnection(fixture.input(mode), limits: limits) + #expect( + result.status == (mode == "pending-initialize" ? .failed(.timeout) : .incomplete(.timeout))) + #expect(result.cleanupComplete) + let pid = try #require(Int32(fixture.text("pid") ?? "")) + #expect(kill(pid, 0) == -1) + } + + @Test func cancellationKillsStubbornChildAndLeavesSameNameProcess() async throws { + let fixture = try MCPFixture() + let unrelated = Process() + let other = try MCPFixture() + unrelated.executableURL = MCPFixture.executable + unrelated.arguments = ["ignore-input", other.root.path] + unrelated.environment = other.environment + try unrelated.run() + defer { + _ = kill(unrelated.processIdentifier, SIGKILL) + let deadline = Date().addingTimeInterval(2) + while unrelated.isRunning && Date() < deadline { usleep(1000) } + if unrelated.isRunning { Issue.record("Owned unrelated-process fixture did not terminate") } + } + #expect(await other.waitFor { other.text("holder-ready") != nil }) + let input = fixture.input("stubborn") + let task = Task { await runConnection(input) } + #expect(await fixture.waitFor { fixture.text("stubborn-ready") != nil }) + task.cancel() + let result = await task.value + #expect(result.status == .incomplete(.cancelled)) + #expect(result.cleanupComplete) + let pid = try #require(Int32(fixture.text("pid") ?? "")) + #expect(kill(pid, 0) == -1) + #expect(unrelated.isRunning) + } + + @Test func groupCleanupAfterLeaderEOFStopsDescendant() async throws { + let fixture = try MCPFixture() + let result = await runConnection(fixture.input("descendant")) + #expect(result.status == .discovered) + #expect(result.cleanupComplete) + let pid = try #require(Int32(fixture.text("pid") ?? "")) + #expect(kill(pid, 0) == -1) + guard let child = fixture.text("descendant-pid").flatMap({ Int32($0) }) else { + Issue.record("Missing owned descendant") + return + } + #if os(Linux) + let stat = try? String(contentsOfFile: "/proc/\(child)/stat", encoding: .utf8) + #expect(stat == nil || stat!.split(separator: ")").last!.hasPrefix(" Z")) + #else + #expect(await fixture.waitFor { kill(child, 0) == -1 }) + #endif + } + + #if os(Linux) + @Test func zombieDescendantLeaderDoesNotHideItsLiveWorker() async throws { + let fixture = try MCPFixture() + let process = try OwnedDuplexProcess(fixture.configuration("thread-descendant")) + func state(_ pid: Int32) -> (state: String, threads: Int)? { + guard let stat = try? String(contentsOfFile: "/proc/\(pid)/stat", encoding: .utf8), + let delimiter = stat.lastIndex(of: ")") + else { return nil } + let fields = stat[stat.index(after: delimiter)...].split(separator: " ") + guard fields.count > 17, let threads = Int(fields[17]) else { return nil } + return (String(fields[0]), threads) + } + let ready = await fixture.waitFor { + var exited = false + guard platform_duplex_observe(process.identifier, &exited) == 0, exited, + fixture.text("holder-ready") == "ready", + let child = fixture.text("descendant-pid").flatMap({ Int32($0) }), + let childState = state(child) + else { return false } + return childState.state == "Z" && childState.threads > 1 + } + #expect(ready) + var quiescent = true + let observation = platform_duplex_group_quiescent(process.identifier, &quiescent) + #expect(observation == 0) + #expect(!quiescent) + let cleaned = await process.finish( + grace: .milliseconds(5), terminate: .milliseconds(5), killWait: .seconds(1)) + #expect(cleaned) + #expect(kill(process.identifier, 0) == -1 && errno == ESRCH) + if let child = fixture.text("descendant-pid").flatMap({ Int32($0) }) { + let final = state(child) + #expect(final == nil || (final!.state == "Z" && final!.threads == 1)) + } else { + Issue.record("Missing owned multithreaded descendant") + } + } + #endif + + @Test func blockedKernelPipeWriteIsNonblockingAndCleanupIsFinite() async throws { + let fixture = try MCPFixture() + let process = try OwnedDuplexProcess(fixture.configuration("ignore-input")) + #expect(await fixture.waitFor { fixture.text("holder-ready") != nil }) + let bytes = Data(repeating: 120, count: 256 * 1024) + var offset = 0 + while offset < bytes.count { + let count = try process.write(bytes, offset: offset) + if count == 0 { break } + offset += count + } + #expect(offset < bytes.count) + let cleaned = await process.finish( + grace: .milliseconds(5), terminate: .milliseconds(5), killWait: .seconds(1)) + #expect(cleaned) + #expect(kill(process.identifier, 0) == -1) + } + + @Test func finiteDiscoveryAndInputAdmission() async throws { + let fixture = try MCPFixture() + var limits = MCPConnectionLimits() + limits.pages = 1 + let result = await runConnection(fixture.input("normal"), limits: limits) + #expect(result.status == .incomplete(.pageLimit)) + #expect(result.tools.count == 1) + #expect(fixture.methods().filter { $0 == "tools/list" }.count == 1) + let originalWire = fixture.text("wire.jsonl") + limits.totalTimeout = .infinity + let invalid = await runConnection(fixture.input("normal"), limits: limits) + #expect(invalid.status == .failed(.invalidInput)) + #expect(invalid.cleanupComplete) + #expect(fixture.text("wire.jsonl") == originalWire) + } + + @Test(arguments: ["tool", "text", "send"]) + func discoveryAndOutputBudgets(_ mode: String) async throws { + let fixture = try MCPFixture() + var limits = MCPConnectionLimits() + if mode == "tool" { limits.tools = 1 } + if mode == "text" { limits.textBytes = 16 } + if mode == "send" { limits.sentBytes = 64 } + let input = fixture.input(mode == "text" ? "long-text" : "normal") + let result = await runConnection(input, limits: limits) + let expected: MCPConnectionOutcome.Status = + mode == "tool" + ? .incomplete(.toolLimit) + : mode == "text" ? .incomplete(.textLimit) : .failed(.sendLimit) + #expect(result.status == expected) + #expect(result.cleanupComplete) + if mode == "send" { #expect(fixture.methods().isEmpty) } + } + + @Test(arguments: ["eof-initialize", "eof-tools"]) + func stdioEOFJoinsPendingRequestsAndDrainsAcceptedResponse(_ mode: String) async throws { + let fixture = try MCPFixture() + var limits = MCPConnectionLimits() + limits.frameBytes = 1024 * 1024 + limits.tools = 1000 + let result = await runConnection(fixture.input(mode), limits: limits) + #expect(result.status == (mode == "eof-tools" ? .discovered : .failed(.connectionClosed))) + #expect(result.cleanupComplete) + if mode == "eof-tools" { #expect(result.tools.count == 1000) } + } + + @Test func finalToolsResponseCannotMaskSameBurstAdmissionFailure() async throws { + let fixture = try MCPFixture() + var limits = MCPConnectionLimits() + limits.frameBytes = 1024 + let result = await runConnection(fixture.input("final-response-limit"), limits: limits) + #expect(result.status == .incomplete(.messageLimit)) + #expect(result.cleanupComplete) + #expect(fixture.methods() == ["initialize", "notifications/initialized", "tools/list"]) + } + + @Test(arguments: ["json", "sse", "legacy", "resume"]) + func actualHTTPModesDiscoverAndCleanUp(_ mode: String) async throws { + let fixture = try MCPFixture() + let url = try await fixture.startHTTP(mode) + let input: MCPConnectionInput = + mode == "legacy" ? .legacySSE(url, headers: [:]) : .streamableHTTP(url, headers: [:]) + let result = await runConnection(input) + #expect(result.status == .discovered) + #expect(result.cleanupComplete) + #expect(result.tools.map(\.name) == ["first", "second"]) + fixture.stopHTTP() + #expect( + fixture.methods() == ["initialize", "notifications/initialized", "tools/list", "tools/list"]) + if mode != "legacy" { + let posts = fixture.records().filter { $0["http"] as? String == "POST" } + #expect( + posts.dropFirst().allSatisfy { + $0["session"] as? String == "fixture-session" && $0["version"] as? String == "2025-11-25" + }) + } + if mode == "resume" { + #expect( + fixture.records().contains { + $0["http"] as? String == "GET" && $0["lastEventID"] as? String == "1" + }) + } + } + + @Test(arguments: [ + "auth", "forbidden", "redirect", "legacy-cross", "event-flood", "comment-flood", "pending-body", + ]) + func httpAuthorityAndStreamBounds(_ mode: String) async throws { + let fixture = try MCPFixture() + let url = try await fixture.startHTTP(mode) + var limits = MCPConnectionLimits() + limits.frameBytes = 1024 + limits.receivedBytes = 8192 + if mode == "event-flood" { limits.receivedBytes = 128 * 1024 } + if mode == "pending-body" { limits.totalTimeout = 0.12 } + let headers = ["Authorization": "fixture-canary"] + let input: MCPConnectionInput = + mode.hasPrefix("legacy") + ? .legacySSE(url, headers: headers) : .streamableHTTP(url, headers: headers) + let result = await runConnection(input, limits: limits) + let expected: MCPConnectionIssue + switch mode { + case "auth": expected = .authenticationRequired + case "forbidden": expected = .forbidden + case "redirect", "legacy-cross": expected = .authorityChanged + case "event-flood": expected = .messageLimit + case "comment-flood": expected = .receiveLimit + default: expected = .timeout + } + #expect(result.status == .failed(expected)) + #expect(result.cleanupComplete) + fixture.stopHTTP() + #expect(fixture.records().filter { $0["http"] != nil }.count == 1) + } +} diff --git a/Tests/ComponentsTests/NativeComponentFieldsTests.swift b/Tests/ComponentsTests/NativeComponentFieldsTests.swift new file mode 100644 index 0000000..9c65b54 --- /dev/null +++ b/Tests/ComponentsTests/NativeComponentFieldsTests.swift @@ -0,0 +1,319 @@ +import AgentsCore +import Foundation +import NativeDocuments +import Testing + +@testable import Components + +@Suite("Parsed native component semantics") +struct NativeComponentFieldsTests { + private func budget(_ nodes: Int = 10000) -> NativeDocumentBudget { + .init( + limits: .init( + storage: 1_000_000, work: 1_000_000, nodes: nodes, depth: 64, uninterruptedBytes: 1_000_000) + ) + } + + @Test func parsedFrontmatterKeepsNativeFieldsAndRejectsIgnoredIntent() throws { + let fields: [String: NativeValue] = [ + "name": .string("auditor"), "description": .string("Inspect source."), + "permissionMode": .string("plan"), "maxTurns": .integer(3), + "tools": .array([.string("Read")]), "disallowedTools": .array([.string("Write")]), + ] + #expect( + try NativeComponentFieldsV1.markdown( + surface: .claudeCode, document: "source.json", kind: .subagent, name: "auditor", + fields: fields, inPlugin: false, + budget: budget()) + == fields) + #expect(throws: NativeComponentFieldIssue.self) { + try NativeComponentFieldsV1.markdown( + surface: .claudeCode, document: "source.json", kind: .subagent, name: "auditor", + fields: fields, + inPlugin: true, budget: budget()) + } + var commaTools = fields + commaTools["tools"] = .string("Read, Grep") + #expect( + try NativeComponentFieldsV1.markdown( + surface: .claudeCode, document: "source.json", kind: .subagent, name: "auditor", + fields: commaTools, inPlugin: false, + budget: budget()) == commaTools) + var unknown = fields + unknown["permissionmode"] = .string("value-canary") + do { + _ = try NativeComponentFieldsV1.markdown( + surface: .claudeCode, document: "source.json", kind: .subagent, name: "auditor", + fields: unknown, inPlugin: false, + budget: budget()) + Issue.record("silently ignored unknown native field") + } catch let issue as NativeComponentFieldIssue { + #expect(issue.reason == .unverified) + #expect(!issue.detail.contains("value-canary")) + } + #expect(throws: NativeComponentFieldIssue.self) { + try NativeComponentFieldsV1.markdown( + surface: .claudeCode, document: "source.json", kind: .command, name: "review", + fields: ["background": .boolean(true)], inPlugin: false, budget: budget()) + } + #expect( + try NativeComponentFieldsV1.markdown( + surface: .claudeCode, document: "source.json", kind: .command, name: "team/review", + fields: [:], + inPlugin: false, budget: budget() + ).isEmpty) + #expect(throws: NativeComponentFieldIssue.self) { + try NativeComponentFieldsV1.markdown( + surface: .cursorEditor, document: "source.json", kind: .command, name: "team/review", + fields: [:], + inPlugin: false, budget: budget()) + } + let cursor: [String: NativeValue] = [ + "readonly": .boolean(true), "is_background": .boolean(true), + ] + #expect( + try NativeComponentFieldsV1.markdown( + surface: .cursorEditor, document: "source.json", kind: .subagent, name: "auditor", + fields: cursor, inPlugin: false, + budget: budget()) + == cursor) + #expect(throws: NativeComponentFieldIssue.self) { + try NativeComponentFieldsV1.markdown( + surface: .cursorEditor, document: "source.json", kind: .subagent, name: "auditor", + fields: ["tools": .array([.string("Read")])], inPlugin: false, budget: budget()) + } + } + + @Test func parsedLSPPreservesArbitraryInitializationAndRejectsUnknownFields() throws { + let fields: [String: NativeValue] = [ + "command": .string("source-lsp"), + "extensionToLanguage": .object([".source": .string("source")]), + "transport": .string("socket"), "requestTimeout": .integer(100), + "initializationOptions": .object([ + "deep": .array([.null, .boolean(true), .string("${kept}\0data")]) + ]), + ] + #expect( + try NativeComponentFieldsV1.lsp( + surface: .claudeCode, document: "source.json", fields: fields, budget: budget()) + == fields) + var unknown = fields + unknown["cwd"] = .string("value-canary") + #expect(throws: NativeComponentFieldIssue.self) { + try NativeComponentFieldsV1.lsp( + surface: .claudeCode, document: "source.json", fields: unknown, budget: budget()) + } + var invalid = fields + invalid["requestTimeout"] = .integer(0) + #expect(throws: NativeComponentFieldIssue.self) { + try NativeComponentFieldsV1.lsp( + surface: .claudeCode, document: "source.json", fields: invalid, budget: budget()) + } + } + + @Test func parsedOpenCodeLSPRetainsNativeEntrySemantics() throws { + let fields: [String: NativeValue] = [ + "command": .array([.string("source-lsp"), .string("--stdio")]), + "extensions": .array([.string(".source")]), + "env": .object(["SOURCE": .string("{env:SOURCE}")]), + "initialization": .object(["any": .array([.null, .integer(7)])]), + ] + #expect( + try NativeComponentFieldsV1.lsp( + surface: .openCodeCLI, document: "source.json", fields: fields, budget: budget()) == fields) + let disabled: [String: NativeValue] = ["disabled": .boolean(true)] + #expect( + try NativeComponentFieldsV1.lsp( + surface: .openCodeCLI, document: "source.json", fields: disabled, budget: budget()) + == disabled) + var invalid = fields + invalid["env"] = .object(["SOURCE": .integer(7)]) + #expect(throws: NativeComponentFieldIssue.self) { + try NativeComponentFieldsV1.lsp( + surface: .openCodeCLI, document: "source.json", fields: invalid, budget: budget()) + } + } + + @Test func parsedPluginUsesProducerRootAndMergeDefaults() throws { + let claudeDefaults = try NativeComponentFieldsV1.pluginDefaults( + surface: .claudeCode, document: "source.json", + explicitFields: ["commands", "agents", "skills", "hooks"]) + #expect(claudeDefaults["commands"] == nil && claudeDefaults["agents"] == nil) + #expect(claudeDefaults["skills"] == "skills" && claudeDefaults["hooks"] == "hooks/hooks.json") + let cursorDefaults = try NativeComponentFieldsV1.pluginDefaults( + surface: .cursorEditor, document: "source.json", + explicitFields: ["commands", "skills", "hooks"]) + #expect(cursorDefaults["commands"] == nil && cursorDefaults["skills"] == nil) + #expect(cursorDefaults["hooks"] == nil && cursorDefaults["mcpServers"] == "mcp.json") + let entries: [LedgerEntry] = [ + .init(path: ".", kind: .directory, executable: false), + .init(path: "commands/review.md", kind: .file, executable: false), + .init(path: "hooks/hooks.json", kind: .file, executable: false), + ] + let valid: [String: NativeValue] = [ + "name": .string("fixture"), "commands": .string("./commands/review.md"), + "hooks": .object([:]), + ] + let badDefault: NativeValue = .object(["hooks": .object(["invented": .array([])])]) + #expect(throws: NativeComponentFieldIssue.self) { + try NativeComponentFieldsV1.plugin( + surface: .claudeCode, document: "source.json", fields: valid, + entries: entries, documents: ["hooks/hooks.json": badDefault], budget: budget()) + } + let emptyHooks: NativeValue = .object(["hooks": .object([:])]) + #expect( + try NativeComponentFieldsV1.plugin( + surface: .claudeCode, document: "source.json", fields: valid, + entries: entries, documents: ["hooks/hooks.json": emptyHooks], budget: budget()) == valid) + // Cursor explicit hooks replace its default; an absent explicit file still fails. + let cursor: [String: NativeValue] = [ + "name": .string("fixture"), "hooks": .string("chosen.json"), + ] + let cursorEntries = entries + [.init(path: "chosen.json", kind: .file, executable: false)] + #expect( + try NativeComponentFieldsV1.plugin( + surface: .cursorEditor, document: "source.json", fields: cursor, + entries: cursorEntries, + documents: ["chosen.json": .object(["version": .integer(1), "hooks": .object([:])])], + budget: budget()) == cursor) + #expect(throws: NativeComponentFieldIssue.self) { + try NativeComponentFieldsV1.plugin( + surface: .cursorEditor, document: "source.json", fields: cursor, + entries: entries, documents: [:], budget: budget()) + } + #expect(throws: (any Error).self) { + try NativeComponentFieldsV1.plugin( + surface: .claudeCode, document: "source.json", fields: valid, + entries: entries, documents: ["hooks/hooks.json": emptyHooks], budget: budget(1)) + } + } + @Test func referencedConfigurationFailuresKeepTheirExactDocumentAndField() throws { + let manifest = ".claude-plugin/plugin.json" + let entries: [LedgerEntry] = [ + .init(path: "first.json", kind: .file, executable: false), + .init(path: "second.json", kind: .file, executable: false), + .init(path: ".lsp.json", kind: .file, executable: false), + .init(path: "hooks/hooks.json", kind: .file, executable: false), + ] + let first: NativeValue = .object([ + "mcpServers": .object(["same": .object(["command": .integer(17)])]) + ]) + let second: NativeValue = .object([ + "mcpServers": .object(["same": .object(["command": .string("valid")])]) + ]) + let fields: [String: NativeValue] = [ + "name": .string("fixture"), + "mcpServers": .array([.string("./first.json"), .string("./second.json")]), + ] + do { + _ = try NativeComponentFieldsV1.plugin( + surface: .claudeCode, document: manifest, fields: fields, entries: entries, + documents: ["first.json": first, "second.json": second], budget: budget()) + Issue.record("invalid overwritten source was accepted") + } catch let issue as NativeComponentFieldIssue { + #expect(issue.document == "first.json") + #expect(issue.field == ["mcpServers", "same", "command"]) + #expect(!issue.detail.contains("17")) + } + do { + _ = try NativeComponentFieldsV1.plugin( + surface: .claudeCode, document: manifest, + fields: ["name": .string("fixture")], entries: entries, + documents: [ + "hooks/hooks.json": .object(["hooks": .object([:])]), + ".lsp.json": .object([ + "same": .object([ + "command": .integer(17), "extensionToLanguage": .object([".x": .string("x")]), + ]) + ]), + ], budget: budget()) + Issue.record("invalid default source was accepted") + } catch let issue as NativeComponentFieldIssue { + #expect(issue.document == ".lsp.json") + #expect(issue.field == ["same", "command"]) + } + do { + _ = try NativeComponentFieldsV1.plugin( + surface: .claudeCode, document: manifest, + fields: [ + "name": .string("fixture"), + "hooks": .array([ + .object([:]), + .object([ + "SessionStart": .array([ + .object([ + "hooks": .array([.object(["type": .string("command"), "command": .integer(17)])]) + ]) + ]) + ]), + ]), + ], entries: [], documents: [:], budget: budget()) + Issue.record("invalid inline source was accepted") + } catch let issue as NativeComponentFieldIssue { + #expect(issue.document == manifest) + #expect(issue.field == ["hooks", "1", "SessionStart", "0", "hooks", "0", "command"]) + } + do { + _ = try NativeComponentFieldsV1.plugin( + surface: .claudeCode, document: manifest, + fields: [ + "name": .string("fixture"), + "mcpServers": .array([ + .object([:]), .string("./missing.json"), + ]), + ], entries: [], documents: [:], budget: budget()) + Issue.record("missing referenced file was accepted") + } catch let issue as NativeComponentFieldIssue { + #expect(issue.document == manifest) + #expect(issue.field == ["mcpServers", "1"]) + } + } + + @Test func externalHookCoordinatesIncludeHandlerIndicesAndRootMetadata() throws { + let file = "hooks/chosen.json" + let entries: [LedgerEntry] = [.init(path: file, kind: .file, executable: false)] + let fields: [String: NativeValue] = ["name": .string("fixture"), "hooks": .string(file)] + for invalidMetadata in [false, true] { + let config: NativeValue = .object([ + "version": invalidMetadata ? .integer(2) : .integer(1), + "hooks": .object([ + "stop": .array([ + .object(["command": .string("keep")]), .object(["command": .integer(17)]), + ]) + ]), + ]) + do { + _ = try NativeComponentFieldsV1.plugin( + surface: .cursorEditor, document: ".cursor-plugin/plugin.json", fields: fields, + entries: entries, documents: [file: config], budget: budget()) + Issue.record("invalid external hooks were accepted") + } catch let issue as NativeComponentFieldIssue { + #expect(issue.document == file) + #expect(issue.field == (invalidMetadata ? ["version"] : ["hooks", "stop", "1", "command"])) + } + } + } + + @Test func directParsedFailuresRetainCallerDocumentAndFieldPrefix() throws { + do { + _ = try NativeComponentFieldsV1.lsp( + surface: .claudeCode, document: "settings.json", fieldPrefix: ["lsp", "same"], + fields: ["command": .integer(17), "extensionToLanguage": .object([".x": .string("x")])], + budget: budget()) + Issue.record("invalid LSP command was accepted") + } catch let issue as NativeComponentFieldIssue { + #expect(issue.document == "settings.json") + #expect(issue.field == ["lsp", "same", "command"]) + } + do { + _ = try NativeComponentFieldsV1.markdown( + surface: .claudeCode, document: "commands/review.md", kind: .command, name: "review", + fields: ["model": .integer(17)], inPlugin: true, budget: budget()) + Issue.record("invalid Markdown field was accepted") + } catch let issue as NativeComponentFieldIssue { + #expect(issue.document == "commands/review.md") + #expect(issue.field == ["model"]) + } + } + +} diff --git a/Tests/ComponentsTests/NativeComponentTests.swift b/Tests/ComponentsTests/NativeComponentTests.swift new file mode 100644 index 0000000..03998b2 --- /dev/null +++ b/Tests/ComponentsTests/NativeComponentTests.swift @@ -0,0 +1,1508 @@ +import AgentsManifest +import Foundation +import NativeDocuments +import Testing + +@testable import AgentsCore +@testable import Components + +@Suite("Concrete native component profiles") +struct NativeComponentTests { + @Test func geminiCommandPreservesQuotedLiteralAndFrozenFileBody() throws { + let fixture = try LinkFixture() + let body = "Review \\\"quoted\\\" paths\nKeep exact content.\n" + try fixture.write(body, to: "prompt.md", base: fixture.project) + let item: [String: Any] = [ + "kind": "command", "name": "review", "description": "Review sources", + "prompt": ["file": ["path": "prompt.md"]], "agents": ["gemini-cli"], + ] + let (linked, frozen) = try freeze([item], fixture) + var ledger = frozen.ledger + ledger.lowerings = [try lower(linked[0], frozen, surface: .geminiCLI)] + ledger = try prepared(ledger, fixture) + let encoded = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + try FileManager.default.removeItem(at: fixture.project) + let restored = try ResolvedLedgerCodec.decode(encoded, limits: .standard) + try replay(restored, fixture) { outputs in + let envelope = try #require(outputs[0].values?.object) + #expect(envelope["route"]?.text == "geminiCommand") + #expect(envelope["path"]?.text == "review.toml") + let file = try #require(envelope["value"]?.text) + let native = try NativeDocument(bytes: Data(file.utf8), format: .toml, budget: budget()) + #expect(try native.read(.init(keys: ["prompt"]))?.value == .string(body)) + #expect(try native.read(.init(keys: ["description"]))?.value == .string("Review sources")) + #expect(!String(describing: envelope).contains(fixture.project.path)) + } + } + + @Test(arguments: [NativeClientSurface.geminiCLI, .cursorEditor]) + func agentFrontmatterKeepsDescriptionAndToolSemantics(_ surface: NativeClientSurface) throws { + let fixture = try LinkFixture() + var item: [String: Any] = [ + "kind": "subagent", "name": "security-auditor", + "description": "Audit: source\n---\nLiteral metadata", + "prompt": "Inspect the source.", + "model": "inherit", "agents": [surface.agent.rawValue], + ] + if surface == .geminiCLI { item["tools"] = ["read_file", "grep_search"] } + let (linked, frozen) = try freeze([item], fixture) + var ledger = frozen.ledger + ledger.lowerings = [try lower(linked[0], frozen, surface: surface)] + ledger = try prepared(ledger, fixture) + try replay(ledger, fixture) { output in + let envelope = try #require(output[0].values?.object) + let text = try #require(envelope["value"]?.text) + #expect(text.hasPrefix("---\ndescription: \"Audit: source\\n---\\nLiteral metadata\"\n")) + #expect(text.hasSuffix("---\nInspect the source.")) + #expect(envelope["knownReaders"] == LedgerPayload.strings([surface.agent.rawValue])) + if surface == .geminiCLI { #expect(text.contains("tools: [\"read_file\", \"grep_search\"]")) } + } + } + + @Test func codexRoleFreezesItsConfigAndRegistrationTogether() throws { + let fixture = try LinkFixture() + let item: [String: Any] = [ + "kind": "subagent", "name": "researcher", "description": "Research-focused role.", + "prompt": "Read exact sources.\n", "model": "fixture-model", "agents": ["codex"], + ] + let (linked, frozen) = try freeze([item], fixture) + var ledger = frozen.ledger + ledger.lowerings = [try lower(linked[0], frozen, surface: .codexCLI)] + ledger = try prepared(ledger, fixture) + try replay(ledger, fixture) { output in + let envelopes = try #require(output[0].values?.array) + #expect(envelopes.count == 2) + let contribution = try NativeComponentLayoutsV1.contribution( + ledger.lowerings[0], ledger: ledger, artifacts: output, limits: .standard) + #expect(contribution.occurrences == linked[0].origins.map(\.occurrence)) + #expect(contribution.outputs.count == 2) + guard case .file(let path, let bytes) = contribution.outputs[0].content, + case .member(let member, let registration) = contribution.outputs[1].content + else { + Issue.record("missing coupled typed role outputs") + return + } + #expect(path == "researcher.toml") + #expect(member.keys == ["agents", "researcher"]) + #expect(contribution.outputs.map(\.route) == [.codexAgent, .codexConfig]) + #expect(contribution.outputs[1].route.documentFormat == .toml) + #expect( + try registration.referenceValue(budget: budget()) + == .object([ + "description": .string("Research-focused role."), + "config_file": .string("./agents/researcher.toml"), + ])) + #expect(bytes == Data(try #require(envelopes[0].object?["value"]?.text).utf8)) + let text = try #require(envelopes[0].object?["value"]?.text) + let doc = try NativeDocument(bytes: Data(text.utf8), format: .toml, budget: budget()) + #expect( + try doc.read(.init(keys: ["developer_instructions"]))?.value + == .string("Read exact sources.\n")) + #expect(envelopes[1].object?["keys"] == LedgerPayload.strings(["agents", "researcher"])) + #expect( + envelopes[1].object?["value"]?.object?["config_file"]?.text == "./agents/researcher.toml") + } + } + + @Test func openCodeCommandAgentAndOrderedNativeToolPermissions() throws { + let fixture = try LinkFixture() + let components: [[String: Any]] = [ + [ + "kind": "command", "name": "review", "description": "Review sources", + "prompt": "Review the source.", "agents": ["opencode"], + ], + [ + "kind": "subagent", "name": "reviewer", "description": "Review sources", + "prompt": "Inspect source.", "model": "provider/model", "agents": ["opencode"], + ], + [ + "kind": "permissions", "name": "policy", + "rules": [ + ["effect": "deny", "operation": ["tool": "read"], "pattern": "*"], + ["effect": "allow", "operation": ["tool": "read"], "pattern": "src/**"], + ["effect": "ask", "operation": ["tool": "read"], "pattern": "src/private/**"], + ], "agents": ["opencode"], + ], + ] + let (linked, frozen) = try freeze(components, fixture) + var ledger = frozen.ledger + ledger.lowerings = try linked.enumerated().map { + try lower($0.element, frozen, surface: .openCodeCLI, id: "component-\($0.offset)") + } + ledger = try prepared(ledger, fixture) + try replay(ledger, fixture) { output in + #expect(output[0].values?.object?["keys"] == LedgerPayload.strings(["commands", "review"])) + #expect(output[0].values?.object?["value"]?.object?["template"]?.text == "Review the source.") + #expect(output[1].values?.object?["value"]?.object?["mode"]?.text == "subagent") + #expect(output[2].values?.object?["selection"]?.text == "orderedAppend") + let rules = try #require(output[2].values?.object?["value"]?.array) + #expect(rules.compactMap { $0.object?["effect"]?.text } == ["deny", "allow", "ask"]) + #expect( + rules.compactMap { $0.object?["resource"]?.text } == ["*", "src/**", "src/private/**"]) + #expect( + output.map { $0.values?.object?["occurrences"] } + == linked.map { .init(array: $0.origins.map { .init(integer: $0.occurrence) }) }) + } + } + + @Test(arguments: [NativeClientSurface.geminiCLI, .codexCLI]) + func nativeHookFreezesProgramAndStagedArgumentsWithoutExecuting(_ surface: NativeClientSurface) + throws + { + let fixture = try LinkFixture() + try fixture.write( + "#!/bin/sh\n# source-owned fixture; never executed\n", to: "scripts/check", + base: fixture.project) + try FileManager.default.setAttributes( + [.posixPermissions: 0o755], + ofItemAtPath: fixture.project.appendingPathComponent("scripts/check").path) + try fixture.write("data", to: "working/data", base: fixture.project) + try fixture.write("executable support", to: "working/check", base: fixture.project) + try FileManager.default.setAttributes( + [.posixPermissions: 0o755], + ofItemAtPath: fixture.project.appendingPathComponent("working/check").path) + try FileManager.default.createDirectory( + at: fixture.project.appendingPathComponent("links"), withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink( + atPath: fixture.project.appendingPathComponent("redirect").path, + withDestinationPath: "working") + try FileManager.default.createSymbolicLink( + atPath: fixture.project.appendingPathComponent("links/working-alias").path, + withDestinationPath: "../redirect") + let item: [String: Any] = [ + "kind": "hook", "name": "check", "event": ["native": "SessionStart"], + "run": [ + "executable": "./scripts/check", + "arguments": ["a'b", "$(never-execute)", surface == .geminiCLI ? "plain" : "$ordinary"], + "workingDirectory": ["path": "links/working-alias"], + "environment": ["TOKEN": ["secret": "fixture/token"]], + ], + "matcher": "startup", "timeoutSeconds": 7, "agents": [surface.agent.rawValue], + ] + let (linked, frozen) = try freeze([item], fixture) + let cwdID = try #require(frozen.ledger.components.values.first?.resources.last) + let cwd = try #require(frozen.ledger.resources[cwdID]) + #expect(cwd.entries.first?.kind == .symlink) + #expect(cwd.support.first(where: { $0.path == "working/check" })?.executable == true) + for remove in [false, true] { + var corrupted = frozen + if remove { + corrupted.ledger.resources[cwdID]!.support.removeAll { $0.path == "working/check" } + } else { + let index = try #require(cwd.support.firstIndex(where: { $0.path == "working/check" })) + corrupted.ledger.resources[cwdID]!.support[index].executable = false + } + #expect(throws: NativeComponentIssue.self) { + try lower(linked[0], corrupted, surface: surface) + } + } + var ledger = frozen.ledger + ledger.lowerings = [try lower(linked[0], frozen, surface: surface)] + ledger = try prepared(ledger, fixture) + let encoded = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + #expect(!String(decoding: encoded, as: UTF8.self).contains("private staged fixture")) + ledger = try ResolvedLedgerCodec.decode(encoded, limits: .standard) + try FileManager.default.removeItem(at: fixture.project) + try replay(ledger, fixture) { output in + let contribution = try NativeComponentLayoutsV1.contribution( + ledger.lowerings[0], ledger: ledger, artifacts: output, limits: .standard) + guard case .hook(let concreteHook) = contribution.outputs[0].content else { + Issue.record("missing typed native group") + return + } + #expect( + concreteHook.value.resourcePlacements.map(\.slot) == [.executable, .workingDirectory]) + let placements = Dictionary( + uniqueKeysWithValues: frozen.ledger.components.values.first!.resources.enumerated().map { + ($0.element, $0.offset == 0 ? "/registered/scripts/check" : "/registered/working") + }) + let native = try concreteHook.value.stagedValue( + bindings: RuntimeBindingValues(["fixture/token": Data("private staged fixture".utf8)]), + environment: fixture.environment, resourcePaths: placements, budget: budget(), + codexCommandShell: .posix) + guard case .object(let group) = native, case .array(let hooks) = group["hooks"], + case .object(let hook) = hooks.first + else { + Issue.record("missing native hook group") + return + } + #expect(hook["timeout"] == .integer(surface == .geminiCLI ? 7000 : 7)) + #expect( + hook["command"] + == .string( + "cd -- '/registered/working' && env 'TOKEN=private staged fixture' '/registered/scripts/check' 'a'\\''b' '$(never-execute)' '" + + (surface == .geminiCLI ? "plain" : "$ordinary") + "'" + )) + } + } + + @Test func openCodeLSPPreservesSymbolicEnvAndInitialization() throws { + let fixture = try LinkFixture() + let item: [String: Any] = [ + "kind": "lspServer", "name": "fixture", + "run": [ + "executable": "fixture-lsp", "arguments": ["--stdio"], + "environment": ["TOKEN": ["env": "SOURCE"]], + ], + "languages": [:], + "initializationOptions": [ + "nested": ["enabled": true], "resource": "ordinary", "program": ["setting": "retained"], + ], + "agents": ["opencode"], + "native": ["opencode": ["extensions": [".fixture"]]], + ] + let (linked, frozen) = try freeze([item], fixture) + var ledger = frozen.ledger + ledger.lowerings = [try lower(linked[0], frozen, surface: .openCodeCLI)] + ledger = try prepared(ledger, fixture) + try replay(ledger, fixture) { output in + let envelope = try #require(output[0].values) + let environment = RuntimeEnvironment( + projectDirectory: fixture.project, homeDirectory: fixture.home, + environment: ["SOURCE": "fixture value"]) + let contribution = try NativeComponentLayoutsV1.contribution( + ledger.lowerings[0], ledger: ledger, artifacts: output, limits: .standard) + guard case .member(let member, let template) = contribution.outputs[0].content else { + Issue.record("missing typed LSP member") + return + } + #expect(member.keys == ["lsp", "fixture"]) + #expect(template.bindings.count == 1) + #expect(template.bindings[0].slot == .environment("TOKEN")) + #expect(template.bindings[0].binding == .environment("SOURCE")) + #expect(template.resourcePlacements.isEmpty) + #expect(throws: NativeComponentIssue.self) { try template.referenceValue(budget: budget()) } + let value = try template.stagedValue( + bindings: RuntimeBindingValues([:]), environment: environment, resourcePaths: [:], + budget: budget()) + #expect( + value + == .object([ + "command": .array([.string("fixture-lsp"), .string("--stdio")]), + "env": .object(["TOKEN": .string("fixture value")]), + "initialization": .object([ + "nested": .object(["enabled": .boolean(true)]), "resource": .string("ordinary"), + "program": .object(["setting": .string("retained")]), + ]), + "extensions": .array([.string(".fixture")]), + ])) + var corrupted = ledger + let component = try #require(ledger.lowerings[0].inputs.first) + var payload = try #require(corrupted.components[component]?.payload.object) + payload["initializationOptions"] = .init(object: [ + "hidden": .init("fixture/hidden", kind: .secret) + ]) + corrupted.components[component]?.payload = .init(object: payload) + var changed = output + var fields = try #require(envelope.object) + var native = try #require(fields["value"]?.object) + native["initialization"] = payload["initializationOptions"] + fields["value"] = .init(object: native) + changed[0].values = .init(object: fields) + corrupted.lowerings[0].artifacts = try changed.map { try $0.digest(limits: .standard) } + do { + _ = try NativeComponentLayoutsV1.contribution( + corrupted.lowerings[0], ledger: corrupted, artifacts: changed, limits: .standard) + Issue.record("accepted a symbolic binding inside arbitrary native data") + } catch let issue as NativeComponentIssue { + #expect(issue.field == ["bindings"]) + #expect(!issue.description.contains("fixture/hidden")) + } + } + } + + @Test func nativePluginColdReplayKeepsManifestScriptsAndExecutableBits() throws { + let fixture = try LinkFixture() + try fixture.write( + #"{"name":"fixture-plugin","version":"1.0.0","description":"Fixture"}"#, + to: "bundle/.claude-plugin/plugin.json", base: fixture.project) + try fixture.write( + "#!/bin/sh\n# never executed\n", to: "bundle/scripts/check", base: fixture.project) + try FileManager.default.setAttributes( + [.posixPermissions: 0o755], + ofItemAtPath: fixture.project.appendingPathComponent("bundle/scripts/check").path) + try fixture.write("Review source.", to: "bundle/commands/review.md", base: fixture.project) + let item: [String: Any] = [ + "kind": "plugin", "name": "fixture-plugin", "path": "bundle", "source": ".", "mode": "native", + "agents": ["claude-code"], + ] + let (linked, frozen) = try freeze([item], fixture) + var ledger = frozen.ledger + ledger.lowerings = [try lower(linked[0], frozen, surface: .claudeCode)] + ledger = try prepared(ledger, fixture) + let bytes = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + try FileManager.default.removeItem(at: fixture.project) + try replay(ResolvedLedgerCodec.decode(bytes, limits: .standard), fixture) { output in + #expect(output[0].values?.object?["route"]?.text == "claudeSkillPlugin") + let contribution = try NativeComponentLayoutsV1.contribution( + ledger.lowerings[0], ledger: ledger, artifacts: output, limits: .standard) + guard + case .nativePlugin(let directory, let resource, let manifest) = contribution.outputs[0] + .content + else { + Issue.record("missing typed frozen plugin") + return + } + #expect(directory == "fixture-plugin") + #expect(manifest == ".claude-plugin/plugin.json") + let entry = try #require( + contribution.resources[resource]?.entries.first { $0.path == "scripts/check" }) + #expect(entry.executable) + var mismatchedResource = ledger + mismatchedResource.resources[resource]?.hash = "sha256:" + String(repeating: "0", count: 64) + #expect(throws: NativeComponentIssue.self) { + try NativeComponentLayoutsV1.contribution( + mismatchedResource.lowerings[0], ledger: mismatchedResource, artifacts: output, + limits: .standard) + } + let root = try #require(output[1].tree) + #expect( + try String(contentsOf: root.appendingPathComponent("commands/review.md"), encoding: .utf8) + == "Review source.") + let attributes = try FileManager.default.attributesOfItem( + atPath: root.appendingPathComponent("scripts/check").path) + #expect((attributes[.posixPermissions] as! NSNumber).intValue & 0o111 != 0) + } + } + + @Test func arrayOccurrenceEvidenceRematchesAndPreservesUnmanagedSiblings() throws { + let before = + #"{"permissions":[{"action":"read","resource":"a","effect":"deny"}, {"action":"read","resource":"b","effect":"ask"}, {"action":"read","resource":"c","effect":"allow"}],"privateSibling":"keep"}"# + let doc = try NativeDocument(bytes: Data(before.utf8), format: .json, budget: budget()) + let array = try #require(try doc.read(.init(keys: ["permissions"]))) + let original = array.occurrences[1] + let retained = NativeOccurrenceEvidence( + snapshot: try #require(original.snapshot), ordinal: try #require(original.ordinal), + previous: original.previous, next: original.next) + let region = NativeRegion([.key("permissions"), .occurrence(retained)]) + let knownOwned = try #require(try doc.read(region)) + let prepared = try doc.prepare([.remove(region: region, expected: .owned(knownOwned))]) + #expect(String(decoding: prepared.bytes, as: UTF8.self).contains(#""privateSibling":"keep""#)) + let changed = try NativeDocument( + bytes: Data( + before.replacingOccurrences(of: #""resource":"b""#, with: #""resource":"external""#).utf8), + format: .json, budget: budget()) + #expect(throws: NativeDocumentError.self) { + try changed.prepare([.remove(region: region, expected: .owned(knownOwned))]) + } + } + + @Test func unsupportedAndUnverifiedRemainPreciseAndValueFree() throws { + let fixture = try LinkFixture() + let item: [String: Any] = [ + "kind": "command", "name": "exact", "description": "Fixture", + "prompt": "SENSITIVE_FIXTURE", "agents": ["codex"], + ] + let (linked, frozen) = try freeze([item], fixture) + do { + _ = try lower(linked[0], frozen, surface: .codexCLI) + Issue.record("persistent Codex command accepted") + } catch let issue as NativeComponentIssue { + #expect(issue.reason == .unsupported) + #expect(issue.field == ["kind"]) + #expect(issue.component == "exact") + #expect(!issue.description.contains("SENSITIVE_FIXTURE")) + } + #expect(throws: NativeComponentIssue.self) { + try CapabilityRegistry.component( + .init(surface: .cursorCloud, scope: .project), kind: .subagent, name: "exact") + } + #expect(throws: NativeComponentIssue.self) { + try CapabilityRegistry.component( + .init(surface: .cursorEditor, scope: .user), kind: .command, name: "exact") + } + #expect(throws: NativeComponentIssue.self) { + try CapabilityRegistry.component( + .init(surface: .codexCLI, scope: .project), kind: .permissions, name: "exact") + } + } + + @Test func currentIgnoreProfilesKeepOrderAndPurpose() throws { + let fixture = try LinkFixture() + for surface in [NativeClientSurface.geminiCLI, .cursorEditor] { + let item: [String: Any] = [ + "kind": "ignore", "name": "private", "patterns": ["private/**", "!private/public.txt"], + "purpose": "context", "agents": [surface.agent.rawValue], + ] + let (linked, frozen) = try freeze([item], fixture) + var ledger = frozen.ledger + ledger.lowerings = [try lower(linked[0], frozen, surface: surface)] + ledger = try prepared(ledger, fixture) + try replay(ledger, fixture) { output in + let contribution = try NativeComponentLayoutsV1.contribution( + ledger.lowerings[0], ledger: ledger, artifacts: output, limits: .standard) + guard case .ignore(let patterns) = contribution.outputs[0].content else { + Issue.record("missing typed context ignore block") + return + } + #expect(patterns == ["private/**", "!private/public.txt"]) + #expect(output[0].values?.object?["selection"]?.text == "managedIgnore") + #expect( + output[0].values?.object?["value"] + == LedgerPayload.strings(["private/**", "!private/public.txt"])) + } + } + } + + @Test func profileLossAndInterpolationFailBeforePublication() throws { + let fixture = try LinkFixture() + let cases: [([String: Any], NativeClientSurface, [String], NativeAdapterIssue.Reason)] = [ + ( + [ + "kind": "command", "name": "exact", "description": "Fixture", + "prompt": "$${input:literal}", "agents": ["gemini-cli"], + ], + .geminiCLI, ["prompt"], .unverified + ), + ( + [ + "kind": "command", "name": "exact", "description": "Fixture", "prompt": "$ARGUMENTS", + "agents": ["opencode"], + ], .openCodeCLI, ["prompt"], .unverified + ), + ( + [ + "kind": "command", "name": "exact", "description": "Fixture", "prompt": " indented", + "agents": ["opencode"], + ], .openCodeCLI, ["prompt"], .unsupported + ), + ( + [ + "kind": "command", "name": "exact", "description": "Fixture", + "prompt": "Use ${input:branch}", + "parameters": [["name": "branch", "description": "Branch", "defaultValue": "main"]], + "agents": ["gemini-cli"], + ], .geminiCLI, ["parameters"], .unsupported + ), + ( + [ + "kind": "subagent", "name": "exact", "description": "Fixture", "prompt": "Prompt", + "native": ["gemini-cli": ["max_turns": 1.5]], "agents": ["gemini-cli"], + ], .geminiCLI, ["native", "gemini-cli", "max_turns"], .invalid + ), + ( + [ + "kind": "lspServer", "name": "exact", "run": ["executable": "fixture"], + "languages": [".ts": "typescript"], "agents": ["opencode"], + ], .openCodeCLI, ["languages"], .unverified + ), + ] + for (item, surface, field, reason) in cases { + let (linked, frozen) = try freeze([item], fixture) + var ledger = frozen.ledger + ledger.lowerings = [try lower(linked[0], frozen, surface: surface)] + do { + _ = try prepared(ledger, fixture) + Issue.record("unrepresentable native profile accepted") + } catch let issue as NativeComponentIssue { + #expect(issue.field == field) + #expect(issue.reason == reason) + #expect(issue.component == "exact") + } + } + } + + @Test func cursorProjectCommandAndGeminiNativeExtensionHaveClosedRoutes() throws { + let fixture = try LinkFixture() + let command: [String: Any] = [ + "kind": "command", "name": "review", "description": "", "prompt": "Review source.\n", + "agents": ["cursor"], + ] + let (linked, frozen) = try freeze([command], fixture) + var ledger = frozen.ledger + ledger.lowerings = [try lower(linked[0], frozen, surface: .cursorEditor)] + ledger = try prepared(ledger, fixture) + try replay(ledger, fixture) { output in + #expect(output[0].values?.object?["value"]?.text == "Review source.\n") + #expect(output[0].values?.object?["route"]?.text == "cursorCommand") + for (name, reason) in [ + ("../escape", NativeAdapterIssue.Reason.invalid), ("nested/review", .unverified), + ] { + var corrupted = ledger + let owner = try #require(corrupted.lowerings[0].inputs.first) + corrupted.components[owner]?.name = name + var payload = try #require(corrupted.components[owner]?.payload.object) + payload["name"] = .init(name) + corrupted.components[owner]?.payload = .init(object: payload) + var fields = try #require(output[0].values?.object) + fields["name"] = .init(name) + fields["path"] = .init(name + ".md") + var artifacts = output + artifacts[0].values = .init(object: fields) + corrupted.lowerings[0].artifacts = try artifacts.map { try $0.digest(limits: .standard) } + do { + _ = try NativeComponentLayoutsV1.contribution( + corrupted.lowerings[0], ledger: corrupted, artifacts: artifacts, limits: .standard) + Issue.record("accepted an unadmitted native filename") + } catch let issue as NativeComponentIssue { + #expect(issue.reason == reason) + } + } + } + try fixture.write( + #"{"name":"extension-fixture","version":"1.0.0"}"#, to: "extension/gemini-extension.json", + base: StateStore(scope: .user, environment: fixture.environment).directory) + try fixture.write( + #"prompt = "Review source.""# + "\n", to: "extension/commands/review.toml", + base: StateStore(scope: .user, environment: fixture.environment).directory) + let plugin: [String: Any] = [ + "kind": "plugin", "name": "extension-fixture", "path": "extension", "source": ".", + "mode": "native", "agents": ["gemini-cli"], + ] + let (plugins, pluginFrozen) = try freeze([plugin], fixture, scope: .user) + var pluginLedger = pluginFrozen.ledger + pluginLedger.lowerings = [ + try NativeComponentLowering.lower( + plugins[0], frozen: pluginFrozen, + request: .init(surface: .geminiCLI, scope: .user), id: "extension", platform: platform) + ] + pluginLedger = try prepared(pluginLedger, fixture) + try replay(pluginLedger, fixture) { output in + #expect(output[0].values?.object?["route"]?.text == "geminiExtension") + #expect(output[0].values?.object?["scope"]?.text == "user") + let root = try #require(output[1].tree) + let bytes = try Data(contentsOf: root.appendingPathComponent("commands/review.toml")) + let native = try NativeDocument(bytes: bytes, format: .toml, budget: budget()) + #expect(try native.read(.init(keys: ["prompt"]))?.value == .string("Review source.")) + } + } + + @Test func sourceDerivedNativeRejectionsAndLockedOutputBudget() throws { + let fixture = try LinkFixture() + let cases: [([String: Any], NativeClientSurface, [String])] = [ + ( + [ + "kind": "hook", "name": "exact", "event": ["native": "SessionEnd"], "timeoutSeconds": 4, + "run": ["executable": "fixture"], "agents": ["codex"], + ], .codexCLI, ["timeoutSeconds"] + ), + ( + [ + "kind": "hook", "name": "exact", "event": ["native": "Stop"], "matcher": "ignored", + "run": ["executable": "fixture"], "agents": ["codex"], + ], .codexCLI, ["matcher"] + ), + ( + [ + "kind": "hook", "name": "exact", "event": ["native": "SessionStart"], + "run": ["executable": "fixture", "arguments": ["$ordinary"]], "agents": ["gemini-cli"], + ], + .geminiCLI, ["run", "arguments", "0"] + ), + ( + [ + "kind": "hook", "name": "exact", "event": "beforeTool", "run": ["executable": "fixture"], + "agents": ["gemini-cli"], + ], .geminiCLI, ["event"] + ), + ( + [ + "kind": "subagent", "name": "exact", "description": "Description", "prompt": "Prompt", + "tools": ["not_a_native_tool"], "agents": ["gemini-cli"], + ], .geminiCLI, ["tools", "0"] + ), + ( + [ + "kind": "subagent", "name": "exact", "description": "Description", + "prompt": "Prompt\u{FEFF}", + "agents": ["gemini-cli"], + ], .geminiCLI, ["prompt"] + ), + ] + for (item, surface, field) in cases { + let (linked, frozen) = try freeze([item], fixture) + var ledger = frozen.ledger + ledger.lowerings = [try lower(linked[0], frozen, surface: surface)] + do { + _ = try prepared(ledger, fixture) + Issue.record("native loss was accepted") + } catch let issue as NativeComponentIssue { #expect(issue.field == field) } + } + let item: [String: Any] = [ + "kind": "command", "name": "budget", "description": "Description", "prompt": "Body", + "agents": ["gemini-cli"], + ] + let (linked, frozen) = try freeze([item], fixture) + let lowering = try lower(linked[0], frozen, surface: .geminiCLI) + var limits = LedgerLimits.standard + limits.resourceBytes = 1 + let render = try #require(NativeComponentLayoutsV1.renderers(limits: limits)[lowering.format]) + #expect(throws: NativeComponentIssue.self) { try render(lowering, frozen.ledger, [:]) } + var ledger = frozen.ledger + ledger.lowerings = [lowering] + ledger = try prepared(ledger, fixture) + ledger.lowerings[0].format = "agents/gemini-components@999" + #expect(throws: CoreError.self) { try replay(ledger, fixture) { _ in } } + } + + @Test func coalescedConditionsKeepInactiveOriginsAndSelectTheActiveOccurrence() throws { + let fixture = try LinkFixture() + let base: [String: Any] = [ + "kind": "permissions", "name": "same", "agents": ["opencode"], + "rules": [["effect": "allow", "operation": ["tool": "read"], "pattern": "src/**"]], + ] + var project = base + project["condition"] = ["scopes": ["project"], "platforms": [platform.rawValue]] + var user = base + user["condition"] = ["scopes": ["user"], "platforms": [platform.rawValue]] + let (linked, frozen) = try freeze([project, user], fixture) + #expect(linked.count == 1) + #expect(linked[0].origins.count == 2) + #expect(frozen.ledger.occurrences.count == 2) + #expect(frozen.ledger.components.values.first?.conditions.count == 2) + var ledger = frozen.ledger + ledger.lowerings = [try lower(linked[0], frozen, surface: .openCodeCLI)] + let otherPlatform: DeclarationPlatform = platform == .macOS ? .linux : .macOS + do { + _ = try NativeComponentLowering.lower( + linked[0], frozen: frozen, request: .init(surface: .openCodeCLI, scope: .project), + id: "wrong-platform", platform: otherPlatform) + Issue.record("accepted an output platform excluded by its frozen occurrence") + } catch let issue as NativeComponentIssue { + #expect(issue.field == ["platform"]) + #expect(issue.reason == .invalid) + } + var mismatched = ledger.lowerings[0] + mismatched.platform = otherPlatform.rawValue + let renderer = try #require( + NativeComponentLayoutsV1.renderers(limits: .standard)[mismatched.format]) + #expect(throws: CoreError.self) { try renderer(mismatched, ledger, [:]) } + #expect( + ledger.lowerings[0].layout.object?["occurrences"] + == .init(array: [.init(integer: linked[0].origins[0].occurrence)])) + ledger = try prepared(ledger, fixture) + try replay(ledger, fixture) { output in + #expect( + output[0].values?.object?["occurrences"] + == .init(array: [.init(integer: linked[0].origins[0].occurrence)])) + } + #expect(ledger.occurrences.count == 2) + } + + @Test func claudeFilesUseTheirDistinctFrontmatterContracts() throws { + let fixture = try LinkFixture() + let items: [[String: Any]] = [ + [ + "kind": "command", "name": "review", "description": "Review sources", + "prompt": "Keep exact text.\n", + "agents": ["claude-code"], + "native": ["claude-code": ["disable-model-invocation": true, "allowed-tools": ["Read"]]], + ], + [ + "kind": "subagent", "name": "reviewer", "description": "Audit: sources", + "prompt": "Review source.", + "tools": ["Read", "Bash"], "model": "inherit", "agents": ["claude-code"], + "native": [ + "claude-code": [ + "disallowedTools": ["Bash"], "maxTurns": 5, "permissionMode": "plan", + "background": false, + ] + ], + ], + ] + let (linked, frozen) = try freeze(items, fixture) + var ledger = frozen.ledger + ledger.lowerings = try linked.enumerated().map { + try lower($0.element, frozen, surface: .claudeCode, id: "file-\($0.offset)") + } + #expect(ledger.lowerings.allSatisfy { $0.format == "agents/claude-components@1" }) + ledger = try prepared(ledger, fixture) + try replay(ledger, fixture) { output in + let command = try #require(output[0].values?.object?["value"]?.text) + #expect(command.contains("disable-model-invocation: true")) + #expect(command.hasSuffix("---\nKeep exact text.\n")) + #expect(!command.contains("\nname:")) + let agent = try #require(output[1].values?.object?["value"]?.text) + #expect(agent.contains("disallowedTools: [\"Bash\"]")) + #expect(agent.contains("maxTurns: 5")) + #expect(agent.contains("permissionMode: \"plan\"")) + #expect(output[0].values?.object?["route"]?.text == "claudeCommand") + #expect(output[1].values?.object?["route"]?.text == "claudeAgent") + #expect( + output[1].values?.object?["knownReaders"] + == LedgerPayload.strings(["claude-code", "cursor"])) + #expect(output[1].values?.object?["recipients"] == LedgerPayload.strings(["claude-code"])) + } + } + + @Test(arguments: [NativeClientSurface.claudeCode, .cursorEditor, .cursorCLI, .cursorCloud]) + func documentedNativeHooksKeepShapesAndPrivateArguments(_ surface: NativeClientSurface) throws { + let fixture = try LinkFixture() + let item: [String: Any] = [ + "kind": "hook", "name": "guard", + "event": ["native": surface == .claudeCode ? "PreToolUse" : "beforeShellExecution"], + "run": [ + "executable": "fixture-hook", "arguments": ["a'b", "$(never-execute)"], + "environment": ["TOKEN": ["secret": "fixture/hook"]], + ], + "matcher": surface == .claudeCode ? "Bash|Edit" : "curl|wget", "timeoutSeconds": 9, + "agents": [surface.agent.rawValue], + "native": [ + surface.agent.rawValue: surface == .claudeCode + ? ["onFailure": "block"] : ["failClosed": true] + ], + ] + let (linked, frozen) = try freeze([item], fixture) + var ledger = frozen.ledger + ledger.lowerings = [try lower(linked[0], frozen, surface: surface)] + ledger = try prepared(ledger, fixture) + let encoded = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + #expect(!String(decoding: encoded, as: UTF8.self).contains("staged hook value")) + try replay(ledger, fixture) { output in + let envelope = try #require(output[0].values) + let contribution = try NativeComponentLayoutsV1.contribution( + ledger.lowerings[0], ledger: ledger, artifacts: output, limits: .standard) + guard case .hook(let hook) = contribution.outputs[0].content else { + Issue.record("missing typed native hook") + return + } + #expect( + hook.keys == ["hooks", surface == .claudeCode ? "PreToolUse" : "beforeShellExecution"]) + #expect(hook.layout == (surface == .claudeCode ? .group : .cursorVersion1)) + #expect(contribution.recipients == [surface.agent]) + #expect( + contribution.knownReaders == (surface == .claudeCode ? [.claudeCode, .cursor] : [.cursor])) + #expect(hook.value.bindings.count == 1) + if surface == .cursorEditor { + #expect(envelope.object?["rootRequirements"]?.object?["version"]?.integer == 1) + #expect(envelope.object?["value"]?.object?["matcher"]?.text == "curl|wget") + #expect(throws: NativeComponentIssue.self) { + try hook.value.stagedValue( + bindings: .init([:]), environment: fixture.environment, resourcePaths: [:], + budget: budget()) + } + } + let native = try hook.value.stagedValue( + bindings: .init(["fixture/hook": Data("staged hook value".utf8)]), + environment: fixture.environment, resourcePaths: [:], budget: budget(), + cursorCommandShell: .posix) + let existing = try NativeDocument( + bytes: Data("{\"version\":1,\"privateSibling\":\"keep\"}".utf8), + format: .json, budget: budget()) + let initial = try existing.prepare([hook.append(value: native, expected: .absent)]) + let fresh = try NativeDocument(bytes: initial.bytes, format: .json, budget: budget()) + let arrayRegion = NativeRegion(keys: hook.keys) + let append = hook.append( + value: native, expected: .owned(try #require(try fresh.read(arrayRegion)))) + let owner = try #require(initial.appendedOccurrences.first).observation + let doubled = try fresh.prepare([ + .put(region: owner.region, expected: .owned(owner), value: native), append, + ]) + #expect(doubled.appendedOccurrences.map(\.editIndex) == [1]) + let published = try NativeDocument(bytes: doubled.bytes, format: .json, budget: budget()) + #expect(try published.read(arrayRegion)?.value == .array([native, native])) + #expect(try published.read(.init(keys: ["privateSibling"]))?.value == .string("keep")) + let addedOwner = try #require(doubled.appendedOccurrences.first).observation + let removed = try published.prepare([ + .remove(region: addedOwner.region, expected: .owned(addedOwner)) + ]) + let afterRemoval = try NativeDocument(bytes: removed.bytes, format: .json, budget: budget()) + #expect(try afterRemoval.read(arrayRegion)?.value == .array([native])) + guard case .object(let object) = native else { + Issue.record("missing native hook") + return + } + let handler: [String: NativeValue] + if surface == .claudeCode { + #expect( + envelope.object?["knownReaders"] == LedgerPayload.strings(["claude-code", "cursor"])) + #expect(envelope.object?["recipients"] == LedgerPayload.strings(["claude-code"])) + #expect(object["matcher"] == .string("Bash|Edit")) + guard case .array(let handlers) = object["hooks"], case .object(let first) = handlers.first + else { + Issue.record("missing Claude group") + return + } + handler = first + #expect(handler["onFailure"] == .string("block")) + } else { + handler = object + #expect(handler["failClosed"] == .boolean(true)) + } + #expect(handler["timeout"] == .integer(9)) + #expect( + handler["command"] + == .string("env 'TOKEN=staged hook value' 'fixture-hook' 'a'\\''b' '$(never-execute)'")) + } + } + + @Test func claudeFailurePolicyRequiresSynchronousExecution() throws { + let fixture = try LinkFixture() + for flag in ["async", "asyncRewake"] { + for policy in ["block", "continue"] { + let item: [String: Any] = [ + "kind": "hook", "name": "guard", "agents": ["claude-code"], + "event": ["native": "PreToolUse"], "run": ["executable": "fixture-hook"], + "native": ["claude-code": [flag: true, "onFailure": policy]], + ] + let (linked, frozen) = try freeze([item], fixture) + var ledger = frozen.ledger + ledger.lowerings = [try lower(linked[0], frozen, surface: .claudeCode)] + do { + _ = try prepared(ledger, fixture) + Issue.record("accepted a failure policy the background native runner ignores") + } catch let issue as NativeComponentIssue { + #expect(issue.field == ["native", "claude-code", "onFailure"]) + #expect(issue.reason == .unsupported) + } + var synchronous = item + synchronous["native"] = ["claude-code": [flag: false, "onFailure": policy]] + let (syncLinked, syncFrozen) = try freeze([synchronous], fixture) + var sync = syncFrozen.ledger + sync.lowerings = [try lower(syncLinked[0], syncFrozen, surface: .claudeCode)] + sync = try prepared(sync, fixture) + try replay(sync, fixture) { output in + let handler = try #require( + output[0].values?.object?["value"]?.object?["hooks"]?.array?.first?.object) + #expect(handler["onFailure"]?.text == policy) + #expect(handler[flag]?.boolean == false) + #expect(handler["timeout"] == nil) + } + } + } + } + + @Test func claudeLSPFreezesGeneratedManifestAndPrivateSlots() throws { + let fixture = try LinkFixture() + try fixture.write("#!/bin/sh\n# never executed\n", to: "bin/server", base: fixture.project) + let item: [String: Any] = [ + "kind": "lspServer", "name": "fixture-lsp", + "run": [ + "executable": "./bin/server", "arguments": ["--stdio"], + "environment": ["TOKEN": ["secret": "fixture/lsp"]], + ], + "languages": [".fixture": "fixture"], + "initializationOptions": ["resource": "ordinary", "program": ["setting": true]], + "agents": ["claude-code"], + "native": [ + "claude-code": [ + "transport": "socket", "startupTimeout": 1000, "shutdownTimeout": 2000, + "requestTimeout": 3000, "restartOnCrash": false, "maxRestarts": 0, "diagnostics": false, + "settings": ["literal": "${ordinary}"], "workspaceFolder": "./workspace", + ] + ], + ] + let (linked, frozen) = try freeze([item], fixture) + var ledger = frozen.ledger + ledger.lowerings = [try lower(linked[0], frozen, surface: .claudeCode)] + ledger = try prepared(ledger, fixture) + let bytes = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + try FileManager.default.removeItem(at: fixture.project) + try replay(ResolvedLedgerCodec.decode(bytes, limits: .standard), fixture) { output in + let envelope = try #require(output[0].values) + #expect(envelope.object?["selection"]?.text == "generatedPlugin") + #expect(envelope.object?["route"]?.text == "claudeSkillPlugin") + let id = try #require(frozen.ledger.components.values.first?.resources.first) + let contribution = try NativeComponentLayoutsV1.contribution( + ledger.lowerings[0], ledger: ledger, artifacts: output, limits: .standard) + guard + case .generatedLSPPlugin(let directory, let manifestPath, let value) = contribution.outputs[ + 0 + ].content + else { + Issue.record("missing typed generated plugin") + return + } + #expect(directory == "fixture-lsp") + #expect(manifestPath == ".claude-plugin/plugin.json") + #expect(value.bindings.count == 1) + #expect(value.bindings[0].slot == .environment("TOKEN")) + #expect(value.bindings[0].binding == .secret("fixture/lsp")) + #expect(value.resourcePlacements.count == 1) + #expect(value.resourcePlacements[0].slot == .executable) + #expect(value.resourcePlacements[0].resource == id) + let materialized = try value.stagedValue( + bindings: .init(["fixture/lsp": Data("staged LSP value".utf8)]), + environment: fixture.environment, + resourcePaths: [id: "/registered/bin/server"], budget: budget()) + guard case .object(let manifest) = materialized, + case .object(let servers) = manifest["lspServers"], + case .object(let config) = servers["fixture-lsp"] + else { + Issue.record("missing generated native manifest") + return + } + #expect(config["command"] == .string("/registered/bin/server")) + #expect(config["transport"] == .string("socket")) + #expect(config["diagnostics"] == .boolean(false)) + #expect(config["requestTimeout"] == .integer(3000)) + #expect(config["settings"] == .object(["literal": .string("${ordinary}")])) + #expect( + config["initializationOptions"] + == .object([ + "resource": .string("ordinary"), "program": .object(["setting": .boolean(true)]), + ])) + #expect(config["env"] == .object(["TOKEN": .string("staged LSP value")])) + for invalid in [Data([0xff]), Data([0]), Data("${CLAUDE_PLUGIN_ROOT}".utf8)] { + do { + _ = try value.stagedValue( + bindings: .init(["fixture/lsp": invalid]), environment: fixture.environment, + resourcePaths: [id: "/registered/bin/server"], budget: budget()) + Issue.record("accepted a nonliteral staged native value") + } catch let issue as NativeComponentIssue { + #expect( + issue.field == [ + ".claude-plugin/plugin.json", "lspServers", "fixture-lsp", "env", "TOKEN", + ]) + #expect(!issue.description.contains("${CLAUDE_PLUGIN_ROOT}")) + } + } + } + #expect(!String(decoding: bytes, as: UTF8.self).contains("staged LSP value")) + } + + @Test func claudeExplicitNativePolicyKeepsCategoryPrecedence() throws { + let fixture = try LinkFixture() + let item: [String: Any] = [ + "kind": "permissions", "name": "native-policy", "rules": [], "agents": ["claude-code"], + "native": [ + "claude-code": [ + "allow": ["Bash(git *)"], "ask": ["Edit"], "deny": ["Read(./secret/**)"], + "defaultMode": "plan", + ] + ], + ] + let (linked, frozen) = try freeze([item], fixture) + var ledger = frozen.ledger + ledger.lowerings = [try lower(linked[0], frozen, surface: .claudeCode)] + ledger = try prepared(ledger, fixture) + try replay(ledger, fixture) { output in + #expect(output[0].values?.object?["selection"]?.text == "nativePolicy") + let policy = try #require(output[0].values?.object?["value"]?.object) + #expect(policy["deny"] == LedgerPayload.strings(["Read(./secret/**)"])) + #expect(policy["allow"] == LedgerPayload.strings(["Bash(git *)"])) + } + } + + @Test func documentedIgnoredAndUnverifiedHookCombinationsAreDiagnosed() throws { + let fixture = try LinkFixture() + let cases: [([String: Any], NativeClientSurface, [String], NativeAdapterIssue.Reason)] = [ + ( + [ + "kind": "subagent", "name": "exact", "description": "Fixture", "prompt": "Prompt", + "agents": ["claude-code"], "native": ["claude-code": ["max_turns": 2]], + ], .claudeCode, ["native", "claude-code", "max_turns"], .unverified + ), + ( + [ + "kind": "hook", "name": "exact", "event": ["native": "Stop"], + "run": ["executable": "fixture"], "matcher": "Bash", "agents": ["claude-code"], + ], .claudeCode, ["matcher"], .unsupported + ), + ( + [ + "kind": "hook", "name": "exact", "event": ["native": "PreToolUse"], + "run": ["executable": "fixture"], "timeoutSeconds": 4, + "native": ["claude-code": ["async": true]], "agents": ["claude-code"], + ], .claudeCode, ["timeoutSeconds"], .unsupported + ), + ( + [ + "kind": "hook", "name": "exact", "event": ["native": "sessionStart"], + "run": ["executable": "fixture"], "native": ["cursor": ["failClosed": true]], + "agents": ["cursor"], + ], .cursorEditor, ["native", "cursor", "failClosed"], .unsupported + ), + ( + [ + "kind": "hook", "name": "exact", "event": ["native": "preToolUse"], + "run": ["executable": "fixture"], "native": ["cursor": ["loop_limit": 3]], + "agents": ["cursor"], + ], .cursorEditor, ["native", "cursor", "loop_limit"], .unsupported + ), + ( + [ + "kind": "hook", "name": "exact", "event": ["native": "sessionStart"], + "run": ["executable": "fixture"], "agents": ["cursor"], + ], .cursorCloud, ["event"], .unsupported + ), + ( + [ + "kind": "permissions", "name": "exact", + "rules": [ + ["effect": "deny", "operation": ["tool": "Read"], "pattern": "*"], + ["effect": "allow", "operation": ["tool": "Read"], "pattern": "src/**"], + ], "agents": ["claude-code"], + ], .claudeCode, ["rules"], .unverified + ), + ( + [ + "kind": "hook", "name": "exact", "event": ["native": "beforeTabFileRead"], + "run": ["executable": "fixture"], "agents": ["cursor"], + ], .cursorCLI, ["event"], .unsupported + ), + ( + [ + "kind": "hook", "name": "exact", "event": ["native": "beforeMCPExecution"], + "run": ["executable": "fixture"], "matcher": "native-server", "agents": ["cursor"], + ], .cursorEditor, ["matcher"], .unverified + ), + ( + [ + "kind": "hook", "name": "exact", "event": ["native": "PreToolUse"], + "run": ["executable": "fixture"], "matcher": "[", "agents": ["claude-code"], + ], .claudeCode, ["matcher"], .unverified + ), + ( + [ + "kind": "hook", "name": "exact", "event": "beforeTool", "run": ["executable": "fixture"], + "agents": ["claude-code"], + ], .claudeCode, ["event"], .unverified + ), + ( + [ + "kind": "hook", "name": "exact", "event": ["native": "preToolUse"], + "run": ["executable": "fixture"], "native": ["cursor": ["type": "prompt"]], + "agents": ["cursor"], + ], .cursorEditor, ["native", "cursor", "type"], .unsupported + ), + ] + for (item, surface, field, reason) in cases { + let (linked, frozen) = try freeze([item], fixture) + var ledger = frozen.ledger + ledger.lowerings = [try lower(linked[0], frozen, surface: surface)] + do { + _ = try prepared(ledger, fixture) + Issue.record("accepted a lost native intent") + } catch let issue as NativeComponentIssue { + #expect(issue.field == field) + #expect(issue.reason == reason) + } + } + } + + @Test func nativeManifestFieldsPreserveFrozenChildrenAndColdReplay() throws { + let fixture = try LinkFixture() + let manifest: [String: Any] = [ + "name": "native-fields", "version": "build-label", "author": ["name": "Fixture"], + "commands": [ + "about": ["content": "Review source.", "argumentHint": "[file]", "allowedTools": ["Read"]] + ], + "agents": ["./agents/reviewer.md"], "skills": ["./skills"], + "userConfig": [ + "token": [ + "type": "string", "title": "Token", "description": "Native client-owned token", + "sensitive": true, + ], + "tone": [ + "type": "string", "title": "Tone", "description": "Picker", + "options": ["neutral", "warm"], "required": true, + ], + ], + "hooks": ["Stop": [["hooks": [["type": "prompt", "prompt": "Review $ARGUMENTS"]]]]], + "mcpServers": [ + "fixture": [ + "type": "stdio", "command": "node", "args": ["${CLAUDE_PLUGIN_ROOT}/server.js"], + ] + ], + "lspServers": [ + "fixture": [ + "command": "fixture-lsp", "extensionToLanguage": [".fixture": "fixture"], + "transport": "socket", "diagnostics": false, + ] + ], + ] + try fixture.write( + String(decoding: JSONSerialization.data(withJSONObject: manifest), as: UTF8.self), + to: "bundle/.claude-plugin/plugin.json", base: fixture.project) + try fixture.write( + "---\nname: reviewer\ndescription: Fixture\n---\nReview source.", + to: "bundle/agents/reviewer.md", base: fixture.project) + try fixture.write("# Fixture", to: "bundle/skills/fixture/SKILL.md", base: fixture.project) + try fixture.write("Default command.", to: "bundle/commands/default.md", base: fixture.project) + let item: [String: Any] = [ + "kind": "plugin", "name": "native-fields", "path": "bundle", "source": ".", "mode": "native", + "agents": ["claude-code"], + ] + let (linked, frozen) = try freeze([item], fixture) + var ledger = frozen.ledger + ledger.lowerings = [try lower(linked[0], frozen, surface: .claudeCode)] + ledger = try prepared(ledger, fixture) + try replay(ledger, fixture) { output in + let root = try #require(output[1].tree) + let bytes = try Data(contentsOf: root.appendingPathComponent(".claude-plugin/plugin.json")) + let object = try #require(JSONSerialization.jsonObject(with: bytes) as? [String: Any]) + #expect(object["version"] as? String == "build-label") + #expect( + FileManager.default.fileExists( + atPath: root.appendingPathComponent("commands/default.md").path)) + #expect(object["commands"] is [String: Any]) + } + var invalid = manifest + invalid["agents"] = ["agents/reviewer.md"] + try fixture.write( + String(decoding: JSONSerialization.data(withJSONObject: invalid), as: UTF8.self), + to: "bundle/.claude-plugin/plugin.json", base: fixture.project) + let (badLinked, badFrozen) = try freeze([item], fixture) + var bad = badFrozen.ledger + bad.lowerings = [try lower(badLinked[0], badFrozen, surface: .claudeCode)] + do { + _ = try prepared(bad, fixture) + Issue.record("accepted a native path without its required prefix") + } catch let issue as NativeComponentIssue { + #expect(issue.field == ["manifest", "agents", "0"]) + #expect(issue.reason == .invalid) + } + invalid = manifest + invalid["hooks"] = [ + "PermissionRequest": [["hooks": [["type": "agent", "prompt": "Review request"]]]] + ] + try fixture.write( + String(decoding: JSONSerialization.data(withJSONObject: invalid), as: UTF8.self), + to: "bundle/.claude-plugin/plugin.json", base: fixture.project) + let (skippedLinked, skippedFrozen) = try freeze([item], fixture) + var skipped = skippedFrozen.ledger + skipped.lowerings = [try lower(skippedLinked[0], skippedFrozen, surface: .claudeCode)] + do { + _ = try prepared(skipped, fixture) + Issue.record("accepted a handler type the native event skips") + } catch let issue as NativeComponentIssue { + #expect(issue.field == ["manifest", "hooks", "PermissionRequest", "0", "hooks", "0", "type"]) + #expect(issue.reason == .unsupported) + } + invalid["hooks"] = [ + "Stop": [["hooks": [["type": "command", "command": "fixture", "onFailure": "block"]]]] + ] + try fixture.write( + String(decoding: JSONSerialization.data(withJSONObject: invalid), as: UTF8.self), + to: "bundle/.claude-plugin/plugin.json", base: fixture.project) + let (ignoredLinked, ignoredFrozen) = try freeze([item], fixture) + var ignored = ignoredFrozen.ledger + ignored.lowerings = [try lower(ignoredLinked[0], ignoredFrozen, surface: .claudeCode)] + do { + _ = try prepared(ignored, fixture) + Issue.record("accepted a native failure policy with no effect") + } catch let issue as NativeComponentIssue { + #expect(issue.field == ["manifest", "hooks", "Stop", "0", "hooks", "0", "onFailure"]) + #expect(issue.reason == .unsupported) + } + let locked = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + try FileManager.default.removeItem(at: fixture.project) + try replay(ResolvedLedgerCodec.decode(locked, limits: .standard), fixture) { output in + #expect(output.count == 2) + #expect(output[0].values?.object?["route"]?.text == "claudeSkillPlugin") + let root = try #require(output[1].tree) + let bytes = try Data(contentsOf: root.appendingPathComponent(".claude-plugin/plugin.json")) + let object = try #require(JSONSerialization.jsonObject(with: bytes) as? [String: Any]) + #expect(object["version"] as? String == "build-label") + let commands = try #require(object["commands"] as? [String: [String: Any]]) + #expect(commands["about"]?["argumentHint"] as? String == "[file]") + let servers = try #require(object["lspServers"] as? [String: [String: Any]]) + #expect(servers["fixture"]?["transport"] as? String == "socket") + #expect( + try String(contentsOf: root.appendingPathComponent("commands/default.md"), encoding: .utf8) + == "Default command.") + } + } + + @Test func cursorManifestUsesSelectedPathsAndCommandOnlyPluginHooks() throws { + let fixture = try LinkFixture() + let base = StateStore(scope: .user, environment: fixture.environment).directory + let manifest: [String: Any] = [ + "name": "cursor-fields", "version": "1.2.3", + "author": ["name": "Fixture", "email": "fixture@example.test"], + "commands": "./commands", "rules": "./rules", "agents": "./agents", "skills": "./skills", + "hooks": "./config/hooks.json", "mcpServers": ["./config/mcp.json"], + "variables": [ + "type": "object", "properties": ["TOKEN": ["type": "string", "title": "Token"]], + "required": ["TOKEN"], + ], + ] + try fixture.write( + String(decoding: JSONSerialization.data(withJSONObject: manifest), as: UTF8.self), + to: "bundle/.cursor-plugin/plugin.json", base: base) + for path in [ + "commands/check.md", "rules/check.mdc", "agents/check.md", "skills/check/SKILL.md", + ] { + try fixture.write("Fixture source.", to: "bundle/" + path, base: base) + } + try fixture.write( + #"{"hooks":{"beforeShellExecution":[{"command":"./scripts/check.sh","matcher":"curl|wget","failClosed":true}]}}"#, + to: "bundle/config/hooks.json", base: base) + try fixture.write( + #"{"mcpServers":{"fixture":{"command":"node","args":["${CURSOR_PLUGIN_ROOT}/server.js"],"cwd":"${CURSOR_PLUGIN_ROOT}"}}}"#, + to: "bundle/config/mcp.json", base: base) + // An explicit Cursor hooks path replaces this default discovery file. + try fixture.write( + #"{"hooks":{"stop":[{"type":"prompt","command":"not-selected"}]}}"#, + to: "bundle/hooks/hooks.json", base: base) + let item: [String: Any] = [ + "kind": "plugin", "name": "cursor-fields", "path": "bundle", "source": ".", "mode": "native", + "agents": ["cursor"], + ] + let (linked, frozen) = try freeze([item], fixture, scope: .user) + var ledger = frozen.ledger + ledger.lowerings = [ + try NativeComponentLowering.lower( + linked[0], frozen: frozen, request: .init(surface: .cursorEditor, scope: .user), + id: "cursor-plugin", platform: platform) + ] + ledger = try prepared(ledger, fixture) + try replay(ledger, fixture) { output in + #expect(output[0].values?.object?["route"]?.text == "cursorLocalPlugin") + let tree = try #require(output[1].tree) + #expect( + try String(contentsOf: tree.appendingPathComponent("config/hooks.json"), encoding: .utf8) + .contains("failClosed")) + #expect( + try String(contentsOf: tree.appendingPathComponent("hooks/hooks.json"), encoding: .utf8) + .contains("not-selected")) + } + var changed = manifest + changed["hooks"] = "./hooks/hooks.json" + try fixture.write( + String(decoding: JSONSerialization.data(withJSONObject: changed), as: UTF8.self), + to: "bundle/.cursor-plugin/plugin.json", base: base) + let (badLinked, badFrozen) = try freeze([item], fixture, scope: .user) + var bad = badFrozen.ledger + bad.lowerings = [ + try NativeComponentLowering.lower( + badLinked[0], frozen: badFrozen, request: .init(surface: .cursorEditor, scope: .user), + id: "cursor-plugin", platform: platform) + ] + do { + _ = try prepared(bad, fixture) + Issue.record("accepted a prompt handler in a Cursor plugin") + } catch let issue as NativeComponentIssue { + #expect(issue.field == ["manifest", "hooks", "stop", "0", "type"]) + #expect(issue.reason == .unsupported) + } + changed["hooks"] = ["hooks": ["stop": [["command": "fixture"]]]] + try fixture.write( + String(decoding: JSONSerialization.data(withJSONObject: changed), as: UTF8.self), + to: "bundle/.cursor-plugin/plugin.json", base: base) + let (inlineLinked, inlineFrozen) = try freeze([item], fixture, scope: .user) + var inline = inlineFrozen.ledger + inline.lowerings = [ + try NativeComponentLowering.lower( + inlineLinked[0], frozen: inlineFrozen, request: .init(surface: .cursorEditor, scope: .user), + id: "cursor-plugin", platform: platform) + ] + do { + _ = try prepared(inline, fixture) + Issue.record("guessed an inline Cursor wrapper") + } catch let issue as NativeComponentIssue { + #expect(issue.field == ["manifest", "hooks"]) + #expect(issue.reason == .unverified) + } + } + + @Test func strictContributionRejectsForgedIdentityRoutesSlotsAndUnsealedOutput() throws { + let fixture = try LinkFixture() + try fixture.write("#!/bin/sh\n# never executed\n", to: "scripts/check", base: fixture.project) + let item: [String: Any] = [ + "kind": "hook", "name": "guard", "agents": ["claude-code"], + "event": ["native": "PreToolUse"], + "run": [ + "executable": "./scripts/check", "environment": ["TOKEN": ["secret": "fixture/token"]], + ], + ] + let (linked, frozen) = try freeze([item], fixture) + var ledger = frozen.ledger + ledger.lowerings = [try lower(linked[0], frozen, surface: .claudeCode)] + ledger = try prepared(ledger, fixture) + try replay(ledger, fixture) { artifacts in + let original = try #require(artifacts[0].values?.object) + var wrongOwner = original + wrongOwner["component"] = .init("unrelated-owner") + var wrongOccurrence = original + wrongOccurrence["occurrences"] = .init(array: [.init(integer: 999)]) + var wrongReaders = original + wrongReaders["knownReaders"] = LedgerPayload.strings(["claude-code"]) + var wrongRoute = original + wrongRoute["route"] = .init("cursorHooks") + var extra = original + extra["arbitraryPatch"] = .init("SENSITIVE_CORRUPTION") + var wrongBinding = original + var value = try #require(original["value"]?.object) + var hook = try #require(value["hooks"]?.array?.first?.object) + var program = try #require(hook["command"]?.object?["program"]?.object) + program["environment"] = .init(object: ["TOKEN": .init("SENSITIVE_CORRUPTION", kind: .secret)] + ) + hook["command"] = .init(object: ["program": .init(object: program)]) + value["hooks"] = .init(array: [.init(object: hook)]) + wrongBinding["value"] = .init(object: value) + var wrongResource = original + program["executable"] = .init(object: ["resource": .init("foreign-resource")]) + hook["command"] = .init(object: ["program": .init(object: program)]) + value["hooks"] = .init(array: [.init(object: hook)]) + wrongResource["value"] = .init(object: value) + for fields in [ + wrongOwner, wrongOccurrence, wrongReaders, wrongRoute, extra, wrongBinding, wrongResource, + ] { + var changed = artifacts + changed[0].values = .init(object: fields) + var resealed = ledger + // Even a supplied new digest cannot turn arbitrary metadata/slots into the frozen profile. + resealed.lowerings[0].artifacts = try changed.map { try $0.digest(limits: .standard) } + do { + _ = try NativeComponentLayoutsV1.contribution( + resealed.lowerings[0], ledger: resealed, artifacts: changed, limits: .standard) + Issue.record("accepted forged native component output") + } catch let issue as NativeComponentIssue { + #expect(issue.reason == .invalid) + #expect(!issue.description.contains("SENSITIVE_CORRUPTION")) + } + } + var invalidProgram = ledger + let owner = try #require(invalidProgram.lowerings[0].inputs.first) + var payload = try #require(invalidProgram.components[owner]?.payload.object) + var run = try #require(payload["run"]?.object) + run["executable"] = .init("SENSITIVE_CORRUPTION", kind: .secret) + payload["run"] = .init(object: run) + invalidProgram.components[owner]?.payload = .init(object: payload) + do { + _ = try NativeComponentLayoutsV1.contribution( + invalidProgram.lowerings[0], ledger: invalidProgram, artifacts: artifacts, + limits: .standard) + Issue.record("accepted a non-string frozen executable") + } catch let issue as NativeComponentIssue { + #expect(issue.field == ["run"]) + #expect(!issue.description.contains("SENSITIVE_CORRUPTION")) + } + var unsealed = ledger + unsealed.lowerings[0].artifacts = [] + #expect(throws: CoreError.self) { + try NativeComponentLayoutsV1.contribution( + unsealed.lowerings[0], ledger: unsealed, artifacts: artifacts, limits: .standard) + } + #expect(throws: NativeComponentIssue.self) { + var changed = artifacts + changed[0].values = .init(object: wrongOwner) + return try NativeComponentLayoutsV1.contribution( + ledger.lowerings[0], ledger: ledger, artifacts: changed, limits: .standard) + } + var oversized = artifacts + var large = original + large["value"] = .init(String(repeating: "x", count: 8192)) + oversized[0].values = .init(object: large) + var limits = LedgerLimits.standard + limits.encodedBytes = 4096 + #expect(throws: NativeDocumentBudget.Failure.self) { + try NativeComponentLayoutsV1.contribution( + ledger.lowerings[0], ledger: ledger, artifacts: oversized, limits: limits) + } + } + } + + @Test func strictContributionKeepsOrderedPolicyAndCategoryOwnershipDistinct() throws { + let fixture = try LinkFixture() + let items: [[String: Any]] = [ + [ + "kind": "permissions", "name": "ordered", "agents": ["opencode"], + "rules": [ + ["effect": "deny", "operation": ["tool": "read"], "pattern": "*"], + ["effect": "allow", "operation": ["tool": "read"], "pattern": "public/**"], + ], + ], + [ + "kind": "permissions", "name": "categories", "agents": ["claude-code"], "rules": [], + "native": [ + "claude-code": ["allow": [], "deny": ["Read(private/**)"], "defaultMode": "plan"] + ], + ], + ] + let (linked, frozen) = try freeze(items, fixture) + var ledger = frozen.ledger + ledger.lowerings = try linked.enumerated().map { + try lower( + $0.element, frozen, surface: $0.offset == 0 ? .openCodeCLI : .claudeCode, + id: "policy-" + String($0.offset)) + } + ledger = try prepared(ledger, fixture) + try replay(ledger, fixture) { artifacts in + let ordered = try NativeComponentLayoutsV1.contribution( + ledger.lowerings[0], ledger: ledger, artifacts: [artifacts[0]], limits: .standard) + guard case .orderedPermissions(let rules) = ordered.outputs[0].content else { + Issue.record("missing typed ordered policy") + return + } + #expect(rules.map(\.tool) == ["read", "read"]) + #expect(rules.map(\.resource) == ["*", "public/**"]) + #expect(rules.map(\.effect) == [.deny, .allow]) + #expect(ordered.outputs[0].route.documentFormat == .jsonc(trailingCommas: true)) + let categorized = try NativeComponentLayoutsV1.contribution( + ledger.lowerings[1], ledger: ledger, artifacts: [artifacts[1]], limits: .standard) + guard case .claudePermissions(let policy) = categorized.outputs[0].content else { + Issue.record("missing typed categorized policy") + return + } + #expect(policy.allow == []) + #expect(policy.ask == nil) + #expect(policy.deny == ["Read(private/**)"]) + #expect(policy.defaultMode == "plan") + #expect(ordered.component != categorized.component) + #expect(ordered.occurrences != categorized.occurrences) + } + } + + private var platform: DeclarationPlatform { + #if os(macOS) + .macOS + #else + .linux + #endif + } + + private func lower( + _ linked: LinkedComponent, _ frozen: LedgerFreeze.Result, + surface: NativeClientSurface, id: String = "native" + ) throws -> LockedLowering { + try NativeComponentLowering.lower( + linked, frozen: frozen, + request: .init(surface: surface, scope: .project), id: id, platform: platform) + } + private func freeze( + _ items: [[String: Any]], _ fixture: LinkFixture, scope: InstallScope = .project + ) throws -> ( + [LinkedComponent], LedgerFreeze.Result + ) { + let bytes = try JSONSerialization.data( + withJSONObject: ["version": 1, "components": items], options: [.sortedKeys]) + let document = try DeclarationDocument( + bytes: Array(bytes), identity: .init("consumer/agents.yaml")) + let store = StateStore(scope: scope, environment: fixture.environment) + let packageRoot = scope == .project ? fixture.project : store.directory + return try ComponentLinker.withLinkedComponents( + document: document, store: store, + platform: platform + ) { graph, session in + ( + graph.components, + try LedgerFreeze.freezeWithSources( + graph, session: session, + locations: .init(sources: [ + "local:" + packageRoot.path: .init( + kind: .registered, root: scope == .project ? "project" : "userState", path: ".") + ]), limits: .standard) + ) + } + } + private func prepared(_ ledger: ResolvedLedger, _ fixture: LinkFixture) throws -> ResolvedLedger { + try LedgerReplay.prepareLowerings( + ledger, store: fixture.store, roots: [:], limits: .standard, + renderers: NativeComponentLayoutsV1.renderers(limits: .standard)) + } + private func replay( + _ ledger: ResolvedLedger, _ fixture: LinkFixture, _ body: ([ReplayedArtifact]) throws -> Void + ) throws { + try LedgerReplay.withReplay( + ledger, store: fixture.store, roots: [:], limits: .standard, + renderers: NativeComponentLayoutsV1.renderers(limits: .standard) + ) { artifacts in + for lowering in ledger.lowerings { + let names = Set(lowering.artifacts.map(\.name)) + _ = try NativeComponentLayoutsV1.contribution( + lowering, ledger: ledger, artifacts: artifacts.filter { names.contains($0.name) }, + limits: .standard) + } + try body(artifacts) + } + } + private func budget() -> NativeDocumentBudget { + .init( + limits: .init( + storage: 32_000_000, work: 100_000_000, nodes: 100_000, depth: 128, + uninterruptedBytes: 1_000_000)) + } +} diff --git a/Tests/ComponentsTests/NativeCoordinateLinkingTests.swift b/Tests/ComponentsTests/NativeCoordinateLinkingTests.swift new file mode 100644 index 0000000..fe895cb --- /dev/null +++ b/Tests/ComponentsTests/NativeCoordinateLinkingTests.swift @@ -0,0 +1,71 @@ +import AgentsCore +import Components +import Foundation +import Testing + +struct NativeCoordinateLinkingTests { + @Test(arguments: [false, true]) + func generatedExecutableAndCwdRebaseOnceAndConsumeAliases(_ nested: Bool) throws { + let f = try LinkFixture() + let producer = f.root.appendingPathComponent("producer") + let container = nested ? "bundle" : "." + let prefix = nested ? "bundle/" : "" + try f.write( + #"{"name":"producer","version":"1.2.3","mcpServers":{"server":{"command":"${extensionPath}/server","cwd":"./cwd"}}}"#, + to: prefix + "gemini-extension.json", base: producer) + try f.write("Never executed", to: prefix + "server", base: producer) + try f.write("Working support", to: prefix + "cwd/config", base: producer) + let graph = try f.link( + """ + version: 1 + sources: {producer: {path: "\(producer.path)"}} + components: [{kind: plugin, name: p, path: "\(container)", source: producer, agents: [gemini-cli]}] + """) + let member = try #require(graph.components.first { $0.key.kind == .mcpServer }) + guard case .declaration(.mcpServer(_, .stdio(let run), _, _, _, _)) = member.payload else { + Issue.record("Expected generated MCP child") + return + } + #expect(run.executable == (nested ? "bundle/server" : "./server")) + #expect(run.executableSource == nil) + #expect(run.workingDirectory == .init(path: prefix + "cwd")) + #expect(member.resources.count == 2) + } + @Test(arguments: [false, true]) + func generatedHookAndLSPRetainResourceSpelling(_ nested: Bool) throws { + let f = try LinkFixture() + let producer = f.root.appendingPathComponent("producer") + let prefix = nested ? "bundle/" : "" + try f.write(#"{"name":"producer"}"#, to: prefix + ".claude-plugin/plugin.json", base: producer) + try f.write("Never executed", to: prefix + "server", base: producer) + try f.write( + #"{"hooks":{"SessionStart":[{"hooks":[{"type":"command","command":"./server"}]}]}}"#, + to: prefix + "hooks/hooks.json", base: producer) + try f.write( + #"{"language":{"command":"./server","extensionToLanguage":{".swift":"swift"}}}"#, + to: prefix + ".lsp.json", base: producer) + let graph = try f.link( + """ + version: 1 + sources: {producer: {path: "\(producer.path)"}} + components: [{kind: plugin, name: p, path: "\(nested ? "bundle" : ".")", source: producer, agents: [claude-code]}] + """) + let members = graph.components.filter { [.hook, .lspServer].contains($0.key.kind) } + #expect(members.count == 2) + for member in members { + let run: ExecutableDeclaration + switch member.payload { + case .declaration(.hook(_, _, let value, _, _, _, _, _)), + .declaration(.lspServer(_, let value, _, _, _, _, _)): + run = value + default: + Issue.record("Expected executable native child") + continue + } + #expect(run.executable == (nested ? "bundle/server" : "./server")) + #expect(run.executableSource == nil) + #expect(member.resources.count == 1) + } + } + +} diff --git a/Tests/ComponentsTests/NativeMCPTests.swift b/Tests/ComponentsTests/NativeMCPTests.swift new file mode 100644 index 0000000..fa73595 --- /dev/null +++ b/Tests/ComponentsTests/NativeMCPTests.swift @@ -0,0 +1,862 @@ +import AgentsManifest +import Foundation +import NativeDocuments +import Testing + +@testable import AgentsCore +@testable import Components + +@Suite("Native MCP mapping and replay") +struct NativeMCPTests { + @Test(arguments: NativeMCPScope.allCases) + func claudeRegionsPreserveClientAndOtherScopeState(_ scope: NativeMCPScope) throws { + try withMCP( + [server("db", transport: stdio(), agents: ["claude-code"])], + request: .init(surface: .claudeCode, scope: scope) + ) { contribution, _, _ in + let source = """ + { + "accountSentinel" : "keep-account", + "mcpServers": {"db": {"command":"old","args":[]}, "user-sibling" : {"command":"keep"}}, + "projects": { + "/work/a.b": {"hasTrustDialogAccepted":false,"mcpServers":{"db":{"command":"old","args":[]}}}, + "/work/other": {"allowedTools":[],"mcpServers":{"other":{"command":"keep"}}} + } + } + """ + let region = try contribution.descriptor.region( + server: contribution.name, nativeProjectKey: "/work/a.b") + let expectedKeys = + scope == .local + ? ["projects", "/work/a.b", "mcpServers", "db"] : ["mcpServers", "db"] + #expect(region == NativeRegion(keys: expectedKeys)) + #expect(contribution.descriptor.request.scope == scope) + #expect(contribution.descriptor.knownReaders == [.claudeCode]) + let doc = try document(source, contribution) + let fixtureOwnedEntry = try #require(try doc.read(region)) + let value = try contribution.referenceValue() + let changed = try doc.prepare([ + .put(region: region, expected: .owned(fixtureOwnedEntry), value: value) + ]) + let changedText = String(decoding: changed.bytes, as: UTF8.self) + #expect(changedText.contains(#""accountSentinel" : "keep-account""#)) + #expect(changedText.contains(#""user-sibling" : {"command":"keep"}"#)) + #expect(changedText.contains(#""hasTrustDialogAccepted":false"#)) + #expect( + changedText.contains( + #""/work/other": {"allowedTools":[],"mcpServers":{"other":{"command":"keep"}}}"#)) + let next = try document(changedText, contribution) + #expect(try next.read(region)?.value == value) + let owned = try #require(try next.read(region)) + #expect( + try next.prepare([.put(region: region, expected: .owned(owned), value: value)]).bytes + == changed.bytes) + #expect(throws: NativeDocumentError.self) { + try next.prepare([.put(region: region, expected: .absent, value: value)]) + } + let removed = try next.prepare([.remove(region: region, expected: .owned(owned))]) + let after = try NativeDocument(bytes: removed.bytes, format: .json, budget: budget()) + #expect(try after.read(region) == nil) + #expect( + String(decoding: removed.bytes, as: UTF8.self).contains( + #""accountSentinel" : "keep-account""#)) + if scope == .local { + #expect( + try after.read(.init(keys: ["projects", "/work/a.b", "hasTrustDialogAccepted"]))?.value + == .boolean(false)) + #expect(throws: NativeAdapterIssue.self) { + try contribution.descriptor.region(server: contribution.name) + } + } + } + } + + @Test(arguments: [false, true]) + func codexQuotedServerAndEnvironmentTOML(_ inline: Bool) throws { + let name = "db.api\"quoted" + let invocation = stdio(environment: ["NOTE": "new", "INHERITED": ["env": "INHERITED"]]) + try withMCP( + [server(name, transport: invocation, agents: ["codex"])], + request: .init(surface: .codexCLI, scope: .project) + ) { contribution, _, _ in + let source = + inline + ? """ + # native client sentinel + model = "keep-model" + mcp_servers.'db.api"quoted' = { command = "old", args = [], env = { NOTE = "before" }, env_vars = ["INHERITED"] } + [mcp_servers.sibling] + command = "keep-sibling" # preserve this comment + """ + : """ + # native client sentinel + model = "keep-model" + [mcp_servers.'db.api"quoted'] + command = "old" + args = [] + env_vars = ["INHERITED"] + [mcp_servers.'db.api"quoted'.env] + NOTE = "before" + [mcp_servers.sibling] + command = "keep-sibling" # preserve this comment + """ + let region = try contribution.descriptor.region(server: contribution.name) + #expect(region == NativeRegion(keys: ["mcp_servers", name])) + let doc = try document(source, contribution) + let knownOwned = try #require(try doc.read(region)) + let changed = try doc.prepare([ + .put(region: region, expected: .owned(knownOwned), value: contribution.referenceValue()) + ]) + #expect( + String(decoding: changed.bytes, as: UTF8.self) + == source.replacingOccurrences(of: "\"old\"", with: "\"fixture-server-never-run\"") + .replacingOccurrences(of: "\"before\"", with: "\"new\"")) + let next = try NativeDocument(bytes: changed.bytes, format: .toml, budget: budget()) + #expect(try next.read(region)?.value == contribution.referenceValue()) + #expect(contribution.bindings.map(\.path) == [[.key("env_vars"), .index(0)]]) + #expect(contribution.bindings.map(\.binding) == [.environment("INHERITED")]) + #expect(contribution.bindings.allSatisfy { $0.reference }) + } + } + + @Test(arguments: [false, true]) + func codexHeaderTablesAndNativeBearerReference(_ inline: Bool) throws { + let transport: [String: Any] = [ + "kind": "streamableHTTP", "url": "https://example.invalid/mcp", + "headers": ["X.Static": "new", "X-Token": ["env": "HTTP_TOKEN"]], + ] + try withMCP( + [ + server( + "api.v1", transport: transport, agents: ["codex"], + native: ["codex": ["bearer_token_env_var": "BEARER_TOKEN"]]) + ], + request: .init(surface: .codexCLI, scope: .user) + ) { contribution, _, _ in + let source = + inline + ? """ + # unmanaged prelude + model = "keep" + mcp_servers.'api.v1' = { url = "https://example.invalid/mcp", bearer_token_env_var = "BEARER_TOKEN", http_headers = { 'X.Static' = "old" }, env_http_headers = { X-Token = "HTTP_TOKEN" } } + [unmanaged] + value = "keep" # suffix + """ + : """ + # unmanaged prelude + model = "keep" + [mcp_servers.'api.v1'] + url = "https://example.invalid/mcp" + bearer_token_env_var = "BEARER_TOKEN" + [mcp_servers.'api.v1'.http_headers] + 'X.Static' = "old" + [mcp_servers.'api.v1'.env_http_headers] + X-Token = "HTTP_TOKEN" + [unmanaged] + value = "keep" # suffix + """ + let doc = try document(source, contribution) + let region = try contribution.descriptor.region(server: contribution.name) + let owned = try #require(try doc.read(region)) + let edited = try doc.prepare([ + .put(region: region, expected: .owned(owned), value: contribution.referenceValue()) + ]) + #expect( + String(decoding: edited.bytes, as: UTF8.self) + == source.replacingOccurrences(of: "\"old\"", with: "\"new\"")) + let fields = try #require(contribution.value.object) + #expect(fields["env_http_headers"] == .init(object: ["X-Token": .init("HTTP_TOKEN")])) + #expect(fields["bearer_token_env_var"] == .init("BEARER_TOKEN")) + #expect( + contribution.bindings.map(\.binding) == [ + .environment("HTTP_TOKEN"), .environment("BEARER_TOKEN"), + ]) + #expect(fields["type"] == nil) + } + } + + @Test(arguments: [ + NativeClientSurface.claudeCode, .codexCLI, .geminiCLI, .openCodeCLI, .cursorEditor, .cursorCLI, + ]) + func mapsRealStdioSchemasAndProductionReplay(_ surface: NativeClientSurface) throws { + let run = stdio(arguments: ["--name", "with spaces"], environment: ["NOTE": "literal"]) + try withMCP( + [server("typed", transport: run, agents: [surface.agent.rawValue])], + request: .init(surface: surface, scope: .project) + ) { contribution, ledger, fixture in + let fields = try #require(contribution.value.object) + let expected: LedgerValue + if surface == .openCodeCLI { + expected = .init(object: [ + "type": .init("local"), + "command": .init(array: [ + .init("fixture-server-never-run"), .init("--name"), .init("with spaces"), + ]), + "environment": .init(object: ["NOTE": .init("literal")]), + ]) + #expect( + try contribution.descriptor.region(server: contribution.name) + == NativeRegion(keys: ["mcp", "servers", "typed"])) + } else { + var expectedFields: [String: LedgerValue] = [ + "command": .init("fixture-server-never-run"), + "args": .init(array: [.init("--name"), .init("with spaces")]), + "env": .init(object: ["NOTE": .init("literal")]), + ] + if surface == .claudeCode || surface == .cursorEditor || surface == .cursorCLI { + expectedFields["type"] = .init("stdio") + } + expected = .init(object: expectedFields) + } + #expect(contribution.value == expected) + #expect(fields["enabled"] == nil) + var candidate = ledger + candidate.lowerings = [ + contribution.lowering(id: "mcp", artifact: "typed", platform: platform) + ] + candidate = try LedgerReplay.prepareLowerings( + candidate, store: fixture.store, roots: [:], limits: .standard) + try LedgerReplay.withReplay(candidate, store: fixture.store, roots: [:], limits: .standard) { + output in + #expect(output.count == 1) + #expect(output[0].kind == .ownedValues) + #expect(output[0].values?.object?["value"] == expected) + #expect(output[0].bytes == nil) + } + } + } + + @Test(arguments: [NativeClientSurface.claudeCode, .geminiCLI]) + func remoteTypesAndReferencesRemainDistinct(_ surface: NativeClientSurface) throws { + for (kind, nativeType) in [("streamableHTTP", "http"), ("sse", "sse")] { + let remote: [String: Any] = [ + "kind": kind, "url": "https://example.invalid/mcp", + "headers": ["X-Token": ["env": "REMOTE_TOKEN"]], + ] + try withMCP( + [server("remote", transport: remote, agents: [surface.agent.rawValue])], + request: .init(surface: surface, scope: .project) + ) { contribution, _, _ in + #expect( + contribution.value + == .init(object: [ + "type": .init(nativeType), "url": .init("https://example.invalid/mcp"), + "headers": .init(object: ["X-Token": .init("${REMOTE_TOKEN}")]), + ])) + #expect(contribution.bindings[0].binding == .environment("REMOTE_TOKEN")) + #expect(contribution.bindings[0].reference) + _ = try contribution.referenceValue() + } + } + } + + @Test func openCodeRemoteProtocolIsNotSSE() throws { + try withMCP( + [ + server( + "remote", + transport: [ + "kind": "streamableHTTP", "url": "https://example.invalid/mcp", + "headers": ["X-Token": ["env": "REMOTE_TOKEN"]], + ], agents: ["opencode"], + native: ["opencode": ["protocol": "legacy", "oauth": false]]) + ], + request: .init(surface: .openCodeCLI, scope: .project) + ) { contribution, _, _ in + #expect( + contribution.value + == .init(object: [ + "type": .init("remote"), "url": .init("https://example.invalid/mcp"), + "headers": .init(object: ["X-Token": .init("REMOTE_TOKEN", kind: .environment)]), + "protocol": .init("legacy"), "codemode": .init(boolean: false), + "oauth": .init(boolean: false), + ])) + #expect(throws: NativeAdapterIssue.self) { try contribution.referenceValue() } + } + } + + @Test(arguments: [false, true]) + func openCodeEnvironmentValuesRequireStagedRendering(_ remote: Bool) throws { + let transport: [String: Any] = + remote + ? [ + "kind": "streamableHTTP", "url": "https://example.invalid/mcp", + "headers": ["X-Token": ["env": "EXACT_VALUE"]], + ] + : stdio(environment: ["TOKEN": ["env": "EXACT_VALUE"]]) + try withMCP( + [server("exact", transport: transport, agents: ["opencode"])], + request: .init(surface: .openCodeCLI, scope: .project) + ) { contribution, ledger, fixture in + let field = remote ? "headers" : "environment" + let key = remote ? "X-Token" : "TOKEN" + #expect( + contribution.value.object?[field]?.object?[key] == .init("EXACT_VALUE", kind: .environment)) + #expect(contribution.bindings.map(\.reference) == [false]) + #expect(throws: NativeAdapterIssue.self) { try contribution.referenceValue() } + var candidate = ledger + candidate.lowerings = [ + contribution.lowering(id: "exact", artifact: "exact", platform: platform) + ] + candidate = try LedgerReplay.prepareLowerings( + candidate, store: fixture.store, roots: [:], limits: .standard) + let restored = try ResolvedLedgerCodec.decode( + ResolvedLedgerCodec.encode(candidate, limits: .standard), limits: .standard) + let replayed = try MCPLayoutV1.contribution(restored.lowerings[0], ledger: restored) + #expect(replayed.bindings == contribution.bindings) + #expect(replayed.value == contribution.value) + #expect(throws: NativeAdapterIssue.self) { try replayed.referenceValue() } + var unsafeReference = restored.lowerings[0] + unsafeReference.layout.object?["bindings"]?.array?[0].object?["reference"] = .init( + boolean: true) + unsafeReference.layout.object?["value"]?.object?[field]?.object?[key] = .init( + "{env:EXACT_VALUE}") + #expect(throws: CoreError.self) { + try MCPLayoutV1.contribution(unsafeReference, ledger: restored) + } + } + } + + @Test(arguments: [false, true]) + func equalPayloadsCannotCrossFrozenSourceOwners(_ resource: Bool) throws { + let a = try LinkFixture() + let b = try LinkFixture() + var run = stdio() + if resource { + run["executable"] = "./server" + for fixture in [a, b] { + try fixture.write("same executable bytes", to: "server", base: fixture.project) + } + } + let declaration: [String: Any] = [ + "version": 1, "components": [server("same", transport: run, agents: ["codex"])], + ] + let (_, frozenA) = try freeze(declaration, a) + let (linkedB, _) = try freeze(declaration, b) + #expect(throws: NativeAdapterIssue.self) { + try NativeMCPLowering.lower( + try #require(linkedB.first), frozen: frozenA, + request: .init(surface: .codexCLI, scope: .project)) + } + } + + @Test func frozenSnapshotsAndResourceProvenanceRemainExact() throws { + let fixture = try LinkFixture() + let producer = fixture.root.appendingPathComponent("producer") + try fixture.initialize(producer) + try fixture.write("same bytes", to: "server", base: producer) + let producerDeclaration: [String: Any] = [ + "version": 1, "exports": ["tools"], + "groups": [ + "tools": [ + "components": [ + server( + "same", transport: ["kind": "stdio", "executable": "./server"], agents: ["codex"]) + ] + ] + ], + ] + try fixture.write( + String(decoding: JSONSerialization.data(withJSONObject: producerDeclaration), as: UTF8.self), + to: ".agent/agents.yaml", base: producer) + try fixture.commit(producer, tag: "1.0.0") + try fixture.write("unrelated revision", to: "README.md", base: producer) + try fixture.commit(producer, tag: "2.0.0") + func declaration(_ version: String) -> [String: Any] { + [ + "version": 1, + "sources": [ + "p": [ + "url": "file://localhost" + producer.path, + "requirement": ["exact": version], + ] + ], "uses": [["source": "p", "group": "tools"]], + ] + } + let (linkedA, frozenA) = try freeze(declaration("1.0.0"), fixture) + let (linkedB, frozenB) = try freeze(declaration("2.0.0"), fixture) + let a = try #require(linkedA.first) + let b = try #require(linkedB.first) + #expect(a.snapshot.source == b.snapshot.source) + #expect(a.snapshot.revision != b.snapshot.revision) + #expect(a.payload == b.payload) + #expect(a.resources.map(\.hash) == b.resources.map(\.hash)) + let request = NativeMCPRequest(surface: .codexCLI, scope: .project) + _ = try NativeMCPLowering.lower(a, frozen: frozenA, request: request) + _ = try NativeMCPLowering.lower(b, frozen: frozenB, request: request) + #expect(throws: NativeAdapterIssue.self) { + try NativeMCPLowering.lower(b, frozen: frozenA, request: request) + } + let mixedResources = LinkedComponent( + key: a.key, declaringSnapshot: a.declaringSnapshot, + snapshot: a.snapshot, pin: a.pin, payload: a.payload, conditions: a.conditions, + recipients: a.recipients, chatGPT: a.chatGPT, resources: b.resources, origins: a.origins) + #expect(throws: NativeAdapterIssue.self) { + try NativeMCPLowering.lower(mixedResources, frozen: frozenA, request: request) + } + } + + @Test(arguments: ["startup_timeout_sec", "tool_timeout_sec"]) + func codexTimeoutMatchesNativeDurationRange(_ field: String) throws { + for (value, accepted) in [ + ("0", true), ("-0.0", true), ("1e-100", true), + ("9223372036854775807", true), ("18446744073709549568.0", true), + ("18446744073709551615.0", false), ("18446744073709551616.0", false), ("1e100", false), + ] { + do { + try withMCP( + [ + server( + "exact", transport: stdio(), agents: ["codex"], + native: ["codex": [field: Double(value)!]]) + ], + request: .init(surface: .codexCLI, scope: .project) + ) { _, _, _ in + #expect(accepted) + } + } catch let issue as NativeAdapterIssue { + #expect(!accepted) + #expect(issue.reason == .invalid) + #expect(issue.request == .init(surface: .codexCLI, scope: .project)) + #expect(issue.component == "exact") + #expect(issue.field == ["native", "codex", field]) + #expect(!issue.description.contains(value)) + } + } + } + + @Test func symbolicBindingsRemainReplayableWithoutMaterializedValues() throws { + try withMCP( + [ + server( + "private", + transport: stdio(environment: [ + "RENAMED": ["env": "ORIGINAL"], "TOKEN": ["secret": "credential/server"], + ]), agents: ["codex"]) + ], request: .init(surface: .codexCLI, scope: .project) + ) { contribution, ledger, fixture in + #expect( + contribution.value.object?["env"] + == .init(object: [ + "RENAMED": .init("ORIGINAL", kind: .environment), + "TOKEN": .init("credential/server", kind: .secret), + ])) + #expect(contribution.bindings.allSatisfy { !$0.reference }) + do { + _ = try contribution.referenceValue() + Issue.record("symbolic bindings were treated as native literal values") + } catch let issue as NativeAdapterIssue { + #expect(issue.reason == .integrationRequired) + #expect(issue.field == ["env", "RENAMED"]) + #expect(!issue.description.contains("credential/server")) + } + var candidate = ledger + candidate.lowerings = [ + contribution.lowering(id: "private", artifact: "private", platform: platform) + ] + candidate = try LedgerReplay.prepareLowerings( + candidate, store: fixture.store, roots: [:], limits: .standard) + let bytes = try ResolvedLedgerCodec.encode(candidate, limits: .standard) + let restored = try ResolvedLedgerCodec.decode(bytes, limits: .standard) + let replayed = try MCPLayoutV1.contribution(restored.lowerings[0], ledger: restored) + #expect(replayed.bindings == contribution.bindings) + #expect(replayed.value == contribution.value) + #expect(replayed.resourcePlacements.isEmpty) + try LedgerReplay.withReplay(restored, store: fixture.store, roots: [:], limits: .standard) { + #expect($0[0].values?.object?["value"] == contribution.value) + } + } + } + + @Test func coldReplayPinsLocalRouteAndRetainsIndependentAndRepeatedOwners() throws { + let fixture = try LinkFixture() + let item = server("same", transport: stdio(), agents: ["claude-code"]) + let declaration: [String: Any] = [ + "version": 1, "exports": ["one", "two"], + "groups": ["one": ["components": [item]], "two": ["components": [item]]], + "uses": [ + ["source": ".", "group": "one"], ["source": ".", "group": "two"], + ["source": ".", "group": "one"], + ], + ] + let (linked, frozen) = try freeze(declaration, fixture) + #expect(linked.count == 3) + #expect(frozen.ledger.components.count == 2) + let contributions = try linked.map { + try NativeMCPLowering.lower( + $0, frozen: frozen, request: .init(surface: .claudeCode, scope: .local)) + } + #expect(contributions[0].component != contributions[1].component) + #expect(contributions[0].component == contributions[2].component) + #expect(contributions.map(\.occurrences) == linked.map { $0.origins.map(\.occurrence) }) + var candidate = frozen.ledger + candidate.lowerings = contributions.enumerated().map { index, contribution in + contribution.lowering(id: "lower-\(index)", artifact: "entry-\(index)", platform: platform) + } + candidate = try LedgerReplay.prepareLowerings( + candidate, store: fixture.store, roots: [:], limits: .standard) + let encoded = try ResolvedLedgerCodec.encode(candidate, limits: .standard) + #expect(!String(decoding: encoded, as: UTF8.self).contains(fixture.project.path)) + try FileManager.default.removeItem(at: fixture.project) + let restored = try ResolvedLedgerCodec.decode(encoded, limits: .standard) + try LedgerReplay.withReplay(restored, store: fixture.store, roots: [:], limits: .standard) { + output in + #expect(output.map(\.name) == ["entry-0", "entry-1", "entry-2"]) + #expect( + output.map { $0.values?.object?["value"] } == contributions.map { Optional($0.value) }) + } + for (index, lowering) in restored.lowerings.enumerated() { + let replayed = try MCPLayoutV1.contribution(lowering, ledger: restored) + #expect(replayed.component == contributions[index].component) + #expect(replayed.occurrences == contributions[index].occurrences) + #expect(replayed.descriptor.request == .init(surface: .claudeCode, scope: .local)) + #expect( + try replayed.descriptor.region( + server: replayed.name, nativeProjectKey: "/relocated/project") + == NativeRegion(keys: ["projects", "/relocated/project", "mcpServers", "same"])) + } + var changed = restored + changed.lowerings[0].layout.object?["scope"] = .init("project") + #expect(throws: CoreError.self) { + try LedgerReplay.withReplay(changed, store: fixture.store, roots: [:], limits: .standard) { + _ in + } + } + changed = restored + changed.lowerings[0].format = "agents/claude-mcp@999" + #expect(throws: CoreError.self) { + try LedgerReplay.withReplay(changed, store: fixture.store, roots: [:], limits: .standard) { + _ in + } + } + } + + @Test func frozenExecutableAndDirectoryUseSymbolicPlacements() throws { + let fixture = try LinkFixture() + try fixture.write("#!/bin/sh\nexit 0\n", to: "bin/server", base: fixture.project) + try FileManager.default.setAttributes( + [.posixPermissions: 0o755], + ofItemAtPath: fixture.project.appendingPathComponent("bin/server").path) + try fixture.write("resource", to: "data/file", base: fixture.project) + var run = stdio() + run["executable"] = "./bin/server" + run["workingDirectory"] = ["path": "data"] + let (linked, frozen) = try freeze( + [ + "version": 1, "components": [server("frozen", transport: run, agents: ["codex"])], + ], fixture) + let contribution = try NativeMCPLowering.lower( + try #require(linked.first), frozen: frozen, + request: .init(surface: .codexCLI, scope: .project)) + #expect(contribution.resourcePlacements.map(\.path) == [[.key("command")], [.key("cwd")]]) + #expect(contribution.resourcePlacements.map(\.resource) == contribution.resources) + let final = try contribution.stagedValue( + bindings: RuntimeBindingValues([:]), + environment: fixture.environment, + resourcePaths: [ + contribution.resources[0]: "/registered/bin/server", + contribution.resources[1]: "/registered/data", + ], + budget: budget()) + #expect( + final + == .object([ + "command": .string("/registered/bin/server"), "args": .array([]), + "cwd": .string("/registered/data"), + ])) + #expect(throws: NativeAdapterIssue.self) { + try contribution.stagedValue( + bindings: RuntimeBindingValues([:]), environment: fixture.environment, + resourcePaths: [:], budget: budget()) + } + #expect(throws: NativeAdapterIssue.self) { try contribution.referenceValue() } + var candidate = frozen.ledger + candidate.lowerings = [ + contribution.lowering(id: "frozen", artifact: "frozen", platform: platform) + ] + candidate = try LedgerReplay.prepareLowerings( + candidate, store: fixture.store, roots: [:], limits: .standard) + let bytes = try ResolvedLedgerCodec.encode(candidate, limits: .standard) + #expect(!String(decoding: bytes, as: UTF8.self).contains(fixture.project.path)) + try FileManager.default.removeItem(at: fixture.project) + try LedgerReplay.withReplay( + ResolvedLedgerCodec.decode(bytes, limits: .standard), store: fixture.store, roots: [:], + limits: .standard + ) { output in + #expect(output[0].values?.object?["value"] == contribution.value) + #expect(output[0].tree == nil) + } + } + + @Test func unsupportedUnknownAndInvalidDiagnosticsAreExact() throws { + for surface in [NativeClientSurface.codexCLI, .openCodeCLI, .cursorEditor, .cursorCLI] { + do { + try withMCP( + [ + server( + "exact", transport: ["kind": "sse", "url": "https://example.invalid/sse"], + agents: [surface.agent.rawValue]) + ], request: .init(surface: surface, scope: .project) + ) { _, _, _ in Issue.record("unexpected mapping") } + Issue.record("transport restriction was lost") + } catch let issue as NativeAdapterIssue { + #expect(issue.request.surface == surface) + #expect(issue.request.scope == .project) + #expect(issue.component == "exact") + #expect(issue.field == ["transport", "kind"]) + #expect( + issue.reason + == (surface == .codexCLI || surface == .openCodeCLI ? .unsupported : .unverified)) + } + } + do { + try withMCP( + [ + server( + "exact", transport: stdio(), agents: ["codex"], + native: ["codex": ["futureField": "SENSITIVE_UNMANAGED_VALUE"]]) + ], request: .init(surface: .codexCLI, scope: .project) + ) { _, _, _ in Issue.record("unknown field accepted") } + Issue.record("unknown field was dropped") + } catch let issue as NativeAdapterIssue { + #expect(issue.reason == .unverified) + #expect(issue.field == ["native", "codex", "futureField"]) + #expect(!issue.description.contains("SENSITIVE_UNMANAGED_VALUE")) + } + do { + try withMCP( + [ + server( + "exact", transport: stdio(), agents: ["codex"], + native: ["codex": ["startup_timeout_sec": -1]]) + ], request: .init(surface: .codexCLI, scope: .project) + ) { _, _, _ in Issue.record("invalid timeout accepted") } + Issue.record("invalid timeout was dropped") + } catch let issue as NativeAdapterIssue { + #expect(issue.reason == .invalid) + #expect(issue.field == ["native", "codex", "startup_timeout_sec"]) + } + #expect(throws: NativeAdapterIssue.self) { + try CapabilityRegistry.mcp(.init(surface: .geminiCLI, scope: .local), component: "exact") + } + #expect(throws: NativeAdapterIssue.self) { + try CapabilityRegistry.mcp(.init(surface: .cursorCloud, scope: .project), component: "exact") + } + } + + @Test func recipientProjectionPreservesTheFrozenOwnerTargeting() throws { + let fixture = try LinkFixture() + let (linked, ledger) = try freeze( + [ + "version": 1, + "components": [server("shared", transport: stdio(), agents: ["claude-code", "codex"])], + ], fixture) + let component = try #require(linked.first) + for surface in [NativeClientSurface.claudeCode, .codexCLI] { + let contribution = try NativeMCPLowering.lower( + component, frozen: ledger, request: .init(surface: surface, scope: .project)) + #expect(contribution.recipients == [surface.agent]) + #expect(contribution.descriptor.knownReaders == [surface.agent]) + #expect( + Set(ledger.ledger.components[contribution.component]!.recipients) == [.claudeCode, .codex]) + #expect(contribution.occurrences == component.origins.map(\.occurrence)) + } + } + + @Test func nativeInterpolationCannotChangeLiteralIdentity() throws { + for (surface, field, text) in [ + (NativeClientSurface.claudeCode, "env", "${CLIENT_TOKEN}"), + (.geminiCLI, "env", "$CLIENT_TOKEN"), + (.openCodeCLI, "environment", "{file:private.txt}"), + (.cursorCLI, "env", "${unknown:CLIENT_TOKEN}"), + ] { + do { + try withMCP( + [ + server( + "literal", transport: stdio(environment: ["TOKEN": text]), + agents: [surface.agent.rawValue]) + ], request: .init(surface: surface, scope: .project) + ) { _, _, _ in + Issue.record("native interpolation was accepted as a portable literal") + } + Issue.record("literal identity was lost") + } catch let issue as NativeAdapterIssue { + #expect(issue.reason == .unverified) + #expect(issue.field == [field, "TOKEN"]) + #expect(!issue.description.contains(text)) + } + } + } + + @Test func producerTargetingAndFrozenIdentityAreNotReinterpreted() throws { + let fixture = try LinkFixture() + var item = server("scoped", transport: stdio(), agents: ["claude-code"]) + item["condition"] = ["scopes": ["project"]] + let (linked, frozen) = try freeze(["version": 1, "components": [item]], fixture) + let component = try #require(linked.first) + #expect(throws: NativeAdapterIssue.self) { + try NativeMCPLowering.lower( + component, frozen: frozen, request: .init(surface: .codexCLI, scope: .project)) + } + #expect(throws: NativeAdapterIssue.self) { + try NativeMCPLowering.lower( + component, frozen: frozen, request: .init(surface: .claudeCode, scope: .user)) + } + var changed = frozen + changed.ledger.occurrences[0].consumerEditable = false + #expect(throws: NativeAdapterIssue.self) { + try NativeMCPLowering.lower( + component, frozen: changed, request: .init(surface: .claudeCode, scope: .project)) + } + } + + @Test func stagedMCPUsesSuppliedValuesAndKeepsReferencesSymbolic() throws { + try withMCP( + [ + server( + "staged", + transport: stdio(environment: [ + "INHERITED": ["env": "INHERITED"], "RENAMED": ["env": "SOURCE"], + "TOKEN": ["secret": "fixture/token"], + ]), agents: ["codex"]) + ], + request: .init(surface: .codexCLI, scope: .project) + ) { contribution, ledger, fixture in + let before = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + let environment = RuntimeEnvironment( + projectDirectory: fixture.project, homeDirectory: fixture.home, + environment: ["SOURCE": "exact environment fixture"]) + let supplied = RuntimeBindingValues(["fixture/token": Data("private fixture value".utf8)]) + let native = try contribution.stagedValue( + bindings: supplied, environment: environment, + resourcePaths: [:], budget: budget()) + guard case .object(let fields) = native else { + Issue.record("missing native object") + return + } + #expect( + fields["env"] + == .object([ + "RENAMED": .string("exact environment fixture"), + "TOKEN": .string("private fixture value"), + ])) + #expect(fields["env_vars"] == .array([.string("INHERITED")])) + #expect(try ResolvedLedgerCodec.encode(ledger, limits: .standard) == before) + #expect(!String(describing: contribution.value).contains("private fixture value")) + for data in [Data([0xff]), Data([0])] { + do { + _ = try contribution.stagedValue( + bindings: RuntimeBindingValues(["fixture/token": data]), + environment: environment, resourcePaths: [:], budget: budget()) + Issue.record("invalid native binding accepted") + } catch let issue as NativeAdapterIssue { + #expect(issue.reason == .invalid) + #expect(issue.field == ["env", "TOKEN"]) + #expect(!issue.description.contains("fixture/token")) + } + } + } + } + + @Test func stagedOpenCodeRejectsInterpolationAndHeaderInjection() throws { + try withMCP( + [ + server( + "staged", + transport: [ + "kind": "streamableHTTP", "url": "https://example.invalid/mcp", + "headers": ["X-Token": ["secret": "fixture/token"]], + ], agents: ["opencode"]) + ], + request: .init(surface: .openCodeCLI, scope: .project) + ) { contribution, _, fixture in + for value in ["{file:private.txt}", "{env:TOKEN}", "line\r\nInjected: value", "nul\0"] { + do { + _ = try contribution.stagedValue( + bindings: RuntimeBindingValues(["fixture/token": Data(value.utf8)]), + environment: fixture.environment, resourcePaths: [:], budget: budget()) + Issue.record("unrepresentable staged literal accepted") + } catch let issue as NativeAdapterIssue { + #expect(issue.field == ["headers", "X-Token"]) + #expect(!issue.description.contains(value)) + } + } + let value = #"C:\new"# + let native = try contribution.stagedValue( + bindings: RuntimeBindingValues(["fixture/token": Data(value.utf8)]), + environment: fixture.environment, resourcePaths: [:], budget: budget()) + let region = try contribution.descriptor.region(server: contribution.name) + let doc = try document("{}", contribution) + let prepared = try doc.prepare([.put(region: region, expected: .absent, value: native)]) + let reread = try NativeDocument(bytes: prepared.bytes, format: .json, budget: budget()) + #expect( + try reread.read(.init(keys: ["mcp", "servers", "staged", "headers", "X-Token"]))?.value + == .string(value)) + } + } + + private var platform: DeclarationPlatform { + #if os(macOS) + .macOS + #else + .linux + #endif + } + + private func server( + _ name: String, transport: [String: Any], agents: [String], native: [String: Any] = [:] + ) -> [String: Any] { + ["kind": "mcpServer", "name": name, "transport": transport, "agents": agents, "native": native] + } + + private func stdio(arguments: [String] = [], environment: [String: Any] = [:]) -> [String: Any] { + [ + "kind": "stdio", "executable": "fixture-server-never-run", "arguments": arguments, + "environment": environment, + ] + } + + private func withMCP( + _ components: [[String: Any]], request: NativeMCPRequest, + _ body: (NativeMCPContribution, ResolvedLedger, LinkFixture) throws -> Void + ) throws { + let fixture = try LinkFixture() + let (linked, ledger) = try freeze(["version": 1, "components": components], fixture) + let contribution = try NativeMCPLowering.lower( + try #require(linked.first), frozen: ledger, request: request) + try body(contribution, ledger.ledger, fixture) + } + + private func freeze(_ declaration: [String: Any], _ fixture: LinkFixture) throws -> ( + [LinkedComponent], LedgerFreeze.Result + ) { + let bytes = try JSONSerialization.data(withJSONObject: declaration, options: [.sortedKeys]) + let document = try DeclarationDocument( + bytes: Array(bytes), identity: DocumentIdentity("consumer/agents.yaml")) + return try ComponentLinker.withLinkedComponents( + document: document, store: fixture.store, platform: platform + ) { linked, session in + let frozen = try LedgerFreeze.freezeWithSources( + linked, session: session, + locations: .init(sources: [ + "local:" + fixture.project.path: .init(kind: .registered, root: "project", path: ".") + ]), limits: .standard) + return (linked.components, frozen) + } + } + + private func budget() -> NativeDocumentBudget { + .init( + limits: .init( + storage: 32_000_000, work: 100_000_000, nodes: 100_000, depth: 128, + uninterruptedBytes: 1_000_000)) + } + + private func document(_ text: String, _ contribution: NativeMCPContribution) throws + -> NativeDocument + { + try NativeDocument( + bytes: Data(text.utf8), format: contribution.descriptor.documentFormat, budget: budget()) + } +} diff --git a/Tests/ComponentsTests/OpaquePluginIdentityTests.swift b/Tests/ComponentsTests/OpaquePluginIdentityTests.swift new file mode 100644 index 0000000..1c6e534 --- /dev/null +++ b/Tests/ComponentsTests/OpaquePluginIdentityTests.swift @@ -0,0 +1,111 @@ +import AgentsManifest +import Foundation +import Testing + +@testable import AgentsCore +@testable import Components + +@Suite("Opaque native plugin producer identity") +struct OpaquePluginIdentityTests { + private var platform: DeclarationPlatform { + #if os(macOS) + .macOS + #else + .linux + #endif + } + + @Test(arguments: [false, true]) + func declaringNamespaceAndSelectedProducerPairThroughColdReplay(_ separateProducer: Bool) throws { + let fixture = try LinkFixture() + let producer = + separateProducer ? fixture.root.appendingPathComponent("producer") : fixture.project + let manifest = #"{"name":"demo-plugin","version":"1.0.0"}"# + try fixture.write(manifest, to: "demo-plugin/.claude-plugin/plugin.json", base: producer) + try fixture.write("#!/bin/sh\n# frozen only\n", to: "demo-plugin/bin/check", base: producer) + try FileManager.default.setAttributes( + [.posixPermissions: 0o755], + ofItemAtPath: producer.appendingPathComponent("demo-plugin/bin/check").path) + try FileManager.default.createSymbolicLink( + atPath: producer.appendingPathComponent("demo-plugin/current").path, + withDestinationPath: "bin/check") + let input: [String: Any] = [ + "version": 1, "sources": ["producer": ["path": producer.path]], + "components": [ + [ + "kind": "plugin", "name": "demo-plugin", "path": "demo-plugin", + "source": "producer", "mode": "native", "agents": ["claude-code"], + ] + ], + ] + let document = try DeclarationDocument( + bytes: Array(JSONSerialization.data(withJSONObject: input, options: [.sortedKeys])), + identity: .init("consumer/agents.yaml")) + let (linked, frozen) = try ComponentLinker.withLinkedComponents( + document: document, store: fixture.store, platform: platform + ) { graph, session in + let locations = Dictionary( + (graph.sourceSnapshots + graph.declaringSnapshots).map { + ( + $0.snapshot.source, + LedgerLocation( + kind: .absolute, path: String($0.snapshot.source.dropFirst("local:".count))) + ) + }, uniquingKeysWith: { first, _ in first }) + return ( + try #require(graph.components.first), + try LedgerFreeze.freezeWithSources( + graph, session: session, locations: .init(sources: locations), limits: .standard) + ) + } + let lowering = try NativeComponentLowering.lower( + linked, frozen: frozen, + request: .init(surface: .claudeCode, scope: .project), id: "opaque", platform: platform) + let record = try #require(frozen.ledger.components[lowering.inputs[0]]) + #expect(linked.key.source == linked.declaringSnapshot.source) + #expect(record.declaringSource == frozen.sources[linked.declaringSnapshot]) + #expect(record.source == frozen.sources[linked.snapshot]) + #expect((linked.declaringSnapshot.source != linked.snapshot.source) == separateProducer) + let resource = try #require(record.resources.first) + #expect(frozen.ledger.resources[resource]?.source == record.source) + var corrupt = frozen + corrupt.ledger.resources[resource]!.source = "missing-selected-producer" + #expect(throws: NativeComponentIssue.self) { + try NativeComponentLowering.lower( + linked, frozen: corrupt, + request: .init(surface: .claudeCode, scope: .project), id: "invalid", platform: platform) + } + var ledger = frozen.ledger + ledger.lowerings = [lowering] + ledger = try LedgerReplay.prepareLowerings( + ledger, store: fixture.store, roots: [:], limits: .standard) + let bytes = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + try FileManager.default.removeItem(at: producer.appendingPathComponent("demo-plugin")) + let restored = try ResolvedLedgerCodec.decode(bytes, limits: .standard) + try LedgerReplay.withReplay(restored, store: fixture.store, roots: [:], limits: .standard) { + artifacts in + let contribution = try NativeComponentLayoutsV1.contribution( + restored.lowerings[0], ledger: restored, + artifacts: artifacts, limits: .standard) + #expect(contribution.occurrences == linked.origins.map(\.occurrence)) + guard + case .nativePlugin(let directory, let selected, let entry) = contribution.outputs[0].content + else { + Issue.record("missing opaque native contribution") + return + } + #expect( + directory == "demo-plugin" && selected == resource && entry == ".claude-plugin/plugin.json") + let root = try #require(artifacts[1].tree) + #expect( + try String(contentsOf: root.appendingPathComponent(entry), encoding: .utf8) == manifest) + #expect( + try FileManager.default.destinationOfSymbolicLink( + atPath: root.appendingPathComponent("current").path) == "bin/check") + let mode = + try FileManager.default.attributesOfItem( + atPath: root.appendingPathComponent("bin/check").path)[.posixPermissions] as? NSNumber + #expect(mode.map { $0.intValue & 0o111 != 0 } == true) + } + } +} diff --git a/Tests/ComponentsTests/PluginLinkingTests.swift b/Tests/ComponentsTests/PluginLinkingTests.swift new file mode 100644 index 0000000..94fe6bd --- /dev/null +++ b/Tests/ComponentsTests/PluginLinkingTests.swift @@ -0,0 +1,401 @@ +import AgentsCore +import Components +import Foundation +import Testing + +@Suite("Plugin occurrence linking", .serialized) +struct PluginLinkingTests { + private func container(_ fixture: LinkFixture, _ path: String, at root: URL) throws { + try fixture.write("{\"name\":\"review\"}", to: path + "/.claude-plugin/plugin.json", base: root) + try fixture.write( + "---\ndescription: Review command\n---\nReview carefully\n", + to: path + "/commands/review.md", base: root) + try fixture.write( + "---\nname: review\ndescription: Review skill\nplatforms: [macos]\n---\nBody\n", + to: path + "/skills/review/SKILL.md", base: root) + try fixture.write("shared support", to: path + "/shared/context.md", base: root) + try fixture.write("#!/bin/sh\nexit 0\n", to: path + "/shared/server", base: root) + try FileManager.default.setAttributes( + [.posixPermissions: 0o755], + ofItemAtPath: root.appendingPathComponent(path + "/shared/server").path) + try FileManager.default.createDirectory( + at: root.appendingPathComponent(path + "/bin"), + withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink( + atPath: root.appendingPathComponent(path + "/bin/server").path, + withDestinationPath: "../shared/server") + try fixture.write( + "{\"mcpServers\":{\"server\":{\"command\":\"${CLAUDE_PLUGIN_ROOT}/bin/server\"}}}", + to: path + "/.mcp.json", base: root) + } + + private func freeze(_ fixture: LinkFixture, _ expression: String) throws -> ResolvedLedger { + try ComponentLinker.withLinkedComponents( + document: fixture.document(expression), + store: fixture.store, platform: .macOS + ) { graph, session in + let locations = Dictionary( + (graph.sourceSnapshots + graph.declaringSnapshots).filter { + $0.source?.kind == .local && $0.container == nil + }.map { + ( + $0.snapshot.source, + LedgerLocation( + kind: .absolute, + path: String($0.snapshot.source.dropFirst("local:".count))) + ) + }, uniquingKeysWith: { first, _ in first }) + return try LedgerFreeze.freeze( + graph, session: session, + locations: .init(sources: locations), limits: .standard) + } + } + + @Test func multiParentSelectionNamespacesAndRestrictions() throws { + let fixture = try LinkFixture() + try container(fixture, "one", at: fixture.project) + try container(fixture, "two", at: fixture.project) + let expression = """ + version: 1 + defaultAgents: ["claude-code", "codex"] + components: + - {kind: plugin, name: first, path: one, source: ".", agents: ["claude-code"]} + - {kind: plugin, name: repeated, path: one, source: ".", condition: {agents: []}} + - {kind: plugin, name: second, path: two, source: ".", select: [command], exclude: [{kind: command, name: review}]} + - {kind: plugin, name: empty, path: one, source: ".", select: []} + """ + let graph = try fixture.link(expression) + let parents = graph.components.filter { $0.key.kind == .plugin } + #expect(parents.count == 4) + #expect(parents.map { $0.origins[0].pluginExpansion!.children.count } == [3, 3, 0, 0]) + let members = graph.components.filter { $0.key.containerRoot != nil } + #expect(members.count == 6) + #expect(Set(members.map(\.key)).count == 3) + #expect(members.prefix(3).allSatisfy { $0.recipients == [.claudeCode] }) + #expect(members.suffix(3).allSatisfy { $0.recipients.isEmpty }) + #expect(members.allSatisfy { !$0.origins[0].consumerEditable }) + #expect(throws: LinkError.self) { try graph.requireEditable(members[0].key) } + let ledger = try freeze(fixture, expression) + #expect(ledger.occurrences.count == 10) + #expect(ledger.occurrences.filter { $0.pluginExpansion != nil }.count == 4) + #expect(ledger.occurrences.filter { $0.pluginMember != nil }.count == 6) + #expect( + ledger.resources.values.allSatisfy { !$0.path.hasSuffix("plugin.json") && $0.path != "one" }) + let bytes = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + #expect(try ResolvedLedgerCodec.decode(bytes, limits: .standard) == ledger) + #expect( + ledger.occurrences.filter { $0.pluginMember != nil }.allSatisfy { + $0.input?.format == "native/claudePluginV1@1" + }) + let both = try fixture.link( + """ + version: 1 + components: [{kind: plugin, name: a, path: one, source: "."}, {kind: plugin, name: b, path: two, source: "."}] + """) + #expect(Set(both.components.filter { $0.key.kind == .command }.map(\.key)).count == 2) + } + + @Test func remoteChildrenAndEmptyFreezeKeepExactProducer() throws { + let fixture = try LinkFixture() + let repository = fixture.root.appendingPathComponent("producer") + try fixture.initialize(repository) + try container(fixture, "plugins/review", at: repository) + let first = try fixture.commit(repository, tag: "1.0.0") + let source = + "sources: {p: {url: \"file://localhost\(repository.path)\", requirement: {exact: \"1.0.0\"}}}" + let expression = + "version: 1\n" + source + + "\ncomponents: [{kind: plugin, name: p, path: plugins/review, source: p}]" + let ledger = try freeze(fixture, expression) + let expansion = try #require(ledger.occurrences.first?.pluginExpansion) + #expect(ledger.sources[expansion.source]?.revision == first) + #expect( + ledger.components.values.filter { $0.containerRoot != nil }.allSatisfy { + $0.declaringSource == expansion.source && $0.source == expansion.source + }) + let executable = try #require(ledger.resources.values.first { $0.path.hasSuffix("bin/server") }) + #expect(!executable.support.isEmpty) + #expect(ledger.resources.values.allSatisfy { $0.kind == .git }) + let mcp = try #require(ledger.components.values.first { $0.kind == "mcpServer" }) + #expect( + mcp.payload.object?["transport"]?.object?["run"]?.object?["executable"]?.text + == "plugins/review/bin/server") + #expect( + !String(decoding: try ResolvedLedgerCodec.encode(ledger, limits: .standard), as: UTF8.self) + .contains("agents-source-")) + let empty = try freeze( + fixture, + "version: 1\n" + source + + "\ncomponents: [{kind: plugin, name: p, path: plugins/review, source: p, select: []}]") + let emptyExpansion = try #require(empty.occurrences.first?.pluginExpansion) + #expect(emptyExpansion.children.isEmpty) + #expect(empty.sources[emptyExpansion.source]?.revision == first) + #expect(empty.resources.isEmpty) + try FileManager.default.removeItem(at: repository) + let decoded = try ResolvedLedgerCodec.decode( + ResolvedLedgerCodec.encode(ledger, limits: .standard), limits: .standard) + #expect(decoded.occurrences == ledger.occurrences) + } + + @Test func memberIdentityDoesNotInheritDeclaringParentGroup() throws { + let fixture = try LinkFixture() + try container(fixture, "one", at: fixture.project) + let graph = try fixture.link( + """ + version: 1 + groups: + left: {components: [{kind: plugin, name: left, path: one, source: ".", select: [command]}]} + right: {components: [{kind: plugin, name: right, path: one, source: ".", select: [command]}]} + uses: [{group: left}, {group: right}] + """) + let children = graph.components.filter { $0.key.kind == .command } + #expect(children.count == 2) + #expect(Set(children.map(\.key)).count == 1) + #expect(children.allSatisfy { $0.key.group == nil && $0.origins[0].reference != nil }) + #expect(Set(children.map { $0.origins[0].pluginMember!.parentOccurrence }).count == 2) + } + + @Test func selectedMembersKeepIndependentDirectPins() throws { + let fixture = try LinkFixture() + let repository = fixture.root.appendingPathComponent("producer") + try fixture.initialize(repository) + try container(fixture, "one", at: repository) + let first = try fixture.commit(repository, tag: "1.0.0") + let expression = """ + version: 1 + sources: {p: {url: "file://localhost\(repository.path)", requirement: {from: "1.0.0"}}} + components: [{kind: skills, source: p, select: [review]}, {kind: plugin, name: p, path: one, source: p, select: [mcpServer]}] + """ + let before = try fixture.link(expression) + let direct = try #require(before.components.first { $0.key.kind == .skills }) + try fixture.write("new binary", to: "one/shared/server", base: repository) + try fixture.write( + "---\nname: review\ndescription: Changed\n---\nChanged\n", + to: "one/skills/review/SKILL.md", base: repository) + let second = try fixture.commit(repository, tag: "1.1.0") + let after = try fixture.link(expression, directPins: [direct.key: try #require(direct.pin)]) + #expect(after.components.first { $0.key.kind == .skills }?.snapshot.revision == first) + #expect(after.components.first { $0.key.kind == .mcpServer }?.snapshot.revision == second) + #expect(!after.protectedChanges(from: before, allowing: [.skills]).isEmpty) + } + + @Test func emptyContainerAndExactExclusionSurviveFreeze() throws { + let fixture = try LinkFixture() + try fixture.write( + "{\"name\":\"empty\"}", to: "empty/.claude-plugin/plugin.json", base: fixture.project) + let empty = try freeze( + fixture, "version: 1\ncomponents: [{kind: plugin, name: empty, path: empty, source: \".\"}]") + #expect(empty.occurrences[0].pluginExpansion?.children == []) + #expect(empty.resources.isEmpty) + try fixture.write( + "{\"name\":\"unicode\"}", to: "unicode/.claude-plugin/plugin.json", base: fixture.project) + try fixture.write("Body", to: "unicode/commands/é.md", base: fixture.project) + let base = "version: 1\ncomponents: [{kind: plugin, name: u, path: unicode, source: \".\"" + let graph = try fixture.link(base + "}]") + let command = try #require(graph.components.first { $0.key.kind == .command }) + let name = command.key.name + let other = name.utf8.elementsEqual("é".utf8) ? "e\u{301}" : "é" + let kept = try fixture.link(base + ", exclude: [{kind: command, name: \"\(other)\"}]}]") + #expect(kept.components.contains { $0.key.kind == .command }) + let excluded = try fixture.link(base + ", exclude: [{kind: command, name: \"\(name)\"}]}]") + #expect(excluded.components.count == 1) + let renumbered = try fixture.link( + "version: 1\ncomponents: [{kind: ignore, name: unrelated, patterns: [temp]}, {kind: plugin, name: u, path: unicode, source: \".\"}]" + ) + #expect(renumbered.protectedChanges(from: graph, allowing: [.ignore]).isEmpty) + } + + @Test func unicodeSelectorsRemainDistinctWithinContainer() throws { + let fixture = try LinkFixture() + try fixture.write( + "{\"name\":\"unicode\"}", to: "unicode/.claude-plugin/plugin.json", base: fixture.project) + for (path, name) in [("first", "é"), ("second", "e\u{301}")] { + try fixture.write( + "---\nname: \(name)\ndescription: Agent\n---\nBody\n", + to: "unicode/agents/" + path + ".md", base: fixture.project) + } + let graph = try fixture.link( + "version: 1\ncomponents: [{kind: plugin, name: u, path: unicode, source: \".\"}]") + let members = graph.components.filter { $0.key.kind == .subagent } + #expect(members.count == 2) + #expect(Set(members.map(\.key)).count == 2) + } + + @Test func nativeModeRemainsOpaqueAndBindingBytesStayPrivate() throws { + let fixture = try LinkFixture() + try container(fixture, "one", at: fixture.project) + try fixture.write( + "{\"mcpServers\":{\"server\":{\"command\":\"server\",\"env\":{\"TOKEN\":\"CANARY-plugin-secret\"}}}}", + to: "one/.mcp.json", base: fixture.project) + let ledger = try freeze( + fixture, "version: 1\ncomponents: [{kind: plugin, name: p, path: one, source: \".\"}]") + #expect( + !String(decoding: try ResolvedLedgerCodec.encode(ledger, limits: .standard), as: UTF8.self) + .contains("CANARY-plugin-secret")) + #expect( + ledger.contentObjects.values.allSatisfy { + !String(decoding: $0, as: UTF8.self).contains("CANARY-plugin-secret") + }) + let opaque = try fixture.link( + "version: 1\ncomponents: [{kind: plugin, name: p, path: one, source: \".\", mode: native, agents: [\"claude-code\"]}]" + ) + #expect(opaque.components.count == 1) + #expect(opaque.components[0].origins[0].pluginExpansion == nil) + #expect(opaque.components[0].resources.count == 1) + #expect(throws: (any Error).self) { + _ = try fixture.link( + "version: 1\ncomponents: [{kind: plugin, name: p, path: one, source: \".\", mode: native, agents: [\"claude-code\"], select: []}]" + ) + } + } + + @Test func emptyExpansionMustIdentifySelectedProducer() throws { + let fixture = try LinkFixture() + let declaring = fixture.root.appendingPathComponent("declaring") + let selected = fixture.root.appendingPathComponent("selected") + try container(fixture, "one", at: selected) + try fixture.manifest( + """ + version: 1 + sources: {b: {path: "\(selected.path)"}} + exports: [bundle] + groups: {bundle: {components: [{kind: plugin, name: empty, path: one, source: b, select: []}]}} + """, at: declaring) + let ledger = try freeze( + fixture, + """ + version: 1 + sources: {a: {path: "\(declaring.path)"}} + uses: [{source: a, group: bundle}] + """) + let parent = try #require(ledger.occurrences.firstIndex { $0.pluginExpansion != nil }) + let occurrence = ledger.occurrences[parent] + let component = try #require(ledger.components[occurrence.component]) + let expansion = try #require(occurrence.pluginExpansion) + #expect(expansion.children.isEmpty) + #expect(expansion.source == component.source) + #expect(component.declaringSource != component.source) + #expect(occurrence.dependencies.contains(component.declaringSource)) + #expect(occurrence.dependencies.contains(component.source)) + let bytes = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + #expect(try ResolvedLedgerCodec.decode(bytes, limits: .standard) == ledger) + var wrongProducer = ledger + wrongProducer.occurrences[parent].pluginExpansion!.source = component.declaringSource + #expect(throws: (any Error).self) { + _ = try ResolvedLedgerCodec.decode( + ResolvedLedgerCodec.bytes(wrongProducer), limits: .standard) + } + } + + @Test func everyContainerArrivalNeedsItsParentRelation() throws { + let fixture = try LinkFixture() + try container(fixture, "one", at: fixture.project) + let ledger = try freeze( + fixture, + """ + version: 1 + components: + - {kind: ignore, name: direct, patterns: [temp]} + - {kind: plugin, name: first, path: one, source: ".", select: [command]} + - {kind: plugin, name: repeated, path: one, source: ".", select: [command]} + """) + let members = ledger.occurrences.filter { $0.pluginMember != nil } + #expect(members.count == 2) + #expect(Set(members.map(\.component)).count == 1) + #expect(Set(members.map { $0.pluginMember!.parent }).count == 2) + #expect( + ledger.occurrences.contains { + $0.pluginMember == nil && ledger.components[$0.component]?.containerRoot == nil + && $0.consumerEditable + }) + let bytes = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + #expect(try ResolvedLedgerCodec.decode(bytes, limits: .standard) == ledger) + for editable in [false, true] { + var orphaned = ledger + var orphan = try #require(members.first) + orphan.id = (ledger.occurrences.map(\.id).max() ?? 0) + 1 + orphan.reference = nil + orphan.pluginMember = nil + orphan.consumerEditable = editable + orphaned.occurrences.append(orphan) + #expect(throws: (any Error).self) { + _ = try ResolvedLedgerCodec.decode( + ResolvedLedgerCodec.bytes(orphaned), limits: .standard) + } + } + } + + @Test func strictClosureAndByteExactNoOp() throws { + let fixture = try LinkFixture() + try container(fixture, "one", at: fixture.project) + let ledger = try freeze( + fixture, + "version: 1\ncomponents: [{kind: plugin, name: p, path: one, source: \".\"}]") + func refused(_ change: (inout ResolvedLedger) -> Void) { + var value = ledger + change(&value) + #expect(throws: (any Error).self) { + _ = try ResolvedLedgerCodec.encode(value, limits: .standard) + } + } + refused { $0.occurrences[0].pluginExpansion!.children.removeLast() } + refused { $0.occurrences[1].pluginMember!.parent = 9 } + refused { $0.occurrences[1].pluginMember!.parent = 1 } + refused { $0.occurrences[1].pluginMember!.kind = "hook" } + refused { $0.occurrences[1].consumerEditable = true } + refused { $0.occurrences[0].pluginExpansion!.containerRoot = "../escape" } + refused { $0.occurrences[0].pluginExpansion!.children.reverse() } + refused { $0.occurrences[0].recipients = [] } + refused { $0.occurrences[0].condition.platforms = [] } + refused { + $0.occurrences[2].component = $0.occurrences[1].component + $0.occurrences[2].pluginMember = $0.occurrences[1].pluginMember + } + refused { $0.occurrences[1].manifestPath = "elsewhere/child.md" } + let encoded = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + var limits = LedgerLimits.standard + limits.encodedBytes = encoded.count + #expect(try ResolvedLedgerCodec.decode(encoded, limits: limits) == ledger) + limits.encodedBytes -= 1 + #expect(throws: (any Error).self) { + _ = try ResolvedLedgerCodec.decode(encoded, limits: limits) + } + var json = try #require( + JSONSerialization.jsonObject(with: ResolvedLedgerCodec.encode(ledger, limits: .standard)) + as? [String: Any]) + var occurrences = try #require(json["occurrences"] as? [[String: Any]]) + var expansion = try #require(occurrences[0]["pluginExpansion"] as? [String: Any]) + expansion["unexpected"] = NSNull() + occurrences[0]["pluginExpansion"] = expansion + json["occurrences"] = occurrences + #expect(throws: (any Error).self) { + _ = try ResolvedLedgerCodec.decode( + JSONSerialization.data(withJSONObject: json), limits: .standard) + } + var before = ResolvedLedger() + before.sources["source"] = .init( + kind: .local, location: .init(kind: .registered, root: "project", path: "."), revision: "é") + var after = before + after.sources["source"]!.revision = "e\u{301}" + let spaced = Data(" \n".utf8) + (try ResolvedLedgerCodec.encode(before, limits: .standard)) + #expect(try ResolvedLedgerCodec.replacement(before, existing: spaced, limits: .standard) == nil) + #expect(try ResolvedLedgerCodec.replacement(after, existing: spaced, limits: .standard) != nil) + let key = ComponentKey( + source: "s", root: ".", group: nil, kind: .command, name: "é", containerRoot: "é") + let other = ComponentKey( + source: "s", root: ".", group: nil, kind: .command, name: "e\u{301}", + containerRoot: "e\u{301}") + #expect(Set([key, other]).count == 2) + #expect( + LedgerPluginMember(parent: 0, kind: "subagent", name: "é") + != LedgerPluginMember(parent: 0, kind: "subagent", name: "e\u{301}")) + let input = LedgerInputProvenance(format: "native/claudePluginV1@1", adapterVersion: "1") + #expect( + LedgerPluginExpansion( + source: "s", root: ".", containerRoot: "é", + document: "é/.claude-plugin/plugin.json", input: input, children: []) + != LedgerPluginExpansion( + source: "s", root: ".", containerRoot: "e\u{301}", + document: "e\u{301}/.claude-plugin/plugin.json", input: input, children: [])) + } +} diff --git a/Tests/ComponentsTests/PromptReferenceTests.swift b/Tests/ComponentsTests/PromptReferenceTests.swift new file mode 100644 index 0000000..44863aa --- /dev/null +++ b/Tests/ComponentsTests/PromptReferenceTests.swift @@ -0,0 +1,137 @@ +import AgentsCore +import Components +import Foundation +import Testing + +@Suite("Frozen prompts and current append references", .serialized) +struct PromptReferenceTests { + @Test func coldReplayDoesNotReadConsumerAppend() throws { + let fixture = try LinkFixture() + try fixture.instruction("guide", at: fixture.project) + let document = try fixture.document( + "version: 1\ncomponents: [{kind: instructions, chatgpt: {daily: {sections: [{name: guide}], append: custom.md}}}]" + ) + var ledger = try ComponentLinker.withLinkedComponents( + document: document, store: fixture.store, platform: .macOS + ) { graph, session in + try LedgerFreeze.freeze( + graph, session: session, + locations: .init(sources: [ + "local:" + fixture.project.path: .init(kind: .registered, root: "project", path: ".") + ]), limits: .standard) + } + let componentID = try #require(ledger.components.keys.first) + let component = ledger.components[componentID]! + #expect(component.resources.count == 1) + #if os(macOS) + let platform = "macos" + #else + let platform = "linux" + #endif + ledger.lowerings = [ + .init( + id: "prompt:daily", format: "agents/chatgpt@1", inputs: [componentID], + resources: component.resources, deployments: [], + layout: .init(object: ["name": .init("prompt:daily"), "sectionCount": .init(integer: 1)]), + platform: platform, artifacts: []) + ] + // An escaping current append must not enter the frozen installation path. + try fixture.write("CURRENT APPEND", to: "outside.md") + try FileManager.default.createSymbolicLink( + at: fixture.project.appendingPathComponent("custom.md"), + withDestinationURL: fixture.root.appendingPathComponent("outside.md")) + ledger = try LedgerReplay.prepareLowerings( + ledger, store: fixture.store, roots: ["project": fixture.project], limits: .standard) + let encoded = try ResolvedLedgerCodec.encode(ledger, limits: .standard) + ledger = try ResolvedLedgerCodec.decode(encoded, limits: .standard) + try FileManager.default.removeItem(at: fixture.project) + try LedgerReplay.withReplay( + ledger, store: fixture.store, roots: ["project": fixture.project], limits: .standard + ) { artifacts in + let bytes = try #require(artifacts.first?.bytes) + let text = String(decoding: bytes, as: UTF8.self) + #expect(text.contains("guide")) + #expect(!text.contains("CURRENT APPEND")) + } + } + + @Test func immutableProducerAppendRemainsAnExactResource() throws { + let fixture = try LinkFixture() + let producer = fixture.root.appendingPathComponent("producer") + try fixture.instruction("guide", at: producer) + try fixture.write("FROZEN APPEND", to: "custom.md", base: producer) + try fixture.write("CONSUMER SHADOW", to: "custom.md", base: fixture.project) + try fixture.manifest( + "version: 1\nexports: [g]\ngroups: {g: {components: [{kind: instructions, chatgpt: {daily: {sections: [{name: guide}], append: custom.md}}}]}}", + at: producer) + let document = try fixture.document( + "version: 1\nsources: {p: {path: '\(producer.path)'}}\nuses: [{source: p, group: g}]") + let ledger = try ComponentLinker.withLinkedComponents( + document: document, store: fixture.store, platform: .macOS + ) { graph, session in + let component = try #require(graph.components.first) + #expect(component.localAppend == nil) + #expect(component.resources.count == 2) + try fixture.write("LIVE PRODUCER SHADOW", to: "custom.md", base: producer) + let append = component.resources[1] + #expect( + try Data(contentsOf: session.resource(snapshot: append.snapshot, path: append.path)) + == Data("FROZEN APPEND".utf8)) + return try LedgerFreeze.freeze( + graph, session: session, + locations: .init(sources: [ + "local:" + producer.path: .init( + kind: .authoringRelative, root: "project", path: "../producer"), + "local:" + fixture.project.path: .init(kind: .registered, root: "project", path: "."), + ]), limits: .standard) + } + let restored = try ResolvedLedgerCodec.decode( + ResolvedLedgerCodec.encode(ledger, limits: .standard), limits: .standard) + let component = try #require(restored.components.values.first) + #expect(component.payload.object?["localAppend"] == nil) + #expect(component.resources.count == 2) + let append = try #require(restored.resources[component.resources[1]]) + let object = try #require(append.entries.first?.object) + #expect(restored.contentObjects[object] == Data("FROZEN APPEND".utf8)) + } + + @Test func codecValidatesLocalAppendLocationRatherThanReadingIt() throws { + let fixture = try LinkFixture() + try fixture.instruction("guide", at: fixture.project) + let document = try fixture.document( + "version: 1\ncomponents: [{kind: instructions, chatgpt: {daily: {sections: [{name: guide}], append: missing.md}}}]" + ) + let ledger = try ComponentLinker.withLinkedComponents( + document: document, store: fixture.store, platform: .macOS + ) { graph, session in + try LedgerFreeze.freeze( + graph, session: session, + locations: .init(sources: [ + "local:" + fixture.project.path: .init(kind: .registered, root: "project", path: ".") + ]), limits: .standard) + } + let id = try #require(ledger.components.keys.first) + for invalid in [ + LedgerValue(object: [ + "kind": .init("registered"), "root": .init("state"), "path": .init("missing.md"), + ]), + LedgerValue(object: [ + "kind": .init("registered"), "root": .init("project"), "path": .init("../outside"), + ]), + LedgerValue(object: ["kind": .init("absolute"), "path": .init("/tmp/append")]), + LedgerValue(object: [ + "kind": .init("registered"), "root": .init("project"), "path": .init("missing.md"), + "fallback": .init(), + ]), + ] { + var invalidLedger = ledger + invalidLedger.components[id]!.payload.object!["localAppend"] = invalid + #expect(throws: (any Error).self) { + try ResolvedLedgerCodec.encode(invalidLedger, limits: .standard) + } + } + #expect( + try ResolvedLedgerCodec.decode( + ResolvedLedgerCodec.encode(ledger, limits: .standard), limits: .standard) == ledger) + } +} diff --git a/Tests/ComponentsTests/SnapshotTests.swift b/Tests/ComponentsTests/SnapshotTests.swift new file mode 100644 index 0000000..e56883d --- /dev/null +++ b/Tests/ComponentsTests/SnapshotTests.swift @@ -0,0 +1,427 @@ +import AgentsCore +import AgentsManifest +import AgentsSkills +import Components +import Foundation +import Testing + +@Suite("Exact component snapshots", .serialized) +struct SnapshotTests { + @Test func failedGitComponentKeepsTypedFailureAndDeclarationLocation() throws { + let fixture = try LinkFixture() + let missing = fixture.root.appendingPathComponent("missing.git") + let source = "file://localhost" + missing.path + let expression = """ + version: 1 + sources: {producer: {url: "\(source)"}} + groups: + selected: + components: + - {kind: skills, source: producer, select: all} + uses: [{group: selected}] + """ + let before = try FileHash.folderHash(fixture.root) + do { + _ = try fixture.link(expression) + Issue.record("Missing Git source was admitted") + } catch let error as GitError { + #expect(error.operation == .clone) + #expect(error.source == source) + #expect(error.command.contains("clone")) + #expect(error.exitCode != 0) + #expect(error.stderr.contains("fatal:")) + #expect( + error.context.map(\.document.rawValue) == ["consumer/agents.yaml", "consumer/agents.yaml"]) + #expect(error.context.map(\.line) == [7, 6]) + #expect(error.context.allSatisfy { $0.start < $0.end && $0.column > 0 }) + #expect(!error.description.contains(fixture.store.cacheDirectory.path)) + #expect(!error.description.contains(".staging-")) + #expect(!error.description.contains("agents-linking-")) + #expect(error.description.contains("consumer/agents.yaml:6:")) + } catch { + Issue.record("Git failure lost its type: \(type(of: error))") + } + #expect(try FileHash.folderHash(fixture.root) == before) + } + + @Test func localDirectoryBeneathRepositoryKeepsItsOwnContent() throws { + let fixture = try LinkFixture() + try fixture.initialize(fixture.project) + try fixture.write("Parent repository", to: "README.md", base: fixture.project) + try fixture.commit(fixture.project) + let content = fixture.project.appendingPathComponent("content") + try fixture.skill("demo", at: content) + let source = SourceDeclaration(kind: .local, location: "./content") + let before = try FileHash.folderHash(fixture.project) + try SourceResolutionSession.withTemporaryRead(store: fixture.store) { session in + #expect(try !session.isGitSource(source)) + let view = try session.localSnapshot(source) + #expect(view.pin == nil) + #expect(try SkillSnapshotReader.read(view).map(\.name) == ["demo"]) + } + let graph = try fixture.link( + """ + version: 1 + sources: {local: {path: ./content}} + components: [{kind: skills, source: local, select: all}] + """) + #expect(graph.components.map(\.key.name) == ["demo"]) + #expect(try FileHash.folderHash(fixture.project) == before) + #expect(!FileManager.default.fileExists(atPath: fixture.store.cacheDirectory.path)) + } + + @Test(arguments: ["repository", "worktree", "bare"]) + func localRepositoryKindsPreserveExplicitDiscoveryRoot(_ kind: String) throws { + let fixture = try LinkFixture() + let repository = fixture.root.appendingPathComponent("repository") + try fixture.initialize(repository) + try fixture.skill("selected", at: repository.appendingPathComponent("packages/content")) + try fixture.skill("root-only", at: repository) + let revision = try fixture.commit(repository) + let location: URL + switch kind { + case "worktree": + location = fixture.root.appendingPathComponent("worktree") + try fixture.git(repository, ["worktree", "add", "--detach", location.path]) + case "bare": + location = fixture.root.appendingPathComponent("bare") + try fixture.git( + repository, ["clone", "--bare", "--no-local", repository.path, location.path]) + try fixture.git(location, ["config", "maintenance.auto", "false"]) + try fixture.git(location, ["config", "gc.auto", "0"]) + default: location = repository + } + let source = SourceDeclaration( + kind: .local, location: location.path, path: "packages/content") + var borrowed: URL? + try SourceResolutionSession.withTemporaryRead(store: fixture.store) { session in + #expect(try session.isGitSource(source)) + if kind == "bare" { + #expect( + try !session.isGitSource( + SourceDeclaration( + kind: .local, location: location.appendingPathComponent("objects").path))) + } + let pin = try #require(session.candidates(for: source, requirements: [nil]).first) + #expect(pin.revision == revision) + let view = try session.snapshot(source, at: pin) + borrowed = view.root + #expect(try SkillSnapshotReader.read(view).map(\.name) == ["selected"]) + } + #expect(!FileManager.default.fileExists(atPath: try #require(borrowed).path)) + #expect(!FileManager.default.fileExists(atPath: fixture.store.cacheDirectory.path)) + } + + @Test func frozenCatalogAndScopedLifetime() throws { + let fixture = try LinkFixture() + let repository = fixture.root.appendingPathComponent("repository") + try fixture.initialize(repository) + try fixture.skill("one", at: repository) + let first = try fixture.commit(repository, tag: "1.0.0") + let source = SourceDeclaration(kind: .local, location: repository.path) + var borrowed: URL? + try SourceResolutionSession.withTemporaryRead(store: fixture.store) { session in + let candidates = try session.candidates(for: source, requirements: [nil]) + #expect(candidates.first?.revision == first) + try fixture.skill("two", at: repository) + try fixture.commit(repository, tag: "1.1.0") + #expect(try session.candidates(for: source, requirements: [nil]) == candidates) + let snapshot = try session.snapshot(source, at: candidates[0]) + var otherHome = source + otherHome.environment = SourceEnvironment( + projectDirectory: fixture.project, + homeDirectory: fixture.root.appendingPathComponent("other-home")) + let otherView = try session.snapshot(otherHome, at: candidates[0]) + #expect(otherView.localEnvironment?.homeDirectory == otherHome.environment?.homeDirectory) + #expect(otherView.localEnvironment?.projectDirectory.path == repository.path) + borrowed = snapshot.root + #expect(try SkillSnapshotReader.read(snapshot).map(\.name) == ["one"]) + #expect(!FileManager.default.fileExists(atPath: fixture.store.cacheDirectory.path)) + } + #expect(!FileManager.default.fileExists(atPath: try #require(borrowed).path)) + } + + @Test func cachedExactPinAndErrorCleanup() throws { + let fixture = try LinkFixture() + let repository = fixture.root.appendingPathComponent("repository") + try fixture.initialize(repository) + try fixture.skill("one", at: repository) + let pin = try fixture.commit(repository) + let source = SourceDeclaration( + kind: .local, location: repository.path, requirement: .revision(pin)) + let cache = SourceCache(store: fixture.store) + _ = try cache.resolve(source) + let before = try FileHash.folderHash(fixture.store.cacheDirectory) + try FileManager.default.removeItem(at: repository) + var borrowed: URL? + enum Stop: Error { case reading } + #expect(throws: Stop.self) { + try SourceResolutionSession.withTemporaryRead(store: fixture.store) { session in + #expect( + try session.candidates(for: source, requirements: [source.requirement]).first?.revision + == pin) + let snapshot = try session.snapshot(source, at: SourceRevision(revision: pin)) + #expect(snapshot.localEnvironment?.projectDirectory.path == repository.path) + #expect(snapshot.liveRoot == nil) + borrowed = snapshot.root + #expect(try SkillSnapshotReader.read(snapshot).first?.name == "one") + throw Stop.reading + } + } + #expect(!FileManager.default.fileExists(atPath: try #require(borrowed).path)) + #expect(try FileHash.folderHash(fixture.store.cacheDirectory) == before) + } + + @Test func remoteContainedSkillsRejectEditAndEscapingLinks() throws { + let fixture = try LinkFixture() + let repository = fixture.root.appendingPathComponent("repository") + try fixture.initialize(repository) + try fixture.skill("one", at: repository) + try fixture.manifest( + """ + version: 1 + exports: ["tools"] + groups: {"tools": {"components": [{"kind": "skills", "source": ".", "mode": "edit"}]}} + """, at: repository) + try fixture.commit(repository) + do { + _ = try fixture.link( + """ + version: 1 + sources: {"p": {"url": "file://localhost\(repository.path)"}} + uses: [{"source": "p", "group": "tools"}] + """) + Issue.record("expected immutable edit rejection") + } catch LinkError.invalid(_, let positions) { + #expect(!positions.isEmpty) + } + let outside = fixture.root.appendingPathComponent("outside") + try fixture.write("outside", to: "outside") + try FileManager.default.createSymbolicLink( + at: repository.appendingPathComponent("escape"), withDestinationURL: outside) + try fixture.commit(repository) + #expect(throws: (any Error).self) { + try fixture.link( + """ + version: 1 + sources: {"p": {"url": "file://localhost\(repository.path)"}} + uses: [{"source": "p", "group": "tools"}] + """) + } + } + + @Test func remoteProducerLocalAliasesRemainImmutableAndContained() throws { + let fixture = try LinkFixture() + let repository = fixture.root.appendingPathComponent("remote") + try fixture.initialize(repository) + try fixture.manifest( + "version: 1\nexports: [\"leaf\"]\ngroups: {\"leaf\": {\"components\": [{\"kind\": \"mcpServer\", \"name\": \"leaf\", \"transport\": {\"kind\": \"stdio\", \"executable\": \"never-run\"}}]}}\n", + at: repository.appendingPathComponent("child")) + func producer(path: String, requirement: String = "") throws { + try fixture.manifest( + """ + version: 1 + exports: [g] + sources: {child: {path: "\(path)"\(requirement)}} + groups: {g: {uses: [{group: leaf, source: child}]}} + """, at: repository) + try fixture.commit(repository) + } + let expression = + "version: 1\nsources: {\"p\": {\"url\": \"file://localhost\(repository.path)\"}}\nuses: [{\"source\": \"p\", \"group\": \"g\"}]\n" + try producer(path: "child") + let graph = try fixture.link(expression) + #expect(graph.components.first?.key.name == "leaf") + #expect(graph.components.first?.snapshot.source.contains(":contained:") == true) + #expect(graph.references[0].snapshot.revision == graph.references[1].snapshot.revision) + for path in ["../outside", fixture.project.path, "~/outside"] { + try producer(path: path) + #expect(throws: (any Error).self) { try fixture.link(expression) } + } + try producer(path: "child", requirement: ", requirement: {exact: \"1.0.0\"}") + #expect(throws: LinkError.self) { try fixture.link(expression) } + try FileManager.default.createSymbolicLink( + at: repository.appendingPathComponent("escape"), withDestinationURL: fixture.project) + try producer(path: "escape") + #expect(throws: (any Error).self) { try fixture.link(expression) } + } +} + +extension SnapshotTests { + @Test func cancellationCleansOwnedSnapshots() async throws { + let fixture = try LinkFixture() + let repository = fixture.root.appendingPathComponent("repository") + try fixture.skill("one", at: repository) + let store = fixture.store + let source = SourceDeclaration(kind: .local, location: repository.path) + let task = Task.detached { () throws -> URL in + var path: URL? + do { + try SourceResolutionSession.withTemporaryRead(store: store) { session in + path = try session.localSnapshot(source).root + withUnsafeCurrentTask { $0?.cancel() } + } + } catch is CancellationError { + return path! + } + throw CoreError.invalidState("expected cooperative cancellation") + } + let borrowed = try await task.value + #expect(!FileManager.default.fileExists(atPath: borrowed.path)) + #expect(!FileManager.default.fileExists(atPath: fixture.store.cacheDirectory.path)) + } + + @Test func namespacesShareVersionWithoutSharingMembers() throws { + let fixture = try LinkFixture() + let repository = fixture.root.appendingPathComponent("repository") + try fixture.initialize(repository) + for name in ["a", "b"] { + let directory = repository.appendingPathComponent(name) + try fixture.manifest( + "version: 1\nexports: [\"tools\"]\ngroups: {\"tools\": {\"components\": [{\"kind\": \"mcpServer\", \"name\": \"\(name)\", \"transport\": {\"kind\": \"stdio\", \"executable\": \"never-run\"}}]}}\n", + at: directory) + } + let commit = try fixture.commit(repository) + var sources: [String] = [] + for name in ["a", "b"] { + let producer = fixture.root.appendingPathComponent("producer-" + name) + try fixture.manifest( + """ + version: 1 + exports: ["tools"] + sources: {"s": {"url": "file://localhost\(repository.path)", "subpath": "\(name)"}} + groups: {"tools": {"uses": [{"source": "s", "group": "tools"}]}} + """, at: producer) + sources.append("\"\(name)\": {\"path\": \"\(producer.path)\"}") + } + let graph = try fixture.link( + "version: 1\nsources: {\(sources.joined(separator: ","))}\nuses: [{\"source\": \"a\", \"group\": \"tools\"}, {\"source\": \"b\", \"group\": \"tools\"}]\n" + ) + #expect(graph.components.map(\.key.name) == ["a", "b"]) + #expect(graph.components.map(\.key.root) == ["a", "b"]) + #expect(graph.components.allSatisfy { $0.snapshot.revision == commit }) + #expect(graph.selections.count == 1) + } +} + +extension SnapshotTests { + @Test func branchRevisionAndVersionConstraintsUseOneAllowedTag() throws { + let fixture = try LinkFixture() + let repository = fixture.root.appendingPathComponent("repository") + try fixture.initialize(repository) + try fixture.write("one", to: "file", base: repository) + let first = try fixture.commit(repository) + try fixture.git(repository, ["tag", "-a", "1.0.0+first", "-m", "tag"]) + try fixture.git(repository, ["tag", "1.0.0+second"]) + let source = SourceDeclaration(kind: .local, location: repository.path) + try SourceResolutionSession.withTemporaryRead(store: fixture.store) { session in + let mixed: [SourceRequirement?] = [ + .branch("main"), .revision("refs/tags/1.0.0+first"), .upToNextMajor(from: "1.0.0"), + ] + #expect(try session.candidates(for: source, requirements: mixed).first?.revision == first) + #expect( + try session.candidates(for: source, requirements: mixed).first?.version == "1.0.0+second") + #expect( + try session.candidates( + for: source, requirements: [.exact("1.0.0+first"), .exact("1.0.0+second")] + ).isEmpty) + try fixture.write("two", to: "file", base: repository) + try fixture.commit(repository) + // Branch evidence remains fixed after the source advances. + #expect(try session.candidates(for: source, requirements: mixed).first?.revision == first) + } + try SourceResolutionSession.withTemporaryRead(store: fixture.store) { session throws -> Void in + #expect( + try session.candidates( + for: source, + requirements: [.branch("main"), .revision(first), .upToNextMajor(from: "1.0.0")] + ).isEmpty) + } + } +} + +extension SnapshotTests { + @Test func missingPersistentMirrorLockIsNotRecreated() throws { + let fixture = try LinkFixture() + let repository = fixture.root.appendingPathComponent("repository") + try fixture.initialize(repository) + try fixture.skill("one", at: repository) + let pin = try fixture.commit(repository) + let source = SourceDeclaration( + kind: .local, location: repository.path, requirement: .revision(pin)) + let cache = SourceCache(store: fixture.store) + _ = try cache.resolve(source) + let locks = fixture.store.cacheDirectory.appendingPathComponent("locks") + for lock in try FileManager.default.contentsOfDirectory( + at: locks, includingPropertiesForKeys: nil) + { + try FileManager.default.removeItem(at: lock) + } + let before = try FileHash.folderHash(fixture.store.cacheDirectory) + try SourceResolutionSession.withTemporaryRead(store: fixture.store) { session in + let view = try session.snapshot(source, at: SourceRevision(revision: pin)) + #expect(try SkillSnapshotReader.read(view).map(\.name) == ["one"]) + } + #expect(try FileHash.folderHash(fixture.store.cacheDirectory) == before) + #expect(try FileManager.default.contentsOfDirectory(atPath: locks.path).isEmpty) + } + + @Test func resourceEvidenceRemainsReadableOnlyDuringSession() throws { + let fixture = try LinkFixture() + let repository = fixture.root.appendingPathComponent("repository") + try fixture.initialize(repository) + try fixture.write("Prompt bytes", to: "prompts/review.md", base: repository) + try fixture.manifest( + """ + version: 1 + exports: ["tools"] + groups: {"tools": {"components": [{"kind": "command", "name": "review", "description": "Review", "prompt": {"file": {"path": "prompts/review.md"}}}]}} + """, at: repository) + let pin = try fixture.commit(repository, tag: "1.0.0") + let document = try fixture.document( + "version: 1\nsources: {\"p\": {\"path\": \"\(repository.path)\"}}\nuses: [{\"source\": \"p\", \"group\": \"tools\"}]\n" + ) + var borrowed: URL? + let graph = try ComponentLinker.withLinkedComponents( + document: document, store: fixture.store, platform: .macOS + ) { graph, session in + let resource = try #require(graph.components.first?.resources.first) + let path = try session.resource(snapshot: resource.snapshot, path: resource.path) + borrowed = path + #expect(try String(contentsOf: path, encoding: .utf8) == "Prompt bytes") + #expect(graph.components.first?.pin?.revision == pin) + #expect(graph.components.first?.pin?.version == "1.0.0") + #expect( + graph.sourceSnapshots.contains { + $0.snapshot == resource.snapshot && $0.source?.kind == .local + }) + return graph + } + #expect(!graph.sourceSnapshots.isEmpty) + #expect(!FileManager.default.fileExists(atPath: try #require(borrowed).path)) + } +} + +extension SnapshotTests { + @Test func ownPackageSkillsUseCommittedContentAndLiveEdit() throws { + let fixture = try LinkFixture() + try fixture.initialize(fixture.project) + try fixture.skill("one", at: fixture.project) + let pin = try fixture.commit(fixture.project) + try fixture.skill("two", at: fixture.project) + let linked = try fixture.link( + "version: 1\ncomponents: [{\"kind\": \"skills\", \"source\": \".\"}]\n") + #expect(linked.components.map(\.key.name) == ["one"]) + #expect(linked.components[0].pin?.revision == pin) + let edited = try fixture.link( + "version: 1\ncomponents: [{\"kind\": \"skills\", \"source\": \".\", \"mode\": \"edit\"}]\n") + #expect(edited.components.map(\.key.name) == ["one", "two"]) + for component in edited.components { + guard case .skill(let skill, .edit, _) = component.payload else { + Issue.record("expected edit") + continue + } + #expect(skill.livePath?.hasPrefix(fixture.project.path) == true) + } + } +} diff --git a/Tests/ComponentsTests/SourceCatalogTests.swift b/Tests/ComponentsTests/SourceCatalogTests.swift new file mode 100644 index 0000000..58f282e --- /dev/null +++ b/Tests/ComponentsTests/SourceCatalogTests.swift @@ -0,0 +1,253 @@ +import AgentsCore +import AgentsManifest +import Foundation +import Testing + +@testable import Components + +@Suite("Explicit source catalogs", .serialized) +struct SourceCatalogTests { + private func inspect( + _ fixture: LinkFixture, path: String = ".", importing document: SourceCatalogImport? = nil + ) throws -> Components.SourceCatalog { + try Components.SourceCatalog.inspect( + alias: "producer", source: .init(kind: .local, location: fixture.project.path, path: path), + store: fixture.store, platform: .macOS, importing: document) + } + + @Test func directMembersAndSymbolicGroupsHaveCompleteCapturedEffects() throws { + let fixture = try LinkFixture() + try fixture.skill("demo", at: fixture.project, restrictions: "agents: [codex]\n") + try fixture.instruction("rules", at: fixture.project, own: false) + try fixture.manifest( + """ + version: 1 + exports: [outer, empty] + groups: + outer: + components: + - {kind: command, name: review, description: Review, prompt: Exact, agents: [codex]} + uses: [{group: inner}, {group: inner}] + inner: + components: + - {kind: mcpServer, name: safe, transport: {kind: stdio, executable: fixture-server}, agents: [codex]} + empty: {} + """, at: fixture.project) + let before = try FileHash.folderHash(fixture.root) + let catalog = try inspect(fixture) + #expect(catalog.choices.count == 4) + let skill = try #require( + catalog.choices.first { + if case .skill = $0.unit { return true } + return false + }) + #expect(skill.graph?.components.first?.recipients == [.codex]) + let group = try #require( + catalog.choices.first { + if case .group(let use) = $0.unit { return use.name == "outer" && use.source == "producer" } + return false + }) + #expect(group.unavailableReason == nil) + #expect(group.graph?.references.count == 3) + #expect(group.graph?.components.flatMap(\.origins).count == 3) + #expect( + group.graph?.components.allSatisfy { $0.origins.allSatisfy { !$0.consumerEditable } } == true) + let empty = try #require( + catalog.choices.first { + if case .group(let use) = $0.unit { return use.name == "empty" } + return false + }) + #expect(empty.graph?.components.isEmpty == true) + #expect(empty.graph?.references.count == 1) + #expect(try catalog.selected([]) == nil) + #expect(try FileHash.folderHash(fixture.root) == before) + #expect(!String(reflecting: catalog).contains("agents-resolution-")) + let other = try inspect(fixture) + #expect(throws: (any Error).self) { try other.selected([group.id]) } + #expect(throws: (any Error).self) { try catalog.selected([group.id, group.id]) } + #expect(try catalog.selected([group.id])?.count == 1) + } + + @Test func pluginStrategiesAndTypedMemberExclusionsRemainExplicit() throws { + let fixture = try LinkFixture() + try fixture.write( + #"{"name":"upstream"}"#, to: "bundle/.claude-plugin/plugin.json", base: fixture.project) + for name in ["one", "two"] { + try fixture.write( + "---\ndescription: Review\n---\nExact body\n", to: "bundle/commands/\(name).md", + base: fixture.project) + } + for (path, name) in [("first", "cafe\u{301}"), ("second", "caf\u{e9}")] { + try fixture.write( + "---\nname: \(name)\ndescription: Agent\n---\nBody\n", + to: "bundle/agents/\(path).md", base: fixture.project) + } + let before = try FileHash.folderHash(fixture.root) + let catalog = try inspect(fixture, path: "bundle") + #expect(catalog.choices.count == 6) + for choice in catalog.choices { + switch choice.unit { + case .nativePlugin(let declaration): + let metadata = try SourceImport.preview( + .init( + profile: .claudePluginV1, root: fixture.project, + document: "bundle/.claude-plugin/plugin.json") + ).packageMetadata + if let metadata { + guard case .plugin(let name, _, _, _, _, _, _, _, _) = declaration else { + Issue.record("wrong native unit") + continue + } + #expect(name.utf8.elementsEqual(metadata.name.utf8)) + #expect(choice.origin == metadata.nameLocation) + #expect(choice.unavailableReason == nil) + #expect(try catalog.selected([choice.id])?.count == 1) + } else { + #expect(choice.unavailableReason?.contains("adapter-issued container name") == true) + #expect(throws: (any Error).self) { try catalog.selected([choice.id]) } + } + guard + case .plugin(_, _, _, let mode, let select, let exclude, let agents, _, _) = declaration + else { + Issue.record("wrong native unit") + continue + } + #expect(mode == .native && select == nil && exclude.isEmpty && agents == [.claudeCode]) + #expect(choice.graph?.components.count == 1) + case .componentsPlugin(let declaration): + guard case .plugin(_, _, _, let mode, let select, let exclude, _, _, _) = declaration + else { + Issue.record("wrong components container") + continue + } + #expect(mode == .components && select == nil && exclude.isEmpty) + #expect( + choice.graph?.components.filter { $0.key.kind == .command }.count == 2 + && choice.graph?.components.filter { $0.key.kind == .subagent }.count == 2) + case .pluginMember(let declaration, _): + guard case .plugin(_, _, _, let mode, let select, let exclude, _, _, _) = declaration + else { + Issue.record("wrong components unit") + continue + } + #expect( + mode == .components && [.command, .subagent].contains(select?.first) && exclude.count == 1 + ) + #expect(choice.graph?.components.filter { $0.key.kind != .plugin }.count == 1) + default: Issue.record("unexpected source choice") + } + } + #expect(try FileHash.folderHash(fixture.root) == before) + #expect(!String(reflecting: catalog).contains("agents-resolution-")) + } + + @Test func importerKeysKeepAllFamiliesFixedEffectsAndProducerClaimsSeparate() throws { + let fixture = try LinkFixture() + try fixture.write( + #"{"mcp":{"servers":{"same":{"type":"local","command":["fixture-server"]}}},"commands":{"same":{"description":"Review","template":"Body"}},"agents":{"same":{"description":"Help","system":"Body","mode":"subagent"}},"lsp":{"fixed":{"command":["fixture-lsp"],"extensions":[".fixture"]}}}"#, + to: "opencode.json", base: fixture.project) + let before = try FileHash.folderHash(fixture.root) + let catalog = try inspect( + fixture, + importing: .init(profile: .openCodeConfigV2, document: "opencode.json", selection: [])) + #expect(catalog.choices.count == 1) + let choice = try #require(catalog.choices.first) + guard case .importer(let metadata) = choice.unit else { + Issue.record("not an importer key") + return + } + #expect(metadata.key == "same") + #expect( + Set(choice.imported!.components.map(\.declaration.kind)) == [.mcpServer, .command, .subagent]) + #expect(catalog.fixedEffects?.components.contains { $0.declaration.kind == .lspServer } == true) + #expect(catalog.importDocument?.selection == []) + #expect(!String(reflecting: catalog).contains("agents-resolution-")) + #expect(try FileHash.folderHash(fixture.root) == before) + } + + @Test func unavailableClosureRemainsVisibleAndEmptySourceDoesNotAddAnything() throws { + let fixture = try LinkFixture() + #expect(try inspect(fixture).selected([]) == nil) + try fixture.manifest( + "version: 1\nsources: {absent: {path: ../missing}}\nexports: [broken]\ngroups: {broken: {uses: [{group: missing, source: absent}]}}", + at: fixture.project) + let catalog = try inspect(fixture) + #expect(catalog.choices.count == 1) + #expect(catalog.choices[0].graph == nil) + #expect(catalog.choices[0].unavailableReason != nil) + } + @Test func emptyPluginStillOffersExplicitStrategiesAndSnapshotEvidence() throws { + let fixture = try LinkFixture() + try fixture.write( + #"{"name":"empty"}"#, to: ".claude-plugin/plugin.json", base: fixture.project) + let catalog = try inspect(fixture) + #expect(catalog.choices.count == 2) + let expanded = try #require( + catalog.choices.first { + if case .componentsPlugin = $0.unit { return true } + return false + }) + #expect(expanded.unavailableReason == nil) + #expect(expanded.graph?.components.count == 1) + #expect(expanded.graph?.components[0].origins[0].pluginExpansion?.children == []) + #expect(expanded.graph?.sourceSnapshots.contains { $0.snapshot == catalog.snapshot } == true) + } + + @Test func gitCatalogUsesSelectedCommitAndChangesItsContentEvidence() throws { + let fixture = try LinkFixture() + try fixture.initialize(fixture.project) + try fixture.skill("committed", at: fixture.project) + let first = try fixture.commit(fixture.project) + try fixture.skill("dirty", at: fixture.project) + let catalog = try inspect(fixture) + #expect(catalog.snapshot.revision == first) + #expect(catalog.choices.count == 1) + #expect(catalog.choices[0].unavailableReason == nil) + _ = try fixture.commit(fixture.project) + let next = try inspect(fixture) + #expect(next.choices.count == 2) + #expect(next.contentHash != catalog.contentHash) + #expect(!String(reflecting: next).contains("agents-resolution-")) + #expect(!FileManager.default.fileExists(atPath: fixture.store.cacheDirectory.path)) + } + + @Test func importedLocalCoordinatesStayRelativeToCapturedSource() throws { + let fixture = try LinkFixture() + try fixture.skill("local", at: fixture.project.appendingPathComponent("content")) + try fixture.write( + "name: package\nversion: '1.0.0'\ndependencies:\n apm:\n - path: content\n", + to: "apm.yml", base: fixture.project) + let catalog = try inspect( + fixture, importing: .init(profile: .apmManifest, document: "apm.yml")) + let choice = try #require(catalog.choices.first) + let source = try #require(choice.imported?.sources.first) + #expect(source.declaration?.location == "content") + #expect(source.declaration?.environment == nil) + #expect(!String(reflecting: catalog).contains("agents-resolution-")) + } + + @Test func nativeRegistrationUsesAdapterIssuedName() throws { + let fixture = try LinkFixture() + try fixture.write( + #"{"name":"actual-producer","version":"1.0.0"}"#, + to: "gemini-extension.json", base: fixture.project) + let catalog = try inspect(fixture) + let choice = try #require( + catalog.choices.first { + if case .nativePlugin = $0.unit { return true } + return false + }) + guard + case .nativePlugin( + .plugin(let name, _, let source, let mode, let select, let exclude, let agents, _, _)) = + choice.unit + else { + Issue.record("missing native declaration") + return + } + #expect(name == "actual-producer" && source == "producer") + #expect(mode == .native && select == nil && exclude.isEmpty && agents == [.geminiCLI]) + #expect(choice.unavailableReason == nil) + } + +} diff --git a/Tests/ComponentsTests/UserScopeTests.swift b/Tests/ComponentsTests/UserScopeTests.swift new file mode 100644 index 0000000..a199bfc --- /dev/null +++ b/Tests/ComponentsTests/UserScopeTests.swift @@ -0,0 +1,153 @@ +import AgentsCore +import Components +import Foundation +import Testing + +@Suite("User package linking", .serialized) +struct UserScopeTests { + @Test func packageResourcesAndSelfSkillsUseStateRootWithStableProvenance() throws { + let fixture = try LinkFixture() + let store = StateStore(scope: .user, environment: fixture.environment) + for (directory, value) in [ + (fixture.project, "project shadow"), (fixture.home, "home shadow"), + (store.directory, "package content"), + ] { + try fixture.write(value, to: "prompt.md", base: directory) + try fixture.write(value, to: "tools/run", base: directory) + try fixture.skill(value.replacingOccurrences(of: " ", with: "-"), at: directory) + } + let document = try fixture.document( + """ + version: 1 + defaultAgents: ["codex"] + components: [{"kind": "command", "name": "review", "description": "Review", "prompt": {"file": {"path": "prompt.md"}}}, {"kind": "hook", "name": "run", "event": "afterTool", "run": {"executable": "tools/run"}}, {"kind": "skills", "source": ".", "mode": "edit"}] + """) + func link() throws -> LinkedComponents { + try ComponentLinker.withLinkedComponents(document: document, store: store, platform: .macOS) { + graph, session in + #expect(graph.components.map(\.key.name) == ["review", "run", "package-content"]) + for component in graph.components { + #expect(component.recipients == [.codex]) + let provenance = try #require(component.origins.first?.provenance) + #expect(provenance.sourceIdentity == "local:" + store.directory.path) + #expect(provenance.relativePath == "agents.yaml") + } + for component in graph.components.prefix(2) { + let resource = try #require(component.resources.first) + let file = try session.resource(snapshot: resource.snapshot, path: resource.path) + #expect(try String(contentsOf: file, encoding: .utf8) == "package content") + #expect(resource.snapshot.source == "local:" + store.directory.path) + } + guard case .skill(let skill, .edit, _) = graph.components[2].payload else { + Issue.record("expected live self-package skill") + return graph + } + #expect( + skill.livePath == store.directory.appendingPathComponent("skills/package-content").path) + return graph + } + } + #expect(try link() == link()) + } + + @Test func namedSourcesKeepDeclaringEnvironmentAndPromptAppendUsesHome() throws { + let fixture = try LinkFixture() + let store = StateStore(scope: .user, environment: fixture.environment) + let source = fixture.project.appendingPathComponent("rules") + try fixture.initialize(source) + try fixture.instruction("rules", at: source, own: false, restrictions: "scopes: [\"user\"]\n") + try fixture.commit(source) + for directory in [fixture.home, store.directory] { + try fixture.instruction("shadow", at: directory.appendingPathComponent("rules"), own: false) + } + for (directory, value) in [ + (fixture.project, "project append shadow"), (store.directory, "package append shadow"), + (fixture.home, "home append"), + ] { + try fixture.write(value, to: "append.md", base: directory) + } + let document = try fixture.document( + """ + version: 1 + sources: {"rules": {"path": "rules"}} + components: [{"kind": "instructions", "sections": [{"name": "rules", "source": "rules"}], "chatgpt": {"p": {"sections": [{"name": "rules", "source": "rules"}], "append": "append.md"}}}] + """) + try ComponentLinker.withLinkedComponents(document: document, store: store, platform: .macOS) { + graph, _ in + #expect(graph.components.map(\.key.name) == ["rules", "rules"]) + #expect(graph.components[0].snapshot.source == "local:" + source.path) + #expect(graph.components[1].chatGPT) + #expect(graph.components[1].resources.count == 1) + let append = try #require(graph.components[1].localAppend) + #expect(append == LedgerLocation(kind: .registered, root: "home", path: "append.md")) + #expect( + try append.readContainedFile(roots: ["home": fixture.home]) == Data("home append".utf8)) + #expect( + !graph.components[1].origins[0].dependencies.contains { + $0.source == "local:" + fixture.home.path + }) + #expect(graph.components[1].origins[0].provenance.relativePath == "agents.yaml") + } + } + + @Test func rootOwnSectionsRequireNamedSourcesAndProducerOwnSectionsRemainValid() throws { + let fixture = try LinkFixture() + let store = StateStore(scope: .user, environment: fixture.environment) + for directory in [fixture.project, fixture.home, store.directory] { + try fixture.instruction("rules", at: directory) + } + for section in ["{name: rules}", "{\"name\": \"rules\", \"source\": \".\"}"] { + for selection in [ + "{\"kind\": \"instructions\", \"sections\": [\(section)]}", + "{\"kind\": \"instructions\", \"chatgpt\": {\"p\": {\"sections\": [\(section)]}}}", + ] { + do { + _ = try ComponentLinker.withLinkedComponents( + document: fixture.document("version: 1\ncomponents: [\(selection)]\n"), + store: store, platform: .macOS + ) { _, _ in Issue.record("expected named-source requirement") } + } catch LinkError.invalid(let message, let spans) { + #expect(message == "root user instructions require a named source") + #expect(!spans.isEmpty) + } + } + } + let producer = fixture.project.appendingPathComponent("producer") + try fixture.initialize(producer) + try fixture.instruction("producer", at: producer) + try fixture.write("producer append", to: "append.md", base: producer) + try fixture.write("package append shadow", to: "append.md", base: store.directory) + try fixture.write("home append", to: "append.md", base: fixture.home) + try fixture.manifest( + """ + version: 1 + defaultAgents: ["claude-code"] + exports: ["g"] + groups: {"g": {"components": [{"kind": "instructions", "sections": [{"name": "producer"}], "chatgpt": {"p": {"sections": [{"name": "producer"}], "append": "append.md"}}}]}} + """, at: producer) + let pin = try fixture.commit(producer) + try ComponentLinker.withLinkedComponents( + document: fixture.document( + "version: 1\nsources: {\"p\": {\"path\": \"producer\"}}\nuses: [{\"source\": \"p\", \"group\": \"g\"}]\n" + ), store: store, platform: .macOS + ) { graph, session in + let component = try #require(graph.components.first) + #expect(component.key.name == "producer") + #expect(component.snapshot.revision == pin) + #expect(component.recipients == [.claudeCode]) + #expect(component.origins[0].provenance.sourceIdentity == "local:" + producer.path) + #expect(component.origins[0].provenance.relativePath == ".agent/agents.yaml") + #expect(!component.origins[0].consumerEditable) + let prompt = try #require(graph.components.last) + #expect(prompt.chatGPT) + #expect(prompt.snapshot == component.snapshot) + #expect(prompt.origins[0].provenance == component.origins[0].provenance) + let append = try #require(prompt.resources.last) + let file = try session.resource(snapshot: append.snapshot, path: append.path) + #expect(try String(contentsOf: file, encoding: .utf8) == "producer append") + #expect(append.snapshot.source == "local:" + producer.path) + #expect(append.snapshot.revision == pin) + #expect(prompt.localAppend == nil) + } + } +} diff --git a/Tests/Documentation/PortableBundles.md b/Tests/Documentation/PortableBundles.md new file mode 100644 index 0000000..b7abd27 --- /dev/null +++ b/Tests/Documentation/PortableBundles.md @@ -0,0 +1,114 @@ +# Portable bundle fixtures for AgentsUpdates + +The behavioral reference is the public APM pack and preview documentation +as published on 2026-11-25. The fixtures exercise a target-independent +selection, locked bytes with per-file integrity, and consumer-side preview +before applying. The Swift API and `agents.bundle` version 1 encoding are +defined here. [APM pack][pack] · [APM preview][preview] + +## Public Swift API + +Import `AgentsCore` and `AgentsUpdates`. Build the export selection from +`UpdateOperations.inspect(scope:environment:).components`. Use an +occurrence selection for an ambiguous component identity. Export retains +instruction order from the lock. A named ChatGPT prompt is outside the +instruction-section selection. + +```swift +public struct BundlePackage { + public init(name: String, version: String) +} + +public struct BundleImportSelection { + public init(componentID: String, targets: [AgentID]) +} + +public enum BundleOperations { + public static func export( + _ package: BundlePackage, selections: [ComponentSelection], + scope: InstallScope, environment: RuntimeEnvironment + ) throws -> Data + + public static func inspect(_ archive: Data) throws -> BundleInspection + + public static func previewImport( + _ bundle: BundleInspection, selections: [BundleImportSelection], + scope: InstallScope, environment: RuntimeEnvironment, replace: Bool = false + ) throws -> BundleImportPreview + + public static func withPreparedImport( + _ preview: BundleImportPreview, bindingProvider: (any RuntimeBindingProvider)? = nil, + _ body: (PreparedUpdate) throws -> Result + ) throws -> Result +} +``` + +`BundleInspection` exposes the package coordinates, format version, exact +archive digest, and component inventory. Each component provides its ID, +kind, name, source evidence, tree entries and, for MCP, symbolic +configuration. A marketplace can publish the exported bytes keyed by +package name and version and compare the consumer's `archiveDigest` with the +catalog digest. Verification covers the bytes and recorded claims. Publisher +authentication uses the consumer's trust policy. + +Pass explicit component IDs and recipients to preview. The preview returns +the ordinary `CombinedUpdateReport` and an `ownershipConflict` when target +admission prevents publication. Conflicts that prevent native composition or +admission of the source tree surface as thrown errors. `replace: true` +authorizes ordinary instruction replacement. An unmanaged skill or native +key still uses the existing ownership checks. Select targets supported by +the component, scope and client adapter. + +After confirmation, call `withPreparedImport` and invoke `apply()` on the +provided `PreparedUpdate`. This compares the re-prepared report with the +displayed fingerprint under the writer lock. The generated producer trees, +deployment files, declaration and lock publish through the same transaction. +Use a binding provider when a client requires runtime materialization. Export +and preview preserve symbolic bindings and avoid starting components. + +## Archive v1 + +The archive is sorted-key UTF-8 JSON with unescaped slashes and a trailing +line feed. Its top-level keys are `format` (the string `agents.bundle`), +`version` (the integer `1`), `manifest`, `manifestDigest` and `contentObjects`. +Digest strings use lowercase hex prefixed by `sha256:`. `manifestDigest` +identifies the independently encoded canonical manifest. `contentObjects` +maps each file digest to its Base64 bytes. Files with identical bytes share +an object. + +The manifest contains `package` (`name` and `version`) and the ordered +`components` array. A component contains `kind` (`instructions`, `skills` or +`mcpServer`), `name`, `sources` and `entries`. It also contains either +`discovery`, the instruction or skill discovery root, or `configuration`, the +tagged MCP transport and native values. Environment and secret fields retain +their symbolic name. Resource-backed MCP commands and working directories +refer to contained member paths. Ordinary executable names, arguments and +transport values retain their authored strings. + +Source records contain the source `kind`, exact `revision` and, when +available, `version` and normalized transport `identity`. Local sources +omit absolute coordinates. An authored live input receives a content +revision. An export of an installed bundle carries forward its original +evidence. The update planner supplies these claims by linked snapshot in +`BundleSourceInputs.evidence`, alongside the destination preconditions. + +Each tree has a directory entry named `.`. Other entries belong under +`payload`. Entries describe a file, directory or relative symlink. File +entries carry the object digest, byte count and executable flag. Links +carry their relative spelling. The archive admits only portable, +noncolliding paths with directory ancestors and resolves each link inside +the payload before materializing the tree. Files materialize with mode +`0644` or `0755` according to the executable flag. Locked instructions +carry the input files recorded for their selected section. + +## Verification + +Run the `PortableBundleTests` Swift Testing suite with an isolated home. +The producer and consumer use different temporary projects and homes. +Fixtures verify locked instructions, nested binary and executable skill +files, empty directories, relative symlinks, and runtime-only MCP bindings. +They also exercise a changed content object, a resealed traversal, an +unmanaged destination, and a stale confirmation. + +[pack]: https://microsoft.github.io/apm/reference/cli/pack/ +[preview]: https://microsoft.github.io/apm/reference/cli/preview/ diff --git a/Tests/MCPTestProcess/main.swift b/Tests/MCPTestProcess/main.swift new file mode 100644 index 0000000..88b1729 --- /dev/null +++ b/Tests/MCPTestProcess/main.swift @@ -0,0 +1,227 @@ +import CPlatform +import Foundation + +#if os(Linux) + import Glibc +#else + import Darwin +#endif + +let arguments = CommandLine.arguments +let scenario = arguments.count > 1 ? arguments[1] : "normal" +let observation = URL(fileURLWithPath: arguments.count > 2 ? arguments[2] : "/tmp") +let root = + scenario == "managed" ? observation.appendingPathComponent(String(getpid())) : observation +if scenario == "managed" { + try? FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + try? Data().write(to: root.appendingPathComponent("ready")) + guard + (try? String( + contentsOfFile: FileManager.default.currentDirectoryPath + "/support", encoding: .utf8)) + == "fixed support" + else { exit(4) } + let deadline = Date().addingTimeInterval(3) + var paired = false + while Date() < deadline { + let ready = + (try? FileManager.default.contentsOfDirectory( + at: observation, includingPropertiesForKeys: nil)) ?? [] + if ready.filter({ + FileManager.default.fileExists(atPath: $0.appendingPathComponent("ready").path) + }).count == 2 { + paired = true + break + } + usleep(1000) + } + guard paired else { exit(3) } +} +func record(_ value: [String: Any]) { + guard let data = try? JSONSerialization.data(withJSONObject: value) else { return } + let file = root.appendingPathComponent("wire.jsonl") + if !FileManager.default.fileExists(atPath: file.path) { + _ = FileManager.default.createFile(atPath: file.path, contents: nil) + } + if let handle = try? FileHandle(forWritingTo: file) { + handle.seekToEndOfFile() + handle.write(data) + handle.write(Data([10])) + try? handle.close() + } +} +func output(_ data: Data, fd: Int32 = 1) { + var offset = 0 + while offset < data.count { + let size = data.withUnsafeBytes { + platform_duplex_write(fd, $0.baseAddress!.advanced(by: offset), data.count - offset) + } + if size <= 0 { exit(0) } + offset += size + } +} +func response(_ id: Any, _ result: [String: Any]) { + if let bytes = try? JSONSerialization.data(withJSONObject: [ + "jsonrpc": "2.0", "id": id, "result": result, + ]) { + output(bytes + Data([10])) + } +} +try? String(getpid()).write( + to: root.appendingPathComponent(scenario == "holder" ? "holder-pid" : "pid"), atomically: true, + encoding: .utf8) +if scenario == "holder" || scenario == "ignore-input" || scenario == "blocked-input" { + if scenario == "blocked-input" { alarm(10) } + _ = signal(SIGTERM, SIG_IGN) + try? "ready".write( + to: root.appendingPathComponent("holder-ready"), atomically: true, encoding: .utf8) + if scenario == "blocked-input" { + while true { + var descriptor = pollfd(fd: STDIN_FILENO, events: Int16(POLLIN), revents: 0) + if poll(&descriptor, 1, 100) > 0 && descriptor.revents & Int16(POLLIN) != 0 { + try? "ready".write( + to: root.appendingPathComponent("stdin-pending"), atomically: true, encoding: .utf8) + break + } + usleep(1000) + } + } + while true { _ = sleep(1) } +} +#if os(Linux) + if scenario == "thread-holder" { + alarm(10) + _ = signal(SIGTERM, SIG_IGN) + var worker: pthread_t = 0 + let created = pthread_create( + &worker, nil, + { @Sendable _ in + while true { _ = sleep(1) } + }, nil) + if created != 0 { exit(2) } + try "ready".write( + to: root.appendingPathComponent("holder-ready"), atomically: true, encoding: .utf8) + pthread_exit(nil) + } +#endif +if scenario == "descendant" || scenario == "thread-descendant" { + let childScenario = scenario == "descendant" ? "holder" : "thread-holder" + let childArguments = [arguments[0], childScenario, root.path(percentEncoded: false)] + let argv = childArguments.map { strdup($0) } + [nil] + let environment = + ProcessInfo.processInfo.environment.map { strdup($0.key + "=" + $0.value) } + [nil] + var pid: pid_t = 0 + if posix_spawn(&pid, arguments[0], nil, nil, argv, environment) != 0 { exit(2) } + for pointer in argv + environment { free(pointer) } + try? String(pid).write( + to: root.appendingPathComponent("descendant-pid"), atomically: true, encoding: .utf8) + var descendantReady = false + for _ in 0..<2000 { + if FileManager.default.fileExists(atPath: root.appendingPathComponent("holder-ready").path) { + descendantReady = true + break + } + usleep(1000) + } + if !descendantReady || getpgid(pid) != getpgrp() { exit(2) } + if scenario == "thread-descendant" { exit(0) } +} +let fd = Int32(ProcessInfo.processInfo.environment["FD_CHECK"] ?? "-1") ?? -1 +record([ + "startup": true, "cwd": FileManager.default.currentDirectoryPath, + "liveMarker": + (try? String( + contentsOfFile: FileManager.default.currentDirectoryPath + "/live-marker", encoding: .utf8)) + ?? "absent", + "environment": ProcessInfo.processInfo.environment["FIXTURE_VALUE"] ?? "absent", + "inheritedFD": fd >= 0 && fcntl(fd, F_GETFD) >= 0, +]) +var line = Data() +while true { + var byte: UInt8 = 0 + let count = read(0, &byte, 1) + if count == 0 { exit(0) } + if count < 0 { + if errno == EINTR { continue } + exit(1) + } + if byte != 10 { + line.append(byte) + if line.count > 1_048_576 { exit(2) } + continue + } + defer { line.removeAll(keepingCapacity: true) } + guard let message = try? JSONSerialization.jsonObject(with: line) as? [String: Any], + let method = message["method"] as? String + else { continue } + record(["method": method, "params": message["params"] ?? [:]]) + guard let id = message["id"] else { continue } + if method == "initialize" { + if scenario == "eof-initialize" { exit(0) } + if scenario == "pending-initialize" { continue } + if scenario == "stdout-flood" { + output(Data(repeating: 120, count: 65536)) + continue + } + if scenario == "stderr-flood" { + output(Data(repeating: 120, count: 65536), fd: 2) + continue + } + let capabilities: [String: Any] = scenario == "no-tools" ? [:] : ["tools": [:]] + response( + id, + [ + "protocolVersion": scenario == "wrong-version" ? "2099-01-01" : "2025-11-25", + "capabilities": capabilities, "serverInfo": ["name": "local-fixture", "version": "1"], + ]) + } else if method == "tools/list" { + if scenario == "final-response-limit" { + let tools: [[String: Any]] = (0..<4).map { index in + [ + "name": "tool-" + String(index), "description": String(repeating: "x", count: 100), + "inputSchema": ["type": "object"], + ] + } + let response = try! JSONSerialization.data(withJSONObject: [ + "jsonrpc": "2.0", "id": id, "result": ["tools": tools], + ]) + precondition(response.count <= 1024) + let burst = response + Data([10]) + Data(repeating: 120, count: 1025) + precondition(burst.count < 4096) + output(burst) + continue + } + if scenario == "eof-tools" { + let tools: [[String: Any]] = (0..<1000).map { index in + [ + "name": "tool-" + String(index), "description": String(repeating: "x", count: 200), + "inputSchema": ["type": "object"], + ] + } + response(id, ["tools": tools]) + exit(0) + } + if scenario == "pending-tools" { continue } + if scenario == "stubborn" { + _ = signal(SIGTERM, SIG_IGN) + try? "ready".write( + to: root.appendingPathComponent("stubborn-ready"), atomically: true, encoding: .utf8) + while true { _ = sleep(1) } + } + let cursor = (message["params"] as? [String: Any])?["cursor"] as? String + let tool: [String: Any] = [ + "name": cursor == nil ? "first" : "second", + "description": scenario == "long-text" + ? String(repeating: "x", count: 17) + : scenario == "facade" + ? ["FACADE_SECRET", "FACADE_LITERAL", "FACADE_ENV", "FACADE_CONTROLLED"].map { + ProcessInfo.processInfo.environment[$0] ?? "absent" + }.map { value in + value + " " + value.replacingOccurrences(of: "-", with: "-\n") + }.joined(separator: " ") : "fixture", + "inputSchema": ["type": "object"], + ] + var result: [String: Any] = ["tools": [tool]] + if cursor == nil || scenario == "cursor-cycle" { result["nextCursor"] = "next" } + response(id, result) + } +} diff --git a/Tests/ManifestTestProcess/main.swift b/Tests/ManifestTestProcess/main.swift new file mode 100644 index 0000000..db697dc --- /dev/null +++ b/Tests/ManifestTestProcess/main.swift @@ -0,0 +1,96 @@ +import AgentsCore +import AgentsManifest +import Foundation +import ManifestTestSupport + +#if canImport(Darwin) + import Darwin +#else + import Glibc +#endif + +func progress(_ stage: FrontEndStage, _ metrics: FrontEndMetrics) { + struct Progress: Encodable { + let configuration: String + let stage: FrontEndStage + let metrics: FrontEndMetrics + } + if let data = try? JSONEncoder().encode( + Progress(configuration: probeConfiguration, stage: stage, metrics: metrics)) + { + FileHandle.standardError.write(data + Data([10])) + } +} + +func peakMemory() -> UInt64 { + var usage = rusage() + #if canImport(Darwin) + _ = getrusage(RUSAGE_SELF, &usage) + return UInt64(max(0, usage.ru_maxrss)) + #else + _ = getrusage(Int32(RUSAGE_SELF.rawValue), &usage) + return UInt64(max(0, usage.ru_maxrss)) * 1024 + #endif +} + +func run(_ bytes: [UInt8], semantics: Bool) -> ProbeReport { + var stage = FrontEndStage.admission + do { + let metrics = try ManifestFrontEnd.inspect( + bytes: bytes, identity: DocumentIdentity("manifest"), + checking: semantics ? .declaration : .syntax + ) { next, metrics in + stage = next + progress(next, metrics) + } + return ProbeReport( + status: "accepted", stage: .teardown, metrics: metrics, peakMemoryBytes: peakMemory()) + } catch let failure as ManifestFailure { + let diagnostic = failure.diagnostics[0] + return ProbeReport( + status: diagnostic.code, stage: failure.stage, offset: diagnostic.span.start, + line: diagnostic.span.line, column: diagnostic.span.column, message: diagnostic.message, + metrics: failure.metrics, peakMemoryBytes: peakMemory()) + } catch { + return ProbeReport( + status: "unexpected", stage: stage, message: String(describing: error), + metrics: FrontEndMetrics(), peakMemoryBytes: peakMemory()) + } +} + +let path = CommandLine.arguments[1] +let handle = try FileHandle(forReadingFrom: URL(fileURLWithPath: path)) +var bytes: [UInt8] = [] +while bytes.count < (ManifestLimits.Input.bytes + 1) { + let data = try handle.read(upToCount: (ManifestLimits.Input.bytes + 1) - bytes.count) ?? Data() + if data.isEmpty { break } + bytes.append(contentsOf: data) +} +try handle.close() +let report: ProbeReport +if CommandLine.arguments.contains("--edit-oversized") { + var preparationBaselinePeakBytes: UInt64? + do { + let document = try DeclarationDocument(bytes: bytes, identity: DocumentIdentity("manifest")) + let component = ComponentDeclaration.ignore( + name: "large", patterns: [String(repeating: "x", count: 20_000_000)]) + preparationBaselinePeakBytes = peakMemory() + _ = try document.preparing([.insertComponent(component, into: .root, at: .first)]) + report = ProbeReport( + status: "accepted", operation: .editing, offset: 0, line: 1, column: 1, message: "", + metrics: document.metrics, peakMemoryBytes: peakMemory(), + preparationBaselinePeakBytes: preparationBaselinePeakBytes) + } catch let error as ManifestFailure { + let diagnostic = error.diagnostics[0] + report = ProbeReport( + status: diagnostic.code, operation: .editing, offset: diagnostic.span.start, + line: diagnostic.span.line, column: diagnostic.span.column, message: diagnostic.message, + metrics: error.metrics, peakMemoryBytes: peakMemory(), + preparationBaselinePeakBytes: preparationBaselinePeakBytes) + } +} else { + report = run(bytes, semantics: CommandLine.arguments.contains("--semantics")) +} +let encoder = JSONEncoder() +encoder.outputFormatting = [.sortedKeys] +FileHandle.standardOutput.write(try encoder.encode(report)) diff --git a/Tests/ManifestTestSupport/ProbeReport.swift b/Tests/ManifestTestSupport/ProbeReport.swift new file mode 100644 index 0000000..8419a1f --- /dev/null +++ b/Tests/ManifestTestSupport/ProbeReport.swift @@ -0,0 +1,54 @@ +import AgentsManifest + +#if DEBUG + package let probeConfiguration = "debug" + package let probeWatchdogSeconds = 30.0 +#else + package let probeConfiguration = "release" + package let probeWatchdogSeconds = 2.0 +#endif + +package enum ProbeOperation: String, Codable { + case frontEnd, editing +} + +/// Wire format shared by the watchdog parent and its isolated child. +package struct ProbeReport: Codable { + package let configuration: String + package let status: String + package let operation: ProbeOperation + package let stage: FrontEndStage? + package let offset: Int + package let line: Int + package let column: Int + package let message: String + package let metrics: FrontEndMetrics + package let peakMemoryBytes: UInt64 + /// Process RSS high-water mark before preparation, including earlier allocations. + package let preparationBaselinePeakBytes: UInt64? + + package var preparationPeakGrowthBytes: UInt64? { + preparationBaselinePeakBytes.map { baseline in + peakMemoryBytes > baseline ? peakMemoryBytes - baseline : 0 + } + } + + package init( + status: String, operation: ProbeOperation = .frontEnd, stage: FrontEndStage? = nil, + offset: Int = 0, line: Int = 1, column: Int = 1, + message: String = "", metrics: FrontEndMetrics, peakMemoryBytes: UInt64, + preparationBaselinePeakBytes: UInt64? = nil + ) { + configuration = probeConfiguration + self.status = status + self.operation = operation + self.stage = stage + self.offset = offset + self.line = line + self.column = column + self.message = message + self.metrics = metrics + self.peakMemoryBytes = peakMemoryBytes + self.preparationBaselinePeakBytes = preparationBaselinePeakBytes + } +} diff --git a/Tests/NativeDocumentsTests/ArrayAuthorityTests.swift b/Tests/NativeDocumentsTests/ArrayAuthorityTests.swift new file mode 100644 index 0000000..2c0f72b --- /dev/null +++ b/Tests/NativeDocumentsTests/ArrayAuthorityTests.swift @@ -0,0 +1,267 @@ +import Foundation +import NativeDocuments +import Testing + +@Suite("Native array semantic authority") +struct ArrayAuthorityTests { + @Test func nativeDigestPinsKindsLexemesDecodedBytesAndObjectOrdering() throws { + let base = try document(#"{"a":[1,"x",true,null]}"#, .json) + let digest = try base.arrayDigest(keyRegion("a")) + #expect(digest.format == "native-array@1") + #expect(digest.digest == "ca94654645dcd00338f30082bb9324bc2af825a26709c3507da05b9215d932fb") + let trivia = try document( + #"{/* retained */"a":[1,"\u0078",true,null,]}"#, .jsonc(trailingCommas: true)) + #expect(try trivia.arrayDigest(keyRegion("a")) == digest) + for changed in [#"[1.0,"x",true,null]"#, #"[1e0,"x",true,null]"#, #"[1,"x",null,true]"#] { + #expect(try document("{\"a\":" + changed + "}", .json).arrayDigest(keyRegion("a")) != digest) + } + let ordered = try document(#"{"a":[{"z":1,"a":2}]}"#, .json) + let reordered = try document(#"{"a":[{"a":2,"z":1}]}"#, .json) + #expect(try ordered.arrayDigest(keyRegion("a")) == reordered.arrayDigest(keyRegion("a"))) + let composed = try document("{\"a\":[{\"é\":1}]}", .json) + let decomposed = try document("{\"a\":[{\"e\u{301}\":1}]}", .json) + #expect(try composed.arrayDigest(keyRegion("a")) != decomposed.arrayDigest(keyRegion("a"))) + let collision = try document("{\"a\":[{\"é\":1,\"e\u{301}\":2}]}", .json) + #expect(try collision.read(keyRegion("a"))?.value == nil) + #expect(try collision.arrayDigest(keyRegion("a")).digest.count == 64) + let hex = try document("a=[0x10,1979-05-27,nan]\n") + let decimal = try document("a=[16,1979-05-27,nan]\n") + #expect(try hex.arrayDigest(keyRegion("a")) != decimal.arrayDigest(keyRegion("a"))) + let ids = try document("{\"a\":[{\"id\":\"é\",\"n\":1},{\"id\":\"e\u{301}\",\"n\":2}]}", .json) + for (id, value) in [("é", 1), ("e\u{301}", 2)] { + let region = NativeRegion([.key("a"), .occurrence(.init(idKey: "id", id: id)), .key("n")]) + #expect(try ids.read(region)?.value == .integer(value)) + } + #expect(!String(describing: digest).contains(digest.digest)) + #expect(!String(reflecting: digest).contains(digest.digest)) + } + + @Test func persistedDigestValidatesWholePreimageBeforeDuplicateOrdinalSelection() throws { + let source = #"{"a":["same","same","same","same","same"]}"# + let original = try document(source, .json) + let array = keyRegion("a") + let digest = try original.arrayDigest(array) + let regions = try original.validatedOccurrences(in: array, matching: digest, ordinals: [2, 4]) + #expect(regions.count == 2) + #expect(try original.read(regions[0])?.value == .string("same")) + for invalid in [ + NativeArrayDigest(format: "native-array@2", digest: digest.digest), + NativeArrayDigest(format: digest.format, digest: String(repeating: "0", count: 64)), + NativeArrayDigest(format: digest.format, digest: "PRIVATE_VALUE"), + ] { + do { + _ = try original.validatedOccurrences(in: array, matching: invalid, ordinals: [2]) + Issue.record("unvalidated persisted evidence selected an occurrence") + } catch let error as NativeDocumentError { + #expect(!error.description.contains("PRIVATE_VALUE")) + #expect(!error.description.contains(digest.digest)) + } + } + for index in [-1, 5] { + #expect(throws: NativeDocumentError.self) { + try original.validatedOccurrences(in: array, matching: digest, ordinals: [index]) + } + } + let changed = try document(#"{"a":["same","same","same","same","changed"]}"#, .json) + #expect(throws: NativeDocumentError.self) { + try changed.validatedOccurrences(in: array, matching: digest, ordinals: [2]) + } + let all = try original.validatedOccurrences(in: array, matching: digest, ordinals: [0, 2, 4]) + let retained = try [all[1], all[2]].map { try #require(try original.read($0)) } + let prepared = try original.prepare( + [ + .remove(region: all[0], expected: owned(original, all[0])), + .append(region: array, expected: owned(original, array), value: .string("same")), + ], retaining: retained, trackingArrays: [array]) + let fresh = try NativeDocument(bytes: prepared.bytes, format: .json, budget: generousBudget()) + #expect(try fresh.arrayDigest(array) == digest) + // Equal final values cannot preserve foreign ordinal authority after remove/append. + #expect(!prepared.arrayTransitions[0].canRetainToken) + let first = try #require(prepared.survivingRegions[0].observation) + let second = try #require(prepared.survivingRegions[1].observation) + guard case .occurrence(let a) = first.region.steps.last, + case .occurrence(let b) = second.region.steps.last + else { + Issue.record("missing remaps") + return + } + #expect(a.ordinal == 1 && b.ordinal == 3) + let removed = try fresh.prepare( + [.remove(region: first.region, expected: .owned(first))], retaining: [second]) + #expect(removed.survivingRegions[0].observation != nil) + #expect(throws: NativeDocumentError.self) { + try changed.prepare([], retaining: retained) + } + } + + @Test func siblingChangesPreservePrivateArrayContinuityAndDescendantChangesRotateIt() throws { + let original = try document( + #"{/* private sibling */"a":[{"secret":"PRIVATE"}],"b":["UNSELECTED"],"other":1}"#, + .jsonc(trailingCommas: false) + ) + let array = keyRegion("a") + let digest = try original.arrayDigest(array) + let selected = try original.validatedOccurrences(in: array, matching: digest, ordinals: [0])[0] + let observation = try #require(try original.read(selected)) + let sibling = try original.prepare( + [ + .put( + region: keyRegion("other"), expected: owned(original, keyRegion("other")), + value: .integer(2)) + ], retaining: [observation], trackingArrays: [array, keyRegion("b")]) + #expect(sibling.arrayTransitions[0].canRetainToken) + #expect(sibling.arrayTransitions[0].digest == digest) + #expect(sibling.arrayTransitions[1].index == 1) + #expect(sibling.arrayTransitions[1].canRetainToken) + #expect(text(sibling).contains("/* private sibling */")) + let secret = NativeRegion(selected.steps + [.key("secret")]) + let updated = try original.prepare( + [ + .put(region: secret, expected: owned(original, secret), value: .string("CHANGED")) + ], retaining: [observation], trackingArrays: [array, keyRegion("b")]) + #expect(!updated.arrayTransitions[0].canRetainToken) + #expect(updated.arrayTransitions[0].digest != digest) + #expect(updated.arrayTransitions[1].canRetainToken) + #expect( + updated.survivingRegions[0].observation?.value == .object(["secret": .string("CHANGED")])) + #expect(throws: NativeDocumentError.self) { + try original.prepare([], trackingArrays: [array, array]) + } + } + + @Test func ancestorReplacementAndArrayRemovalCannotContinueEqualAuthority() throws { + let original = try document(#"{"parent":{"a":[1],"other":true}}"#, .json) + let parent = keyRegion("parent") + let array = keyRegion("parent", "a") + let old = try #require(try original.read(array)) + let replacement = try original.prepare( + [ + .put( + region: parent, expected: owned(original, parent), + value: .object(["a": .array([.integer(1)]), "other": .boolean(false)])) + ], retaining: [old], trackingArrays: [array]) + #expect(try replacement.arrayTransitions[0].digest == original.arrayDigest(array)) + #expect(!replacement.arrayTransitions[0].canRetainToken) + #expect(replacement.survivingRegions[0].observation == nil) + let noOp = try original.prepare( + [ + .put( + region: parent, expected: owned(original, parent), + value: .object(["a": .array([.integer(1)]), "other": .boolean(true)])) + ], retaining: [old], trackingArrays: [array]) + #expect(noOp.bytes == original.bytes) + #expect(noOp.arrayTransitions[0].canRetainToken) + let removed = try original.prepare( + [.remove(region: array, expected: .owned(old))], retaining: [old], trackingArrays: [array]) + #expect(removed.arrayTransitions[0].region == nil) + #expect(removed.arrayTransitions[0].digest == nil) + #expect(removed.survivingRegions[0].observation == nil) + #expect(throws: NativeDocumentError.self) { + try original.prepare([ + .remove(region: array, expected: .owned(old)), + .put(region: array, expected: .owned(old), value: .array([.integer(1)])), + ]) + } + } + + @Test func movedPositionalAncestorsRotateButStableNativeIDsKeepTheirAddress() throws { + for stable in [false, true] { + let original = try document(#"{"items":[{"id":"first"},{"id":"second","a":[1]}]}"#, .json) + let items = keyRegion("items") + let occurrences = try #require(try original.read(items)).occurrences + let first = NativeRegion(items.steps + [.occurrence(occurrences[0])]) + let second = NativeRegion( + items.steps + [.occurrence(stable ? .init(idKey: "id", id: "second") : occurrences[1])]) + let array = NativeRegion(second.steps + [.key("a")]) + let prepared = try original.prepare( + [.remove(region: first, expected: owned(original, first))], trackingArrays: [array]) + #expect(prepared.arrayTransitions[0].canRetainToken == stable) + let fresh = try NativeDocument(bytes: prepared.bytes, format: .json, budget: generousBudget()) + #expect( + try fresh.read(#require(prepared.arrayTransitions[0].region))?.value + == .array([.integer(1)])) + } + } + + @Test func ancestorAppendPreservesStableIDNestedArrayWhileOuterArrayRotates() throws { + let original = try document(#"{"items":[{"id":"first","hooks":[1]}]}"#, .json) + let items = keyRegion("items") + let hooks = NativeRegion([ + .key("items"), .occurrence(.init(idKey: "id", id: "first")), .key("hooks"), + ]) + let old = try #require(try original.read(hooks)) + let digest = try original.arrayDigest(hooks) + let appended = try original.prepare( + [ + .append( + region: items, expected: owned(original, items), value: .object(["id": .string("second")]) + ) + ], retaining: [old], trackingArrays: [hooks, items]) + #expect(appended.arrayTransitions[0].canRetainToken) + #expect(appended.arrayTransitions[0].digest == digest) + #expect(appended.arrayTransitions[0].region == hooks) + #expect(!appended.arrayTransitions[1].canRetainToken) + let fresh = try NativeDocument(bytes: appended.bytes, format: .json, budget: generousBudget()) + #expect(try fresh.read(hooks)?.value == .array([.integer(1)])) + let surviving = try #require(appended.survivingRegions[0].observation) + let edited = try fresh.prepare( + [ + .append(region: hooks, expected: .owned(surviving), value: .integer(2)) + ], trackingArrays: [hooks]) + #expect(!edited.arrayTransitions[0].canRetainToken) + #expect(edited.arrayTransitions[0].digest != digest) + } + + @Test func conditionalPruningReportsArrayDisappearanceAndSurvivorRemoval() throws { + let original = try document(#"{"a":[1],"keep":true}"#, .json) + let array = keyRegion("a") + let digest = try original.arrayDigest(array) + let element = try original.validatedOccurrences(in: array, matching: digest, ordinals: [0])[0] + let observed = try #require(try original.read(element)) + let prepared = try original.prepare( + [ + .remove(region: element, expected: .owned(observed)), + .pruneCreatedContainer(region: array, observed: #require(try original.read(array))), + ], retaining: [observed], trackingArrays: [array]) + #expect(text(prepared) == #"{"keep":true}"#) + #expect(prepared.arrayTransitions[0].region == nil) + #expect(!prepared.arrayTransitions[0].canRetainToken) + #expect(prepared.survivingRegions[0].observation == nil) + } + + @Test func nativeAtomArraysRetainContinuityWithoutProjectingTheirValues() throws { + let original = try document("a=[1979-05-27,nan] # native atoms\nother=1\n") + let array = keyRegion("a") + let digest = try original.arrayDigest(array) + let region = try original.validatedOccurrences(in: array, matching: digest, ordinals: [0])[0] + let observation = try #require(try original.read(region)) + #expect(observation.value == nil) + let prepared = try original.prepare( + [ + .put( + region: keyRegion("other"), expected: owned(original, keyRegion("other")), + value: .integer(2)) + ], retaining: [observation], trackingArrays: [array]) + #expect(prepared.arrayTransitions[0].canRetainToken) + #expect(prepared.arrayTransitions[0].digest == digest) + #expect(prepared.survivingRegions[0].observation?.nativeKind == "dateTime") + #expect(text(prepared).contains("a=[1979-05-27,nan] # native atoms\n")) + } + + @Test func repeatedDigestQueriesShareBudgetAndCancellationStillApplies() throws { + var cancelled = false + let budget = NativeDocumentBudget( + limits: .init( + storage: 2_000_000, work: 200_000, nodes: 10_000, depth: 64, uninterruptedBytes: 1_000_000), + cancellation: { cancelled }) + let source = "{\"a\":[\"" + String(repeating: "x", count: 4096) + "\"]}" + let original = try NativeDocument(bytes: Data(source.utf8), format: .json, budget: budget) + let digest = try original.arrayDigest(keyRegion("a")) + for _ in 0..<100 { #expect(try original.arrayDigest(keyRegion("a")) == digest) } + cancelled = true + do { + _ = try original.arrayDigest(keyRegion("a")) + Issue.record("cached digest bypassed cancellation") + } catch NativeDocumentError.cancelled {} + } +} diff --git a/Tests/NativeDocumentsTests/ConditionalPruningTests.swift b/Tests/NativeDocumentsTests/ConditionalPruningTests.swift new file mode 100644 index 0000000..d047ecb --- /dev/null +++ b/Tests/NativeDocumentsTests/ConditionalPruningTests.swift @@ -0,0 +1,258 @@ +import AgentsCore +import Foundation +import NativeDocuments +import Testing + +@Test(arguments: ["json", "jsonc", "toml-table", "toml-dotted", "toml-inline"]) +func childRemovalPrunesCreatedAncestorsInOnePrepare(_ syntax: String) throws { + let source: String + let format: NativeDocumentFormat + switch syntax { + case "json": + source = #"{"keep":true,"outer":{"inner":{"owned":1}}}"# + format = .json + case "jsonc": + source = #"{/* root note */"keep":true,"outer":{"inner":{"owned":1}}}"# + format = .jsonc(trailingCommas: false) + case "toml-table": + source = "keep=true\n[outer.inner]\nowned=1\n" + format = .toml + case "toml-dotted": + source = "keep=true\nouter.inner.owned=1\n" + format = .toml + default: + source = "keep=true\nouter={inner={owned=1}}\n" + format = .toml + } + let doc = try document(source, format) + let outer = keyRegion("outer") + let inner = keyRegion("outer", "inner") + let child = keyRegion("outer", "inner", "owned") + let pruneOuter = NativeRegionEdit.pruneCreatedContainer( + region: outer, observed: try #require(try doc.read(outer))) + let pruneInner = NativeRegionEdit.pruneCreatedContainer( + region: inner, observed: try #require(try doc.read(inner))) + let removal = NativeRegionEdit.remove(region: child, expected: try owned(doc, child)) + let result = try doc.prepare([pruneOuter, removal, pruneInner]) + #expect(try doc.prepare([removal, pruneInner, pruneOuter]).bytes == result.bytes) + let checked = try NativeDocument(bytes: result.bytes, format: format, budget: generousBudget()) + #expect(try checked.read(outer) == nil) + #expect(try checked.read(keyRegion("keep"))?.value == .boolean(true)) + #expect(result.changedRegions.contains(outer)) + #expect(result.changedRegions.contains(inner)) + if syntax == "json" { #expect(text(result) == #"{"keep":true}"#) } + if syntax == "jsonc" { #expect(text(result) == #"{/* root note */"keep":true}"#) } + if format == .toml { #expect(text(result).hasPrefix("keep=true\n")) } +} + +@Test(arguments: ["jsonc", "jsonc-between", "toml"]) +func conditionalPruningRetainsCommentsAndUnmanagedSiblings(_ syntax: String) throws { + let source: String + switch syntax { + case "jsonc": + source = #"{"outer":{"owned":1 /* keep note */},"other":{"owned":2,"unmanaged":3},"empty":{}}"# + case "jsonc-between": + source = #"{"outer":/* keep note */{"owned":1},"other":{"owned":2,"unmanaged":3},"empty":{}}"# + default: + source = "[outer] # keep note\nowned=1\n[other]\nowned=2\nunmanaged=3\n[empty]\n" + } + let format: NativeDocumentFormat = + syntax.hasPrefix("jsonc") ? .jsonc(trailingCommas: true) : .toml + let doc = try document(source, format) + var edits: [NativeRegionEdit] = [] + for name in ["outer", "other"] { + let parent = keyRegion(name) + let child = keyRegion(name, "owned") + edits.append( + .pruneCreatedContainer(region: parent, observed: try #require(try doc.read(parent)))) + edits.append(.remove(region: child, expected: try owned(doc, child))) + } + let result = try doc.prepare(edits) + let checked = try NativeDocument(bytes: result.bytes, format: format, budget: generousBudget()) + #expect(try checked.read(keyRegion("outer"))?.value == .object([:])) + #expect(try checked.read(keyRegion("other"))?.value == .object(["unmanaged": .integer(3)])) + #expect(try checked.read(keyRegion("empty"))?.value == .object([:])) + #expect(text(result).contains("keep note")) + #expect(!result.changedRegions.contains(keyRegion("outer"))) + #expect(!result.changedRegions.contains(keyRegion("other"))) + if syntax == "toml" { + #expect(text(result).contains("[outer] # keep note\n")) + #expect(text(result).hasSuffix("unmanaged=3\n[empty]\n")) + } else { + #expect(text(result).contains("/* keep note */")) + #expect(text(result).hasSuffix(#""unmanaged":3},"empty":{}}"#)) + } +} + +@Test func creationResultsSupplyOnlyTheContainersActuallyCreated() throws { + let original = try document(#"{"existing":{},"keep":true}"#, .json) + let child = keyRegion("outer", "inner", "owned") + let installation = try original.prepare([ + .put(region: child, expected: .absent, value: .integer(1)) + ]) + #expect(!installation.createdContainers.contains(keyRegion("existing"))) + let fresh = try NativeDocument( + bytes: installation.bytes, format: .json, budget: generousBudget()) + var edits: [NativeRegionEdit] = [.remove(region: child, expected: try owned(fresh, child))] + for region in installation.createdContainers { + edits.append( + .pruneCreatedContainer(region: region, observed: try #require(try fresh.read(region)))) + } + let removal = try fresh.prepare(edits) + #expect(removal.bytes == original.bytes) +} + +@Test func pruningUsesFreshRegionEvidenceWithoutAdoptingEmptyContainers() throws { + let original = try document(#"{"created":{"owned":1},"equal":{"owned":1},"unowned":{}}"#, .json) + let parent = keyRegion("created") + let child = keyRegion("created", "owned") + let observation = try #require(try original.read(parent)) + let changed = try document(#"{"created":{"owned":2},"equal":{"owned":1},"unowned":{}}"#, .json) + do { + _ = try changed.prepare([ + .remove(region: child, expected: owned(changed, child)), + .pruneCreatedContainer(region: parent, observed: observation), + ]) + Issue.record("stale creation observation authorized a draft") + } catch NativeDocumentError.ownershipMismatch {} + do { + _ = try original.prepare([ + .pruneCreatedContainer(region: keyRegion("equal"), observed: observation) + ]) + Issue.record("equal payload supplied another region's authority") + } catch NativeDocumentError.ownershipMismatch {} + let removal = try original.prepare([.remove(region: child, expected: owned(original, child))]) + let checked = try NativeDocument(bytes: removal.bytes, format: .json, budget: generousBudget()) + #expect(try checked.read(parent)?.value == .object([:])) + #expect(try checked.read(keyRegion("unowned"))?.value == .object([:])) + #expect(throws: NativeDocumentError.self) { + try original.prepare([ + .pruneCreatedContainer( + region: NativeRegion(keys: []), + observed: #require(try original.read(NativeRegion(keys: [])))) + ]) + } + let commented = try document( + #"{"created":{/* new note */"owned":1},"equal":{"owned":1},"unowned":{}}"#, + .jsonc(trailingCommas: false)) + let retained = try commented.prepare([ + .remove(region: child, expected: owned(commented, child)), + .pruneCreatedContainer(region: parent, observed: observation), + ]) + #expect(text(retained).contains(#""created":{/* new note */}"#)) +} + +@Test func conditionalAncestorsDoNotWeakenOrdinaryOverlapChecks() throws { + let doc = try document(#"{"outer":{"child":{"owned":1}}}"#, .json) + let parent = keyRegion("outer") + let child = keyRegion("outer", "child") + let parentObservation = try #require(try doc.read(parent)) + let childObservation = try #require(try doc.read(child)) + let conflicting: [[NativeRegionEdit]] = [ + [ + .remove(region: parent, expected: .owned(parentObservation)), + .remove(region: child, expected: .owned(childObservation)), + ], + [ + .remove(region: parent, expected: .owned(parentObservation)), + .pruneCreatedContainer(region: child, observed: childObservation), + ], + [ + .pruneCreatedContainer(region: parent, observed: parentObservation), + .pruneCreatedContainer(region: parent, observed: parentObservation), + ], + ] + for edits in conflicting { + do { + _ = try doc.prepare(edits) + Issue.record("overlapping mandatory/duplicate authority was accepted") + } catch NativeDocumentError.unsupportedEdit(.overlappingEdits, _, _) {} + } + do { + _ = try doc.prepare([.remove(region: parent, expected: .createdContainer(parentObservation))]) + Issue.record("mandatory creation-only removal accepted a populated preimage") + } catch NativeDocumentError.ownershipMismatch {} +} + +@Test(arguments: ["json", "toml"]) +func conditionalPruningRemapsOccurrencesAfterOwnedRemovals(_ syntax: String) throws { + let source = + syntax == "json" + ? #"{"items":[{"id":"first","owned":0},{"payload":{"owned":1}},{"keep":true}],"outside":7}"# + : "[[items]]\nid='first'\nowned=0\n[[items]]\n[items.payload]\nowned=1\n[[items]]\nkeep=true\n[outside]\nx=7\n" + let format: NativeDocumentFormat = syntax == "json" ? .json : .toml + let doc = try document(source, format) + let array = keyRegion("items") + let occurrences = try #require(try doc.read(array)).occurrences + let first = NativeRegion([.key("items"), .occurrence(.init(idKey: "id", id: "first"))]) + let selected = NativeRegion([.key("items"), .occurrence(occurrences[1])]) + let payload = NativeRegion(selected.steps + [.key("payload")]) + let child = NativeRegion(payload.steps + [.key("owned")]) + let kept = NativeRegion([.key("items"), .occurrence(occurrences[2]), .key("keep")]) + let result = try doc.prepare([ + .pruneCreatedContainer(region: array, observed: #require(try doc.read(array))), + .pruneCreatedContainer(region: selected, observed: #require(try doc.read(selected))), + .remove(region: first, expected: owned(doc, first)), + .remove(region: child, expected: owned(doc, child)), + .put(region: kept, expected: owned(doc, kept), value: .boolean(false)), + .pruneCreatedContainer(region: payload, observed: #require(try doc.read(payload))), + ]) + let checked = try NativeDocument(bytes: result.bytes, format: format, budget: generousBudget()) + #expect(try checked.read(array)?.value == .array([.object(["keep": .boolean(false)])])) + #expect(!result.changedRegions.contains(array)) + let observation = try #require(result.observations.first) + #expect(try checked.read(observation.region)?.value == .boolean(false)) + if syntax == "json" { + #expect(text(result) == #"{"items":[{"keep":false}],"outside":7}"#) + } else { + #expect(text(result).hasSuffix("keep=false\n[outside]\nx=7\n")) + } +} + +@Test func implicitTOMLParentsRequireTheirOwnCreationAuthority() throws { + let doc = try document("outer.inner.owned=1\nkeep=true\n") + let inner = keyRegion("outer", "inner") + let child = keyRegion("outer", "inner", "owned") + do { + _ = try doc.prepare([ + .remove(region: child, expected: owned(doc, child)), + .pruneCreatedContainer(region: inner, observed: #require(try doc.read(inner))), + ]) + Issue.record("an unrecorded implicit ancestor disappeared") + } catch NativeDocumentError.unsupportedEdit(.wouldRewriteUnownedStructure, _, _) {} +} + +@Test(arguments: ["json", "toml"]) +func lastOwnedOccurrenceAndCreatedArrayCanBeRemovedTogether(_ syntax: String) throws { + let format: NativeDocumentFormat = syntax == "json" ? .json : .toml + let doc = try document( + syntax == "json" ? #"{"items":[{"owned":1}]}"# : "[[items]]\nowned=1\n", format) + let array = keyRegion("items") + let occurrence = NativeRegion([ + .key("items"), .occurrence(try #require(try doc.read(array)).occurrences[0]), + ]) + let result = try doc.prepare([ + .remove(region: occurrence, expected: owned(doc, occurrence)), + .pruneCreatedContainer(region: array, observed: #require(try doc.read(array))), + ]) + let checked = try NativeDocument(bytes: result.bytes, format: format, budget: generousBudget()) + #expect(try checked.read(NativeRegion(keys: []))?.value == .object([:])) +} + +@Test(arguments: ["json", "toml"]) +func conditionalPruningDoesNotResolveNewAmbiguityByPosition(_ syntax: String) throws { + let format: NativeDocumentFormat = syntax == "json" ? .json : .toml + let doc = try document( + syntax == "json" + ? #"{"items":[{},{},{"owned":1},{},{}]}"# : "items=[{},{},{owned=1},{},{}]\n", format) + let evidence = try #require(try doc.read(keyRegion("items"))).occurrences[2] + let selected = NativeRegion([.key("items"), .occurrence(evidence)]) + let child = NativeRegion(selected.steps + [.key("owned")]) + do { + _ = try doc.prepare([ + .remove(region: child, expected: owned(doc, child)), + .pruneCreatedContainer(region: selected, observed: #require(try doc.read(selected))), + ]) + Issue.record("an ambiguous empty occurrence was selected by its old position") + } catch NativeDocumentError.unsupportedEdit(.ambiguousOccurrence, _, _) {} +} diff --git a/Tests/NativeDocumentsTests/NativeDocumentTests.swift b/Tests/NativeDocumentsTests/NativeDocumentTests.swift new file mode 100644 index 0000000..a35c146 --- /dev/null +++ b/Tests/NativeDocumentsTests/NativeDocumentTests.swift @@ -0,0 +1,801 @@ +import AgentsCore +import Foundation +import NativeDocuments +import Testing + +func document( + _ text: String, _ format: NativeDocumentFormat = .toml, budget: NativeDocumentBudget? = nil +) throws -> NativeDocument { + try NativeDocument(bytes: Data(text.utf8), format: format, budget: budget ?? generousBudget()) +} +func keyRegion(_ keys: String...) -> NativeRegion { NativeRegion(keys: keys) } +func owned(_ doc: NativeDocument, _ region: NativeRegion) throws -> NativeExpectedRegion { + .owned(try #require(try doc.read(region))) +} +func text(_ change: PreparedNativeChange) -> String { + String(decoding: change.bytes, as: UTF8.self) +} + +@Test func jsoncRegionalOwnershipAndBytes() throws { + let source = """ + { + // client-owned , [ ] \" sentinel + "accountSentinel": "keep", + "projects": { + "/work/a.b": { + "hasTrustDialogAccepted": false, + "mcpServers": {"db": {"command": "old", "args": []}} + }, + "/work/b": {"mcpServers": {"other": {"command": "keep"}}} + }, + "mcpServers": {"user": {"command": "keep"}} + } + """ + let doc = try document(source, .jsonc(trailingCommas: true)) + let command = keyRegion("projects", "/work/a.b", "mcpServers", "db", "command") + let commandObservation = try #require(try doc.read(command)) + #expect( + commandObservation.entryRanges.contains { + String(decoding: Array(source.utf8)[$0], as: UTF8.self) == "\"command\": \"old\"" + }) + let updated = try doc.prepare([ + .put(region: command, expected: owned(doc, command), value: .string("new")) + ]) + #expect(text(updated) == source.replacingOccurrences(of: "\"old\"", with: "\"new\"")) + let db = keyRegion("projects", "/work/a.b", "mcpServers", "db") + let removed = try doc.prepare([.remove(region: db, expected: owned(doc, db))]) + #expect(text(removed).contains("\"mcpServers\": {}")) + #expect(text(removed).contains("// client-owned , [ ] \" sentinel")) + #expect(text(removed).contains("\"hasTrustDialogAccepted\": false")) + #expect(text(removed).contains("\"user\": {\"command\": \"keep\"}")) + #expect(throws: NativeDocumentError.self) { + try doc.prepare([.put(region: command, expected: .absent, value: .string("old"))]) + } + #expect(try doc.prepare([]).bytes == Data(source.utf8)) + let crlf = "\u{feff}" + source.replacingOccurrences(of: "\n", with: "\r\n") + let crDoc = try document(crlf, .jsonc(trailingCommas: false)) + #expect( + try crDoc.prepare([ + .put(region: command, expected: owned(crDoc, command), value: .string("old")) + ]).bytes == Data(crlf.utf8)) +} + +@Test func jsonSyntaxExactIdentityAndNumbers() throws { + for source in [ + #"{"db":1,"\u0064b":2}"#, "{}{}", "[1,]", "{/*comment*/}", "{a:1}", "[01]", "[1.]", "[NaN]", + #"["\uD800"]"#, + ] { + #expect(throws: NativeDocumentError.self) { try document(source, .json) } + } + let source = #"{"é":1,"e\u0301":2,"value":"\u00e9","decimal":12345678901234567890.00100}"# + let doc = try document(source, .json) + #expect(try doc.read(keyRegion("é"))?.value == .integer(1)) + #expect(try doc.read(keyRegion("e\u{301}"))?.value == .integer(2)) + #expect(try doc.read(NativeRegion(keys: []))?.value == nil) + let r = keyRegion("value") + #expect( + try doc.prepare([.put(region: r, expected: owned(doc, r), value: .string("é"))]).bytes + == Data(source.utf8)) + let change = try doc.prepare([ + .put(region: r, expected: owned(doc, r), value: .string("e\u{301}")) + ]) + #expect(change.bytes != Data(source.utf8)) + #expect(text(change).contains("12345678901234567890.00100")) + for format: NativeDocumentFormat in [.json, .toml] { + for decimal in ["1", "1.00", "1E+2", "-0", "123456789012345678901234567890"] { + let doc = try document(format == .json ? "{}" : "", format) + let c = try doc.prepare([ + .put(region: keyRegion("n"), expected: .absent, value: .decimal(decimal)) + ]) + let result = try NativeDocument(bytes: c.bytes, format: format, budget: generousBudget()) + #expect(try result.read(keyRegion("n")) != nil) + #expect(text(c).contains(decimal)) + } + } +} + +let t1 = #""" + title = "keep" + stamp = 1979-05-27T07:32:00Z + + [mcp_servers."db.prod"] # keep table note + command = "old" # keep field note + args = ["a", "b"] + description = """first + second # literal content + """ + + [mcp_servers."db.prod".env] + TOKEN = "${REFERENCE}" + [mcp_servers.other] + command = "keep" + """# + +@Test func tomlQuotedNestedAndNativeAtoms() throws { + let doc = try document(t1) + let command = keyRegion("mcp_servers", "db.prod", "command") + #expect( + text( + try doc.prepare([.put(region: command, expected: owned(doc, command), value: .string("new"))]) + ) == t1.replacingOccurrences(of: "\"old\"", with: "\"new\"")) + #expect(try doc.read(keyRegion("stamp"))?.value == nil) + let token = keyRegion("mcp_servers", "db.prod", "env", "TOKEN") + let newKey = keyRegion("mcp_servers", "db.prod", "env", "NEW") + let added = try doc.prepare([.put(region: newKey, expected: .absent, value: .string("added"))]) + #expect(text(added).contains("TOKEN = \"${REFERENCE}\"")) + #expect(text(added).contains("\"NEW\" = \"added\"\n[mcp_servers.other]")) + #expect( + text(try doc.prepare([.remove(region: token, expected: owned(doc, token))])).contains( + "[mcp_servers.other]")) + let server = keyRegion("mcp_servers", "db.prod") + let serverObservation = try #require(try doc.read(server)) + #expect( + serverObservation.entryRanges.contains { + String(decoding: Array(t1.utf8)[$0], as: UTF8.self) == "TOKEN = \"${REFERENCE}\"" + }) + let removed = text(try doc.prepare([.remove(region: server, expected: owned(doc, server))])) + #expect(removed.contains("# keep table note")) + #expect(removed.contains("# keep field note")) + #expect(removed.contains("stamp = 1979-05-27T07:32:00Z")) + #expect(!removed.contains("TOKEN =")) + #expect(removed.contains("[mcp_servers.other]\ncommand = \"keep\"")) + #expect(throws: NativeDocumentError.self) { + try doc.prepare([.put(region: command, expected: owned(doc, command), value: .null)]) + } + #expect( + try doc.prepare([.put(region: command, expected: owned(doc, command), value: .string("old"))]) + .bytes == Data(t1.utf8)) +} + +@Test func tomlDottedInlineAndScope() throws { + let source = #""" + mcp_servers."db.prod".command = "tool" + mcp_servers."db.prod".env = { "A.B" = "old", C = "keep" } + """# + let doc = try document(source) + let r = keyRegion("mcp_servers", "db.prod", "env", "A.B") + #expect( + text(try doc.prepare([.put(region: r, expected: owned(doc, r), value: .string("new"))])) + == source.replacingOccurrences(of: "\"old\"", with: "\"new\"")) + let added = try doc.prepare([ + .put( + region: keyRegion("mcp_servers", "db.prod", "env", "D"), expected: .absent, + value: .boolean(true)) + ]) + #expect(text(added).contains("C = \"keep\"")) + let deleted = try doc.prepare([.remove(region: r, expected: owned(doc, r))]) + #expect(text(deleted).contains("C = \"keep\"")) + let sibling = try doc.prepare([ + .put( + region: keyRegion("mcp_servers", "new"), expected: .absent, + value: .object(["command": .string("new")])) + ]) + #expect( + try NativeDocument(bytes: sibling.bytes, format: .toml, budget: generousBudget()).read( + keyRegion("mcp_servers", "new", "command"))?.value == .string("new")) + #expect(throws: NativeDocumentError.self) { + try document(source + "\n[mcp_servers.\"db.prod\"]\na=1") + } +} + +@Test func tomlArrayTablesLatestChildAndRemoval() throws { + let source = """ + [[checks]] + id = "first" + [checks.env] + MODE = "a" + [[checks]] + id = "second" + [checks.env] + MODE = "b" + """ + let doc = try document(source) + let second = NativeRegion([ + .key("checks"), .occurrence(.init(idKey: "id", id: "second")), .key("env"), .key("MODE"), + ]) + #expect(try doc.read(second)?.value == .string("b")) + let changed = try doc.prepare([ + .put(region: second, expected: owned(doc, second), value: .string("new")) + ]) + #expect(text(changed) == source.replacingOccurrences(of: "\"b\"", with: "\"new\"")) + let first = NativeRegion([.key("checks"), .occurrence(.init(idKey: "id", id: "first"))]) + let removed = try doc.prepare([.remove(region: first, expected: owned(doc, first))]) + #expect(!text(removed).contains("MODE = \"a\"")) + #expect(text(removed).contains("id = \"second\"\n[checks.env]\nMODE = \"b\"")) + let duplicates = try document(String(repeating: "[[checks]]\nid=\"same\"\n", count: 5)) + let occurrences = try #require(try duplicates.read(keyRegion("checks"))).occurrences + #expect(throws: NativeDocumentError.self) { + try duplicates.read(NativeRegion([.key("checks"), .occurrence(occurrences[2])])) + } + +} + +@Test func readOnlyBudgetsAndSafeErrors() throws { + let source = "x = {\na = 1,\n}" + let doc = try document(source) + #expect(try doc.read(keyRegion("x", "a"))?.value == .integer(1)) + #expect(throws: NativeDocumentError.self) { + try doc.prepare([ + .put( + region: keyRegion("x", "a"), expected: owned(doc, keyRegion("x", "a")), value: .integer(2)) + ]) + } + for source in [ + "x=\"" + String(repeating: "a", count: 2000) + "\"", "#" + String(repeating: "a", count: 2000), + "x=1\n" + String(repeating: " ", count: 2000), + ] { + let budget = NativeDocumentBudget( + limits: .init( + storage: 100_000, work: 100_000, nodes: 1000, depth: 20, uninterruptedBytes: 100)) + #expect(throws: NativeDocumentError.self) { try document(source, budget: budget) } + } + let budget = NativeDocumentBudget( + limits: .init(storage: 100_000, work: 300, nodes: 1000, depth: 20, uninterruptedBytes: 1000)) + let bounded = try document("x=1", budget: budget) + var exhausted = false + for _ in 0..<30 { + do { + _ = try bounded.prepare([ + .put(region: keyRegion("x"), expected: owned(bounded, keyRegion("x")), value: .integer(2)) + ]) + } catch NativeDocumentError.budgetExceeded { + exhausted = true + break + } + } + #expect(exhausted) + do { _ = try document("secret=\"PRIVATE_SENTINEL\"\nbad=1979-05") } catch { + #expect(!String(describing: error).contains("PRIVATE_SENTINEL")) + } +} + +@Test func structuralObjectsTriviaAndContainerEvidence() throws { + let source = "{\"a\": 1, /* sibling */ \"b\": 2, \"c\": 3}" + let doc = try document(source, .jsonc(trailingCommas: true)) + let object = keyRegion("owned") + let parent = try document( + "{\"owned\": " + source + ", \"keep\": true}", .jsonc(trailingCommas: true)) + let result = try parent.prepare([ + .put( + region: object, expected: owned(parent, object), + value: .object(["a": .integer(1), "new": .string("yes")])) + ]) + #expect(text(result).contains("/* sibling */")) + #expect(text(result).contains("\"keep\": true")) + #expect( + try doc.prepare([.remove(region: keyRegion("b"), expected: owned(doc, keyRegion("b")))]).bytes + != doc.bytes) + let populated = try document(#"{"owned":{"client":true}}"#, .json) + let populatedEvidence = try #require(try populated.read(object)) + do { + _ = try populated.prepare([ + .remove(region: object, expected: .createdContainer(populatedEvidence)) + ]) + Issue.record("creation evidence removed later children") + } catch NativeDocumentError.ownershipMismatch {} + #expect( + text(try populated.prepare([.remove(region: object, expected: .owned(populatedEvidence))])) + == "{}") + for value: NativeValue in [ + .object([:]), .string("replacement"), .object(["client": .boolean(true)]), + ] { + do { + _ = try populated.prepare([ + .put(region: object, expected: .createdContainer(populatedEvidence), value: value) + ]) + Issue.record("creation-only evidence authorized a put") + } catch NativeDocumentError.ownershipMismatch {} + } + #expect( + text( + try populated.prepare([ + .put(region: object, expected: .owned(populatedEvidence), value: .object([:])) + ])) == #"{"owned":{}}"#) + let empty = try document("{\"owned\":{}}", .json) + let observed = try #require(try empty.read(object)) + do { + _ = try empty.prepare([ + .put(region: object, expected: .createdContainer(observed), value: .object([:])) + ]) + Issue.record("creation-only evidence authorized an empty-container no-op put") + } catch NativeDocumentError.ownershipMismatch {} + #expect(throws: NativeDocumentError.self) { + try empty.prepare([.remove(region: object, expected: .owned(observed))]) + } + #expect( + text(try empty.prepare([.remove(region: object, expected: .createdContainer(observed))])) + == "{}") + let commented = try document("{\"owned\":{/* preserve */}}", .jsonc(trailingCommas: true)) + let commentEvidence = try #require(try commented.read(object)) + #expect(throws: NativeDocumentError.self) { + try commented.prepare([.remove(region: object, expected: .createdContainer(commentEvidence))]) + } + let created = try empty.prepare([ + .put(region: keyRegion("new", "child"), expected: .absent, value: .object([:])) + ]) + #expect(created.createdContainers.contains(keyRegion("new"))) + #expect(created.createdContainers.contains(keyRegion("new", "child"))) + let invalid = try document("{\"a\": /* ambiguous */ 1}", .jsonc(trailingCommas: true)) + #expect(throws: NativeDocumentError.self) { + try invalid.prepare([.remove(region: keyRegion("a"), expected: owned(invalid, keyRegion("a")))]) + } + let trailing = try document("{\"a\":1,}", .jsonc(trailingCommas: true)) + _ = try trailing.prepare([.put(region: keyRegion("b"), expected: .absent, value: .integer(2))]) +} + +@Test func tomlUnicodeBOMAndInlinePunctuation() throws { + let source = "\u{feff}\"é\"=1\r\n\"e\u{301}\"=2\r\nx=\"\\u00e9\"\r\nstamp=nan\r\n" + let doc = try document(source) + #expect(try doc.read(keyRegion("é"))?.value == .integer(1)) + #expect(try doc.read(keyRegion("e\u{301}"))?.value == .integer(2)) + let x = keyRegion("x") + #expect( + try doc.prepare([.put(region: x, expected: owned(doc, x), value: .string("é"))]).bytes + == Data(source.utf8)) + let changed = try doc.prepare([ + .put(region: x, expected: owned(doc, x), value: .string("e\u{301}")) + ]) + #expect(text(changed) == source.replacingOccurrences(of: "\\u00e9", with: "e\u{301}")) + let inline = try document("x={ a=\"first\", b=[], c=\"last\" }") + let b = keyRegion("x", "b") + #expect( + text(try inline.prepare([.remove(region: b, expected: owned(inline, b))])).contains( + "c=\"last\"")) + let r = keyRegion("a") + let before = try document("a=\"old\"") + let after = try document("a=\"new\"") + #expect(throws: NativeDocumentError.self) { + try after.prepare([.put(region: r, expected: owned(before, r), value: .string("replace"))]) + } +} + +@Test func exactEvidenceAndMultiEditFailure() throws { + let region = keyRegion("owned") + let original = try document(#"{"owned":{"a":{},"b":"x"}}"#, .json) + let changed = try document(#"{"owned":{"a":{"b":"x"}}}"#, .json) + #expect(throws: NativeDocumentError.self) { + try changed.prepare([ + .put(region: region, expected: owned(original, region), value: .object([:])) + ]) + } + let valid = try document(#"{"a":1,"b":2}"#, .json) + let before = valid.bytes + #expect(throws: NativeDocumentError.self) { + try valid.prepare([ + .put(region: keyRegion("a"), expected: owned(valid, keyRegion("a")), value: .integer(3)), + .put(region: keyRegion("b"), expected: .absent, value: .integer(4)), + ]) + } + #expect(valid.bytes == before) + let source = "[owned]\nargs=[\n# keep array note\n\"a\"\n]\n" + let table = try document(source) + #expect(throws: NativeDocumentError.self) { + try table.prepare([ + .remove(region: keyRegion("owned"), expected: owned(table, keyRegion("owned"))) + ]) + } +} + +@Test func occurrenceIdentityEvidenceAndAliasOverlap() throws { + let source = "[[checks]]\nid=\"é\"\nx=1\n[[checks]]\nid=\"e\u{301}\"\nx=2" + let doc = try document(source) + let array = try #require(try doc.read(keyRegion("checks"))) + let second = NativeRegion([ + .key("checks"), .occurrence(.init(idKey: "id", id: "e\u{301}")), .key("x"), + ]) + #expect(try doc.read(second)?.value == .integer(2)) + let same = NativeRegion([.key("checks"), .occurrence(array.occurrences[1]), .key("x")]) + #expect(throws: NativeDocumentError.self) { + try doc.prepare([ + .put(region: second, expected: owned(doc, second), value: .integer(3)), + .put(region: same, expected: owned(doc, same), value: .integer(4)), + ]) + } + let id = NativeRegion([.key("checks"), .occurrence(.init(idKey: "id", id: "é")), .key("id")]) + let renamed = try doc.prepare([ + .put(region: id, expected: owned(doc, id), value: .string("renamed")) + ]) + #expect(renamed.observations.first?.value == .string("renamed")) + #expect( + renamed.observations.first?.region + == NativeRegion([.key("checks"), .occurrence(.init(idKey: "id", id: "renamed")), .key("id")])) + let duplicates = try document("[[checks]]\nx=1\n[[checks]]\nx=2\n[[checks]]\nx=1") + let evidence = try #require(try duplicates.read(keyRegion("checks"))).occurrences[2] + #expect( + try duplicates.read(NativeRegion([.key("checks"), .occurrence(evidence), .key("x")]))?.value + == .integer(1)) +} + +@Test func arrayDraftsPreserveOriginalOwnershipAddresses() throws { + let doc = try document( + "[[checks]]\nid=\"first\"\nx=1\n[[checks]]\nid=\"second\"\nx=2\n[[checks]]\nid=\"third\"\nx=3") + func occurrence(_ id: String, _ key: String? = nil) -> NativeRegion { + var steps: [NativePathStep] = [.key("checks"), .occurrence(.init(idKey: "id", id: id))] + if let key { steps.append(.key(key)) } + return NativeRegion(steps) + } + let renamed = try doc.prepare([ + .put( + region: occurrence("second", "id"), expected: owned(doc, occurrence("second", "id")), + value: .string("renamed")), + .put( + region: occurrence("second", "x"), expected: owned(doc, occurrence("second", "x")), + value: .integer(22)), + ]) + #expect(renamed.observations.count == 2) + #expect(renamed.observations.last?.value == .integer(22)) + let removed = try doc.prepare([ + .remove(region: occurrence("first"), expected: owned(doc, occurrence("first"))), + .remove(region: occurrence("second"), expected: owned(doc, occurrence("second"))), + ]) + #expect(text(removed).contains("id=\"third\"")) + #expect(!text(removed).contains("id=\"second\"")) +} + +@Test func exactTOMLDecimalProjectionAndTrueEOF() throws { + let doc = try document("n=+1_000.00\nx=12:13:14.1") + let region = keyRegion("n") + let observation = try #require(try doc.read(region)) + #expect(observation.value == .decimal("1000.00")) + #expect(observation.numericLexeme == "+1_000.00") + #expect( + try doc.prepare([ + .put(region: region, expected: .owned(observation), value: .decimal("1000.00")) + ]).bytes == doc.bytes) + #expect(try doc.prepare([]).bytes == doc.bytes) + #expect(throws: NativeDocumentError.self) { + try doc.prepare([.put(region: region, expected: .owned(observation), value: .decimal("1_000"))]) + } +} + +@Test func nativeCanonicalTableCollisionAndReadOnlyReasons() throws { + let a = "prefixabcdefgh-a\u{301}\u{327}-zyxwvuts" + let b = "prefixabcdefgh-a\u{327}\u{301}-zyxwvuts" + let source = "title=\"old\"\n[\"\(a)\"]\nx=1\n[\"\(b)\"]\nx=2" + let doc = try document(source) + #expect(try doc.read(keyRegion(a, "x"))?.value == .integer(1)) + #expect(try doc.read(keyRegion(b, "x"))?.value == .integer(2)) + #expect( + text( + try doc.prepare([ + .put( + region: keyRegion("title"), expected: owned(doc, keyRegion("title")), + value: .string("new")) + ])) == source.replacingOccurrences(of: "\"old\"", with: "\"new\"")) + for source in ["x={\na=1,\n}", #"x="\x41""#, #"x="\e""#, "x=12:13"] { + let doc = try document(source) + #expect(try doc.read(keyRegion("x")) != nil) + do { + _ = try doc.prepare([ + .put(region: keyRegion("x"), expected: owned(doc, keyRegion("x")), value: .string("new")) + ]) + Issue.record("read-only syntax was edited") + } catch NativeDocumentError.unsupportedEdit(.syntaxNotLocated, _, _) {} + } +} + +@Test func cancellationAndReadOnlyAdmissionAreNotSyntaxFallbacks() throws { + var checks = 0 + let cancelled = NativeDocumentBudget( + limits: .init( + storage: 1_000_000, work: 1_000_000, nodes: 10_000, depth: 30, uninterruptedBytes: 100_000), + cancellation: { + checks += 1 + return checks > 100 + }) + do { + _ = try document("#" + String(repeating: "x", count: 10_000), budget: cancelled) + Issue.record("cancellation was ignored") + } catch NativeDocumentError.cancelled {} + let wide = "x={\n" + (0..<1000).map { "k\($0)=1," }.joined(separator: "\n") + "\n}" + let bounded = NativeDocumentBudget( + limits: .init( + storage: 1_000_000, work: 20_000, nodes: 100_000, depth: 30, uninterruptedBytes: 100_000)) + do { + _ = try document(wide, budget: bounded) + Issue.record("read-only semantics escaped the work budget") + } catch NativeDocumentError.budgetExceeded {} + for source in [ + "#" + String(repeating: "x", count: 2000), "x=1\n" + String(repeating: " ", count: 2000), + "x=\"" + String(repeating: "x", count: 2000) + "\"", + ] { + let budget = NativeDocumentBudget( + limits: .init( + storage: 1_000_000, work: 1_000_000, nodes: 100_000, depth: 30, uninterruptedBytes: 100)) + do { + _ = try document(source, budget: budget) + Issue.record("CST envelope was not enforced") + } catch NativeDocumentError.budgetExceeded(let stage) { + #expect(stage == "CST uninterrupted input") + } + } +} + +@Test func regionalInsertionUsesLocalWhitespace() throws { + let pretty = "{\n \"owned\": {\n \"a\":1 // keep field note\n },\n \"keep\": true\n}" + let doc = try document(pretty, .jsonc(trailingCommas: false)) + let result = try doc.prepare([ + .put(region: keyRegion("owned", "b"), expected: .absent, value: .integer(2)) + ]) + #expect( + text(result) + == pretty.replacingOccurrences(of: "\"a\":1", with: "\"a\":1,").replacingOccurrences( + of: " },", with: " \"b\":2\n },")) + let compact = try document("{\"a\":1}", .json) + #expect( + text(try compact.prepare([.put(region: keyRegion("b"), expected: .absent, value: .integer(2))])) + == "{\"a\":1,\"b\":2}") + let inline = try document("x={ a = 1, b = 2 }") + #expect( + text( + try inline.prepare([.put(region: keyRegion("x", "c"), expected: .absent, value: .integer(3))]) + ) == "x={ a = 1, b = 2, \"c\" = 3 }") +} + +@Test func absentOccurrenceAppendAndOwnedArrayTables() throws { + let source = "[[checks]]\nid=\"first\"\n[checks.env]\nMODE=\"a\"\n[other]\nvalue=\"keep\"" + let doc = try document(source) + let second = NativeRegion([.key("checks"), .occurrence(.init(idKey: "id", id: "second"))]) + #expect(try doc.read(second) == nil) + let appended = try doc.prepare([ + .put( + region: second, expected: .absent, + value: .object(["id": .string("second"), "env": .object(["MODE": .string("b")])])) + ]) + #expect(text(appended).hasPrefix(source)) + let parsed = try NativeDocument(bytes: appended.bytes, format: .toml, budget: generousBudget()) + #expect( + try parsed.read(NativeRegion(second.steps + [.key("env"), .key("MODE")]))?.value == .string("b") + ) + #expect(try parsed.read(keyRegion("other", "value"))?.value == .string("keep")) + #expect(throws: NativeDocumentError.self) { + try doc.prepare([ + .put(region: second, expected: .absent, value: .object(["id": .string("wrong")])) + ]) + } + let array = keyRegion("checks") + let replaced = try doc.prepare([ + .put( + region: array, expected: owned(doc, array), + value: .array([ + .object(["id": .string("renamed"), "env": .object(["MODE": .string("new")])]), + .object(["id": .string("second")]), + ])) + ]) + #expect(text(replaced).contains("value=\"keep\"")) + #expect( + try NativeDocument(bytes: replaced.bytes, format: .toml, budget: generousBudget()).read( + NativeRegion([ + .key("checks"), .occurrence(.init(idKey: "id", id: "renamed")), .key("env"), .key("MODE"), + ]))?.value == .string("new")) + let json = try document("{\"checks\":[{\"id\":\"first\"}],\"keep\":true}", .json) + let jsonAppend = try json.prepare([ + .put(region: second, expected: .absent, value: .object(["id": .string("second")])) + ]) + #expect( + try NativeDocument(bytes: jsonAppend.bytes, format: .json, budget: generousBudget()).read( + second)?.value == .object(["id": .string("second")])) +} + +@Test func finalArrayOccurrenceRetainsItsContainer() throws { + let doc = try document( + "[[checks]] # keep table note\nid=\"last\"\n[checks.env]\nMODE=\"a\"\n[other]\nx=1") + let occurrence = NativeRegion([.key("checks"), .occurrence(.init(idKey: "id", id: "last"))]) + let removed = try doc.prepare([.remove(region: occurrence, expected: owned(doc, occurrence))]) + let result = try NativeDocument(bytes: removed.bytes, format: .toml, budget: generousBudget()) + #expect(try result.read(keyRegion("checks"))?.value == .array([])) + #expect(text(removed).contains("# keep table note")) + #expect(text(removed).contains("[other]\nx=1")) + let mixed = try doc.prepare([ + .put( + region: keyRegion("checks"), expected: owned(doc, keyRegion("checks")), + value: .array([.integer(1), .string("two")])) + ]) + #expect( + try NativeDocument(bytes: mixed.bytes, format: .toml, budget: generousBudget()).read( + keyRegion("checks"))?.value == .array([.integer(1), .string("two")])) + let emptySet = try doc.prepare([ + .put(region: keyRegion("checks"), expected: owned(doc, keyRegion("checks")), value: .array([])) + ]) + #expect( + try NativeDocument(bytes: emptySet.bytes, format: .toml, budget: generousBudget()).read( + keyRegion("checks"))?.value == .array([])) +} + +@Test func completeJSONCObjectIntentPreservesUnselectedBytes() throws { + let source = + "{\n \"owned\": {\"a\": 1, /* keep */ \"b\": 2, \"c\": 3},\n \"outside\": { \"sentinel\": true }\n}" + let doc = try document(source, .jsonc(trailingCommas: false)) + let region = keyRegion("owned") + let change = try doc.prepare([ + .put( + region: region, expected: owned(doc, region), + value: .object(["a": .integer(1), "b": .integer(20), "new": .string("yes")])) + ]) + let result = try NativeDocument( + bytes: change.bytes, format: .jsonc(trailingCommas: false), budget: generousBudget()) + #expect( + try result.read(region)?.value + == .object([ + "a": .integer(1), "b": .integer(20), "new": .string("yes"), + ])) + #expect(try result.read(keyRegion("owned", "c")) == nil) + #expect(text(change).contains("/* keep */")) + #expect(text(change).hasSuffix(",\n \"outside\": { \"sentinel\": true }\n}")) +} + +@Test func occurrenceEvidenceAcrossExternalChanges() throws { + let original = try document(#"{"items":[{"x":0},{"x":1},{"x":2}]}"#, .json) + let evidence = try #require(try original.read(keyRegion("items"))).occurrences[1] + let selected = NativeRegion([.key("items"), .occurrence(evidence), .key("x")]) + let observation = try #require(try original.read(selected)) + #expect(observation.value == .integer(1)) + let changed = try document(#"{"items":[{"x":0},{"x":1},{"x":2},{"x":0},{"x":1},{"x":2}]}"#, .json) + do { + _ = try changed.prepare([ + .put(region: selected, expected: .owned(observation), value: .integer(9)) + ]) + Issue.record("ambiguous occurrence was edited") + } catch NativeDocumentError.unsupportedEdit(.ambiguousOccurrence, _, _) {} + + let first = try document(#"{"items":[{"id":"a","x":1},{"id":"b","x":2}]}"#, .json) + let stable = NativeRegion([.key("items"), .occurrence(.init(idKey: "id", id: "b")), .key("x")]) + let prior = try #require(try first.read(stable)) + let inserted = try document( + #"{"items":[{"id":"new","x":0},{"id":"a","x":1},{"id":"b","x":2}]}"#, .json) + let result = try inserted.prepare([ + .put(region: stable, expected: .owned(prior), value: .integer(7)) + ]) + #expect(text(result) == #"{"items":[{"id":"new","x":0},{"id":"a","x":1},{"id":"b","x":7}]}"#) +} + +@Test func sharedBudgetAcrossDocumentsAndDrafts() throws { + func budget(_ work: Int) -> NativeDocumentBudget { + NativeDocumentBudget( + limits: .init( + storage: 1_000_000, work: work, nodes: 10_000, depth: 30, uninterruptedBytes: 10_000)) + } + func consume(_ budget: NativeDocumentBudget) throws { + let doc = try document(#"{"data":[1,2,3,4,5,6,7,8]}"#, .json, budget: budget) + _ = try doc.read(keyRegion("data")) + } + func setup(_ budget: NativeDocumentBudget) throws -> (NativeDocument, [NativeRegionEdit]) { + let doc = try document(#"{"a":1,"b":2}"#, .json, budget: budget) + let edits: [NativeRegionEdit] = try [ + .put(region: keyRegion("a"), expected: owned(doc, keyRegion("a")), value: .integer(3)), + .put(region: keyRegion("b"), expected: owned(doc, keyRegion("b")), value: .integer(4)), + ] + return (doc, edits) + } + var demonstrated = false + for limit in stride(from: 100, through: 5000, by: 50) { + do { + try consume(budget(limit)) + let (doc, edits) = try setup(budget(limit)) + _ = try doc.prepare(edits) + } catch NativeDocumentError.budgetExceeded { continue } + let shared = budget(limit) + try consume(shared) + let doc: NativeDocument + let edits: [NativeRegionEdit] + do { + (doc, edits) = try setup(shared) + } catch NativeDocumentError.budgetExceeded { continue } + do { + _ = try doc.prepare(edits) + } catch NativeDocumentError.budgetExceeded { + demonstrated = true + break + } + } + #expect(demonstrated) +} + +@Test func publicErrorsDistinguishInvalidDocumentsAndOwnership() throws { + for source in ["deep=[{bad=2023-02-30}]", #"deep=[{bad="\q"}]"#, "x=9223372036854775808"] { + do { + _ = try document(source) + Issue.record("invalid document was accepted") + } catch NativeDocumentError.invalidDocument {} + } + let doc = try document(#"{"a":1}"#, .json) + do { + _ = try doc.prepare([.put(region: keyRegion("a"), expected: .absent, value: .integer(1))]) + Issue.record("unowned value was adopted") + } catch NativeDocumentError.ownershipMismatch {} +} + +@Test func dottedInlineInsertionStaysWithinBraces() throws { + let source = "# keep\nx = { a.b = 1, z = 2 } # outside\n" + let doc = try document(source) + let region = keyRegion("x", "a", "c") + for ownedParent in [false, true] { + let edit: NativeRegionEdit + if ownedParent { + let parent = keyRegion("x", "a") + edit = .put( + region: parent, expected: try owned(doc, parent), + value: .object([ + "b": .integer(1), "c": .object(["d": .integer(2)]), + ])) + } else { + edit = .put(region: region, expected: .absent, value: .object(["d": .integer(2)])) + } + let change = try doc.prepare([edit]) + #expect(text(change) == "# keep\nx = { a.b = 1, z = 2, \"a\".\"c\" = {\"d\" = 2} } # outside\n") + let added = try NativeDocument(bytes: change.bytes, format: .toml, budget: generousBudget()) + #expect(try added.read(region)?.value == .object(["d": .integer(2)])) + let child = keyRegion("x", "a", "c", "d") + let update = try added.prepare([ + .put(region: child, expected: owned(added, child), value: .integer(3)) + ]) + #expect(text(update) == text(change).replacingOccurrences(of: "= 2}", with: "= 3}")) + let remove = try added.prepare([.remove(region: region, expected: owned(added, region))]) + #expect( + try NativeDocument(bytes: remove.bytes, format: .toml, budget: generousBudget()).read( + keyRegion("x"))?.value == .object(["a": .object(["b": .integer(1)]), "z": .integer(2)])) + #expect(text(remove).contains("a.b = 1, z = 2")) + #expect(text(remove).hasSuffix(" # outside\n")) + } + let whole = keyRegion("x") + let desired: NativeValue = .object([ + "a": .object(["b": .integer(1), "c": .integer(3)]), "z": .integer(2), "extra": .integer(4), + ]) + let additions = NativeRegionEdit.put( + region: whole, expected: try owned(doc, whole), value: desired) + do { + let change = try doc.prepare([additions]) + #expect( + text(change) == "# keep\nx = { a.b = 1, z = 2, \"a\".\"c\" = 3, \"extra\" = 4 } # outside\n") + let checked = try NativeDocument(bytes: change.bytes, format: .toml, budget: generousBudget()) + #expect(try checked.read(whole)?.value == desired) + #expect(try doc.prepare([additions]).bytes == change.bytes) + } catch { + Issue.record(error) + } + do { + _ = try doc.prepare([ + additions, .put(region: region, expected: .absent, value: .integer(3)), + ]) + Issue.record("overlapping owned and child intents were accepted") + } catch NativeDocumentError.unsupportedEdit(.overlappingEdits, _, _) {} + let implicit = keyRegion("x", "a") + let removals: [NativeRegionEdit] = try [ + .remove(region: implicit, expected: owned(doc, implicit)), + .put(region: whole, expected: owned(doc, whole), value: .object(["z": .integer(2)])), + ] + for edit in removals { + do { + let change = try doc.prepare([edit]) + #expect(text(change) == source.replacingOccurrences(of: "a.b = 1,", with: "")) + let checked = try NativeDocument(bytes: change.bytes, format: .toml, budget: generousBudget()) + #expect(try checked.read(whole)?.value == .object(["z": .integer(2)])) + } catch { + Issue.record(error) + } + } +} + +@Test(arguments: invalidTOMLExtensionsAndTimes) +func invalidTOMLCannotBecomeReadOnly(_ source: String) throws { + do { + _ = try document(source) + Issue.record("invalid TOML admitted as a document") + } catch NativeDocumentError.invalidDocument {} +} + +@Test func tomlDELStringsAndKeysRoundTrip() throws { + let source = #"x="\u007F""# + let doc = try document(source) + let x = keyRegion("x") + #expect( + try doc.prepare([.put(region: x, expected: owned(doc, x), value: .string("\u{7f}"))]).bytes + == doc.bytes) + let key = "key\u{7f}" + let change = try doc.prepare([ + .put(region: keyRegion(key), expected: .absent, value: .string("value\u{7f}")) + ]) + #expect(!change.bytes.contains(127)) + let result = try NativeDocument(bytes: change.bytes, format: .toml, budget: generousBudget()) + #expect(try result.read(keyRegion(key))?.value == .string("value\u{7f}")) +} diff --git a/Tests/NativeDocumentsTests/OccurrenceInsertionTests.swift b/Tests/NativeDocumentsTests/OccurrenceInsertionTests.swift new file mode 100644 index 0000000..e8d7445 --- /dev/null +++ b/Tests/NativeDocumentsTests/OccurrenceInsertionTests.swift @@ -0,0 +1,286 @@ +import AgentsCore +import Foundation +import NativeDocuments +import Testing + +@Suite("Ordered native occurrence insertion") +struct OccurrenceInsertionTests { + @Test func equalUnmanagedHooksRemainDistinctAndOwnersRemoveIndependently() throws { + let source = + #"{"hooks":{"SessionStart":[{"command":"check"},{"command":"check"}]},"other":true}"# + let array = keyRegion("hooks", "SessionStart") + let hook = NativeValue.object(["command": .string("check")]) + let original = try document(source, .json) + let added = try original.prepare([ + .append(region: array, expected: owned(original, array), value: hook), + .append(region: array, expected: owned(original, array), value: hook), + ]) + #expect( + text(added) + == source.replacingOccurrences( + of: "]}", with: ", {\"command\": \"check\"}, {\"command\": \"check\"}]}")) + #expect(added.appendedOccurrences.map(\.editIndex) == [0, 1]) + let first = added.appendedOccurrences[0].observation + let second = added.appendedOccurrences[1].observation + #expect(first.region != second.region) + let live = try NativeDocument(bytes: added.bytes, format: .json, budget: generousBudget()) + #expect(try live.read(first.region)?.value == hook) + #expect(try live.read(second.region)?.value == hook) + let removed = try live.prepare([ + .remove(region: first.region, expected: .owned(first)), + .put(region: second.region, expected: .owned(second), value: hook), + ]) + #expect(removed.observations.count == 1) + let retained = try #require(removed.observations.first) + let fresh = try NativeDocument(bytes: removed.bytes, format: .json, budget: generousBudget()) + // A stale duplicate must not move ownership to the last equal unmanaged occurrence. + #expect(try fresh.read(second.region) == nil) + let restored = try fresh.prepare([ + .remove(region: retained.region, expected: .owned(retained)) + ]) + #expect(text(restored) == source.replacingOccurrences(of: "]}", with: " ]}")) + } + + @Test func appendPreservesJSONCCommentsAndCreatesOnlyMissingContainers() throws { + let source = + "{\n \"hooks\": {\"BeforeAgent\": [\n {\"command\":\"unmanaged\"} // retained\n ]},\n // sibling\n \"other\": 7\n}" + let original = try document(source, .jsonc(trailingCommas: true)) + let array = keyRegion("hooks", "BeforeAgent") + let changed = try original.prepare([ + .append( + region: array, expected: owned(original, array), value: .object(["command": .string("new")]) + ) + ]) + #expect( + text(changed) + == source.replacingOccurrences( + of: "{\"command\":\"unmanaged\"} // retained\n", + with: "{\"command\":\"unmanaged\"}, // retained\n {\"command\": \"new\"}\n")) + let empty = try document("{\"other\":7}", .json) + let created = try empty.prepare([ + .append(region: array, expected: .absent, value: .object(["command": .string("new")])) + ]) + let new = try NativeDocument(bytes: created.bytes, format: .json, budget: generousBudget()) + #expect(try new.read(array)?.occurrences.count == 1) + #expect(try new.read(keyRegion("other"))?.value == .integer(7)) + #expect(created.createdContainers.contains(keyRegion("hooks"))) + #expect(created.createdContainers.contains(array)) + let inserted = try #require(created.appendedOccurrences.first).observation + let removed = try new.prepare([ + .pruneCreatedContainer( + region: keyRegion("hooks"), observed: #require(try new.read(keyRegion("hooks")))), + .pruneCreatedContainer(region: array, observed: #require(try new.read(array))), + .remove(region: inserted.region, expected: .owned(inserted)), + ]) + #expect(text(removed) == "{\"other\":7}") + } + + @Test func createdContainersUnderSnapshotParentsResolveAndPrune() throws { + for removeEarlier in [false, true] { + let source = + removeEarlier + ? #"{"items":[{"remove":true},{"keep":true}]}"# : #"{"items":[{"keep":true}]}"# + let original = try document(source, .json) + let items = keyRegion("items") + let occurrences = try #require(try original.read(items)).occurrences + let parent = NativeRegion(items.steps + [.occurrence(occurrences[removeEarlier ? 1 : 0])]) + let array = NativeRegion(parent.steps + [.key("nested"), .key("hooks")]) + var edits: [NativeRegionEdit] = [ + .append(region: array, expected: .absent, value: .integer(1)), + .append(region: array, expected: .absent, value: .integer(2)), + ] + if removeEarlier { + let first = NativeRegion(items.steps + [.occurrence(occurrences[0])]) + edits.append(.remove(region: first, expected: try owned(original, first))) + } + let changed = try original.prepare(edits) + let live = try NativeDocument(bytes: changed.bytes, format: .json, budget: generousBudget()) + #expect(changed.createdContainers.count == 2) + var removals: [NativeRegionEdit] = [] + for region in changed.createdContainers { + let observed = try #require(try live.read(region)) + removals.append(.pruneCreatedContainer(region: region, observed: observed)) + } + for insertion in changed.appendedOccurrences { + removals.append( + .remove(region: insertion.observation.region, expected: .owned(insertion.observation))) + } + let restored = try live.prepare(removals) + let restoredDocument = try NativeDocument( + bytes: restored.bytes, format: .json, budget: generousBudget()) + #expect( + try restoredDocument.read(items)?.value == .array([.object(["keep": .boolean(true)])])) + #expect(!text(restored).contains("nested")) + } + } + + @Test func tomlOccurrencesAppendWithoutNativeIDsAndPreserveUnrelatedBytes() throws { + for source in [ + "hooks = [{ command = 'keep' }] # retained\nother = 7\n", + "# retained\nother = 7\n[[hooks]]\ncommand = 'keep'\n", + ] { + let original = try document(source) + let array = keyRegion("hooks") + let changed = try original.prepare([ + .append( + region: array, expected: owned(original, array), + value: .object(["command": .string("new")])) + ]) + #expect(text(changed).contains("command = 'keep'")) + #expect(text(changed).contains("# retained\n")) + #expect(text(changed).contains("other = 7\n")) + #expect(!text(changed).contains("id")) + let live = try NativeDocument(bytes: changed.bytes, format: .toml, budget: generousBudget()) + let inserted = try #require(changed.appendedOccurrences.first).observation + let removed = try live.prepare([.remove(region: inserted.region, expected: .owned(inserted))]) + #expect(text(removed) == (source.hasPrefix("#") ? source + "\n\n" : source)) + } + } + + @Test func sameSnapshotRemovalAppendAndRefreshPreserveOrder() throws { + let original = try document(#"{"items":["unmanaged","old","retained"]}"#, .json) + let array = keyRegion("items") + let entries = try #require(try original.read(array)).occurrences + let old = NativeRegion(array.steps + [.occurrence(entries[1])]) + let retained = NativeRegion(array.steps + [.occurrence(entries[2])]) + let changed = try original.prepare([ + .append(region: array, expected: owned(original, array), value: .string("new")), + .remove(region: old, expected: owned(original, old)), + .put(region: retained, expected: owned(original, retained), value: .string("retained")), + .append(region: array, expected: owned(original, array), value: .string("last")), + ]) + let live = try NativeDocument(bytes: changed.bytes, format: .json, budget: generousBudget()) + #expect( + try live.read(array)?.value + == .array([.string("unmanaged"), .string("retained"), .string("new"), .string("last")])) + #expect(changed.appendedOccurrences.map(\.editIndex) == [0, 3]) + #expect( + try live.read(changed.appendedOccurrences[0].observation.region)?.value == .string("new")) + #expect( + try live.read(changed.appendedOccurrences[1].observation.region)?.value == .string("last")) + } + + @Test func appendRetainsIdentityThroughConditionalOccurrencePruning() throws { + let original = try document(#"{"items":[{"payload":{"owned":1}},{"unmanaged":true}]}"#, .json) + let array = keyRegion("items") + let first = try #require(try original.read(array)).occurrences[0] + let selected = NativeRegion(array.steps + [.occurrence(first)]) + let payload = NativeRegion(selected.steps + [.key("payload")]) + let child = NativeRegion(payload.steps + [.key("owned")]) + let changed = try original.prepare([ + .append( + region: array, expected: owned(original, array), value: .object(["new": .boolean(true)])), + .pruneCreatedContainer(region: selected, observed: #require(try original.read(selected))), + .pruneCreatedContainer(region: payload, observed: #require(try original.read(payload))), + .remove(region: child, expected: owned(original, child)), + ]) + let live = try NativeDocument(bytes: changed.bytes, format: .json, budget: generousBudget()) + let inserted = try #require(changed.appendedOccurrences.first).observation + #expect( + try live.read(array)?.value + == .array([ + .object(["unmanaged": .boolean(true)]), .object(["new": .boolean(true)]), + ])) + #expect(try live.read(inserted.region)?.value == .object(["new": .boolean(true)])) + } + + @Test func explicitAppendComposesWithExistingNativeIDInsertion() throws { + let original = try document(#"{"items":[{"id":"existing"}]}"#, .json) + let array = keyRegion("items") + let nativeID = NativeRegion(array.steps + [.occurrence(.init(idKey: "id", id: "named"))]) + let changed = try original.prepare([ + .append(region: array, expected: owned(original, array), value: .string("last")), + .put(region: nativeID, expected: .absent, value: .object(["id": .string("named")])), + ]) + let live = try NativeDocument(bytes: changed.bytes, format: .json, budget: generousBudget()) + let inserted = try #require(changed.appendedOccurrences.first).observation + #expect( + try live.read(array)?.value + == .array([ + .object(["id": .string("existing")]), .object(["id": .string("named")]), .string("last"), + ])) + #expect(try live.read(inserted.region)?.value == .string("last")) + } + + @Test func insertionEvidenceReconstructsWithoutOffsetsAndRejectsCorruption() throws { + let original = try document(#"{"items":["same","same"]}"#, .json) + let array = keyRegion("items") + let changed = try original.prepare([ + .append(region: array, expected: owned(original, array), value: .string("same")) + ]) + let observation = try #require(changed.appendedOccurrences.first).observation + guard case .occurrence(let saved) = observation.region.steps.last else { + Issue.record("missing insertion evidence") + return + } + let snapshot = try #require(saved.snapshot) + let ordinal = try #require(saved.ordinal) + let arraySnapshot = try #require(saved.arraySnapshot) + let retained = NativeOccurrenceEvidence( + snapshot: snapshot, ordinal: ordinal, + previous: saved.previous, next: saved.next, arraySnapshot: arraySnapshot) + let selected = NativeRegion(array.steps + [.occurrence(retained)]) + let live = try NativeDocument(bytes: changed.bytes, format: .json, budget: generousBudget()) + #expect(try live.read(selected)?.value == .string("same")) + let corrupt = NativeOccurrenceEvidence( + snapshot: snapshot, ordinal: ordinal, + previous: saved.previous, next: saved.next, arraySnapshot: Data("corrupt".utf8)) + #expect(try live.read(NativeRegion(array.steps + [.occurrence(corrupt)])) == nil) + } + + @Test func appendSharesTheOperationBudgetAcrossDraftsAndEvidence() throws { + func bounded() -> NativeDocumentBudget { + NativeDocumentBudget( + limits: .init( + storage: 1_000_000, work: 100_000, nodes: 10_000, depth: 30, + uninterruptedBytes: 10_000)) + } + let source = #"{"items":[]}"# + let array = keyRegion("items") + let value = NativeValue.string(String(repeating: "x", count: 2048)) + let single = try document(source, .json, budget: bounded()) + #expect( + try single.prepare([ + .append(region: array, expected: owned(single, array), value: value) + ]).appendedOccurrences.count == 1) + let batch = try document(source, .json, budget: bounded()) + let edits = try (0..<16).map { _ in + NativeRegionEdit.append(region: array, expected: try owned(batch, array), value: value) + } + do { + _ = try batch.prepare(edits) + Issue.record("unbounded cumulative append work") + } catch NativeDocumentError.budgetExceeded {} + #expect(batch.bytes == Data(source.utf8)) + } + + @Test func staleAppendPreimageOrdinaryOverlapAndAmbiguousEvidenceRefuse() throws { + let array = keyRegion("items") + let original = try document(#"{"items":[1,1]}"#, .json) + let changed = try document(#"{"items":[1,1,1]}"#, .json) + #expect(throws: NativeDocumentError.self) { + try changed.prepare([ + .append(region: array, expected: owned(original, array), value: .integer(2)) + ]) + } + #expect(throws: NativeDocumentError.self) { + try original.prepare([ + .put(region: array, expected: owned(original, array), value: .array([])), + .append(region: array, expected: owned(original, array), value: .integer(2)), + ]) + } + let ambiguous = try document(#"{"items":[1,1,1,1,1]}"#, .json) + let evidence = try #require(try ambiguous.read(array)).occurrences[2] + #expect(throws: NativeDocumentError.self) { + try ambiguous.read(NativeRegion(array.steps + [.occurrence(evidence)])) + } + let insertion = try original.prepare([ + .append(region: array, expected: owned(original, array), value: .integer(1)) + ]) + let owner = try #require(insertion.appendedOccurrences.first).observation + let externallyChanged = try document(#"{"items":[1,1,1,1]}"#, .json) + #expect(throws: NativeDocumentError.self) { + try externallyChanged.prepare([.remove(region: owner.region, expected: .owned(owner))]) + } + } +} diff --git a/Tests/NativeDocumentsTests/SemanticTests.swift b/Tests/NativeDocumentsTests/SemanticTests.swift new file mode 100644 index 0000000..4b7e19a --- /dev/null +++ b/Tests/NativeDocumentsTests/SemanticTests.swift @@ -0,0 +1,144 @@ +import Foundation +import NativeDocuments +import Testing + +@testable import TOMLSemantics + +func generousBudget() -> SemanticBudget { + SemanticBudget( + limits: .init( + storage: 20_000_000, work: 20_000_000, nodes: 100_000, depth: 128, + uninterruptedBytes: 1_000_000)) +} + +@Test func exactKeysAndLazyValidation() throws { + let a = "prefixabcdefgh-a\u{301}\u{327}-zyxwvuts" + let b = "prefixabcdefgh-a\u{327}\u{301}-zyxwvuts" + let doc = try SemanticDocument( + source: "\"é\"=1\n\"e\u{301}\"=2\n\"\(a)\"=3\n\"\(b)\"=4", budget: generousBudget()) + guard case .object(let pairs) = doc.root else { + Issue.record("root") + return + } + #expect(pairs.count == 4) + #expect(pairs[0].key.utf8.elementsEqual("é".utf8)) + #expect(pairs[1].key.utf8.elementsEqual("e\u{301}".utf8)) + #expect(throws: (any Error).self) { + try SemanticDocument(source: "a=1\n\"\\u0061\"=2", budget: generousBudget()) + } + for source in [ + "deep=[{bad=2023-02-30}]", #"deep=[{bad="\q"}]"#, "x=9223372036854775808", "x=1979-05", + "x=12:13:", + ] { + #expect(throws: (any Error).self) { + try SemanticDocument(source: source, budget: generousBudget()) + } + } + for source in ["x=12:13:14.1", "x=12:13", "x={\na=1,\n}", "x=[0xFE,1.0,true,1979-05-27,\"yes\"]"] + { + _ = try SemanticDocument(source: source, budget: generousBudget()) + } +} + +@Test func semanticBudgetAndCancellation() throws { + let tiny = SemanticBudget( + limits: .init(storage: 2, work: 100, nodes: 10, depth: 3, uninterruptedBytes: 10)) + #expect(throws: SemanticBudget.Failure.self) { try SemanticDocument(source: "x=1", budget: tiny) } + let cancelled = SemanticBudget( + limits: .init(storage: 1000, work: 1000, nodes: 100, depth: 10, uninterruptedBytes: 1000), + cancellation: { true }) + #expect(throws: SemanticBudget.Failure.self) { + try SemanticDocument(source: "x=1", budget: cancelled) + } + var cancellationChecks = 0 + let scanning = SemanticBudget( + limits: .init( + storage: 100_000, work: 100_000, nodes: 10_000, depth: 10, uninterruptedBytes: 100_000), + cancellation: { + cancellationChecks += 1 + return cancellationChecks > 100 + }) + do { + _ = try SemanticDocument(source: "#" + String(repeating: "x", count: 5000), budget: scanning) + Issue.record("semantic comment scanning ignored cancellation") + } catch SemanticBudget.Failure.cancelled {} + let depth = SemanticBudget( + limits: .init( + storage: 100_000, work: 100_000, nodes: 1000, depth: 3, uninterruptedBytes: 100_000)) + #expect(throws: SemanticBudget.Failure.self) { + try SemanticDocument(source: "x={\na={\nb={\nc={\nd=1\n}\n}\n}\n}", budget: depth) + } +} + +let invalidTOMLExtensionsAndTimes = [ + "x={a.b=1,z=2}\n[x.a.c]\nd=2", + "x={a.b=1,z=2}\nx.a.c=2", + "x={a.b=1}\n[[x.a.c]]", + "a=[{}]\n[[a]]", + "x.a=[{}]\n[[x.a]]", + "a=[{id=1}]\n[[a]]", + "x=12:13:14Z", + "x=12:13:14+01:00", +] + +@Test(arguments: invalidTOMLExtensionsAndTimes) +func semanticRejectsClosedInlineStaticArrayAndInvalidTime(_ source: String) throws { + #expect(throws: TOMLError.self) { + try SemanticDocument(source: source, budget: generousBudget()) + } +} + +@Test(arguments: ["", "x={", "x={a={"]) +func dottedDescentAdmitsDepthBeforeParsing(_ prefix: String) throws { + let source = + prefix + String(repeating: "a.", count: 256) + "leaf=1" + + String(repeating: "}", count: prefix.filter { $0 == "{" }.count) + let budget = SemanticBudget( + limits: .init( + storage: 20_000_000, work: 20_000_000, nodes: 100_000, depth: 3, uninterruptedBytes: 1_000_000 + )) + var parser = Parser(budget: budget) + do { + try Array(source.utf8).withUnsafeBufferPointer { try parser.parse(bytes: $0) } + Issue.record("dotted descent bypassed caller depth before semantic traversal") + } catch SemanticBudget.Failure.exceeded(let stage) { + #expect(stage == "depth") + } +} + +@Test(arguments: [2, 4, 3]) +func multilineEOFBackslashParity(_ backslashes: Int) throws { + let source = + "x = " + String(repeating: "\"", count: 3) + String(repeating: "\\", count: backslashes) + + String(repeating: "\"", count: backslashes.isMultiple(of: 2) ? 3 : 4) + let doc = try SemanticDocument(source: source, budget: generousBudget()) + guard case .object(let entries) = doc.root, + case .scalar(kind: .string, let decoded, _, _) = entries[0].value + else { + Issue.record("missing decoded multiline value") + return + } + let expected = + String(repeating: "\\", count: backslashes / 2) + (backslashes.isMultiple(of: 2) ? "" : "\"") + #expect(decoded.utf8.elementsEqual(expected.utf8)) + let native = try document(source) + let region = keyRegion("x") + #expect(try native.read(region)?.value == .string(expected)) + #expect( + try native.prepare([ + .put(region: region, expected: owned(native, region), value: .string(expected)) + ]).bytes == native.bytes) +} + +@Test(arguments: ["1979-05-27", "12:13:14.1", "1979-05-27T07:32:00", "1979-05-27T07:32:00Z"]) +func dateTimeComponentKindsRetainLexemes(_ raw: String) throws { + let doc = try SemanticDocument(source: "x=" + raw, budget: generousBudget()) + guard case .object(let entries) = doc.root, + case .scalar(kind: .dateTime, let decoded, let lexeme, _) = entries[0].value + else { + Issue.record("missing native date/time atom") + return + } + #expect(decoded == raw) + #expect(lexeme == raw) +} diff --git a/Tests/SourcePolicyFixtures.md b/Tests/SourcePolicyFixtures.md new file mode 100644 index 0000000..85f1998 --- /dev/null +++ b/Tests/SourcePolicyFixtures.md @@ -0,0 +1,69 @@ +# Source policy fixtures + +The source-policy tests use disposable projects, homes, Git repositories and +HTTP listeners bound to loopback. Fixtures are independently authored against +Core's public API and the documented allow-list intersection, deny precedence +and identity casing behavior in the [APM policy reference][apm-policy]. + +## Policy inputs + +`SourcePolicyOperations.policyURL` identifies the optional user and project +files (`~/.agents/source-policy.yaml` and `.agent/source-policy.yaml`). A trusted +CLI or App configuration can set `RuntimeEnvironment.organizationSourcePolicyURL` +to an explicitly managed local policy file. A project install evaluates all +configured layers. A user install evaluates the user and explicit organization +layers. A missing explicitly configured organization file fails preparation. + +```yaml +version: 1 +allow: + - git: https://github.com/example/skill-producer.git + - http: https://index.example.org + - local: /absolute/physical/producer + - inline +deny: + - missing +``` + +Git rules name exact host and repository identities. HTTP rules match the +scheme, host and port. Defaults and DNS spelling are normalized. GitHub owner +and repository names are case-insensitive. Git HTTP and git-protocol origins +remain distinct from HTTPS and SSH origins. The bare `local` rule matches any +local source. `inline` describes a consumer-authored component. `missing` +describes external content with unavailable provenance and requires an explicit +allow entry in every configured layer. Omit `allow` for a deny-only layer. +`allow: []` denies every origin in that layer. + +`SourcePolicyDocument.parse` and `bytes(for:)` support CLI and App file editing. +`SourcePolicyOperations.inspect` reports all applicable layers and the read +interests for changes to the policy files. `SourcePolicyOperations.audit` +reports machine-readable violations of committed sources and artifact origins +without acquiring sources. An absent lock produces `hasLock: false`. + +## Integration fixtures + +Registry and bundle implementations share `SourceOrigin` and +`EffectiveSourcePolicy.require` for lookup and selection. Capture +`SourcePolicySnapshot` in the consuming scope, include its entry dependencies in +preview, bind its fingerprint to any preview/apply handle, and register it as +`PreparedEvidence` in the publication transaction. + +Record every acquisition origin in the installed provenance, including the +catalog or registry, fetched artifacts, and upstream and transitive origins. +For bundles, preserve independent evidence of the original source coordinates +of each selected item across export, import, update and replay. The transport +used to deliver the bundle is an additional origin. Evaluate `.missing` when +that original provenance cannot be established. A local staging directory or +inline representation carries no authority to reclassify external content. +The sibling registry and bundle workflows own that evidence and its persistence +in their declarations and lock records. Their integration should exercise the +same rejection and no-publication assertions for offline restore. + +The existing lock can audit the provenance it recorded. Older Git and HTTP +acquisitions may lack the ultimate redirect or rewrite destination. New +policy-controlled Git reads reject rewrites and disable HTTP redirects. New +policy-controlled index reads permit redirects on the original HTTP origin and +require explicit URLs for cross-origin artifacts. Scope and recovery locks use +the existing transaction protocol. + +[apm-policy]: https://microsoft.github.io/apm/reference/policy-schema/#allow-list-semantics diff --git a/Tests/StateTestProcess/LedgerProbe.swift b/Tests/StateTestProcess/LedgerProbe.swift new file mode 100644 index 0000000..28e46f4 --- /dev/null +++ b/Tests/StateTestProcess/LedgerProbe.swift @@ -0,0 +1,106 @@ +import AgentsCore +import AgentsManifest +import Components +import Foundation + +/// An internal assembly probe, deliberately absent from the production renderer table. +private let probeFormat = "test/generated-bundle@1" + +func ledgerProbe(_ action: String, store: StateStore) throws { + let roots = [ + "project": store.environment.projectDirectory, "home": store.environment.homeDirectory, + "state": store.directory, + ] + let limits = LedgerLimits.standard + let renderers: [String: LedgerRenderer] = [ + probeFormat: { lowering, ledger, resources in + let destination = store.environment.projectDirectory.appendingPathComponent("probe-bundle") + if FileManager.default.fileExists(atPath: destination.path) { + try FileManager.default.removeItem(at: destination) + } + try FileManager.default.createDirectory(at: destination, withIntermediateDirectories: true) + let manifest = try ResolvedLedgerCodec.bytes(lowering.inputs.map { ledger.components[$0]! }) + try manifest.write(to: destination.appendingPathComponent("manifest.json")) + for (index, id) in lowering.resources.enumerated() { + try FileManager.default.copyItem( + at: resources[id]!, to: destination.appendingPathComponent("resource-\(index)")) + } + guard let registration = lowering.layout.object?["registration"], + let values = lowering.layout.object?["values"] + else { throw CoreError.invalidState("probe layout") } + return [ + ReplayedArtifact(name: "bundle", kind: .tree, tree: destination), + ReplayedArtifact( + name: "registration", kind: .registration, + bytes: try ResolvedLedgerCodec.bytes(registration)), + ReplayedArtifact(name: "owned", kind: .ownedValues, values: values), + ] + } + ] + if action == "ledger-freeze" { + let document = try DeclarationDocument( + bytes: Array(Data(contentsOf: store.declarationURL)), + identity: DocumentIdentity("probe/agents.yaml")) + let ledger = try ComponentLinker.withLinkedComponents( + document: document, store: store, + platform: { + #if os(macOS) + return .macOS + #else + return .linux + #endif + }() + ) { linked, session in + try LedgerFreeze.freeze( + linked, session: session, + locations: .init(sources: [ + "local:" + store.environment.projectDirectory.path: + LedgerLocation(kind: .registered, root: "project", path: ".") + ]), limits: limits) + } + var candidate = ledger + let inputs = ledger.occurrences.map(\.component) + let resourceIDs = inputs.flatMap { ledger.components[$0]!.resources } + candidate.lowerings = [ + LockedLowering( + id: "bundle", format: probeFormat, inputs: inputs, + resources: resourceIDs, deployments: [], + layout: .init(object: [ + "registration": .init(object: ["root": .init("project"), "path": .init("plugins/bundle")] + ), + "values": .init(object: ["server": ledger.components[inputs[0]]!.payload]), + ]), + platform: { + #if os(macOS) + return "macos" + #else + return "linux" + #endif + }(), artifacts: []) + ] + candidate = try LedgerReplay.prepareLowerings( + candidate, store: store, roots: roots, + limits: limits, renderers: renderers) + try ResolvedLedgerCodec.encode(candidate, limits: limits).write(to: store.resolvedURL) + } else if action == "ledger-compatibility" { + let ledger = try store.loadLedger(limits: limits) + try LedgerReplay.withReplay(ledger, store: store, roots: roots, limits: limits) { artifacts in + try ResolvedLedgerCodec.bytes(try artifacts.map { try $0.digest(limits: limits) }) + .write( + to: store.environment.projectDirectory.appendingPathComponent( + "compatibility-summary.json")) + } + } else if action == "ledger-replay" { + let ledger = try store.loadLedger(limits: limits) + try LedgerReplay.withReplay( + ledger, store: store, roots: roots, limits: limits, + renderers: renderers + ) { artifacts in + let summaries = try artifacts.map { try $0.digest(limits: limits) } + try ResolvedLedgerCodec.bytes(summaries).write( + to: store.environment.projectDirectory.appendingPathComponent("replay-summary.json")) + } + } else { + throw CoreError.invalidState("unknown ledger probe") + } +} diff --git a/Tests/StateTestProcess/OpenFileLimitProbe.swift b/Tests/StateTestProcess/OpenFileLimitProbe.swift new file mode 100644 index 0000000..ab523b3 --- /dev/null +++ b/Tests/StateTestProcess/OpenFileLimitProbe.swift @@ -0,0 +1,120 @@ +import AgentsCore +import Foundation + +#if os(Linux) + import Glibc +#else + import Darwin +#endif + +func openFileLimitProbe(_ mode: String, root: URL, store: StateStore) throws { + #if os(Linux) + let resource = Int32(RLIMIT_NOFILE.rawValue) + #else + let resource = RLIMIT_NOFILE + #endif + var before = rlimit() + guard getrlimit(resource, &before) == 0 else { + throw POSIXError(.EINVAL) + } + if mode == "bounded" { + before.rlim_max = min(before.rlim_max, 64) + before.rlim_cur = min(before.rlim_max, 32) + } else if mode == "worker" { + before.rlim_cur = min(before.rlim_max, 4096) + } else { + before.rlim_cur = min(before.rlim_max, 256) + } + guard setrlimit(resource, &before) == 0 else { throw POSIXError(.EINVAL) } + + if mode == "raised" || mode == "bounded" { ProcessLimits.raiseOpenFileLimit() } + var after = rlimit() + guard getrlimit(resource, &after) == 0 else { throw POSIXError(.EINVAL) } + + let large = + if mode == "worker" { + try sharedCoordinationWorkerProbe(store: store) + } else { + try sharedCoordinationAdmission(store: store, count: 96) + } + let result = """ + \(before.rlim_cur) + \(before.rlim_max) + \(after.rlim_cur) + \(after.rlim_max) + \(large) + """ + try Data(result.utf8).write(to: root.appendingPathComponent("open-file-limit-\(mode)")) +} + +private func sharedCoordinationAdmission(store: StateStore, count: Int) throws -> String { + let routes = try (0..) throws { + var calls = 0 + let value: Int? = try store.withReadLock(footprint: footprint) { + calls += 1 + return nil + } + precondition(calls == 1 && value == nil) + } + try read(Set(routes.prefix(2))) + do { + try read(Set(routes)) + return "admitted" + } catch where error.localizedDescription.hasPrefix("Too many open files for this process:") { + return error.localizedDescription + } +} + +private func sharedCoordinationWorkerProbe(store: StateStore) throws -> String { + func check(_ code: Int32) throws { + guard code == 0 else { throw POSIXError(POSIXErrorCode(rawValue: code) ?? .EINVAL) } + } + var attributes = pthread_attr_t() + try check(pthread_attr_init(&attributes)) + defer { pthread_attr_destroy(&attributes) } + try check(pthread_attr_setstacksize(&attributes, SharedCoordinationWorker.stackSize)) + #if os(Linux) + var thread: pthread_t = 0 + #else + var thread: pthread_t? + #endif + let worker = SharedCoordinationWorker(store: store) + let argument = Unmanaged.passRetained(worker) + let created = pthread_create( + &thread, &attributes, + { pointer in + let argument: UnsafeMutableRawPointer? = pointer + guard let argument else { return nil } + let worker = Unmanaged.fromOpaque(argument).takeRetainedValue() + worker.run() + return nil + }, argument.toOpaque()) + if created != 0 { + argument.release() + try check(created) + } + #if os(Linux) + try check(pthread_join(thread, nil)) + #else + try check(pthread_join(thread!, nil)) + #endif + guard let result = worker.result else { + throw CoreError.invalidState("coordination worker did not report a result") + } + return try result.get() +} + +private final class SharedCoordinationWorker { + static let stackSize = 512 * 1024 + let store: StateStore + var result: Result? + + init(store: StateStore) { self.store = store } + + func run() { + result = Result { try sharedCoordinationAdmission(store: store, count: 196) } + } +} diff --git a/Tests/StateTestProcess/PrivateMaterializationProbe.swift b/Tests/StateTestProcess/PrivateMaterializationProbe.swift new file mode 100644 index 0000000..ef73b21 --- /dev/null +++ b/Tests/StateTestProcess/PrivateMaterializationProbe.swift @@ -0,0 +1,184 @@ +import AgentsCore +import AgentsInstructions +import AgentsSkills +import AgentsUpdates +import CPlatform +import Foundation + +func privateMaterializationProbe( + _ command: String, store: StateStore, checkpoint: @escaping (String) throws -> Void +) throws { + let root = store.environment.projectDirectory + if command.hasPrefix("private-legacy-") { + let target = try store.skillInstallationTarget(for: .claudeCode, named: "private-fixture") + try store.withLock(checkpoint: checkpoint, installations: [target]) { + try Data().write(to: root.appendingPathComponent("legacy-callback")) + let transaction = FileTransaction(store: store, checkpoint: checkpoint) + try transaction.replaceSkill(target, with: .copy(root.appendingPathComponent("new"))) + try transaction.commit() + } + return + } + if command.hasPrefix("private-tree-") { + if command == "private-tree-recover" { + do { try store.withLock(checkpoint: checkpoint, {}) } catch CoreError.transactionRecovered {} + return + } + let route = try NativeTargetRoute.named( + .claudeSkillPlugin, scope: .user, name: "private-fixture") + try store.withLock(checkpoint: checkpoint, footprint: [route]) { + if command == "private-tree-lock" { + try checkpoint("tree.locked") + return + } + let target = try store.nativeTarget(for: route) + let prepared = try store.preparePrivateMaterialization(target, changingAccess: true) + let transaction = FileTransaction(store: store, checkpoint: checkpoint) + try transaction.replacePrivateTree( + prepared, + entries: [ + .init("nested", content: .directory), + .init( + "nested/run", + content: .boundFile(bindings: ["value"], executable: true) { + try $0.value(for: "value") + }), + .init("config", content: .boundFile(bindings: ["value"]) { try $0.value(for: "value") }), + .init("alias", content: .symlink("nested/run")), + ], provider: TreeProbeBindings(root: root)) + try transaction.commit() + } + return + } + if command == "private-recover" { + do { try store.withLock(checkpoint: checkpoint, {}) } catch CoreError.transactionRecovered {} + return + } + try store.withLock { + let target = try store.materializationTarget(at: root.appendingPathComponent("AGENTS.md")) + let prepared = try store.preparePrivateMaterialization(target, changingAccess: true) + let transaction = FileTransaction(store: store, checkpoint: checkpoint) + try transaction.replacePrivate( + prepared, bindings: ["value"], provider: ProbeBindings(root: root) + ) { + try $0.value(for: "value") + } + try transaction.commit() + } +} + +private struct ProbeBindings: RuntimeBindingProvider { + let root: URL + func value(for binding: String, environment: RuntimeEnvironment) throws -> Data { + try Data().write(to: root.appendingPathComponent("provider-called")) + return Data("private-after".utf8) + } +} + +func sharedMaterializationProbe( + _ command: String, store: StateStore, checkpoint: @escaping (String) throws -> Void +) throws { + if command == "shared-admission-wait" { + do { + try store.withLock(checkpoint: checkpoint) { + try Data().write( + to: store.environment.projectDirectory.appendingPathComponent("admission-body")) + _ = try ProbeBindings(root: store.environment.projectDirectory).value( + for: "value", environment: store.environment) + } + } catch CoreError.transactionRecovered { + try Data().write( + to: store.environment.projectDirectory.appendingPathComponent("admission-recovered")) + } + return + } + if command == "shared-hold-lock" { + guard let index = CommandLine.arguments.firstIndex(of: "--lock-path"), + CommandLine.arguments.indices.contains(index + 1) + else { throw CoreError.invalidState("missing test lock path") } + try FileLock.withLock(at: URL(fileURLWithPath: CommandLine.arguments[index + 1])) { + try checkpoint("shared.rawLocked") + } + return + } + if command == "shared-skill-recover" { + do { + _ = try SkillOperations.remove(skillNames: ["absent"], environment: store.environment) + } catch CoreError.transactionRecovered {} + return + } + if command == "shared-watch-recover" { + do { + _ = try SkillOperations.watchOperations().remove("absent", environment: store.environment) + } catch CoreError.transactionRecovered {} + return + } + if command == "shared-instruction-recover" { + do { + _ = try InstructionOperations.remove(names: ["absent"], environment: store.environment) + } catch CoreError.transactionRecovered {} + return + } + if command == "shared-recover" { + do { try store.withLock(checkpoint: checkpoint, {}) } catch CoreError.transactionRecovered {} + return + } + let routes: [NativeTargetRoute] + if let index = CommandLine.arguments.firstIndex(of: "--native-routes"), + CommandLine.arguments.indices.contains(index + 1) + { + routes = try CommandLine.arguments[index + 1].split(separator: ",").map { + guard let route = NativeTargetRoute(rawValue: String($0)) else { + throw CoreError.invalidState("invalid test native route") + } + return route + } + } else { + routes = [.claudeMCPLocal] + } + try store.withLock(checkpoint: checkpoint, footprint: Set(routes)) { + if command == "shared-lock" { + try checkpoint("shared.locked") + return + } + if command == "shared-readmission-writer" { try checkpoint("shared.beforeJournal") } + let transaction = FileTransaction(store: store, checkpoint: checkpoint) + for route in routes { + let target = try store.nativeTarget(for: route) + if command == "shared-array-edit" { + let arrays = try store.materializationReceipt(for: target)?.nativeArrays ?? [] + try transaction.replace( + target.url, with: .data(Data(#"{"hooks":["private-value"],"sibling":1}"#.utf8)), + nativeArrayTransitions: arrays.map { .init(previous: $0, current: $0) }) + } else if command == "shared-delete" { + try transaction.delete(target.url) + } else if command == "shared-install" { + let prepared = try store.preparePrivateMaterialization(target, changingAccess: true) + try transaction.replacePrivate( + prepared, bindings: ["value"], + provider: ProbeBindings(root: store.environment.projectDirectory) + ) { try $0.value(for: "value") } + } else { + try transaction.replace(target.url, with: .data(Data("secret sibling; edited region".utf8))) + } + } + if store.scope == .project && command != "shared-array-edit" { + try transaction.replace( + store.environment.projectDirectory.appendingPathComponent("old-data/AGENTS.md"), + with: .data(Data("ordinary after".utf8))) + } + try transaction.commit() + } +} + +private struct TreeProbeBindings: RuntimeBindingProvider { + let root: URL + func value(for binding: String, environment: RuntimeEnvironment) throws -> Data { + let descriptor = open( + root.appendingPathComponent("tree-provider-resolved").path, + O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0o600) + guard descriptor >= 0 else { throw CoreError.invalidState("tree provider cannot replay") } + close(descriptor) + return Data("tree-private-after".utf8) + } +} diff --git a/Tests/StateTestProcess/SourceArchiveProbe.swift b/Tests/StateTestProcess/SourceArchiveProbe.swift new file mode 100644 index 0000000..2e83f5b --- /dev/null +++ b/Tests/StateTestProcess/SourceArchiveProbe.swift @@ -0,0 +1,33 @@ +import AgentsCore +import AgentsUpdates +import Foundation + +func sourceArchiveProbe( + root: URL, input: URL, checkpoint: @escaping (String) throws -> Void +) throws { + let bytes = try Data(contentsOf: input) + let authority = try SourceAuthority(host: "origin.invalid", port: 8443) + let mirror = try SourceArchiveMirror( + source: authority, base: URL(string: "https://mirror.invalid:9443/base/")!, flavor: .github) + let environment = RuntimeEnvironment( + projectDirectory: root.appendingPathComponent("project"), + homeDirectory: root.appendingPathComponent("home"), environment: [:], + acquisitionCacheRoot: root.appendingPathComponent("disposable"), + sourceAccess: .init(egress: .proxyOnly, mirrors: [mirror])) + let declaration = Declaration( + agents: [.codex], + sources: [ + "fixture": .init( + kind: .git, location: "https://origin.invalid:8443/org/repo.git", + requirement: .revision("refs/tags/release/v1")) + ], + skills: ["fixture": .init(select: .names(["demo"]), mode: .link)]) + try PackageSourceHTTP.$fixture.withValue( + { _, _ in .init(status: 200, body: bytes) }, + operation: { + try UpdateOperations.withPreparedUpdate( + .init(operation: .declaration(declaration)), environment: environment, + checkpoint: checkpoint + ) { _ = try $0.apply() } + }) +} diff --git a/Tests/StateTestProcess/main.swift b/Tests/StateTestProcess/main.swift index 1bedbe9..74ec142 100644 --- a/Tests/StateTestProcess/main.swift +++ b/Tests/StateTestProcess/main.swift @@ -1,23 +1,67 @@ import AgentsCore import AgentsInstructions +import AgentsManifest import AgentsSkills import AgentsUpdates -import Darwin +import CPlatform import Foundation +import StateTestSupport +import Synchronization let arguments = CommandLine.arguments let root = URL(fileURLWithPath: arguments[1]) -let scope: InstallScope = arguments.count > 4 && arguments[4] == "user" ? .user : .project +let scopeIndex = arguments.firstIndex(of: "--scope") +let scope: InstallScope = + scopeIndex.flatMap { InstallScope(rawValue: arguments[$0 + 1]) } ?? .project +let sharedConfigIndex = arguments.firstIndex(of: "--shared-config") +let sharedConfig = + sharedConfigIndex.map { arguments[$0 + 1] } + ?? root.appendingPathComponent("configured-claude").path let store = StateStore( scope: scope, environment: RuntimeEnvironment( projectDirectory: root, homeDirectory: root.appendingPathComponent("home"), - environment: ["CLAUDE_CONFIG_DIR": root.appendingPathComponent("configured-claude").path])) -func stop(_ step: String, marker: String = "ready") throws { - if step == arguments[3] { - try Data(step.utf8).write(to: root.appendingPathComponent(marker), options: .atomic) + environment: arguments.contains("--native-routes") + ? [ + "CLAUDE_CONFIG_DIR": sharedConfig, "CODEX_HOME": sharedConfig, + "OPENCODE_CONFIG_DIR": sharedConfig, "GEMINI_CLI_HOME": sharedConfig, + ] + : ["CLAUDE_CONFIG_DIR": sharedConfig])) +if arguments[2] == "open-file-limit" { + try openFileLimitProbe(arguments[3], root: root, store: store) + exit(EXIT_SUCCESS) +} +let checkpointState = Mutex( + (requested: arguments.count > 3 ? arguments[3] : "", seen: Set())) +let traceURL = root.appendingPathComponent( + "checkpoint-\(ProcessInfo.processInfo.processIdentifier).log") +FileManager.default.createFile(atPath: traceURL.path, contents: nil) +let trace = try FileHandle(forWritingTo: traceURL) +/// Names must be unique across the whole recorded process: a repeated name would make a kill +/// point ambiguous, so the recorder fails the run. Each command runs one recorded operation. +func stop(_ point: String, marker: String = "ready") throws { + let (repeated, shouldStop) = checkpointState.withLock { state in + ( + !state.seen.insert(point).inserted, + point == state.requested + || (state.requested == "scope-contention" && point.hasPrefix("scope.") + && FileLock.isContentionCheckpoint(point)) + ) + } + try trace.write(contentsOf: Data((point + "\n").utf8)) + if repeated { fatalError("repeated checkpoint: \(point)") } + // The last visible journal survives its own removal for the parent's assertions. + if let bytes = try? Data(contentsOf: store.directory.appendingPathComponent("transaction.json")) { + try bytes.write(to: root.appendingPathComponent("last-journal")) + } + if shouldStop { + try Data(point.utf8).write(to: root.appendingPathComponent(marker), options: .atomic) raise(SIGSTOP) + // A resumed handshake may select the next stop once, rather than reading on every checkpoint. + let next = + (try? String(contentsOf: root.appendingPathComponent("stop-at"), encoding: .utf8)) ?? "" + checkpointState.withLock { $0.requested = next } } } func signalContention() throws { @@ -25,7 +69,65 @@ func signalContention() throws { defer { try? signal.close() } try signal.write(contentsOf: Data("contended\n".utf8)) } -if arguments[2] == "git-environment" { +if arguments[2].hasPrefix("acquisition-") { + let environment = RuntimeEnvironment( + projectDirectory: root.appendingPathComponent("project"), + homeDirectory: root.appendingPathComponent("home"), environment: [:], + acquisitionCacheRoot: root.appendingPathComponent("shared/cache")) + let cache = AcquisitionCache(environment: environment) + let key = String(repeating: "a", count: 64) + switch arguments[2] { + case "acquisition-publish": + try cache.write(Data("fixture".utf8), store: .git, key: key, object: "test-commit") + case "acquisition-read": + let bytes = try cache.read(.git, key: key, maximumBytes: 1024) { value in + try stop("leased") + return value.data + } + precondition(bytes == Data("fixture".utf8)) + case "acquisition-clean": + let result = try cache.apply(cache.preview(.clean), afterDetach: { try stop("detached") }) + precondition(result.isComplete) + case "acquisition-private-install": + var environment = environment + environment.projectDirectory = root.appendingPathComponent(arguments[3]) + environment.credentialedGitHosts = ["127.0.0.1"] + try FileManager.default.createDirectory( + at: environment.projectDirectory, withIntermediateDirectories: true) + let requirement: SourceRequirement = + arguments.count > 6 ? .revision(arguments[6]) : .branch("main") + let source = SourceDeclaration(kind: .git, location: arguments[4], requirement: requirement) + let intent = Declaration( + agents: [.codex], sources: ["fixture": source], + skills: ["fixture": .init(select: .names(["fixture"]), mode: .link)]) + let expected = arguments[5] == "applied" + let applied: Bool + do { + try UpdateOperations.withPreparedUpdate( + .init(operation: .declaration(intent)), environment: environment + ) { _ = try $0.apply() } + applied = true + } catch { + if expected { throw error } + applied = false + } + precondition(applied == expected) + default: + fatalError("unknown acquisition test operation") + } +} else if arguments[2] == "source-archive" { + try sourceArchiveProbe( + root: root, input: URL(fileURLWithPath: arguments[4]), checkpoint: { try stop($0) }) +} else if arguments[2].hasPrefix("ledger-") { + try ledgerProbe(arguments[2], store: store) +} else if arguments[2] == "existing-configuration" { + let preview = try ExistingGlobalConfiguration.preview(environment: store.environment) + try ExistingGlobalConfiguration.apply(preview, checkpoint: { try stop($0) }) +} else if arguments[2].hasPrefix("shared-") { + try sharedMaterializationProbe(arguments[2], store: store, checkpoint: { try stop($0) }) +} else if arguments[2].hasPrefix("private-") { + try privateMaterializationProbe(arguments[2], store: store, checkpoint: { try stop($0) }) +} else if arguments[2] == "git-environment" { let before = ProcessInfo.processInfo.environment let cache = SourceCache(store: store) let source = SourceDeclaration(kind: .local, location: root.appendingPathComponent("source").path) @@ -71,7 +173,7 @@ if arguments[2] == "git-environment" { } else if arguments[2] == "lock-contender" { try FileLock.withLock( at: root.appendingPathComponent(arguments[3]), - checkpoint: { if $0 == "lock.contended" { try signalContention() } }, + checkpoint: { if FileLock.isContentionCheckpoint($0) { try signalContention() } }, { try Data().write(to: root.appendingPathComponent("lock-acquired")) }) } else if arguments[2] == "closed-streams" { let mask = Int(arguments[3])! @@ -115,9 +217,9 @@ if arguments[2] == "git-environment" { } else if ["watch-subscribe", "watch-acknowledge"].contains(arguments[2]) { let watch = WatchOperations( discoverSkills: { _ in [] }, - fetchArtifacts: { _ in throw CoreError.unsupported("Git fixture") }, + fetchArtifacts: { _ in throw CoreError.unsupported("Git fixture") }, declarations: .manifest, checkpoint: { step in - if step == "mirror.lock.contended" { + if step.hasPrefix("mirror."), FileLock.isContentionCheckpoint(step) { try signalContention() } }) @@ -134,7 +236,7 @@ if arguments[2] == "git-environment" { } else if ["watch-add", "watch-seen", "watch-remove"].contains(arguments[2]) { let watch = WatchOperations( discoverSkills: { _ in [] }, - fetchArtifacts: { _ in throw CoreError.unsupported("Git fixture") }, + fetchArtifacts: { _ in throw CoreError.unsupported("Git fixture") }, declarations: .manifest, checkpoint: { try stop($0) }) if arguments[2] == "watch-add" { try watch.add( @@ -144,23 +246,110 @@ if arguments[2] == "git-environment" { } else { try watch.remove("source", environment: store.environment) } +} else if arguments[2] == "skill-add" { + _ = try SkillOperations.add( + AddOptions( + source: root.appendingPathComponent("source").path, agents: [.codex], + skillNames: ["demo"], mode: .edit, environment: store.environment), + checkpoint: { try stop($0) }) +} else if arguments[2] == "watch-add-artifact" { + let bytes = Data("---\nname: demo\ndescription: Fixture skill.\n---\nBody\n".utf8) + let digest = "sha256:" + FileHash.sha256Hex(data: bytes) + let artifact = WatchArtifact( + name: "demo", + artifact: LockedArtifact( + type: .skillMD, url: "https://watch.example.test/demo/SKILL.md", digest: digest), + files: ["SKILL.md": bytes], payloads: [digest: bytes]) + let watch = WatchOperations( + discoverSkills: { _ in [] }, fetchArtifacts: { _ in [artifact] }, declarations: .manifest, + checkpoint: { try stop($0) }) + try watch.add("https://watch.example.test", alias: "site", environment: store.environment) } else if arguments[2] == "watch-recover" { - try store.withLock(checkpoint: { try stop($0) }, {}) + do { try store.withLock(checkpoint: { try stop($0) }, {}) } catch CoreError.transactionRecovered { + } +} else if arguments[2] == "publication-recover" { + let outcome = TransactionOutcome() + let result: String + do { + try store.withLock(checkpoint: { try stop($0, marker: "recovery-ready") }, outcome: outcome, {}) + result = "clean" + } catch CoreError.transactionRecovered { result = "recovered" } catch { + result = "unresolved: \(error)" + } + try Data(result.utf8).write(to: root.appendingPathComponent("recovery-result")) +} else if arguments[2] == "publication" { + let outcome = TransactionOutcome() + var failure = "" + do { + try store.withLock(outcome: outcome) { + let transaction = FileTransaction(store: store, outcome: outcome) { + try Data(String(describing: outcome.disposition).utf8).write( + to: root.appendingPathComponent("stopped-outcome")) + try stop($0) + } + try transaction.replace( + root.appendingPathComponent("GEMINI.md"), with: .data(Data("auxiliary postimage".utf8))) + let target = + arguments[4] == "crossParentReplace" + ? root.appendingPathComponent(".agents/skills/target") + : root.appendingPathComponent("AGENTS.md") + switch arguments[4] { + case "directoryReplace": + let source = root.appendingPathComponent("new") + try transaction.replace( + target, with: .copy(source), expectedHash: "sha256:" + FileHash.folderHash(source)) + case "directoryDelete": try transaction.delete(target) + case "symlinkCreate": + try transaction.replace(target, with: .link(root.appendingPathComponent("new"))) + default: try transaction.replace(target, with: .data(Data("postimage".utf8))) + } + try transaction.commit() + } + } catch { failure = String(describing: error) } + try Data((String(describing: outcome.disposition) + "\n" + failure).utf8).write( + to: root.appendingPathComponent("publication-result")) } else if arguments[2] == "recover" { - try FileLock.withLock(at: store.directory.appendingPathComponent(".agents.lock")) { - _ = try FileTransaction.recover(store: store) { try stop($0, marker: "recovery-ready") } + if scope == .user { + do { + try store.withLock(checkpoint: { try stop($0, marker: "recovery-ready") }, {}) + } catch CoreError.transactionRecovered {} + } else { + try FileLock.withLock(at: store.directory.appendingPathComponent(".agents.lock")) { + _ = try FileTransaction.recover(store: store) { try stop($0, marker: "recovery-ready") } + } } } else if arguments[2] == "read" { try Data().write(to: root.appendingPathComponent("reader-started")) - do { _ = try store.loadResolved() } catch CoreError.transactionRecovered { - _ = try store.loadResolved() - } + // The reader waits for the writer lock and reports, rather than replays, pending recovery. + do { _ = try store.loadResolved() } catch CoreError.recoveryPending {} try Data().write(to: root.appendingPathComponent("reader-finished")) +} else if arguments[2] == "lifecycle-crash" { + let home = URL(fileURLWithPath: arguments[4]) + let admin = URL(fileURLWithPath: arguments[5]) + let environment = RuntimeEnvironment( + projectDirectory: root, homeDirectory: home, + environment: ["HOME": home.path, "PATH": "/usr/bin:/bin"]) + let killAt = arguments[3] + let request = UpdateRequest(operation: .edit([.setDefaultAgents([.codex])])) + try await LifecycleOperations.$administratorDirectoryForTesting.withValue(admin) { + let review = try UpdateOperations.previewLifecycle( + request, intent: .install, environment: environment) + let attempted = await LifecycleOperations.$transactionCheckpointForTesting.withValue({ step in + if step == killAt { _ = kill(getpid(), SIGKILL) } + }) { + await UpdateOperations.perform(review) + } + switch attempted { + case .completed(let operation): _ = try operation.package.result.get() + case .alreadyRunning: throw CoreError.invalidState("Synthetic review was already running.") + } + throw CoreError.invalidState("Synthetic crash checkpoint was not reached.") + } } else if arguments[2] == "combined-crash" { _ = try UpdateOperations.withPreparedUpdate( scope: scope, environment: store.environment, checkpoint: { step in - if arguments[3] == "between-kinds", step.hasPrefix("replace.") { + if arguments[3] == "between-kinds", step.hasPrefix("entry.") && step.hasSuffix(".applied") { let journal = try JSONSerialization.jsonObject( with: Data(contentsOf: store.directory.appendingPathComponent("transaction.json"))) @@ -169,7 +358,7 @@ if arguments[2] == "git-environment" { let firstInstruction = entries.firstIndex { ($0["path"] as! String).hasPrefix("instructions-") }! - if step == "replace.\(firstInstruction - 1)" { try stop("between-kinds") } + if step == "entry.\(firstInstruction - 1).applied" { try stop("between-kinds") } } else { try stop(step) } @@ -194,6 +383,12 @@ if arguments[2] == "git-environment" { default: _ = try store.loadResolved() } try Data().write(to: root.appendingPathComponent("contender-finished")) +} else if arguments[2] == "pause" { + try stop("paused") +} else if arguments[2] == "unstopped-marker" { + // The marker exists but the process never stops, as when it is killed before its self-stop. + try Data().write(to: root.appendingPathComponent("ready"), options: .atomic) + while true { sleep(1) } } else if arguments[2] == "create-scope" { try FileLock.withLock( at: store.directory.appendingPathComponent(".agents.lock"), checkpoint: { try stop($0) }, @@ -201,63 +396,79 @@ if arguments[2] == "git-environment" { try Data().write(to: root.appendingPathComponent("lock-acquired")) }) } else { - try store.withLock { + let createdSkill = + arguments[2] == "crash" && scope == .user + ? try store.skillInstallationTarget(for: .claudeCode, named: "created") : nil + try store.withLock( + footprint: createdSkill?.footprint ?? [], installations: createdSkill.map { [$0] } ?? [] + ) { if arguments[2] == "cache-content" || arguments[2] == "cache-git" || arguments[2] == "cache-bytes" { let cache = SourceCache(store: store) { try stop($0) } - let lock = try store.readResolved() - guard let skill = lock.skills["demo"], let hash = skill.hash else { - throw CoreError.invalidState("missing fixture skill") + let ledger = try store.readLedger() + guard let resource = ledger.resources["resource"], + let source = ledger.sources[resource.source] + else { + throw CoreError.invalidState("missing fixture resource") } - if arguments[2] == "cache-content", let artifact = skill.artifact { + if arguments[2] == "cache-content", let artifact = resource.artifact { _ = try cache.materializeArtifact( - root.appendingPathComponent("new"), digest: artifact.digest, hash: hash) - } else if arguments[2] == "cache-bytes", let artifact = skill.artifact { + root.appendingPathComponent("new"), digest: artifact.digest, hash: resource.hash) + } else if arguments[2] == "cache-bytes", let artifact = resource.artifact { _ = try cache.storeArtifact( Data(contentsOf: root.appendingPathComponent("payload")), digest: artifact.digest) - } else if let revision = skill.revision, let source = lock.sources[skill.source] { - _ = try cache.materialize(sourceID: skill.source, source: source, revision: revision) + } else if let location = source.location { + let identity = "local:" + (try location.resolve(roots: store.ledgerRoots).path) + _ = try cache.materialize( + sourceID: identity, source: LockedSource(kind: .local), revision: source.revision) } else { throw CoreError.invalidState("missing fixture pin") } + } else if arguments[2] == "inspection-transaction" { let transaction = FileTransaction(store: store) { try stop($0) } try transaction.replace( AgentRegistry.installSkillsDirectory( for: .codex, scope: scope, environment: store.environment - ).appendingPathComponent("target"), content: root.appendingPathComponent("new")) - try transaction.replace( - InstructionLocations.file(for: .codex, scope: scope, environment: store.environment)!, - content: nil) + ).appendingPathComponent("target"), with: .copy(root.appendingPathComponent("new"))) + try transaction.delete( + InstructionLocations.file(for: .codex, scope: scope, environment: store.environment)!) try transaction.replace( InstructionLocations.file(for: .geminiCLI, scope: scope, environment: store.environment)!, - content: nil, data: Data("New instructions\n".utf8)) + with: .data(Data("New instructions\n".utf8))) try transaction.replace( - store.declarationURL, content: nil, data: StateStore.encode(Declaration(agents: [.cursor]))) + store.declarationURL, with: .data(manifestText("defaultAgents: [\"cursor\"]\n"))) try transaction.replace( - store.resolvedURL, content: nil, data: StateStore.encode(ResolvedState())) + store.resolvedURL, + with: .data(try ResolvedLedgerCodec.encode(ResolvedLedger(), limits: .standard))) try transaction.commit() } else if arguments[2] == "watch-crash" { - var declaration = try store.readDeclaration() + let baseline = try StatePrecondition(store: store) + let previous = try store.readDeclaration(prepared: baseline) + var declaration = previous declaration.watch = ["source"] let watch = WatchState(sources: [ "local:/source": WatchSourceState(seen: .revision(String(repeating: "b", count: 40))) ]) let transaction = FileTransaction(store: store) { try stop($0) } - try transaction.replace( - store.declarationURL, content: nil, data: StateStore.encode(declaration)) - try transaction.replace(store.watchURL, content: nil, data: StateStore.encode(watch)) + try store.stageDeclaration( + store.planDeclaration(declaration, replacing: previous, prepared: baseline), + in: transaction, prepared: baseline) + try transaction.replace(store.watchURL, with: .data(StateStore.encode(watch))) try transaction.commit() } else if arguments[2] == "writer" { for index in 0..<5 { - var declaration = try store.readDeclaration() + let baseline = try StatePrecondition(store: store) + let previous = try store.readDeclaration(prepared: baseline) + var declaration = previous declaration.sources["\(arguments[3])-\(index)"] = SourceDeclaration( kind: .local, location: root.appendingPathComponent("\(arguments[3])-\(index)").path) usleep(10_000) let transaction = FileTransaction(store: store) - try transaction.replace( - store.declarationURL, content: nil, data: StateStore.encode(declaration)) + try store.stageDeclaration( + store.planDeclaration(declaration, replacing: previous, prepared: baseline), + in: transaction, prepared: baseline) try transaction.commit() } } else { @@ -268,24 +479,24 @@ if arguments[2] == "git-environment" { AgentRegistry.installSkillsDirectory( for: .codex, scope: scope, environment: store.environment ) - .appendingPathComponent("target"), - content: root.appendingPathComponent("new")) - try transaction.replace( - store.declarationURL, content: nil, data: StateStore.encode(Declaration(agents: [.codex]))) - try transaction.replace( - store.resolvedURL, content: nil, - data: StateStore.encode(ResolvedState(sources: ["local:/new": LockedSource(kind: .local)]))) - try transaction.replace( - store.cacheDirectory.appendingPathComponent("artifact-content/pruned"), content: nil) + .appendingPathComponent("target"), with: .copy(root.appendingPathComponent("new"))) try transaction.replace( - AgentRegistry.installSkillsDirectory( - for: .claudeCode, scope: scope, environment: store.environment - ).appendingPathComponent("created"), - content: root.appendingPathComponent("new"), - link: true) + store.declarationURL, with: .data(manifestText("defaultAgents: [\"codex\"]\n"))) + var ledger = ResolvedLedger() + ledger.sources["local:/new"] = LedgerSource(kind: .local, revision: "live") + try transaction.replace(store.resolvedURL, with: .data(StateStore.encode(ledger))) + try transaction.delete(store.cacheDirectory.appendingPathComponent("artifact-content/pruned")) + if let createdSkill { + try transaction.replaceSkill(createdSkill, with: .link(root.appendingPathComponent("new"))) + } else { + try transaction.replace( + AgentRegistry.installSkillsDirectory( + for: .claudeCode, scope: scope, environment: store.environment + ).appendingPathComponent("created"), with: .link(root.appendingPathComponent("new"))) + } try transaction.replace( InstructionLocations.file(for: .codex, scope: scope, environment: store.environment)!, - content: nil, data: Data("new instructions".utf8)) + with: .data(Data("new instructions".utf8))) try transaction.commit() } } diff --git a/Tests/StateTestSupport/DeclarationStateFixture.swift b/Tests/StateTestSupport/DeclarationStateFixture.swift new file mode 100644 index 0000000..bf479d2 --- /dev/null +++ b/Tests/StateTestSupport/DeclarationStateFixture.swift @@ -0,0 +1,67 @@ +import AgentsCore +import AgentsManifest +import Foundation + +extension StateStore { + package func save(declaration: Declaration, resolved: ResolvedState, watch: WatchState? = nil) + throws + { + try withLock { + try declaration.validate(environment: environment) + try resolved.validate() + try watch?.validate() + let baseline = try StatePrecondition(store: self) + let previous = try readDeclaration(prepared: baseline) + var change = try planDeclaration(declaration, replacing: previous, prepared: baseline) + if change == nil, try declarationBytes(prepared: baseline) == nil { + change = DeclarationChange(bytes: Data("version: 1\n".utf8)) + } + let transaction = FileTransaction(store: self) + transaction.requireUnchanged(since: baseline) + try stageDeclaration(change, in: transaction, prepared: baseline) + let existing = try readLedger(prepared: baseline) + let view = try existing.domainProjection(roots: ledgerRoots) + guard resolved == ResolvedState() || view == resolved + else { + throw CoreError.invalidState("fixture must seed an explicit resolved ledger") + } + let ledger = resolved == ResolvedState() ? ResolvedLedger() : existing + try stageLedger(ledger, limits: .standard, transaction: transaction, prepared: baseline) + if let watch { + try transaction.replace( + watchURL, with: .data(StateStore.encode(watch)), + expecting: baseline.evidence(for: watchURL)) + } + try transaction.commit() + } + } + +} + +extension StateStore { + package func save( + declaration: Declaration, ledger: ResolvedLedger, watch: WatchState? = nil + ) throws { + try withLock { + try declaration.validate(environment: environment) + try watch?.validate() + _ = try readWatch() + let baseline = try StatePrecondition(store: self) + let previous = try readDeclaration(prepared: baseline) + let change = + try planDeclaration(declaration, replacing: previous, prepared: baseline) + ?? (try declarationBytes(prepared: baseline) == nil + ? DeclarationChange(bytes: Data("version: 1\n".utf8)) : nil) + let transaction = FileTransaction(store: self) + transaction.requireUnchanged(since: baseline) + try stageDeclaration(change, in: transaction, prepared: baseline) + try stageLedger(ledger, limits: .standard, transaction: transaction, prepared: baseline) + if let watch { + try transaction.replace( + watchURL, with: .data(StateStore.encode(watch)), + expecting: baseline.evidence(for: watchURL)) + } + try transaction.commit() + } + } +} diff --git a/Tests/StateTestSupport/ManifestText.swift b/Tests/StateTestSupport/ManifestText.swift new file mode 100644 index 0000000..53a7564 --- /dev/null +++ b/Tests/StateTestSupport/ManifestText.swift @@ -0,0 +1,6 @@ +import Foundation + +/// YAML fields for transaction fixtures that need bytes without the declaration model. +package func manifestText(_ fields: String = "") -> Data { + Data(("version: 1\n" + fields + (fields.hasSuffix("\n") || fields.isEmpty ? "" : "\n")).utf8) +} diff --git a/Tests/StateTestSupport/ProcessWait.swift b/Tests/StateTestSupport/ProcessWait.swift new file mode 100644 index 0000000..c2c70b4 --- /dev/null +++ b/Tests/StateTestSupport/ProcessWait.swift @@ -0,0 +1,105 @@ +import Foundation + +/// Every wait on a test child is bounded. Marker, stop and exit waits share one deadline and a +/// diagnostic naming the child's last checkpoint; termination has its own shorter deadline. +package enum ProcessWait { + package static func marker(_ file: URL, child: Process, root: URL, timeout: TimeInterval = 120) + throws + { + try until(child, root: root, timeout: timeout, description: file.lastPathComponent) { + FileManager.default.fileExists(atPath: file.path) + } + } + + package static func exit(_ child: Process, root: URL, timeout: TimeInterval = 120) throws { + try until(child, root: root, timeout: timeout, description: "process exit") { !child.isRunning } + } + + /// A checkpoint writes its marker before raising SIGSTOP. Signals sent before the stop takes + /// effect can be lost, so a paused child is resumed or killed only after this returns. + package static func stopped(_ child: Process, root: URL, timeout: TimeInterval = 120) throws { + try until(child, root: root, timeout: timeout, description: "process stop") { + isStopped(child.processIdentifier) + } + } + + /// `WNOWAIT` leaves the stop reportable; Foundation reaps only exits. + private static func isStopped(_ processIdentifier: Int32) -> Bool { + var info = siginfo_t() + guard waitid(P_PID, id_t(processIdentifier), &info, WSTOPPED | WNOHANG | WNOWAIT) == 0 else { + return false + } + return info.si_signo == SIGCHLD && info.si_code == Int32(CLD_STOPPED) + } + + /// SIGKILL can be lost while a child is stopping itself, so it is resent until the exit is + /// observed. The deadline bounds the whole termination. + package static func terminate( + _ child: Process, timeout: TimeInterval = 30, retry: TimeInterval = 0.2, + send: (Int32) -> Void = { _ = kill($0, SIGKILL) } + ) throws { + let deadline = Date().addingTimeInterval(timeout) + while child.isRunning { + guard Date() < deadline else { + throw WaitFailure( + message: + "Process \(child.processIdentifier) survived SIGKILL for \(timeout) seconds") + } + send(child.processIdentifier) + let resend = min(deadline, Date().addingTimeInterval(retry)) + while child.isRunning, Date() < resend { Thread.sleep(forTimeInterval: 0.005) } + } + } + + package static func condition(_ child: Process, root: URL, description: String, ready: () -> Bool) + throws + { + try until(child, root: root, timeout: 120, description: description, ready: ready) + } + + /// A grandchild has no waitable exit status in this process; its parent owns that status. + package static func condition( + processIdentifier: Int32, root: URL, description: String, + isRunning: () -> Bool, ready: () -> Bool + ) throws { + try until( + processIdentifier: processIdentifier, root: root, timeout: 120, description: description, + isRunning: isRunning, status: { "unavailable: not a direct child" }, ready: ready) + } + + private static func until( + _ child: Process, root: URL, timeout: TimeInterval, + description: String, ready: () -> Bool + ) throws { + try until( + processIdentifier: child.processIdentifier, root: root, timeout: timeout, + description: description, isRunning: { child.isRunning }, + status: { + child.isRunning + ? "unavailable while running" : "\(child.terminationStatus) (\(child.terminationReason))" + }, ready: ready) + } + + private static func until( + processIdentifier: Int32, root: URL, timeout: TimeInterval, description: String, + isRunning: () -> Bool, status: () -> String, ready: () -> Bool + ) throws { + let deadline = Date().addingTimeInterval(timeout) + while !ready(), isRunning(), Date() < deadline { Thread.sleep(forTimeInterval: 0.01) } + guard ready() else { + let trace = root.appendingPathComponent("checkpoint-\(processIdentifier).log") + let last = + (try? String(contentsOf: trace, encoding: .utf8))?.split(separator: "\n").last.map( + String.init) ?? "none" + throw WaitFailure( + message: + "Timed out or exited before \(description); alive=\(isRunning()), exit=\(status()), last checkpoint=\(last)" + ) + } + } + + private struct WaitFailure: Error, CustomStringConvertible { + let message: String + var description: String { message } + } +} From c67ec0892f4f37bbfb581b24d2270af4e3d100ec Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:33:02 +0800 Subject: [PATCH 2/9] fix: restore release validation across platforms --- .../AcquisitionCache/AcquisitionStorage.swift | 4 +- .../AuthorLockedPackageTests.swift | 17 ++++---- Tests/ComponentsTests/LinkBudgetTests.swift | 40 +++++++++++++++---- 3 files changed, 43 insertions(+), 18 deletions(-) diff --git a/Sources/AgentsCore/AcquisitionCache/AcquisitionStorage.swift b/Sources/AgentsCore/AcquisitionCache/AcquisitionStorage.swift index cc7c07b..44e8d5d 100644 --- a/Sources/AgentsCore/AcquisitionCache/AcquisitionStorage.swift +++ b/Sources/AgentsCore/AcquisitionCache/AcquisitionStorage.swift @@ -431,7 +431,7 @@ extension AcquisitionCache { errno, at: entry.url.appendingPathComponent(file), otherwise: .invalidState("cannot remove cache file")) } - reclaimed += info.st_size + reclaimed += Int64(info.st_size) } try entry.sync() guard try trash.info(entryName).map(FileObjectIdentity.init) == expected.identities["."] @@ -458,7 +458,7 @@ extension AcquisitionCache { } stats[name] = info identities[name] = FileObjectIdentity(info) - let sum = bytes.addingReportingOverflow(info.st_size) + let sum = bytes.addingReportingOverflow(Int64(info.st_size)) guard !sum.overflow else { throw AcquisitionCacheError.invalidEntry } bytes = sum.partialValue } diff --git a/Tests/AgentsUpdatesTests/AuthorLockedPackageTests.swift b/Tests/AgentsUpdatesTests/AuthorLockedPackageTests.swift index f38da27..7c27d9b 100644 --- a/Tests/AgentsUpdatesTests/AuthorLockedPackageTests.swift +++ b/Tests/AgentsUpdatesTests/AuthorLockedPackageTests.swift @@ -40,11 +40,10 @@ struct AuthorLockedPackageTests { let ledger = try fixture.store.loadLedger() #expect(ledger.resources.values.contains { $0.kind == .git }) #expect(ledger.resources.values.contains { $0.kind == .embedded }) + let lockedSkill = MarketplaceMemberKey(kind: .skills, name: "getting-started") let spec = AuthorPackageSpecification( package: .init(name: "mixed", version: "2.0.0"), - lockedMembers: [ - .init(kind: .skills, name: "getting-started"), .init(kind: .instructions, name: "rules"), - ]) + lockedMembers: [lockedSkill, .init(kind: .instructions, name: "rules")]) try FileManager.default.removeItem(at: catalog) let before = try FileHash.folderHash(fixture.root) let artifact = try AuthorPackageOperations.preview(spec, environment: fixture.environment) @@ -62,21 +61,23 @@ struct AuthorLockedPackageTests { let installed = try UpdateOperations.inspect(environment: consumer.environment) #expect(installed.components.map(\.name) == ["getting-started"]) + let policySpec = AuthorPackageSpecification(package: spec.package, lockedMembers: [lockedSkill]) + let policyArtifact = try AuthorPackageOperations.preview( + policySpec, environment: fixture.environment) let policy = fixture.root.appendingPathComponent("org.yaml") var denied = fixture.environment denied.userOrganizationPolicy = .init(.local(policy)) try fixture.write("enforcement: block\ndependencies: {deny: ['_local/leaf']}", to: policy) do { - _ = try AuthorPackageOperations.preview(spec, environment: denied) + _ = try AuthorPackageOperations.preview(policySpec, environment: denied) Issue.record("Transitive package was not denied.") } catch let error as OrganizationPolicyFailure { - #expect( - error.report.findings.contains { $0.rule == "package-deny" && $0.identity == "_local/leaf" } - ) + let findings = error.report.findings.map { "\($0.rule): \($0.identity)" } + #expect(findings.contains("package-deny: _local/leaf")) } let output = fixture.root.appendingPathComponent("denied.bundle") #expect(throws: OrganizationPolicyFailure.self) { - try AuthorPackageOperations.write(artifact, to: output, environment: denied) + try AuthorPackageOperations.write(policyArtifact, to: output, environment: denied) } #expect(!FileManager.default.fileExists(atPath: output.path)) } diff --git a/Tests/ComponentsTests/LinkBudgetTests.swift b/Tests/ComponentsTests/LinkBudgetTests.swift index 87ecfd3..efa72a1 100644 --- a/Tests/ComponentsTests/LinkBudgetTests.swift +++ b/Tests/ComponentsTests/LinkBudgetTests.swift @@ -1,4 +1,5 @@ import AgentsCore +import AgentsManifest import Components import Foundation import Testing @@ -32,18 +33,41 @@ struct LinkBudgetTests { } } - @Test func repeatedContributionsReachLimitAndRejectOverflow() throws { + @Test func oversizedInstructionSectionsFailManifestAdmission() throws { let fixture = try LinkFixture() - try fixture.instruction("rules", at: fixture.project) - func expression(overflow: Bool) -> String { - let sections = Array(repeating: "name: rules", count: 10_000).joined(separator: ",") - let extra = overflow ? ", {kind: instructions, sections: [{name: rules}]}" : "" - return "version: 1\ncomponents: [{kind: instructions, sections: [\(sections)]}\(extra)]\n" + let sections = Array(repeating: "name: rules", count: 10_000).joined(separator: ",") + let expression = "version: 1\ncomponents: [{kind: instructions, sections: [\(sections)]}]\n" + + do { + _ = try fixture.document(expression) + Issue.record("expected source map limit") + } catch let failure as ManifestFailure { + #expect(failure.stage == .admission) + #expect(failure.diagnostics.first?.code == "manifest.limit") + #expect(failure.diagnostics.first?.message == "source map budget") + } + } + @Test func repeatedContributionsReachLimitAndRejectOverflow() throws { + let fixture = try LinkFixture() + let source = fixture.root.appendingPathComponent("skills-source") + for index in 0..<500 { + try fixture.skill("skill-\(index)", at: source) + } + let selection = "{kind: skills, source: p, mode: edit}" + let selections = Array(repeating: selection, count: 20) + let extra = "{kind: skills, source: p, mode: edit, select: [skill-0]}" + func expression(_ selections: [String]) -> String { + """ + version: 1 + sources: {p: {path: "\(source.path)"}} + components: [\(selections.joined(separator: ","))] + """ } - #expect(try fixture.link(expression(overflow: false)).components.count == 10_000) + + #expect(try fixture.link(expression(selections)).components.count == 10_000) do { - _ = try fixture.link(expression(overflow: true)) + _ = try fixture.link(expression(selections + [extra])) Issue.record("expected occurrence limit") } catch LinkError.budget(let name) { #expect(name == "contribution occurrences") From f9ee42d6d05b66864a7b06dbfc8ac6c88fa0a9be Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:45:10 +0800 Subject: [PATCH 3/9] fix(instructions): scope Claude forwarding update previews --- Documentation/Architecture/Instructions.md | 11 +++++++---- .../InstructionLifecycleModels.swift | 3 ++- Sources/AgentsUpdates/InstructionOperations.swift | 1 + .../AgentsUpdates/InstructionOutputPreview.swift | 2 +- Sources/AgentsUpdates/UpdateReporting.swift | 11 +++++++---- .../AgentsUpdatesTests/InstructionBuildTests.swift | 14 +++++++++++--- .../LifecycleCompositionTests.swift | 9 ++++++--- 7 files changed, 35 insertions(+), 16 deletions(-) diff --git a/Documentation/Architecture/Instructions.md b/Documentation/Architecture/Instructions.md index 43e1d77..4328ad1 100644 --- a/Documentation/Architecture/Instructions.md +++ b/Documentation/Architecture/Instructions.md @@ -203,10 +203,13 @@ operations supply their own dependencies. Planning validates required content before applying. Reports include old and new section records, target before/after bytes and recipients, drift, foreign targets, a missing-lock status and changed prompt names. -`InstructionUpdateReport.outputs` provides the complete candidate bytes for -each local recipient and target, including unchanged files and the assembled -Claude forwarding file. Recipients that share a file have the same URL and -bytes. ChatGPT App and Gemini App produce ordered Markdown with no file URL. +`InstructionUpdateReport.outputs` provides candidate bytes for each local +recipient and target, including unchanged targets. Update reviews show the +managed import block for Claude forwarding files. The read-only +`InstructionOperations.previewOutputs` operation shows the assembled +forwarding file, including handwritten content. Recipients that share a file +have the same URL and bytes. ChatGPT App and Gemini App produce ordered +Markdown with no file URL. Their selections and input pins can be saved with the declaration and lock. Named prompt exports use their own declaration and append file. `InstructionTargetChange.beforeAgents` is nil when the previous lock has no target diff --git a/Sources/AgentsInstructions/InstructionLifecycleModels.swift b/Sources/AgentsInstructions/InstructionLifecycleModels.swift index 2d5cbb6..c51143b 100644 --- a/Sources/AgentsInstructions/InstructionLifecycleModels.swift +++ b/Sources/AgentsInstructions/InstructionLifecycleModels.swift @@ -134,7 +134,8 @@ public struct InstructionUpdateReport: Codable, Sendable, Equatable { private let buildOutputs: [InstructionBuildOutput]? private let advisoryMessages: [String]? private let conflictMessages: [String]? - /// Complete candidate bytes for each selected recipient and target, including unchanged files. + /// Candidate bytes for each selected recipient and target, including unchanged targets. + /// Update reviews expose the managed import block for a shared Claude forwarding file. public var outputs: [InstructionBuildOutput] { buildOutputs ?? [] } /// Informational guidance about applying the selected instructions. public var advisories: [String] { advisoryMessages ?? [] } diff --git a/Sources/AgentsUpdates/InstructionOperations.swift b/Sources/AgentsUpdates/InstructionOperations.swift index b439acb..2216e12 100644 --- a/Sources/AgentsUpdates/InstructionOperations.swift +++ b/Sources/AgentsUpdates/InstructionOperations.swift @@ -13,6 +13,7 @@ struct InstructionAddition: Sendable { extension InstructionOperations { /// Compiles the saved instruction outputs under read locks without preparing publication. + /// Claude forwarding output includes the assembled destination file. public static func previewOutputs( scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment() ) throws -> CombinedUpdateReport { diff --git a/Sources/AgentsUpdates/InstructionOutputPreview.swift b/Sources/AgentsUpdates/InstructionOutputPreview.swift index 6d12136..da50bab 100644 --- a/Sources/AgentsUpdates/InstructionOutputPreview.swift +++ b/Sources/AgentsUpdates/InstructionOutputPreview.swift @@ -47,7 +47,7 @@ enum InstructionOutputPreview { changes: aggregation.changes, ledger: aggregation.ledger, artifacts: artifacts, lockMissing: lockMissing, included: true, store: store, stateChanged: prior.lowerings.flatMap(\.artifacts) != next.lowerings.flatMap(\.artifacts), - conflicts: aggregation.antigravityConflicts) + conflicts: aggregation.antigravityConflicts, includeUnmanagedForwardingContent: true) let locations = try UpdateOperations.readLocations( declarations: [], ledgers: [aggregation.ledger], store: store, roots: roots) diff --git a/Sources/AgentsUpdates/UpdateReporting.swift b/Sources/AgentsUpdates/UpdateReporting.swift index b8f99df..ae8049e 100644 --- a/Sources/AgentsUpdates/UpdateReporting.swift +++ b/Sources/AgentsUpdates/UpdateReporting.swift @@ -133,7 +133,7 @@ enum UpdateReporting { before: LockedInstructions, after: LockedInstructions, changes: [AggregatedChange], ledger: ResolvedLedger, artifacts: [ReplayedArtifact], lockMissing: Bool, included: Bool, store: StateStore, stateChanged: Bool, - conflicts: [String] + conflicts: [String], includeUnmanagedForwardingContent: Bool = false ) throws -> InstructionUpdateReport { guard included else { return InstructionUpdateReport( @@ -187,10 +187,13 @@ enum UpdateReporting { "Antigravity shares a 20,000-token budget across active global and always-on rules. " + "When exceeded, the largest rules may be loaded as file pointers." ] : [] - var outputs = changes.flatMap { change -> [InstructionBuildOutput] in - guard !change.native, InstructionLocations.isInstructionFormat(change.deployment.route), - let content = change.after + var outputs = try changes.flatMap { change -> [InstructionBuildOutput] in + guard !change.native, InstructionLocations.isInstructionFormat(change.deployment.route) else { return [] } + let bytes = + includeUnmanagedForwardingContent || change.deployment.ownership != .importBlock + ? change.after : try InstructionTargets.ownedImportBytes(change.after) + guard let content = bytes else { return [] } let key = InstructionLocations.key(for: change.url, store: store) return (after.targets[key]?.agents ?? []).map { agent in InstructionBuildOutput( diff --git a/Tests/AgentsUpdatesTests/InstructionBuildTests.swift b/Tests/AgentsUpdatesTests/InstructionBuildTests.swift index 42a27e1..d9401ae 100644 --- a/Tests/AgentsUpdatesTests/InstructionBuildTests.swift +++ b/Tests/AgentsUpdatesTests/InstructionBuildTests.swift @@ -194,8 +194,8 @@ struct InstructionBuildTests { #expect(Set(local.map(\.content)).count == 1) #expect(local.allSatisfy { !String(decoding: $0.content, as: UTF8.self).contains("old") }) let claude = try #require(outputs.first { $0.fileURL?.path == forwarding.path }) - #expect(String(decoding: claude.content, as: UTF8.self).hasSuffix(original)) - #expect(String(decoding: claude.content, as: UTF8.self).contains("@AGENTS.md")) + let importBlock = Data(ClaudeForwarding.renderBlock(for: .root).utf8) + #expect(claude.content == importBlock) #expect(!FileManager.default.fileExists(atPath: shared.path)) #expect(!FileManager.default.fileExists(atPath: fixture.store.declarationURL.path)) #expect(!FileManager.default.fileExists(atPath: fixture.store.resolvedURL.path)) @@ -207,8 +207,16 @@ struct InstructionBuildTests { } #expect(applied.report.instructions.outputs == outputs) for output in outputs { - if let file = output.fileURL { #expect(try fixture.bytes(file) == output.content) } + if let file = output.fileURL, file.path != forwarding.path { + #expect(try fixture.bytes(file) == output.content) + } } + let assembled = importBlock + Data(("\n" + original).utf8) + #expect(try fixture.bytes(forwarding) == assembled) + let explicitPreview = try InstructionOperations.previewOutputs(environment: fixture.environment) + let forwardingOutput = try #require( + explicitPreview.instructions.outputs.first { $0.fileURL?.path == forwarding.path }) + #expect(forwardingOutput.content == assembled) let unchanged = try fixture.preview().instructions #expect(!unchanged.hasChanges) #expect(unchanged.outputs == outputs) diff --git a/Tests/AgentsUpdatesTests/LifecycleCompositionTests.swift b/Tests/AgentsUpdatesTests/LifecycleCompositionTests.swift index 495c4b7..bdca133 100644 --- a/Tests/AgentsUpdatesTests/LifecycleCompositionTests.swift +++ b/Tests/AgentsUpdatesTests/LifecycleCompositionTests.swift @@ -396,9 +396,11 @@ extension LifecycleCompositionTests { let file = fixture.root.appendingPathComponent("CLAUDE.md") try fixture.write("# Private sibling sentinel\n", to: file) let report = try fixture.preview() - #expect( - !String(decoding: try JSONEncoder().encode(report), as: UTF8.self).contains( - "Private sibling sentinel")) + let decoded = try JSONDecoder().decode( + CombinedUpdateReport.self, from: JSONEncoder().encode(report)) + let forwarding = try #require( + decoded.instructions.outputs.first { $0.fileURL?.path == file.path }) + #expect(forwarding.content == Data(ClaudeForwarding.renderBlock(for: .root).utf8)) _ = try fixture.apply() let before = try fixture.bytes(file) let fingerprint = try fixture.preview().displayedFingerprint @@ -410,6 +412,7 @@ extension LifecycleCompositionTests { try before.write(to: file) #expect(throws: UpdateApplyError.self) { try update.apply() } } + #expect(try fixture.bytes(file) == before) } } From ac40235e141d0e76b26db154157cf1055883a0d7 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:48:00 +0800 Subject: [PATCH 4/9] fix: distinguish unknown producer origins from conflicts --- Sources/AgentsUpdates/ProducerPatchLineage.swift | 5 +++-- Tests/AgentsUpdatesTests/ProducerPatchTests.swift | 4 +++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/Sources/AgentsUpdates/ProducerPatchLineage.swift b/Sources/AgentsUpdates/ProducerPatchLineage.swift index 3a4a0e0..ba63abf 100644 --- a/Sources/AgentsUpdates/ProducerPatchLineage.swift +++ b/Sources/AgentsUpdates/ProducerPatchLineage.swift @@ -83,9 +83,10 @@ final class ProducerPatchLineage { } if members[id] != nil { return nil } if let claims = source.bundleSources { - let origins = Set(claims.filter { !Self.localClaim($0) }.map(\.policyOrigin)) + let origins = Set( + claims.lazy.filter { !Self.localClaim($0) }.map(\.policyOrigin).filter { $0 != .missing }) if origins.count > 1 { return .ambiguousProducer } - if let origin = origins.first, origin != .missing { return .missingPathAttribution } + if !origins.isEmpty { return .missingPathAttribution } } return source.kind == .wellKnown ? .missingPathAttribution : .missingProducerIdentity } diff --git a/Tests/AgentsUpdatesTests/ProducerPatchTests.swift b/Tests/AgentsUpdatesTests/ProducerPatchTests.swift index 942d6c3..2eaa41c 100644 --- a/Tests/AgentsUpdatesTests/ProducerPatchTests.swift +++ b/Tests/AgentsUpdatesTests/ProducerPatchTests.swift @@ -314,6 +314,7 @@ struct ProducerPatchTests { let bundle = try BundleOperations.inspect(archive) let member = try #require(bundle.components.first) #expect(member.sources.contains { $0.kind == .git && $0.revision == base }) + #expect(member.sources.contains { $0.policyOrigin == .missing }) let consumer = try UpdateFixture() let imported = try BundleOperations.previewImport( @@ -335,7 +336,8 @@ struct ProducerPatchTests { try consumer.write("edited\n", to: copy.appendingPathComponent("run.sh")) let report = try UpdateOperations.previewProducerPatches(environment: consumer.environment) #expect(report.patches.isEmpty) - #expect(report.skipped.contains { $0.path == copy && $0.reason == .missingPathAttribution }) + let copyReasons = report.skipped.filter { $0.path == copy }.map(\.reason) + #expect(copyReasons == [.missingPathAttribution]) #expect( report.skipped.contains { $0.path == consumer.target() && $0.reason == .linkedDeployment }) } From 569efc95d87b37c4558b536420f29c042bae44c1 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Fri, 27 Nov 2026 16:30:50 +0800 Subject: [PATCH 5/9] test: frame loopback Git HTTPS fixture responses --- Tests/AgentsUpdatesTests/GitAcquisitionTests.swift | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Tests/AgentsUpdatesTests/GitAcquisitionTests.swift b/Tests/AgentsUpdatesTests/GitAcquisitionTests.swift index e693d63..5877f2b 100644 --- a/Tests/AgentsUpdatesTests/GitAcquisitionTests.swift +++ b/Tests/AgentsUpdatesTests/GitAcquisitionTests.swift @@ -514,11 +514,13 @@ private final class GitHTTPSFixture { if headers.get("Authorization") != expected: self.send_response(401) self.send_header("WWW-Authenticate", 'Basic realm="Fixture"') + self.send_header("Content-Length", "0") self.end_headers() return if parsed.path.startswith("/redirect.git/"): self.send_response(302) self.send_header("Location", self.path.replace("/redirect.git/", "/package.git/")) + self.send_header("Content-Length", "0") self.end_headers() return length = int(headers.get("Content-Length", "0")) @@ -536,8 +538,10 @@ private final class GitHTTPSFixture { if name.lower() == b"status"), 200) self.send_response(status) for name, value in response: - if name.lower() != b"status": + if name.lower() not in (b"status", b"content-length"): self.send_header(name.decode(), value.decode()) + # GnuTLS needs a complete HTTP message before the fixture closes the socket. + self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) From 4cffd26f8d82ef9ea5ea8d100d171400b3ec2bb1 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Fri, 27 Nov 2026 16:36:12 +0800 Subject: [PATCH 6/9] ci: pin release checks to the merged workflows --- .github/workflows/ci.yml | 2 +- .github/workflows/source-policy.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 14087b8..effcad7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -19,4 +19,4 @@ jobs: permissions: contents: read actions: read - uses: agents-tools/github-workflows/.github/workflows/swift-package.yml@f5d8edff9e7230ffe93006a0c50edf1e19bd625d + uses: agents-tools/github-workflows/.github/workflows/swift-package.yml@314a41dcae51ff835a9418acfde6542d970b7f16 diff --git a/.github/workflows/source-policy.yml b/.github/workflows/source-policy.yml index c328110..0d95ed5 100644 --- a/.github/workflows/source-policy.yml +++ b/.github/workflows/source-policy.yml @@ -17,7 +17,7 @@ concurrency: jobs: policy: if: github.event_name != 'push' || !github.event.deleted - uses: agents-tools/github-workflows/.github/workflows/policy.yml@f5d8edff9e7230ffe93006a0c50edf1e19bd625d + uses: agents-tools/github-workflows/.github/workflows/policy.yml@314a41dcae51ff835a9418acfde6542d970b7f16 with: allow-terms: | ChatGPT From 852e2ca5d61c8596fbe7834b9ff362ad4193bf6b Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Fri, 27 Nov 2026 17:41:22 +0800 Subject: [PATCH 7/9] test: make registry fixture startup independent of DNS --- .../AgentsUpdatesTests/MCPRegistryTests.swift | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/Tests/AgentsUpdatesTests/MCPRegistryTests.swift b/Tests/AgentsUpdatesTests/MCPRegistryTests.swift index 97d278f..8d1ed45 100644 --- a/Tests/AgentsUpdatesTests/MCPRegistryTests.swift +++ b/Tests/AgentsUpdatesTests/MCPRegistryTests.swift @@ -704,7 +704,7 @@ private final class RegistryFixture { fixture.process.standardError = FileHandle.nullDevice try fixture.process.run() let clock = ContinuousClock() - let deadline = clock.now + .seconds(3) + let deadline = clock.now + .seconds(10) while fixture.process.isRunning { if let value = try? fixture.text("port"), let port = Int(value), (1...65535).contains(port) { fixture.port = port @@ -847,9 +847,15 @@ private final class RegistryFixture { """# private static let server = #""" - import http.server, json, pathlib, sys, threading, time, urllib.parse + import http.server, json, pathlib, socketserver, sys, threading, time, urllib.parse root = pathlib.Path(sys.argv[1]) + class LoopbackServer(http.server.ThreadingHTTPServer): + def server_bind(self): + # The fixture uses numeric loopback addresses; startup needs no reverse DNS. + socketserver.TCPServer.server_bind(self) + self.server_name, self.server_port = self.server_address[:2] + class Handler(http.server.BaseHTTPRequestHandler): def do_GET(self): path = urllib.parse.urlsplit(self.path) @@ -894,10 +900,12 @@ private final class RegistryFixture { self.end_headers() self.wfile.write(body) - sink = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) - main = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) + sink = LoopbackServer(("127.0.0.1", 0), Handler) + main = LoopbackServer(("127.0.0.1", 0), Handler) threading.Thread(target=sink.serve_forever, daemon=True).start() - (root / "port").write_text(str(main.server_port)) + port_file = root / "port.tmp" + port_file.write_text(str(main.server_port)) + port_file.replace(root / "port") main.serve_forever() """# } From 0ac06da70bba1861a2ff516b60a2f15b08ac99da Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Fri, 27 Nov 2026 19:11:57 +0800 Subject: [PATCH 8/9] fix: keep process fixtures out of the test bundle --- .github/swift-package.json | 2 +- Documentation/Architecture/Package.md | 4 ++++ Package.swift | 13 ++++++------- 3 files changed, 11 insertions(+), 8 deletions(-) diff --git a/.github/swift-package.json b/.github/swift-package.json index 1dafec3..49a28fd 100644 --- a/.github/swift-package.json +++ b/.github/swift-package.json @@ -21,7 +21,7 @@ "xcode": "26.6" } ], - "timeout_minutes": 120, + "timeout_minutes": 180, "environment": { "SWT_EXPERIMENTAL_MAXIMUM_PARALLELIZATION_WIDTH": "1" } diff --git a/Documentation/Architecture/Package.md b/Documentation/Architecture/Package.md index 1518f7a..1f463c8 100644 --- a/Documentation/Architecture/Package.md +++ b/Documentation/Architecture/Package.md @@ -25,6 +25,10 @@ AgentsCore → CPlatform, CSQLite, Crypto, Markdown, TOMLSemantics, Yams parser/scanner and headers, with upstream license and per-file provenance. The runtime is a normal SwiftPM dependency. Consumers never receive parser types. +SwiftPM builds `ManifestTestProcess`, `StateTestProcess` and `MCPTestProcess` +as standalone fixture executables. Tests locate and launch them from the build +products directory. Test bundles link the support libraries they import. + ## NativeDocuments `NativeDocuments` inspects provided JSON, JSONC and TOML bytes and prepares diff --git a/Package.swift b/Package.swift index 77e0500..66bfd7a 100644 --- a/Package.swift +++ b/Package.swift @@ -83,8 +83,9 @@ let package = Package( name: "ComponentsTests", dependencies: [ "Components", "AgentsCore", "AgentsManifest", "AgentsSkills", "AgentsInstructions", - "StateTestProcess", "StateTestSupport", "MCPTestProcess", + "StateTestSupport", ], resources: [.copy("Fixtures")]), + // SwiftPM builds the process fixtures as executables. Tests launch them by path. .executableTarget( name: "MCPTestProcess", dependencies: ["CPlatform"], path: "Tests/MCPTestProcess"), .target( @@ -100,7 +101,7 @@ let package = Package( .testTarget( name: "AgentsCoreTests", dependencies: [ - "AgentsCore", "AgentsManifest", "StateTestProcess", "StateTestSupport", "CPlatform", + "AgentsCore", "AgentsManifest", "StateTestSupport", "CPlatform", ]), .testTarget( name: "AgentsInstructionsTests", @@ -117,21 +118,19 @@ let package = Package( .testTarget( name: "AgentsManifestTests", dependencies: [ - "AgentsManifest", "AgentsCore", "ManifestTestProcess", - "ManifestTestSupport", + "AgentsManifest", "AgentsCore", "ManifestTestSupport", ]), .testTarget( name: "AgentsUpdatesTests", dependencies: [ - "AgentsUpdates", "AgentsManifest", "StateTestProcess", "StateTestSupport", "CPlatform", - "MCPTestProcess", + "AgentsUpdates", "AgentsManifest", "StateTestSupport", "CPlatform", ]), .testTarget( name: "AgentsSkillsTests", dependencies: [ "AgentsSkills", "AgentsCore", "AgentsManifest", "AgentsInstructions", "AgentsUpdates", "Yams", - "StateTestProcess", "StateTestSupport", "CPlatform", + "StateTestSupport", "CPlatform", ]), ], swiftLanguageModes: [.v6] From 5d23160b3b2c93d2c1d1ee0c4caa7c8ca2b37cba Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Fri, 27 Nov 2026 20:40:13 +0800 Subject: [PATCH 9/9] fix: bind restore and source fixtures on Swift 6.3 Optimized synchronous TaskLocal bindings can crash with an optional function value. Store nominal Sendable callback values for the three affected test hooks. --- .../BackupRestoreTransaction.swift | 14 +++++--- Sources/AgentsCore/PackageSourceHTTP.swift | 12 +++++-- .../Lifecycle/LifecycleInvocation.swift | 8 ++--- .../Lifecycle/LifecycleTrust.swift | 18 +++++++---- Tests/AgentsCoreTests/ClientBackupTests.swift | 6 ++-- .../GitAcquisitionTests.swift | 2 +- .../PackageLifecycleTests.swift | 32 ++++++++++++------- .../SourceAccessTests.swift | 30 ++++++++--------- .../StateTestProcess/SourceArchiveProbe.swift | 2 +- 9 files changed, 75 insertions(+), 49 deletions(-) diff --git a/Sources/AgentsCore/ClientBackups/BackupRestoreTransaction.swift b/Sources/AgentsCore/ClientBackups/BackupRestoreTransaction.swift index c7d8c3b..0e1ca8d 100644 --- a/Sources/AgentsCore/ClientBackups/BackupRestoreTransaction.swift +++ b/Sources/AgentsCore/ClientBackups/BackupRestoreTransaction.swift @@ -4,7 +4,11 @@ import Foundation /// Publication uses atomic exchange or exclusive rename on each destination volume. /// The private journal records intent before every publication and survives process exit. enum BackupRestoreTransaction { - @TaskLocal static var checkpoint: (@Sendable (String) throws -> Void)? + struct Checkpoint: Sendable { + let run: @Sendable (String) throws -> Void + } + + @TaskLocal static var checkpoint: Checkpoint? private struct Leaf: Codable { let path: String @@ -172,7 +176,7 @@ enum BackupRestoreTransaction { try validate(plan) journal.phase = .publishing try persist(journal, in: journalRoot, name: name) - try checkpoint?("publishing") + try checkpoint?.run("publishing") for (index, group) in groups.enumerated() { let unit = journal.units[index] let parent = try unit.openParent() @@ -202,15 +206,15 @@ enum BackupRestoreTransaction { } } _ = try unit.openParent() - try checkpoint?("published") + try checkpoint?.run("published") } journal.phase = .committed try persist(journal, in: journalRoot, name: name) - try checkpoint?("committed") + try checkpoint?.run("committed") } catch { let original = error do { - try checkpoint?("recovering") + try checkpoint?.run("recovering") try recover(in: journalRoot, named: name, client: plan.client) } catch { throw ClientBackupError.storageFailure( diff --git a/Sources/AgentsCore/PackageSourceHTTP.swift b/Sources/AgentsCore/PackageSourceHTTP.swift index f37ec30..287b24a 100644 --- a/Sources/AgentsCore/PackageSourceHTTP.swift +++ b/Sources/AgentsCore/PackageSourceHTTP.swift @@ -17,14 +17,22 @@ package enum PackageSourceHTTP { } } + package struct Fixture: Sendable { + let respond: @Sendable (URLRequest, Int?) throws -> Response + + package init(_ respond: @escaping @Sendable (URLRequest, Int?) throws -> Response) { + self.respond = respond + } + } + // Tests supply a local transport without modifying URLSession or OS trust. - @TaskLocal package static var fixture: (@Sendable (URLRequest, Int?) throws -> Response)? + @TaskLocal package static var fixture: Fixture? static func read(_ request: URLRequest, maximumBytes: Int?) throws -> Response { guard let url = request.url else { throw SourceAccessError.requestFailed } _ = try SourceURL.https(url) if let fixture { - let response = try fixture(request, maximumBytes) + let response = try fixture.respond(request, maximumBytes) if let maximumBytes, response.body.count > maximumBytes { throw SourceAccessError.requestFailed } diff --git a/Sources/AgentsUpdates/Lifecycle/LifecycleInvocation.swift b/Sources/AgentsUpdates/Lifecycle/LifecycleInvocation.swift index 761380b..2e5f6fd 100644 --- a/Sources/AgentsUpdates/Lifecycle/LifecycleInvocation.swift +++ b/Sources/AgentsUpdates/Lifecycle/LifecycleInvocation.swift @@ -125,7 +125,7 @@ struct LifecycleInvocation: Sendable { private func handoff( _ captured: CapturedLifecycleAction, _ start: (DirectoryHandle) throws -> Value ) throws -> Value { - LifecycleOperations.checkpoint?(.beforeHandoff) + LifecycleOperations.checkpoint?.notify(.beforeHandoff) if Task.isCancelled { throw Withheld(reason: .cancelled) } do { try context.store.withReadLock {} @@ -187,7 +187,7 @@ struct LifecycleInvocation: Sendable { do { try policy.snapshot?.validate() } catch { throw Withheld(reason: .policyUnavailable) } if Task.isCancelled { throw Withheld(reason: .cancelled) } let launched = try start(directory) - LifecycleOperations.checkpoint?(.handedOff) + LifecycleOperations.checkpoint?.notify(.handedOff) return launched } @@ -310,7 +310,7 @@ extension LifecycleOperations { onDispatch: (@Sendable (LifecycleActionSummary) -> Void)? = nil ) async -> LifecycleSubmission<[LifecycleActionResult]> { await review.confirmation.submit { - checkpoint?(.confirmationClaimed) + checkpoint?.notify(.confirmationClaimed) let client = LifecycleHTTPClient() let session = client.session() defer { session.invalidateAndCancel() } @@ -360,7 +360,7 @@ extension UpdateOperations { onDispatch: (@Sendable (LifecycleActionSummary) -> Void)? = nil ) async -> LifecycleSubmission> { await review.confirmation.submit { - LifecycleOperations.checkpoint?(.confirmationClaimed) + LifecycleOperations.checkpoint?.notify(.confirmationClaimed) let plan = review.plan let client = LifecycleHTTPClient() let session = client.session() diff --git a/Sources/AgentsUpdates/Lifecycle/LifecycleTrust.swift b/Sources/AgentsUpdates/Lifecycle/LifecycleTrust.swift index b928a10..98b8b6e 100644 --- a/Sources/AgentsUpdates/Lifecycle/LifecycleTrust.swift +++ b/Sources/AgentsUpdates/Lifecycle/LifecycleTrust.swift @@ -55,7 +55,13 @@ extension LifecycleOperations { case handedOff } - @TaskLocal static var checkpoint: (@Sendable (Checkpoint) -> Void)? + struct CheckpointObserver: Sendable { + let notify: @Sendable (Checkpoint) -> Void + + init(_ notify: @escaping @Sendable (Checkpoint) -> Void) { self.notify = notify } + } + + @TaskLocal static var checkpoint: CheckpointObserver? @TaskLocal package static var transactionCheckpointForTesting: (@Sendable (String) throws -> Void)? @@ -86,7 +92,7 @@ extension LifecycleOperations { _ review: LifecycleEnableReview ) async -> LifecycleSubmission> { await review.confirmation.submit { - checkpoint?(.confirmationClaimed) + checkpoint?.notify(.confirmationClaimed) return Result { try review.context.publishEnable(review.enablement) } } } @@ -130,14 +136,14 @@ extension LifecycleOperations { _ review: LifecycleDeclarationReview, enable: Bool = false ) async -> LifecycleSubmission> { await review.confirmation.submit { - checkpoint?(.confirmationClaimed) + checkpoint?.notify(.confirmationClaimed) return Result { let proposed = enable ? review.enablement : nil if enable && proposed == nil { throw CoreError.invalidState("Enablement requires a reviewed project declaration.") } try review.context.publishDeclaration(review) - checkpoint?(.declarationSaved) + checkpoint?.notify(.declarationSaved) guard let proposed else { return .saved } do { return .savedAndEnabled(try review.context.publishEnable(proposed)) @@ -282,7 +288,7 @@ extension LifecycleContext { guard expectedRevision == nil || revision == expectedRevision, revision < UInt64.max else { throw CoreError.invalidState("The project's lifecycle trust revision changed.") } - LifecycleOperations.checkpoint?(.beforeReceiptPublication) + LifecycleOperations.checkpoint?.notify(.beforeReceiptPublication) try validate() try Task.checkCancellation() let record = LifecycleTrustRecord(project: project, revision: revision + 1, digest: digest) @@ -294,7 +300,7 @@ extension LifecycleContext { try directory.replacePrivateLifecycleFile(LifecycleReceipts.file, bytes: bytes) return record } - LifecycleOperations.checkpoint?(.receiptPublished) + LifecycleOperations.checkpoint?.notify(.receiptPublished) return record } diff --git a/Tests/AgentsCoreTests/ClientBackupTests.swift b/Tests/AgentsCoreTests/ClientBackupTests.swift index 0dd61e4..f8c4ec3 100644 --- a/Tests/AgentsCoreTests/ClientBackupTests.swift +++ b/Tests/AgentsCoreTests/ClientBackupTests.swift @@ -343,7 +343,7 @@ import Testing if step == "published" { throw PublicationFailure.injected } } #expect(throws: PublicationFailure.self) { - try BackupRestoreTransaction.$checkpoint.withValue(fault) { + try BackupRestoreTransaction.$checkpoint.withValue(.init(run: fault)) { try ClientBackups.restore(plan) } } @@ -374,7 +374,7 @@ import Testing if step == "published" || step == "recovering" { throw PublicationFailure.injected } } #expect(throws: ClientBackupError.self) { - try BackupRestoreTransaction.$checkpoint.withValue(fault) { + try BackupRestoreTransaction.$checkpoint.withValue(.init(run: fault)) { try ClientBackups.restore(preview) } } @@ -535,7 +535,7 @@ import Testing } } #expect(throws: PublicationFailure.self) { - try BackupRestoreTransaction.$checkpoint.withValue(rollback) { + try BackupRestoreTransaction.$checkpoint.withValue(.init(run: rollback)) { try ClientBackups.restore(preview) } } diff --git a/Tests/AgentsUpdatesTests/GitAcquisitionTests.swift b/Tests/AgentsUpdatesTests/GitAcquisitionTests.swift index 5877f2b..22988e9 100644 --- a/Tests/AgentsUpdatesTests/GitAcquisitionTests.swift +++ b/Tests/AgentsUpdatesTests/GitAcquisitionTests.swift @@ -280,7 +280,7 @@ struct GitAcquisitionTests { ]) let archive = try Data(contentsOf: zip) try PackageSourceHTTP.$fixture.withValue( - { request, _ in + .init { request, _ in #expect( request.url?.absoluteString == "https://archive-fixture.invalid/base/org/private/archive/refs/heads/main.zip") diff --git a/Tests/AgentsUpdatesTests/PackageLifecycleTests.swift b/Tests/AgentsUpdatesTests/PackageLifecycleTests.swift index e12fc05..4d6e5ce 100644 --- a/Tests/AgentsUpdatesTests/PackageLifecycleTests.swift +++ b/Tests/AgentsUpdatesTests/PackageLifecycleTests.swift @@ -141,9 +141,11 @@ struct PackageLifecycleTests { #expect(!fixture.exists(fixture.counter)) let barrier = LifecycleBarrier() let running = Task { - await LifecycleOperations.$checkpoint.withValue({ step in - if step == .confirmationClaimed { barrier.pause() } - }) { + await LifecycleOperations.$checkpoint.withValue( + .init { step in + if step == .confirmationClaimed { barrier.pause() } + } + ) { await UpdateOperations.perform(review) } } @@ -243,9 +245,11 @@ struct PackageLifecycleTests { try LifecycleFixture.subtree(), environment: fixture.environment) let barrier = LifecycleBarrier() let task = Task { - await LifecycleOperations.$checkpoint.withValue({ step in - if step == .declarationSaved { barrier.pause() } - }) { + await LifecycleOperations.$checkpoint.withValue( + .init { step in + if step == .declarationSaved { barrier.pause() } + } + ) { await LifecycleOperations.save(staged, enable: true) } } @@ -426,9 +430,11 @@ struct PackageLifecycleTests { let review = LifecycleOperations.simulate(.preInstall, environment: fixture.environment) let handoff = LifecycleBarrier() let running = Task { - await LifecycleOperations.$checkpoint.withValue({ point in - if point == .handedOff { handoff.pause() } - }) { + await LifecycleOperations.$checkpoint.withValue( + .init { point in + if point == .handedOff { handoff.pause() } + } + ) { await LifecycleOperations.executeTest(review) } } @@ -437,9 +443,11 @@ struct PackageLifecycleTests { let published = DispatchSemaphore(value: 0) let returned = DispatchSemaphore(value: 0) let revoking = Task { - try LifecycleOperations.$checkpoint.withValue({ point in - if point == .receiptPublished { published.signal() } - }) { + try LifecycleOperations.$checkpoint.withValue( + .init { point in + if point == .receiptPublished { published.signal() } + } + ) { defer { returned.signal() } return try LifecycleOperations.revoke(grant.project, environment: fixture.environment) } diff --git a/Tests/AgentsUpdatesTests/SourceAccessTests.swift b/Tests/AgentsUpdatesTests/SourceAccessTests.swift index 3bc585e..1ad9468 100644 --- a/Tests/AgentsUpdatesTests/SourceAccessTests.swift +++ b/Tests/AgentsUpdatesTests/SourceAccessTests.swift @@ -69,7 +69,7 @@ struct SourceAccessTests { let requests = Mutex([String]()) try PackageSourceHTTP.$fixture.withValue( - { request, maximum in + .init { request, maximum in #expect(request.url == endpoint) #expect(maximum == nil) let header = request.value(forHTTPHeaderField: "Authorization") ?? "" @@ -178,7 +178,7 @@ struct SourceAccessTests { } try PackageSourceHTTP.$fixture.withValue( - { _, _ in + .init { _, _ in Issue.record("denied route ran a request") throw SourceAccessError.requestFailed }, @@ -226,7 +226,7 @@ struct SourceAccessTests { } ]) try PackageSourceHTTP.$fixture.withValue( - { request, _ in + .init { request, _ in #expect( request.value(forHTTPHeaderField: "Authorization") == "Bearer fixture-mirror-route-secret" ) @@ -263,7 +263,7 @@ struct SourceAccessTests { let bytes = fixture.zip() let calls = Mutex(0) try PackageSourceHTTP.$fixture.withValue( - { request, _ in + .init { request, _ in #expect(request.url?.path.hasSuffix("refs/tags/v1.2.3.zip") == true) calls.withLock { $0 += 1 } return .init(status: 200, body: bytes) @@ -292,7 +292,7 @@ struct SourceAccessTests { let requests = Mutex(0) let bytes = fixture.zip() try PackageSourceHTTP.$fixture.withValue( - { request, _ in + .init { request, _ in #expect(request.url?.path == "/base/org/repo/archive/refs/tags/release/v1.zip") requests.withLock { $0 += 1 } return .init(status: 200, body: bytes) @@ -323,7 +323,7 @@ struct SourceAccessTests { let damage = mode == .link ? retained.appendingPathComponent("tree") : deployed try FileManager.default.removeItem(at: damage) try PackageSourceHTTP.$fixture.withValue( - { _, _ in + .init { _, _ in Issue.record("offline replay ran an HTTP request") throw SourceAccessError.requestFailed }, @@ -351,7 +351,7 @@ struct SourceAccessTests { try VerifiedVCSArchive(original).treeDigest != VerifiedVCSArchive(fixture.zip(executable: false)).treeDigest) try PackageSourceHTTP.$fixture.withValue( - { _, _ in .init(status: 200, body: original) }, + .init { _, _ in .init(status: 200, body: original) }, operation: { try fixture.install(.link) }) @@ -361,7 +361,7 @@ struct SourceAccessTests { let sealed = try Data(contentsOf: representation) try FileManager.default.removeItem(at: representation) try PackageSourceHTTP.$fixture.withValue( - { _, _ in .init(status: 200, body: recompressed) }, + .init { _, _ in .init(status: 200, body: recompressed) }, operation: { if strict { #expect(throws: SourceAccessError.archiveChanged) { @@ -406,7 +406,7 @@ struct SourceAccessTests { agents: [.codex], sources: ["fixture": fixture.source], instructions: .init(agents: [.codex], sections: ["fixture:guidance"])) try PackageSourceHTTP.$fixture.withValue( - { _, _ in .init(status: 200, body: archive) }, + .init { _, _ in .init(status: 200, body: archive) }, operation: { try UpdateOperations.withPreparedUpdate( .init(operation: .declaration(declaration)), environment: fixture.environment @@ -425,7 +425,7 @@ struct SourceAccessTests { defer { fixture.remove() } let bytes = fixture.zip() try PackageSourceHTTP.$fixture.withValue( - { _, _ in .init(status: 200, body: bytes) }, + .init { _, _ in .init(status: 200, body: bytes) }, operation: { try fixture.install(.link) }) @@ -461,7 +461,7 @@ struct SourceAccessTests { #expect(!FileManager.default.fileExists(atPath: fixture.store.resolvedURL.path)) #expect(!FileManager.default.fileExists(atPath: fixture.skill.path)) try PackageSourceHTTP.$fixture.withValue( - { _, _ in .init(status: 200, body: bytes) }, + .init { _, _ in .init(status: 200, body: bytes) }, operation: { try fixture.install(.link) }) @@ -479,7 +479,7 @@ struct SourceAccessTests { #expect(try cache.apply(cache.preview(.clean)).isComplete) try FileManager.default.removeItem(at: fixture.skill.deletingLastPathComponent()) try PackageSourceHTTP.$fixture.withValue( - { _, _ in + .init { _, _ in Issue.record("offline crash recovery made a request") throw SourceAccessError.requestFailed }, @@ -497,7 +497,7 @@ struct SourceAccessTests { at: destinationParent, withIntermediateDirectories: true) let bytes = fixture.zip() PackageSourceHTTP.$fixture.withValue( - { _, _ in .init(status: 200, body: bytes) }, + .init { _, _ in .init(status: 200, body: bytes) }, operation: { #expect(throws: UpdateApplyError.self) { try UpdateOperations.withPreparedUpdate( @@ -727,7 +727,7 @@ extension SourceAccessTests { let bytes = fixture.zip() let requests = Mutex(0) try PackageSourceHTTP.$fixture.withValue( - { request, _ in + .init { request, _ in requests.withLock { $0 += 1 } #expect( request.url?.absoluteString @@ -831,7 +831,7 @@ extension SourceAccessTests { let bytes = fixture.zip() let requests = Mutex(0) try PackageSourceHTTP.$fixture.withValue( - { _, _ in + .init { _, _ in requests.withLock { $0 += 1 } return .init(status: 200, body: bytes) }, diff --git a/Tests/StateTestProcess/SourceArchiveProbe.swift b/Tests/StateTestProcess/SourceArchiveProbe.swift index 2e83f5b..27dcc14 100644 --- a/Tests/StateTestProcess/SourceArchiveProbe.swift +++ b/Tests/StateTestProcess/SourceArchiveProbe.swift @@ -23,7 +23,7 @@ func sourceArchiveProbe( ], skills: ["fixture": .init(select: .names(["demo"]), mode: .link)]) try PackageSourceHTTP.$fixture.withValue( - { _, _ in .init(status: 200, body: bytes) }, + .init { _, _ in .init(status: 200, body: bytes) }, operation: { try UpdateOperations.withPreparedUpdate( .init(operation: .declaration(declaration)), environment: environment,